xref: /openbsd/sys/kern/uipc_socket.c (revision cca36db2)
1 /*	$OpenBSD: uipc_socket.c,v 1.100 2012/04/24 16:35:08 deraadt Exp $	*/
2 /*	$NetBSD: uipc_socket.c,v 1.21 1996/02/04 02:17:52 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)uipc_socket.c	8.3 (Berkeley) 4/15/94
33  */
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/proc.h>
38 #include <sys/file.h>
39 #include <sys/filedesc.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/domain.h>
43 #include <sys/kernel.h>
44 #include <sys/event.h>
45 #include <sys/protosw.h>
46 #include <sys/socket.h>
47 #include <sys/unpcb.h>
48 #include <sys/socketvar.h>
49 #include <sys/signalvar.h>
50 #include <sys/resourcevar.h>
51 #include <net/route.h>
52 #include <sys/pool.h>
53 
54 void	sbsync(struct sockbuf *, struct mbuf *);
55 
56 int	sosplice(struct socket *, int, off_t, struct timeval *);
57 void	sounsplice(struct socket *, struct socket *, int);
58 int	somove(struct socket *, int);
59 void	soidle(void *);
60 
61 void	filt_sordetach(struct knote *kn);
62 int	filt_soread(struct knote *kn, long hint);
63 void	filt_sowdetach(struct knote *kn);
64 int	filt_sowrite(struct knote *kn, long hint);
65 int	filt_solisten(struct knote *kn, long hint);
66 
67 struct filterops solisten_filtops =
68 	{ 1, NULL, filt_sordetach, filt_solisten };
69 struct filterops soread_filtops =
70 	{ 1, NULL, filt_sordetach, filt_soread };
71 struct filterops sowrite_filtops =
72 	{ 1, NULL, filt_sowdetach, filt_sowrite };
73 
74 
75 #ifndef SOMINCONN
76 #define SOMINCONN 80
77 #endif /* SOMINCONN */
78 
79 int	somaxconn = SOMAXCONN;
80 int	sominconn = SOMINCONN;
81 
82 struct pool socket_pool;
83 
84 void
85 soinit(void)
86 {
87 
88 	pool_init(&socket_pool, sizeof(struct socket), 0, 0, 0, "sockpl", NULL);
89 }
90 
91 /*
92  * Socket operation routines.
93  * These routines are called by the routines in
94  * sys_socket.c or from a system process, and
95  * implement the semantics of socket operations by
96  * switching out to the protocol specific routines.
97  */
98 /*ARGSUSED*/
99 int
100 socreate(int dom, struct socket **aso, int type, int proto)
101 {
102 	struct proc *p = curproc;		/* XXX */
103 	struct protosw *prp;
104 	struct socket *so;
105 	int error, s;
106 
107 	if (proto)
108 		prp = pffindproto(dom, proto, type);
109 	else
110 		prp = pffindtype(dom, type);
111 	if (prp == NULL || prp->pr_usrreq == 0)
112 		return (EPROTONOSUPPORT);
113 	if (prp->pr_type != type)
114 		return (EPROTOTYPE);
115 	s = splsoftnet();
116 	so = pool_get(&socket_pool, PR_WAITOK | PR_ZERO);
117 	TAILQ_INIT(&so->so_q0);
118 	TAILQ_INIT(&so->so_q);
119 	so->so_type = type;
120 	if (suser(p, 0) == 0)
121 		so->so_state = SS_PRIV;
122 	so->so_ruid = p->p_cred->p_ruid;
123 	so->so_euid = p->p_ucred->cr_uid;
124 	so->so_rgid = p->p_cred->p_rgid;
125 	so->so_egid = p->p_ucred->cr_gid;
126 	so->so_cpid = p->p_pid;
127 	so->so_proto = prp;
128 	error = (*prp->pr_usrreq)(so, PRU_ATTACH, NULL,
129 	    (struct mbuf *)(long)proto, NULL, p);
130 	if (error) {
131 		so->so_state |= SS_NOFDREF;
132 		sofree(so);
133 		splx(s);
134 		return (error);
135 	}
136 	splx(s);
137 	*aso = so;
138 	return (0);
139 }
140 
141 int
142 sobind(struct socket *so, struct mbuf *nam, struct proc *p)
143 {
144 	int s = splsoftnet();
145 	int error;
146 
147 	error = (*so->so_proto->pr_usrreq)(so, PRU_BIND, NULL, nam, NULL, p);
148 	splx(s);
149 	return (error);
150 }
151 
152 int
153 solisten(struct socket *so, int backlog)
154 {
155 	int s, error;
156 
157 #ifdef SOCKET_SPLICE
158 	if (so->so_splice || so->so_spliceback)
159 		return (EOPNOTSUPP);
160 #endif /* SOCKET_SPLICE */
161 	s = splsoftnet();
162 	error = (*so->so_proto->pr_usrreq)(so, PRU_LISTEN, NULL, NULL, NULL,
163 	    curproc);
164 	if (error) {
165 		splx(s);
166 		return (error);
167 	}
168 	if (TAILQ_FIRST(&so->so_q) == NULL)
169 		so->so_options |= SO_ACCEPTCONN;
170 	if (backlog < 0 || backlog > somaxconn)
171 		backlog = somaxconn;
172 	if (backlog < sominconn)
173 		backlog = sominconn;
174 	so->so_qlimit = backlog;
175 	splx(s);
176 	return (0);
177 }
178 
179 /*
180  *  Must be called at splsoftnet()
181  */
182 
183 void
184 sofree(struct socket *so)
185 {
186 	splsoftassert(IPL_SOFTNET);
187 
188 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
189 		return;
190 	if (so->so_head) {
191 		/*
192 		 * We must not decommission a socket that's on the accept(2)
193 		 * queue.  If we do, then accept(2) may hang after select(2)
194 		 * indicated that the listening socket was ready.
195 		 */
196 		if (!soqremque(so, 0))
197 			return;
198 	}
199 #ifdef SOCKET_SPLICE
200 	if (so->so_spliceback)
201 		sounsplice(so->so_spliceback, so, so->so_spliceback != so);
202 	if (so->so_splice)
203 		sounsplice(so, so->so_splice, 0);
204 #endif /* SOCKET_SPLICE */
205 	sbrelease(&so->so_snd);
206 	sorflush(so);
207 	pool_put(&socket_pool, so);
208 }
209 
210 /*
211  * Close a socket on last file table reference removal.
212  * Initiate disconnect if connected.
213  * Free socket when disconnect complete.
214  */
215 int
216 soclose(struct socket *so)
217 {
218 	struct socket *so2;
219 	int s = splsoftnet();		/* conservative */
220 	int error = 0;
221 
222 	if (so->so_options & SO_ACCEPTCONN) {
223 		while ((so2 = TAILQ_FIRST(&so->so_q0)) != NULL) {
224 			(void) soqremque(so2, 0);
225 			(void) soabort(so2);
226 		}
227 		while ((so2 = TAILQ_FIRST(&so->so_q)) != NULL) {
228 			(void) soqremque(so2, 1);
229 			(void) soabort(so2);
230 		}
231 	}
232 	if (so->so_pcb == 0)
233 		goto discard;
234 	if (so->so_state & SS_ISCONNECTED) {
235 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
236 			error = sodisconnect(so);
237 			if (error)
238 				goto drop;
239 		}
240 		if (so->so_options & SO_LINGER) {
241 			if ((so->so_state & SS_ISDISCONNECTING) &&
242 			    (so->so_state & SS_NBIO))
243 				goto drop;
244 			while (so->so_state & SS_ISCONNECTED) {
245 				error = tsleep(&so->so_timeo,
246 				    PSOCK | PCATCH, "netcls",
247 				    so->so_linger * hz);
248 				if (error)
249 					break;
250 			}
251 		}
252 	}
253 drop:
254 	if (so->so_pcb) {
255 		int error2 = (*so->so_proto->pr_usrreq)(so, PRU_DETACH, NULL,
256 		    NULL, NULL, curproc);
257 		if (error == 0)
258 			error = error2;
259 	}
260 discard:
261 	if (so->so_state & SS_NOFDREF)
262 		panic("soclose: NOFDREF");
263 	so->so_state |= SS_NOFDREF;
264 	sofree(so);
265 	splx(s);
266 	return (error);
267 }
268 
269 /*
270  * Must be called at splsoftnet.
271  */
272 int
273 soabort(struct socket *so)
274 {
275 	splsoftassert(IPL_SOFTNET);
276 
277 	return (*so->so_proto->pr_usrreq)(so, PRU_ABORT, NULL, NULL, NULL,
278 	   curproc);
279 }
280 
281 int
282 soaccept(struct socket *so, struct mbuf *nam)
283 {
284 	int s = splsoftnet();
285 	int error = 0;
286 
287 	if ((so->so_state & SS_NOFDREF) == 0)
288 		panic("soaccept: !NOFDREF");
289 	so->so_state &= ~SS_NOFDREF;
290 	if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
291 	    (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
292 		error = (*so->so_proto->pr_usrreq)(so, PRU_ACCEPT, NULL,
293 		    nam, NULL, curproc);
294 	else
295 		error = ECONNABORTED;
296 	splx(s);
297 	return (error);
298 }
299 
300 int
301 soconnect(struct socket *so, struct mbuf *nam)
302 {
303 	int s;
304 	int error;
305 
306 	if (so->so_options & SO_ACCEPTCONN)
307 		return (EOPNOTSUPP);
308 	s = splsoftnet();
309 	/*
310 	 * If protocol is connection-based, can only connect once.
311 	 * Otherwise, if connected, try to disconnect first.
312 	 * This allows user to disconnect by connecting to, e.g.,
313 	 * a null address.
314 	 */
315 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
316 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
317 	    (error = sodisconnect(so))))
318 		error = EISCONN;
319 	else
320 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONNECT,
321 		    NULL, nam, NULL, curproc);
322 	splx(s);
323 	return (error);
324 }
325 
326 int
327 soconnect2(struct socket *so1, struct socket *so2)
328 {
329 	int s = splsoftnet();
330 	int error;
331 
332 	error = (*so1->so_proto->pr_usrreq)(so1, PRU_CONNECT2, NULL,
333 	    (struct mbuf *)so2, NULL, curproc);
334 	splx(s);
335 	return (error);
336 }
337 
338 int
339 sodisconnect(struct socket *so)
340 {
341 	int s = splsoftnet();
342 	int error;
343 
344 	if ((so->so_state & SS_ISCONNECTED) == 0) {
345 		error = ENOTCONN;
346 		goto bad;
347 	}
348 	if (so->so_state & SS_ISDISCONNECTING) {
349 		error = EALREADY;
350 		goto bad;
351 	}
352 	error = (*so->so_proto->pr_usrreq)(so, PRU_DISCONNECT, NULL, NULL,
353 	    NULL, curproc);
354 bad:
355 	splx(s);
356 	return (error);
357 }
358 
359 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
360 /*
361  * Send on a socket.
362  * If send must go all at once and message is larger than
363  * send buffering, then hard error.
364  * Lock against other senders.
365  * If must go all at once and not enough room now, then
366  * inform user that this would block and do nothing.
367  * Otherwise, if nonblocking, send as much as possible.
368  * The data to be sent is described by "uio" if nonzero,
369  * otherwise by the mbuf chain "top" (which must be null
370  * if uio is not).  Data provided in mbuf chain must be small
371  * enough to send all at once.
372  *
373  * Returns nonzero on error, timeout or signal; callers
374  * must check for short counts if EINTR/ERESTART are returned.
375  * Data and control buffers are freed on return.
376  */
377 int
378 sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top,
379     struct mbuf *control, int flags)
380 {
381 	struct mbuf **mp;
382 	struct mbuf *m;
383 	long space, len, mlen, clen = 0;
384 	quad_t resid;
385 	int error, s, dontroute;
386 	int atomic = sosendallatonce(so) || top;
387 
388 	if (uio)
389 		resid = uio->uio_resid;
390 	else
391 		resid = top->m_pkthdr.len;
392 	/*
393 	 * In theory resid should be unsigned (since uio->uio_resid is).
394 	 * However, space must be signed, as it might be less than 0
395 	 * if we over-committed, and we must use a signed comparison
396 	 * of space and resid.  On the other hand, a negative resid
397 	 * causes us to loop sending 0-length segments to the protocol.
398 	 * MSG_EOR on a SOCK_STREAM socket is also invalid.
399 	 */
400 	if (resid < 0 ||
401 	    (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
402 		error = EINVAL;
403 		goto out;
404 	}
405 	dontroute =
406 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
407 	    (so->so_proto->pr_flags & PR_ATOMIC);
408 	if (uio && uio->uio_procp)
409 		uio->uio_procp->p_ru.ru_msgsnd++;
410 	if (control) {
411 		clen = control->m_len;
412 		/* reserve extra space for AF_LOCAL's internalize */
413 		if (so->so_proto->pr_domain->dom_family == AF_LOCAL &&
414 		    clen >= CMSG_ALIGN(sizeof(struct cmsghdr)) &&
415 		    mtod(control, struct cmsghdr *)->cmsg_type == SCM_RIGHTS)
416 			clen = CMSG_SPACE(
417 			    (clen - CMSG_ALIGN(sizeof(struct cmsghdr))) *
418 			    (sizeof(struct file *) / sizeof(int)));
419 	}
420 
421 #define	snderr(errno)	{ error = errno; splx(s); goto release; }
422 
423 restart:
424 	if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
425 		goto out;
426 	so->so_state |= SS_ISSENDING;
427 	do {
428 		s = splsoftnet();
429 		if (so->so_state & SS_CANTSENDMORE)
430 			snderr(EPIPE);
431 		if (so->so_error) {
432 			error = so->so_error;
433 			so->so_error = 0;
434 			splx(s);
435 			goto release;
436 		}
437 		if ((so->so_state & SS_ISCONNECTED) == 0) {
438 			if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
439 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
440 				    !(resid == 0 && clen != 0))
441 					snderr(ENOTCONN);
442 			} else if (addr == 0)
443 				snderr(EDESTADDRREQ);
444 		}
445 		space = sbspace(&so->so_snd);
446 		if (flags & MSG_OOB)
447 			space += 1024;
448 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
449 		    (so->so_proto->pr_domain->dom_family != AF_LOCAL &&
450 		    clen > so->so_snd.sb_hiwat))
451 			snderr(EMSGSIZE);
452 		if (space < resid + clen &&
453 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
454 			if (so->so_state & SS_NBIO)
455 				snderr(EWOULDBLOCK);
456 			sbunlock(&so->so_snd);
457 			error = sbwait(&so->so_snd);
458 			so->so_state &= ~SS_ISSENDING;
459 			splx(s);
460 			if (error)
461 				goto out;
462 			goto restart;
463 		}
464 		splx(s);
465 		mp = &top;
466 		space -= clen;
467 		do {
468 			if (uio == NULL) {
469 				/*
470 				 * Data is prepackaged in "top".
471 				 */
472 				resid = 0;
473 				if (flags & MSG_EOR)
474 					top->m_flags |= M_EOR;
475 			} else do {
476 				if (top == 0) {
477 					MGETHDR(m, M_WAIT, MT_DATA);
478 					mlen = MHLEN;
479 					m->m_pkthdr.len = 0;
480 					m->m_pkthdr.rcvif = (struct ifnet *)0;
481 				} else {
482 					MGET(m, M_WAIT, MT_DATA);
483 					mlen = MLEN;
484 				}
485 				if (resid >= MINCLSIZE && space >= MCLBYTES) {
486 					MCLGET(m, M_NOWAIT);
487 					if ((m->m_flags & M_EXT) == 0)
488 						goto nopages;
489 					mlen = MCLBYTES;
490 					if (atomic && top == 0) {
491 						len = lmin(MCLBYTES - max_hdr, resid);
492 						m->m_data += max_hdr;
493 					} else
494 						len = lmin(MCLBYTES, resid);
495 					space -= len;
496 				} else {
497 nopages:
498 					len = lmin(lmin(mlen, resid), space);
499 					space -= len;
500 					/*
501 					 * For datagram protocols, leave room
502 					 * for protocol headers in first mbuf.
503 					 */
504 					if (atomic && top == 0 && len < mlen)
505 						MH_ALIGN(m, len);
506 				}
507 				error = uiomove(mtod(m, caddr_t), (int)len,
508 				    uio);
509 				resid = uio->uio_resid;
510 				m->m_len = len;
511 				*mp = m;
512 				top->m_pkthdr.len += len;
513 				if (error)
514 					goto release;
515 				mp = &m->m_next;
516 				if (resid <= 0) {
517 					if (flags & MSG_EOR)
518 						top->m_flags |= M_EOR;
519 					break;
520 				}
521 			} while (space > 0 && atomic);
522 			if (dontroute)
523 				so->so_options |= SO_DONTROUTE;
524 			s = splsoftnet();		/* XXX */
525 			if (resid <= 0)
526 				so->so_state &= ~SS_ISSENDING;
527 			error = (*so->so_proto->pr_usrreq)(so,
528 			    (flags & MSG_OOB) ? PRU_SENDOOB : PRU_SEND,
529 			    top, addr, control, curproc);
530 			splx(s);
531 			if (dontroute)
532 				so->so_options &= ~SO_DONTROUTE;
533 			clen = 0;
534 			control = 0;
535 			top = 0;
536 			mp = &top;
537 			if (error)
538 				goto release;
539 		} while (resid && space > 0);
540 	} while (resid);
541 
542 release:
543 	so->so_state &= ~SS_ISSENDING;
544 	sbunlock(&so->so_snd);
545 out:
546 	if (top)
547 		m_freem(top);
548 	if (control)
549 		m_freem(control);
550 	return (error);
551 }
552 
553 /*
554  * Following replacement or removal of the first mbuf on the first
555  * mbuf chain of a socket buffer, push necessary state changes back
556  * into the socket buffer so that other consumers see the values
557  * consistently.  'nextrecord' is the callers locally stored value of
558  * the original value of sb->sb_mb->m_nextpkt which must be restored
559  * when the lead mbuf changes.  NOTE: 'nextrecord' may be NULL.
560  */
561 void
562 sbsync(struct sockbuf *sb, struct mbuf *nextrecord)
563 {
564 
565 	/*
566 	 * First, update for the new value of nextrecord.  If necessary,
567 	 * make it the first record.
568 	 */
569 	if (sb->sb_mb != NULL)
570 		sb->sb_mb->m_nextpkt = nextrecord;
571 	else
572 		sb->sb_mb = nextrecord;
573 
574         /*
575          * Now update any dependent socket buffer fields to reflect
576          * the new state.  This is an inline of SB_EMPTY_FIXUP, with
577          * the addition of a second clause that takes care of the
578          * case where sb_mb has been updated, but remains the last
579          * record.
580          */
581         if (sb->sb_mb == NULL) {
582                 sb->sb_mbtail = NULL;
583                 sb->sb_lastrecord = NULL;
584         } else if (sb->sb_mb->m_nextpkt == NULL)
585                 sb->sb_lastrecord = sb->sb_mb;
586 }
587 
588 /*
589  * Implement receive operations on a socket.
590  * We depend on the way that records are added to the sockbuf
591  * by sbappend*.  In particular, each record (mbufs linked through m_next)
592  * must begin with an address if the protocol so specifies,
593  * followed by an optional mbuf or mbufs containing ancillary data,
594  * and then zero or more mbufs of data.
595  * In order to avoid blocking network interrupts for the entire time here,
596  * we splx() while doing the actual copy to user space.
597  * Although the sockbuf is locked, new data may still be appended,
598  * and thus we must maintain consistency of the sockbuf during that time.
599  *
600  * The caller may receive the data as a single mbuf chain by supplying
601  * an mbuf **mp0 for use in returning the chain.  The uio is then used
602  * only for the count in uio_resid.
603  */
604 int
605 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
606     struct mbuf **mp0, struct mbuf **controlp, int *flagsp,
607     socklen_t controllen)
608 {
609 	struct mbuf *m, **mp;
610 	struct mbuf *cm;
611 	int flags, len, error, s, offset;
612 	struct protosw *pr = so->so_proto;
613 	struct mbuf *nextrecord;
614 	int moff, type = 0;
615 	size_t orig_resid = uio->uio_resid;
616 	int uio_error = 0;
617 	int resid;
618 
619 	mp = mp0;
620 	if (paddr)
621 		*paddr = 0;
622 	if (controlp)
623 		*controlp = 0;
624 	if (flagsp)
625 		flags = *flagsp &~ MSG_EOR;
626 	else
627 		flags = 0;
628 	if (so->so_state & SS_NBIO)
629 		flags |= MSG_DONTWAIT;
630 	if (flags & MSG_OOB) {
631 		m = m_get(M_WAIT, MT_DATA);
632 		error = (*pr->pr_usrreq)(so, PRU_RCVOOB, m,
633 		    (struct mbuf *)(long)(flags & MSG_PEEK), NULL, curproc);
634 		if (error)
635 			goto bad;
636 		do {
637 			error = uiomove(mtod(m, caddr_t),
638 			    (int) min(uio->uio_resid, m->m_len), uio);
639 			m = m_free(m);
640 		} while (uio->uio_resid && error == 0 && m);
641 bad:
642 		if (m)
643 			m_freem(m);
644 		return (error);
645 	}
646 	if (mp)
647 		*mp = NULL;
648 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
649 		(*pr->pr_usrreq)(so, PRU_RCVD, NULL, NULL, NULL, curproc);
650 
651 restart:
652 	if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0)
653 		return (error);
654 	s = splsoftnet();
655 
656 	m = so->so_rcv.sb_mb;
657 #ifdef SOCKET_SPLICE
658 	if (so->so_splice)
659 		m = NULL;
660 #endif /* SOCKET_SPLICE */
661 	/*
662 	 * If we have less data than requested, block awaiting more
663 	 * (subject to any timeout) if:
664 	 *   1. the current count is less than the low water mark,
665 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
666 	 *	receive operation at once if we block (resid <= hiwat), or
667 	 *   3. MSG_DONTWAIT is not set.
668 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
669 	 * we have to do the receive in sections, and thus risk returning
670 	 * a short count if a timeout or signal occurs after we start.
671 	 */
672 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
673 	    so->so_rcv.sb_cc < uio->uio_resid) &&
674 	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
675 	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
676 	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
677 #ifdef DIAGNOSTIC
678 		if (m == NULL && so->so_rcv.sb_cc)
679 #ifdef SOCKET_SPLICE
680 		    if (so->so_splice == NULL)
681 #endif /* SOCKET_SPLICE */
682 			panic("receive 1");
683 #endif
684 		if (so->so_error) {
685 			if (m)
686 				goto dontblock;
687 			error = so->so_error;
688 			if ((flags & MSG_PEEK) == 0)
689 				so->so_error = 0;
690 			goto release;
691 		}
692 		if (so->so_state & SS_CANTRCVMORE) {
693 			if (m)
694 				goto dontblock;
695 			else if (so->so_rcv.sb_cc == 0)
696 				goto release;
697 		}
698 		for (; m; m = m->m_next)
699 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
700 				m = so->so_rcv.sb_mb;
701 				goto dontblock;
702 			}
703 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
704 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
705 			error = ENOTCONN;
706 			goto release;
707 		}
708 		if (uio->uio_resid == 0 && controlp == NULL)
709 			goto release;
710 		if ((so->so_state & SS_NBIO) || (flags & MSG_DONTWAIT)) {
711 			error = EWOULDBLOCK;
712 			goto release;
713 		}
714 		SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
715 		SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
716 		sbunlock(&so->so_rcv);
717 		error = sbwait(&so->so_rcv);
718 		splx(s);
719 		if (error)
720 			return (error);
721 		goto restart;
722 	}
723 dontblock:
724 	/*
725 	 * On entry here, m points to the first record of the socket buffer.
726 	 * From this point onward, we maintain 'nextrecord' as a cache of the
727 	 * pointer to the next record in the socket buffer.  We must keep the
728 	 * various socket buffer pointers and local stack versions of the
729 	 * pointers in sync, pushing out modifications before operations that
730 	 * may sleep, and re-reading them afterwards.
731 	 *
732 	 * Otherwise, we will race with the network stack appending new data
733 	 * or records onto the socket buffer by using inconsistent/stale
734 	 * versions of the field, possibly resulting in socket buffer
735 	 * corruption.
736 	 */
737 	if (uio->uio_procp)
738 		uio->uio_procp->p_ru.ru_msgrcv++;
739 	KASSERT(m == so->so_rcv.sb_mb);
740 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
741 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
742 	nextrecord = m->m_nextpkt;
743 	if (pr->pr_flags & PR_ADDR) {
744 #ifdef DIAGNOSTIC
745 		if (m->m_type != MT_SONAME)
746 			panic("receive 1a");
747 #endif
748 		orig_resid = 0;
749 		if (flags & MSG_PEEK) {
750 			if (paddr)
751 				*paddr = m_copy(m, 0, m->m_len);
752 			m = m->m_next;
753 		} else {
754 			sbfree(&so->so_rcv, m);
755 			if (paddr) {
756 				*paddr = m;
757 				so->so_rcv.sb_mb = m->m_next;
758 				m->m_next = 0;
759 				m = so->so_rcv.sb_mb;
760 			} else {
761 				MFREE(m, so->so_rcv.sb_mb);
762 				m = so->so_rcv.sb_mb;
763 			}
764 			sbsync(&so->so_rcv, nextrecord);
765 		}
766 	}
767 	while (m && m->m_type == MT_CONTROL && error == 0) {
768 		if (flags & MSG_PEEK) {
769 			if (controlp)
770 				*controlp = m_copy(m, 0, m->m_len);
771 			m = m->m_next;
772 		} else {
773 			sbfree(&so->so_rcv, m);
774 			so->so_rcv.sb_mb = m->m_next;
775 			m->m_next = 0;
776 			cm = m;
777 			m = so->so_rcv.sb_mb;
778 			sbsync(&so->so_rcv, nextrecord);
779 			if (controlp) {
780 				if (pr->pr_domain->dom_externalize &&
781 				    mtod(cm, struct cmsghdr *)->cmsg_type ==
782 				    SCM_RIGHTS)
783 				   error = (*pr->pr_domain->dom_externalize)(cm,
784 				       controllen);
785 				*controlp = cm;
786 			} else {
787 				/*
788 				 * Dispose of any SCM_RIGHTS message that went
789 				 * through the read path rather than recv.
790 				 */
791 				if (pr->pr_domain->dom_dispose &&
792 				    mtod(cm, struct cmsghdr *)->cmsg_type == SCM_RIGHTS)
793 					pr->pr_domain->dom_dispose(cm);
794 				m_free(cm);
795 			}
796 		}
797 		if (m != NULL)
798 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
799 		else
800 			nextrecord = so->so_rcv.sb_mb;
801 		if (controlp) {
802 			orig_resid = 0;
803 			controlp = &(*controlp)->m_next;
804 		}
805 	}
806 
807 	/* If m is non-NULL, we have some data to read. */
808 	if (m) {
809 		type = m->m_type;
810 		if (type == MT_OOBDATA)
811 			flags |= MSG_OOB;
812 		if (m->m_flags & M_BCAST)
813 			flags |= MSG_BCAST;
814 		if (m->m_flags & M_MCAST)
815 			flags |= MSG_MCAST;
816 	}
817 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
818 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
819 
820 	moff = 0;
821 	offset = 0;
822 	while (m && uio->uio_resid > 0 && error == 0) {
823 		if (m->m_type == MT_OOBDATA) {
824 			if (type != MT_OOBDATA)
825 				break;
826 		} else if (type == MT_OOBDATA)
827 			break;
828 #ifdef DIAGNOSTIC
829 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
830 			panic("receive 3");
831 #endif
832 		so->so_state &= ~SS_RCVATMARK;
833 		len = uio->uio_resid;
834 		if (so->so_oobmark && len > so->so_oobmark - offset)
835 			len = so->so_oobmark - offset;
836 		if (len > m->m_len - moff)
837 			len = m->m_len - moff;
838 		/*
839 		 * If mp is set, just pass back the mbufs.
840 		 * Otherwise copy them out via the uio, then free.
841 		 * Sockbuf must be consistent here (points to current mbuf,
842 		 * it points to next record) when we drop priority;
843 		 * we must note any additions to the sockbuf when we
844 		 * block interrupts again.
845 		 */
846 		if (mp == NULL && uio_error == 0) {
847 			SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
848 			SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
849 			resid = uio->uio_resid;
850 			splx(s);
851 			uio_error =
852 				uiomove(mtod(m, caddr_t) + moff, (int)len,
853 					uio);
854 			s = splsoftnet();
855 			if (uio_error)
856 				uio->uio_resid = resid - len;
857 		} else
858 			uio->uio_resid -= len;
859 		if (len == m->m_len - moff) {
860 			if (m->m_flags & M_EOR)
861 				flags |= MSG_EOR;
862 			if (flags & MSG_PEEK) {
863 				m = m->m_next;
864 				moff = 0;
865 			} else {
866 				nextrecord = m->m_nextpkt;
867 				sbfree(&so->so_rcv, m);
868 				if (mp) {
869 					*mp = m;
870 					mp = &m->m_next;
871 					so->so_rcv.sb_mb = m = m->m_next;
872 					*mp = NULL;
873 				} else {
874 					MFREE(m, so->so_rcv.sb_mb);
875 					m = so->so_rcv.sb_mb;
876 				}
877 				/*
878 				 * If m != NULL, we also know that
879 				 * so->so_rcv.sb_mb != NULL.
880 				 */
881 				KASSERT(so->so_rcv.sb_mb == m);
882 				if (m) {
883 					m->m_nextpkt = nextrecord;
884 					if (nextrecord == NULL)
885 						so->so_rcv.sb_lastrecord = m;
886 				} else {
887 					so->so_rcv.sb_mb = nextrecord;
888 					SB_EMPTY_FIXUP(&so->so_rcv);
889 				}
890 				SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
891 				SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
892 			}
893 		} else {
894 			if (flags & MSG_PEEK)
895 				moff += len;
896 			else {
897 				if (mp)
898 					*mp = m_copym(m, 0, len, M_WAIT);
899 				m->m_data += len;
900 				m->m_len -= len;
901 				so->so_rcv.sb_cc -= len;
902 				so->so_rcv.sb_datacc -= len;
903 			}
904 		}
905 		if (so->so_oobmark) {
906 			if ((flags & MSG_PEEK) == 0) {
907 				so->so_oobmark -= len;
908 				if (so->so_oobmark == 0) {
909 					so->so_state |= SS_RCVATMARK;
910 					break;
911 				}
912 			} else {
913 				offset += len;
914 				if (offset == so->so_oobmark)
915 					break;
916 			}
917 		}
918 		if (flags & MSG_EOR)
919 			break;
920 		/*
921 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
922 		 * we must not quit until "uio->uio_resid == 0" or an error
923 		 * termination.  If a signal/timeout occurs, return
924 		 * with a short count but without error.
925 		 * Keep sockbuf locked against other readers.
926 		 */
927 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
928 		    !sosendallatonce(so) && !nextrecord) {
929 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
930 				break;
931 			SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
932 			SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
933 			error = sbwait(&so->so_rcv);
934 			if (error) {
935 				sbunlock(&so->so_rcv);
936 				splx(s);
937 				return (0);
938 			}
939 			if ((m = so->so_rcv.sb_mb) != NULL)
940 				nextrecord = m->m_nextpkt;
941 		}
942 	}
943 
944 	if (m && pr->pr_flags & PR_ATOMIC) {
945 		flags |= MSG_TRUNC;
946 		if ((flags & MSG_PEEK) == 0)
947 			(void) sbdroprecord(&so->so_rcv);
948 	}
949 	if ((flags & MSG_PEEK) == 0) {
950 		if (m == NULL) {
951 			/*
952 			 * First part is an inline SB_EMPTY_FIXUP().  Second
953 			 * part makes sure sb_lastrecord is up-to-date if
954 			 * there is still data in the socket buffer.
955 			 */
956 			so->so_rcv.sb_mb = nextrecord;
957 			if (so->so_rcv.sb_mb == NULL) {
958 				so->so_rcv.sb_mbtail = NULL;
959 				so->so_rcv.sb_lastrecord = NULL;
960 			} else if (nextrecord->m_nextpkt == NULL)
961 				so->so_rcv.sb_lastrecord = nextrecord;
962 		}
963 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
964 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
965 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
966 			(*pr->pr_usrreq)(so, PRU_RCVD, NULL,
967 			    (struct mbuf *)(long)flags, NULL, curproc);
968 	}
969 	if (orig_resid == uio->uio_resid && orig_resid &&
970 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
971 		sbunlock(&so->so_rcv);
972 		splx(s);
973 		goto restart;
974 	}
975 
976 	if (uio_error)
977 		error = uio_error;
978 
979 	if (flagsp)
980 		*flagsp |= flags;
981 release:
982 	sbunlock(&so->so_rcv);
983 	splx(s);
984 	return (error);
985 }
986 
987 int
988 soshutdown(struct socket *so, int how)
989 {
990 	struct protosw *pr = so->so_proto;
991 
992 	switch (how) {
993 	case SHUT_RD:
994 	case SHUT_RDWR:
995 		sorflush(so);
996 		if (how == SHUT_RD)
997 			return (0);
998 		/* FALLTHROUGH */
999 	case SHUT_WR:
1000 		return (*pr->pr_usrreq)(so, PRU_SHUTDOWN, NULL, NULL, NULL,
1001 		    curproc);
1002 	default:
1003 		return (EINVAL);
1004 	}
1005 }
1006 
1007 void
1008 sorflush(struct socket *so)
1009 {
1010 	struct sockbuf *sb = &so->so_rcv;
1011 	struct protosw *pr = so->so_proto;
1012 	int s;
1013 	struct sockbuf asb;
1014 
1015 	sb->sb_flags |= SB_NOINTR;
1016 	(void) sblock(sb, M_WAITOK);
1017 	s = splnet();
1018 	socantrcvmore(so);
1019 	sbunlock(sb);
1020 	asb = *sb;
1021 	bzero(sb, sizeof (*sb));
1022 	/* XXX - the bzero stumps all over so_rcv */
1023 	if (asb.sb_flags & SB_KNOTE) {
1024 		sb->sb_sel.si_note = asb.sb_sel.si_note;
1025 		sb->sb_flags = SB_KNOTE;
1026 	}
1027 	splx(s);
1028 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1029 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1030 	sbrelease(&asb);
1031 }
1032 
1033 #ifdef SOCKET_SPLICE
1034 int
1035 sosplice(struct socket *so, int fd, off_t max, struct timeval *tv)
1036 {
1037 	struct file	*fp;
1038 	struct socket	*sosp;
1039 	int		 s, error = 0;
1040 
1041 	if ((so->so_proto->pr_flags & PR_SPLICE) == 0)
1042 		return (EPROTONOSUPPORT);
1043 	if (so->so_options & SO_ACCEPTCONN)
1044 		return (EOPNOTSUPP);
1045 	if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0)
1046 		return (ENOTCONN);
1047 
1048 	/* If no fd is given, unsplice by removing existing link. */
1049 	if (fd < 0) {
1050 		s = splsoftnet();
1051 		if (so->so_splice)
1052 			sounsplice(so, so->so_splice, 1);
1053 		splx(s);
1054 		return (0);
1055 	}
1056 
1057 	if (max && max < 0)
1058 		return (EINVAL);
1059 
1060 	if (tv && (tv->tv_sec < 0 || tv->tv_usec < 0))
1061 		return (EINVAL);
1062 
1063 	/* Find sosp, the drain socket where data will be spliced into. */
1064 	if ((error = getsock(curproc->p_fd, fd, &fp)) != 0)
1065 		return (error);
1066 	sosp = fp->f_data;
1067 
1068 	/* Lock both receive and send buffer. */
1069 	if ((error = sblock(&so->so_rcv,
1070 	    (so->so_state & SS_NBIO) ? M_NOWAIT : M_WAITOK)) != 0) {
1071 		FRELE(fp, curproc);
1072 		return (error);
1073 	}
1074 	if ((error = sblock(&sosp->so_snd, M_WAITOK)) != 0) {
1075 		sbunlock(&so->so_rcv);
1076 		FRELE(fp, curproc);
1077 		return (error);
1078 	}
1079 	s = splsoftnet();
1080 
1081 	if (so->so_splice || sosp->so_spliceback) {
1082 		error = EBUSY;
1083 		goto release;
1084 	}
1085 	if (sosp->so_proto->pr_usrreq != so->so_proto->pr_usrreq) {
1086 		error = EPROTONOSUPPORT;
1087 		goto release;
1088 	}
1089 	if (sosp->so_options & SO_ACCEPTCONN) {
1090 		error = EOPNOTSUPP;
1091 		goto release;
1092 	}
1093 	if ((sosp->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0) {
1094 		error = ENOTCONN;
1095 		goto release;
1096 	}
1097 
1098 	/* Splice so and sosp together. */
1099 	so->so_splice = sosp;
1100 	sosp->so_spliceback = so;
1101 	so->so_splicelen = 0;
1102 	so->so_splicemax = max;
1103 	if (tv)
1104 		so->so_idletv = *tv;
1105 	else
1106 		timerclear(&so->so_idletv);
1107 	timeout_set(&so->so_idleto, soidle, so);
1108 
1109 	/*
1110 	 * To prevent softnet interrupt from calling somove() while
1111 	 * we sleep, the socket buffers are not marked as spliced yet.
1112 	 */
1113 	if (somove(so, M_WAIT)) {
1114 		so->so_rcv.sb_flags |= SB_SPLICE;
1115 		sosp->so_snd.sb_flags |= SB_SPLICE;
1116 	}
1117 
1118  release:
1119 	splx(s);
1120 	sbunlock(&sosp->so_snd);
1121 	sbunlock(&so->so_rcv);
1122 	FRELE(fp, curproc);
1123 	return (error);
1124 }
1125 
1126 void
1127 sounsplice(struct socket *so, struct socket *sosp, int wakeup)
1128 {
1129 	splsoftassert(IPL_SOFTNET);
1130 
1131 	timeout_del(&so->so_idleto);
1132 	sosp->so_snd.sb_flags &= ~SB_SPLICE;
1133 	so->so_rcv.sb_flags &= ~SB_SPLICE;
1134 	so->so_splice = sosp->so_spliceback = NULL;
1135 	if (wakeup && soreadable(so))
1136 		sorwakeup(so);
1137 }
1138 
1139 /*
1140  * Move data from receive buffer of spliced source socket to send
1141  * buffer of drain socket.  Try to move as much as possible in one
1142  * big chunk.  It is a TCP only implementation.
1143  * Return value 0 means splicing has been finished, 1 continue.
1144  */
1145 int
1146 somove(struct socket *so, int wait)
1147 {
1148 	struct socket	*sosp = so->so_splice;
1149 	struct mbuf	*m = NULL, **mp;
1150 	u_long		 len, off, oobmark;
1151 	long		 space;
1152 	int		 error = 0, maxreached = 0;
1153 	short		 state;
1154 
1155 	splsoftassert(IPL_SOFTNET);
1156 
1157 	if (so->so_error) {
1158 		error = so->so_error;
1159 		goto release;
1160 	}
1161 	if (sosp->so_state & SS_CANTSENDMORE) {
1162 		error = EPIPE;
1163 		goto release;
1164 	}
1165 	if (sosp->so_error && sosp->so_error != ETIMEDOUT) {
1166 		error = sosp->so_error;
1167 		goto release;
1168 	}
1169 	if ((sosp->so_state & SS_ISCONNECTED) == 0)
1170 		goto release;
1171 
1172 	/* Calculate how many bytes can be copied now. */
1173 	len = so->so_rcv.sb_cc;
1174 	if (len == 0)
1175 		goto release;
1176 	if (so->so_splicemax) {
1177 		KASSERT(so->so_splicelen < so->so_splicemax);
1178 		if (so->so_splicemax <= so->so_splicelen + len) {
1179 			len = so->so_splicemax - so->so_splicelen;
1180 			maxreached = 1;
1181 		}
1182 	}
1183 	space = sbspace(&sosp->so_snd);
1184 	if (so->so_oobmark && so->so_oobmark < len &&
1185 	    so->so_oobmark < space + 1024)
1186 		space += 1024;
1187 	if (space <= 0) {
1188 		maxreached = 0;
1189 		goto release;
1190 	}
1191 	if (space < len) {
1192 		maxreached = 0;
1193 		if (space < sosp->so_snd.sb_lowat)
1194 			goto release;
1195 		len = space;
1196 	}
1197 	sosp->so_state |= SS_ISSENDING;
1198 
1199 	/* Take at most len mbufs out of receive buffer. */
1200 	m = so->so_rcv.sb_mb;
1201 	for (off = 0, mp = &m; off < len;
1202 	    off += (*mp)->m_len, mp = &(*mp)->m_next) {
1203 		u_long size = len - off;
1204 
1205 		if ((*mp)->m_len > size) {
1206 			if (!maxreached || (*mp = m_copym(
1207 			    so->so_rcv.sb_mb, 0, size, wait)) == NULL) {
1208 				len -= size;
1209 				break;
1210 			}
1211 			so->so_rcv.sb_mb->m_data += size;
1212 			so->so_rcv.sb_mb->m_len -= size;
1213 			so->so_rcv.sb_cc -= size;
1214 			so->so_rcv.sb_datacc -= size;
1215 		} else {
1216 			*mp = so->so_rcv.sb_mb;
1217 			sbfree(&so->so_rcv, *mp);
1218 			so->so_rcv.sb_mb = (*mp)->m_next;
1219 		}
1220 	}
1221 	*mp = NULL;
1222 	SB_EMPTY_FIXUP(&so->so_rcv);
1223 	so->so_rcv.sb_lastrecord = so->so_rcv.sb_mb;
1224 
1225 	SBLASTRECORDCHK(&so->so_rcv, "somove");
1226 	SBLASTMBUFCHK(&so->so_rcv, "somove");
1227 	KDASSERT(m->m_nextpkt == NULL);
1228 	KASSERT(so->so_rcv.sb_mb == so->so_rcv.sb_lastrecord);
1229 #ifdef SOCKBUF_DEBUG
1230 	sbcheck(&so->so_rcv);
1231 #endif
1232 
1233 	/* Send window update to source peer if receive buffer has changed. */
1234 	if (m)
1235 		(so->so_proto->pr_usrreq)(so, PRU_RCVD, NULL,
1236 		    (struct mbuf *)0L, NULL, NULL);
1237 
1238 	/* Receive buffer did shrink by len bytes, adjust oob. */
1239 	state = so->so_state;
1240 	so->so_state &= ~SS_RCVATMARK;
1241 	oobmark = so->so_oobmark;
1242 	so->so_oobmark = oobmark > len ? oobmark - len : 0;
1243 	if (oobmark) {
1244 		if (oobmark == len)
1245 			so->so_state |= SS_RCVATMARK;
1246 		if (oobmark >= len)
1247 			oobmark = 0;
1248 	}
1249 
1250 	/*
1251 	 * Handle oob data.  If any malloc fails, ignore error.
1252 	 * TCP urgent data is not very reliable anyway.
1253 	 */
1254 	while (m && ((state & SS_RCVATMARK) || oobmark) &&
1255 	    (so->so_options & SO_OOBINLINE)) {
1256 		struct mbuf *o = NULL;
1257 
1258 		if (state & SS_RCVATMARK) {
1259 			o = m_get(wait, MT_DATA);
1260 			state &= ~SS_RCVATMARK;
1261 		} else if (oobmark) {
1262 			o = m_split(m, oobmark, wait);
1263 			if (o) {
1264 				error = (*sosp->so_proto->pr_usrreq)(sosp,
1265 				    PRU_SEND, m, NULL, NULL, NULL);
1266 				m = NULL;
1267 				if (error) {
1268 					m_freem(o);
1269 					if (sosp->so_state & SS_CANTSENDMORE)
1270 						error = EPIPE;
1271 					goto release;
1272 				}
1273 				len -= oobmark;
1274 				so->so_splicelen += oobmark;
1275 				m = o;
1276 				o = m_get(wait, MT_DATA);
1277 			}
1278 			oobmark = 0;
1279 		}
1280 		if (o) {
1281 			o->m_len = 1;
1282 			*mtod(o, caddr_t) = *mtod(m, caddr_t);
1283 			error = (*sosp->so_proto->pr_usrreq)(sosp, PRU_SENDOOB,
1284 			    o, NULL, NULL, NULL);
1285 			if (error) {
1286 				if (sosp->so_state & SS_CANTSENDMORE)
1287 					error = EPIPE;
1288 				goto release;
1289 			}
1290 			len -= 1;
1291 			so->so_splicelen += 1;
1292 			if (oobmark) {
1293 				oobmark -= 1;
1294 				if (oobmark == 0)
1295 					state |= SS_RCVATMARK;
1296 			}
1297 			m_adj(m, 1);
1298 		}
1299 	}
1300 
1301 	/* Append all remaining data to drain socket. */
1302 	if (m) {
1303 		if (so->so_rcv.sb_cc == 0 || maxreached)
1304 			sosp->so_state &= ~SS_ISSENDING;
1305 		error = (*sosp->so_proto->pr_usrreq)(sosp, PRU_SEND, m, NULL,
1306 		    NULL, NULL);
1307 		m = NULL;
1308 		if (error) {
1309 			if (sosp->so_state & SS_CANTSENDMORE)
1310 				error = EPIPE;
1311 			goto release;
1312 		}
1313 		so->so_splicelen += len;
1314 	}
1315 
1316  release:
1317 	if (m)
1318 		m_freem(m);
1319 	sosp->so_state &= ~SS_ISSENDING;
1320 	if (error)
1321 		so->so_error = error;
1322 	if (((so->so_state & SS_CANTRCVMORE) && so->so_rcv.sb_cc == 0) ||
1323 	    (sosp->so_state & SS_CANTSENDMORE) || maxreached || error) {
1324 		sounsplice(so, sosp, 1);
1325 		return (0);
1326 	}
1327 	if (timerisset(&so->so_idletv))
1328 		timeout_add_tv(&so->so_idleto, &so->so_idletv);
1329 	return (1);
1330 }
1331 
1332 void
1333 sorwakeup(struct socket *so)
1334 {
1335 	if (so->so_rcv.sb_flags & SB_SPLICE) {
1336 		(void) somove(so, M_DONTWAIT);
1337 		return;
1338 	}
1339 	_sorwakeup(so);
1340 }
1341 
1342 void
1343 sowwakeup(struct socket *so)
1344 {
1345 	if (so->so_snd.sb_flags & SB_SPLICE)
1346 		(void) somove(so->so_spliceback, M_DONTWAIT);
1347 	_sowwakeup(so);
1348 }
1349 
1350 void
1351 soidle(void *arg)
1352 {
1353 	struct socket *so = arg;
1354 	int s;
1355 
1356 	s = splsoftnet();
1357 	so->so_error = ETIMEDOUT;
1358 	sounsplice(so, so->so_splice, 1);
1359 	splx(s);
1360 }
1361 #endif /* SOCKET_SPLICE */
1362 
1363 int
1364 sosetopt(struct socket *so, int level, int optname, struct mbuf *m0)
1365 {
1366 	int error = 0;
1367 	struct mbuf *m = m0;
1368 
1369 	if (level != SOL_SOCKET) {
1370 		if (so->so_proto && so->so_proto->pr_ctloutput)
1371 			return ((*so->so_proto->pr_ctloutput)
1372 				  (PRCO_SETOPT, so, level, optname, &m0));
1373 		error = ENOPROTOOPT;
1374 	} else {
1375 		switch (optname) {
1376 		case SO_BINDANY:
1377 			if ((error = suser(curproc, 0)) != 0)	/* XXX */
1378 				goto bad;
1379 			break;
1380 		}
1381 
1382 		switch (optname) {
1383 
1384 		case SO_LINGER:
1385 			if (m == NULL || m->m_len != sizeof (struct linger) ||
1386 			    mtod(m, struct linger *)->l_linger < 0 ||
1387 			    mtod(m, struct linger *)->l_linger > SHRT_MAX) {
1388 				error = EINVAL;
1389 				goto bad;
1390 			}
1391 			so->so_linger = mtod(m, struct linger *)->l_linger;
1392 			/* FALLTHROUGH */
1393 
1394 		case SO_BINDANY:
1395 		case SO_DEBUG:
1396 		case SO_KEEPALIVE:
1397 		case SO_DONTROUTE:
1398 		case SO_USELOOPBACK:
1399 		case SO_BROADCAST:
1400 		case SO_REUSEADDR:
1401 		case SO_REUSEPORT:
1402 		case SO_OOBINLINE:
1403 		case SO_TIMESTAMP:
1404 			if (m == NULL || m->m_len < sizeof (int)) {
1405 				error = EINVAL;
1406 				goto bad;
1407 			}
1408 			if (*mtod(m, int *))
1409 				so->so_options |= optname;
1410 			else
1411 				so->so_options &= ~optname;
1412 			break;
1413 
1414 		case SO_SNDBUF:
1415 		case SO_RCVBUF:
1416 		case SO_SNDLOWAT:
1417 		case SO_RCVLOWAT:
1418 		    {
1419 			u_long cnt;
1420 
1421 			if (m == NULL || m->m_len < sizeof (int)) {
1422 				error = EINVAL;
1423 				goto bad;
1424 			}
1425 			cnt = *mtod(m, int *);
1426 			if ((long)cnt <= 0)
1427 				cnt = 1;
1428 			switch (optname) {
1429 
1430 			case SO_SNDBUF:
1431 				if (so->so_state & SS_CANTSENDMORE) {
1432 					error = EINVAL;
1433 					goto bad;
1434 				}
1435 				if (sbcheckreserve(cnt, so->so_snd.sb_wat) ||
1436 				    sbreserve(&so->so_snd, cnt)) {
1437 					error = ENOBUFS;
1438 					goto bad;
1439 				}
1440 				so->so_snd.sb_wat = cnt;
1441 				break;
1442 
1443 			case SO_RCVBUF:
1444 				if (so->so_state & SS_CANTRCVMORE) {
1445 					error = EINVAL;
1446 					goto bad;
1447 				}
1448 				if (sbcheckreserve(cnt, so->so_rcv.sb_wat) ||
1449 				    sbreserve(&so->so_rcv, cnt)) {
1450 					error = ENOBUFS;
1451 					goto bad;
1452 				}
1453 				so->so_rcv.sb_wat = cnt;
1454 				break;
1455 
1456 			case SO_SNDLOWAT:
1457 				so->so_snd.sb_lowat =
1458 				    (cnt > so->so_snd.sb_hiwat) ?
1459 				    so->so_snd.sb_hiwat : cnt;
1460 				break;
1461 			case SO_RCVLOWAT:
1462 				so->so_rcv.sb_lowat =
1463 				    (cnt > so->so_rcv.sb_hiwat) ?
1464 				    so->so_rcv.sb_hiwat : cnt;
1465 				break;
1466 			}
1467 			break;
1468 		    }
1469 
1470 		case SO_SNDTIMEO:
1471 		case SO_RCVTIMEO:
1472 		    {
1473 			struct timeval *tv;
1474 			u_short val;
1475 
1476 			if (m == NULL || m->m_len < sizeof (*tv)) {
1477 				error = EINVAL;
1478 				goto bad;
1479 			}
1480 			tv = mtod(m, struct timeval *);
1481 			if (tv->tv_sec > (USHRT_MAX - tv->tv_usec / tick) / hz) {
1482 				error = EDOM;
1483 				goto bad;
1484 			}
1485 			val = tv->tv_sec * hz + tv->tv_usec / tick;
1486 			if (val == 0 && tv->tv_usec != 0)
1487 				val = 1;
1488 
1489 			switch (optname) {
1490 
1491 			case SO_SNDTIMEO:
1492 				so->so_snd.sb_timeo = val;
1493 				break;
1494 			case SO_RCVTIMEO:
1495 				so->so_rcv.sb_timeo = val;
1496 				break;
1497 			}
1498 			break;
1499 		    }
1500 
1501 		case SO_RTABLE:
1502 			if (so->so_proto && so->so_proto->pr_domain &&
1503 			    so->so_proto->pr_domain->dom_protosw &&
1504 			    so->so_proto->pr_ctloutput) {
1505 				struct domain *dom = so->so_proto->pr_domain;
1506 
1507 				level = dom->dom_protosw->pr_protocol;
1508 				return ((*so->so_proto->pr_ctloutput)
1509 				    (PRCO_SETOPT, so, level, optname, &m0));
1510 			}
1511 			error = ENOPROTOOPT;
1512 			break;
1513 
1514 #ifdef SOCKET_SPLICE
1515 		case SO_SPLICE:
1516 			if (m == NULL) {
1517 				error = sosplice(so, -1, 0, NULL);
1518 			} else if (m->m_len < sizeof(int)) {
1519 				error = EINVAL;
1520 				goto bad;
1521 			} else if (m->m_len < sizeof(struct splice)) {
1522 				error = sosplice(so, *mtod(m, int *), 0, NULL);
1523 			} else {
1524 				error = sosplice(so,
1525 				    mtod(m, struct splice *)->sp_fd,
1526 				    mtod(m, struct splice *)->sp_max,
1527 				   &mtod(m, struct splice *)->sp_idle);
1528 			}
1529 			break;
1530 #endif /* SOCKET_SPLICE */
1531 
1532 		default:
1533 			error = ENOPROTOOPT;
1534 			break;
1535 		}
1536 		if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1537 			(void) ((*so->so_proto->pr_ctloutput)
1538 				  (PRCO_SETOPT, so, level, optname, &m0));
1539 			m = NULL;	/* freed by protocol */
1540 		}
1541 	}
1542 bad:
1543 	if (m)
1544 		(void) m_free(m);
1545 	return (error);
1546 }
1547 
1548 int
1549 sogetopt(struct socket *so, int level, int optname, struct mbuf **mp)
1550 {
1551 	struct mbuf *m;
1552 
1553 	if (level != SOL_SOCKET) {
1554 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1555 			return ((*so->so_proto->pr_ctloutput)
1556 				  (PRCO_GETOPT, so, level, optname, mp));
1557 		} else
1558 			return (ENOPROTOOPT);
1559 	} else {
1560 		m = m_get(M_WAIT, MT_SOOPTS);
1561 		m->m_len = sizeof (int);
1562 
1563 		switch (optname) {
1564 
1565 		case SO_LINGER:
1566 			m->m_len = sizeof (struct linger);
1567 			mtod(m, struct linger *)->l_onoff =
1568 				so->so_options & SO_LINGER;
1569 			mtod(m, struct linger *)->l_linger = so->so_linger;
1570 			break;
1571 
1572 		case SO_BINDANY:
1573 		case SO_USELOOPBACK:
1574 		case SO_DONTROUTE:
1575 		case SO_DEBUG:
1576 		case SO_KEEPALIVE:
1577 		case SO_REUSEADDR:
1578 		case SO_REUSEPORT:
1579 		case SO_BROADCAST:
1580 		case SO_OOBINLINE:
1581 		case SO_TIMESTAMP:
1582 			*mtod(m, int *) = so->so_options & optname;
1583 			break;
1584 
1585 		case SO_TYPE:
1586 			*mtod(m, int *) = so->so_type;
1587 			break;
1588 
1589 		case SO_ERROR:
1590 			*mtod(m, int *) = so->so_error;
1591 			so->so_error = 0;
1592 			break;
1593 
1594 		case SO_SNDBUF:
1595 			*mtod(m, int *) = so->so_snd.sb_hiwat;
1596 			break;
1597 
1598 		case SO_RCVBUF:
1599 			*mtod(m, int *) = so->so_rcv.sb_hiwat;
1600 			break;
1601 
1602 		case SO_SNDLOWAT:
1603 			*mtod(m, int *) = so->so_snd.sb_lowat;
1604 			break;
1605 
1606 		case SO_RCVLOWAT:
1607 			*mtod(m, int *) = so->so_rcv.sb_lowat;
1608 			break;
1609 
1610 		case SO_SNDTIMEO:
1611 		case SO_RCVTIMEO:
1612 		    {
1613 			int val = (optname == SO_SNDTIMEO ?
1614 			    so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1615 
1616 			m->m_len = sizeof(struct timeval);
1617 			mtod(m, struct timeval *)->tv_sec = val / hz;
1618 			mtod(m, struct timeval *)->tv_usec =
1619 			    (val % hz) * tick;
1620 			break;
1621 		    }
1622 
1623 		case SO_RTABLE:
1624 			(void)m_free(m);
1625 			if (so->so_proto && so->so_proto->pr_domain &&
1626 			    so->so_proto->pr_domain->dom_protosw &&
1627 			    so->so_proto->pr_ctloutput) {
1628 				struct domain *dom = so->so_proto->pr_domain;
1629 
1630 				level = dom->dom_protosw->pr_protocol;
1631 				return ((*so->so_proto->pr_ctloutput)
1632 				    (PRCO_GETOPT, so, level, optname, mp));
1633 			}
1634 			return (ENOPROTOOPT);
1635 			break;
1636 
1637 #ifdef SOCKET_SPLICE
1638 		case SO_SPLICE:
1639 		    {
1640 			int s = splsoftnet();
1641 
1642 			m->m_len = sizeof(off_t);
1643 			*mtod(m, off_t *) = so->so_splicelen;
1644 			splx(s);
1645 			break;
1646 		    }
1647 #endif /* SOCKET_SPLICE */
1648 
1649 		case SO_PEERCRED:
1650 			if (so->so_proto->pr_protocol == AF_UNIX) {
1651 				struct unpcb *unp = sotounpcb(so);
1652 
1653 				if (unp->unp_flags & UNP_FEIDS) {
1654 					m->m_len = sizeof(unp->unp_connid);
1655 					bcopy((caddr_t)(&(unp->unp_connid)),
1656 					    mtod(m, caddr_t),
1657 					    m->m_len);
1658 					break;
1659 				}
1660 				(void)m_free(m);
1661 				return (ENOTCONN);
1662 			}
1663 			(void)m_free(m);
1664 			return (EOPNOTSUPP);
1665 			break;
1666 
1667 		default:
1668 			(void)m_free(m);
1669 			return (ENOPROTOOPT);
1670 		}
1671 		*mp = m;
1672 		return (0);
1673 	}
1674 }
1675 
1676 void
1677 sohasoutofband(struct socket *so)
1678 {
1679 	csignal(so->so_pgid, SIGURG, so->so_siguid, so->so_sigeuid);
1680 	selwakeup(&so->so_rcv.sb_sel);
1681 }
1682 
1683 int
1684 soo_kqfilter(struct file *fp, struct knote *kn)
1685 {
1686 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1687 	struct sockbuf *sb;
1688 	int s;
1689 
1690 	switch (kn->kn_filter) {
1691 	case EVFILT_READ:
1692 		if (so->so_options & SO_ACCEPTCONN)
1693 			kn->kn_fop = &solisten_filtops;
1694 		else
1695 			kn->kn_fop = &soread_filtops;
1696 		sb = &so->so_rcv;
1697 		break;
1698 	case EVFILT_WRITE:
1699 		kn->kn_fop = &sowrite_filtops;
1700 		sb = &so->so_snd;
1701 		break;
1702 	default:
1703 		return (EINVAL);
1704 	}
1705 
1706 	s = splnet();
1707 	SLIST_INSERT_HEAD(&sb->sb_sel.si_note, kn, kn_selnext);
1708 	sb->sb_flags |= SB_KNOTE;
1709 	splx(s);
1710 	return (0);
1711 }
1712 
1713 void
1714 filt_sordetach(struct knote *kn)
1715 {
1716 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1717 	int s = splnet();
1718 
1719 	SLIST_REMOVE(&so->so_rcv.sb_sel.si_note, kn, knote, kn_selnext);
1720 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.si_note))
1721 		so->so_rcv.sb_flags &= ~SB_KNOTE;
1722 	splx(s);
1723 }
1724 
1725 /*ARGSUSED*/
1726 int
1727 filt_soread(struct knote *kn, long hint)
1728 {
1729 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1730 
1731 	kn->kn_data = so->so_rcv.sb_cc;
1732 #ifdef SOCKET_SPLICE
1733 	if (so->so_splice)
1734 		return (0);
1735 #endif /* SOCKET_SPLICE */
1736 	if (so->so_state & SS_CANTRCVMORE) {
1737 		kn->kn_flags |= EV_EOF;
1738 		kn->kn_fflags = so->so_error;
1739 		return (1);
1740 	}
1741 	if (so->so_error)	/* temporary udp error */
1742 		return (1);
1743 	if (kn->kn_sfflags & NOTE_LOWAT)
1744 		return (kn->kn_data >= kn->kn_sdata);
1745 	return (kn->kn_data >= so->so_rcv.sb_lowat);
1746 }
1747 
1748 void
1749 filt_sowdetach(struct knote *kn)
1750 {
1751 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1752 	int s = splnet();
1753 
1754 	SLIST_REMOVE(&so->so_snd.sb_sel.si_note, kn, knote, kn_selnext);
1755 	if (SLIST_EMPTY(&so->so_snd.sb_sel.si_note))
1756 		so->so_snd.sb_flags &= ~SB_KNOTE;
1757 	splx(s);
1758 }
1759 
1760 /*ARGSUSED*/
1761 int
1762 filt_sowrite(struct knote *kn, long hint)
1763 {
1764 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1765 
1766 	kn->kn_data = sbspace(&so->so_snd);
1767 	if (so->so_state & SS_CANTSENDMORE) {
1768 		kn->kn_flags |= EV_EOF;
1769 		kn->kn_fflags = so->so_error;
1770 		return (1);
1771 	}
1772 	if (so->so_error)	/* temporary udp error */
1773 		return (1);
1774 	if (((so->so_state & SS_ISCONNECTED) == 0) &&
1775 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
1776 		return (0);
1777 	if (kn->kn_sfflags & NOTE_LOWAT)
1778 		return (kn->kn_data >= kn->kn_sdata);
1779 	return (kn->kn_data >= so->so_snd.sb_lowat);
1780 }
1781 
1782 /*ARGSUSED*/
1783 int
1784 filt_solisten(struct knote *kn, long hint)
1785 {
1786 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1787 
1788 	kn->kn_data = so->so_qlen;
1789 	return (so->so_qlen != 0);
1790 }
1791