2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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 DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
63 * $FreeBSD: src/sys/kern/uipc_socket.c,v 1.68.2.24 2003/11/11 17:18:18 silby Exp $
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/fcntl.h>
72 #include <sys/malloc.h>
74 #include <sys/domain.h>
75 #include <sys/file.h> /* for struct knote */
76 #include <sys/kernel.h>
77 #include <sys/event.h>
79 #include <sys/protosw.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/socketops.h>
83 #include <sys/resourcevar.h>
84 #include <sys/signalvar.h>
85 #include <sys/sysctl.h>
88 #include <vm/vm_zone.h>
90 #include <net/netmsg2.h>
91 #include <net/netisr2.h>
93 #include <sys/thread2.h>
94 #include <sys/socketvar2.h>
95 #include <sys/spinlock2.h>
97 #include <machine/limits.h>
100 extern int tcp_sosend_agglim;
101 extern int tcp_sosend_async;
102 extern int tcp_sosend_jcluster;
103 extern int udp_sosend_async;
104 extern int udp_sosend_prepend;
106 static int do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
109 static void filt_sordetach(struct knote *kn);
110 static int filt_soread(struct knote *kn, long hint);
111 static void filt_sowdetach(struct knote *kn);
112 static int filt_sowrite(struct knote *kn, long hint);
113 static int filt_solisten(struct knote *kn, long hint);
115 static void sodiscard(struct socket *so);
116 static int soclose_sync(struct socket *so, int fflag);
117 static void soclose_fast(struct socket *so);
119 static struct filterops solisten_filtops =
120 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_solisten };
121 static struct filterops soread_filtops =
122 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_soread };
123 static struct filterops sowrite_filtops =
124 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sowdetach, filt_sowrite };
125 static struct filterops soexcept_filtops =
126 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_soread };
128 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
129 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
130 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
133 static int somaxconn = SOMAXCONN;
134 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
135 &somaxconn, 0, "Maximum pending socket connection queue size");
137 static int use_soclose_fast = 1;
138 SYSCTL_INT(_kern_ipc, OID_AUTO, soclose_fast, CTLFLAG_RW,
139 &use_soclose_fast, 0, "Fast socket close");
141 int use_soaccept_pred_fast = 1;
142 SYSCTL_INT(_kern_ipc, OID_AUTO, soaccept_pred_fast, CTLFLAG_RW,
143 &use_soaccept_pred_fast, 0, "Fast socket accept predication");
145 int use_sendfile_async = 1;
146 SYSCTL_INT(_kern_ipc, OID_AUTO, sendfile_async, CTLFLAG_RW,
147 &use_sendfile_async, 0, "sendfile uses asynchronized pru_send");
149 int use_soconnect_async = 1;
150 SYSCTL_INT(_kern_ipc, OID_AUTO, soconnect_async, CTLFLAG_RW,
151 &use_soconnect_async, 0, "soconnect uses asynchronized pru_connect");
153 int use_rand_initport = 1;
154 SYSCTL_INT(_kern_ipc, OID_AUTO, rand_initport, CTLFLAG_RW,
155 &use_rand_initport, 0, "socket uses random initial msgport");
158 * Socket operation routines.
159 * These routines are called by the routines in
160 * sys_socket.c or from a system process, and
161 * implement the semantics of socket operations by
162 * switching out to the protocol specific routines.
166 * Get a socket structure, and initialize it.
167 * Note that it would probably be better to allocate socket
168 * and PCB at the same time, but I'm not convinced that all
169 * the protocols can be easily modified to do this.
172 soalloc(int waitok, struct protosw *pr)
177 waitmask = waitok ? M_WAITOK : M_NOWAIT;
178 so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
180 /* XXX race condition for reentrant kernel */
182 TAILQ_INIT(&so->so_aiojobq);
183 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
184 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
185 lwkt_token_init(&so->so_rcv.ssb_token, "rcvtok");
186 lwkt_token_init(&so->so_snd.ssb_token, "sndtok");
187 spin_init(&so->so_rcvd_spin);
188 netmsg_init(&so->so_rcvd_msg.base, so, &netisr_adone_rport,
189 MSGF_DROPABLE | MSGF_PRIORITY,
190 so->so_proto->pr_usrreqs->pru_rcvd);
191 so->so_rcvd_msg.nm_pru_flags |= PRUR_ASYNC;
192 so->so_state = SS_NOFDREF;
199 socreate(int dom, struct socket **aso, int type,
200 int proto, struct thread *td)
202 struct proc *p = td->td_proc;
205 struct pru_attach_info ai;
209 prp = pffindproto(dom, proto, type);
211 prp = pffindtype(dom, type);
213 if (prp == NULL || prp->pr_usrreqs->pru_attach == 0)
214 return (EPROTONOSUPPORT);
216 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
217 prp->pr_domain->dom_family != PF_LOCAL &&
218 prp->pr_domain->dom_family != PF_INET &&
219 prp->pr_domain->dom_family != PF_INET6 &&
220 prp->pr_domain->dom_family != PF_ROUTE) {
221 return (EPROTONOSUPPORT);
224 if (prp->pr_type != type)
226 so = soalloc(p != NULL, prp);
231 * Callers of socreate() presumably will connect up a descriptor
232 * and call soclose() if they cannot. This represents our so_refs
233 * (which should be 1) from soalloc().
235 soclrstate(so, SS_NOFDREF);
238 * Set a default port for protocol processing. No action will occur
239 * on the socket on this port until an inpcb is attached to it and
240 * is able to match incoming packets, or until the socket becomes
241 * available to userland.
243 * We normally default the socket to the protocol thread on cpu 0.
244 * If PR_SYNC_PORT is set (unix domain sockets) there is no protocol
245 * thread and all pr_*()/pru_*() calls are executed synchronously.
247 if (prp->pr_flags & PR_SYNC_PORT) {
248 so->so_port = &netisr_sync_port;
249 } else if (prp->pr_flags & PR_RAND_INITPORT) {
250 if (use_rand_initport)
251 so->so_port = netisr_cpuport(mycpuid & ncpus2_mask);
253 so->so_port = netisr_cpuport(0);
255 so->so_port = netisr_cpuport(0);
258 TAILQ_INIT(&so->so_incomp);
259 TAILQ_INIT(&so->so_comp);
261 so->so_cred = crhold(p->p_ucred);
262 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
263 ai.p_ucred = p->p_ucred;
264 ai.fd_rdir = p->p_fd->fd_rdir;
267 * Auto-sizing of socket buffers is managed by the protocols and
268 * the appropriate flags must be set in the pru_attach function.
270 error = so_pru_attach(so, proto, &ai);
272 sosetstate(so, SS_NOFDREF);
273 sofree(so); /* from soalloc */
278 * NOTE: Returns referenced socket.
285 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
289 error = so_pru_bind(so, nam, td);
294 sodealloc(struct socket *so)
296 if (so->so_rcv.ssb_hiwat)
297 (void)chgsbsize(so->so_cred->cr_uidinfo,
298 &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
299 if (so->so_snd.ssb_hiwat)
300 (void)chgsbsize(so->so_cred->cr_uidinfo,
301 &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
303 /* remove accept filter if present */
304 if (so->so_accf != NULL)
305 do_setopt_accept_filter(so, NULL);
308 if (so->so_faddr != NULL)
309 kfree(so->so_faddr, M_SONAME);
314 solisten(struct socket *so, int backlog, struct thread *td)
318 short oldopt, oldqlimit;
321 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))
325 oldopt = so->so_options;
326 oldqlimit = so->so_qlimit;
329 lwkt_gettoken(&so->so_rcv.ssb_token);
330 if (TAILQ_EMPTY(&so->so_comp))
331 so->so_options |= SO_ACCEPTCONN;
332 lwkt_reltoken(&so->so_rcv.ssb_token);
333 if (backlog < 0 || backlog > somaxconn)
335 so->so_qlimit = backlog;
336 /* SCTP needs to look at tweak both the inbound backlog parameter AND
337 * the so_options (UDP model both connect's and gets inbound
338 * connections .. implicitly).
340 error = so_pru_listen(so, td);
343 /* Restore the params */
344 so->so_options = oldopt;
345 so->so_qlimit = oldqlimit;
353 * Destroy a disconnected socket. This routine is a NOP if entities
354 * still have a reference on the socket:
356 * so_pcb - The protocol stack still has a reference
357 * SS_NOFDREF - There is no longer a file pointer reference
360 sofree(struct socket *so)
365 * This is a bit hackish at the moment. We need to interlock
366 * any accept queue we are on before we potentially lose the
367 * last reference to avoid races against a re-reference from
368 * someone operating on the queue.
370 while ((head = so->so_head) != NULL) {
371 lwkt_getpooltoken(head);
372 if (so->so_head == head)
374 lwkt_relpooltoken(head);
378 * Arbitrage the last free.
380 KKASSERT(so->so_refs > 0);
381 if (atomic_fetchadd_int(&so->so_refs, -1) != 1) {
383 lwkt_relpooltoken(head);
387 KKASSERT(so->so_pcb == NULL && (so->so_state & SS_NOFDREF));
388 KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
391 * We're done, remove ourselves from the accept queue we are
392 * on, if we are on one.
395 if (so->so_state & SS_INCOMP) {
396 TAILQ_REMOVE(&head->so_incomp, so, so_list);
398 } else if (so->so_state & SS_COMP) {
400 * We must not decommission a socket that's
401 * on the accept(2) queue. If we do, then
402 * accept(2) may hang after select(2) indicated
403 * that the listening socket was ready.
405 lwkt_relpooltoken(head);
408 panic("sofree: not queued");
410 soclrstate(so, SS_INCOMP);
412 lwkt_relpooltoken(head);
414 ssb_release(&so->so_snd, so);
420 * Close a socket on last file table reference removal.
421 * Initiate disconnect if connected.
422 * Free socket when disconnect complete.
425 soclose(struct socket *so, int fflag)
429 funsetown(&so->so_sigio);
430 if (!use_soclose_fast ||
431 (so->so_proto->pr_flags & PR_SYNC_PORT) ||
432 ((so->so_state & SS_ISCONNECTED) &&
433 (so->so_options & SO_LINGER))) {
434 error = soclose_sync(so, fflag);
443 sodiscard(struct socket *so)
445 lwkt_getpooltoken(so);
446 if (so->so_options & SO_ACCEPTCONN) {
449 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
450 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
451 soclrstate(sp, SS_INCOMP);
456 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
457 TAILQ_REMOVE(&so->so_comp, sp, so_list);
458 soclrstate(sp, SS_COMP);
464 lwkt_relpooltoken(so);
466 if (so->so_state & SS_NOFDREF)
467 panic("soclose: NOFDREF");
468 sosetstate(so, SS_NOFDREF); /* take ref */
472 soinherit(struct socket *so, struct socket *so_inh)
474 TAILQ_HEAD(, socket) comp, incomp;
478 KASSERT(so->so_options & SO_ACCEPTCONN,
479 ("so does not accept connection"));
480 KASSERT(so_inh->so_options & SO_ACCEPTCONN,
481 ("so_inh does not accept connection"));
486 lwkt_getpooltoken(so);
487 lwkt_getpooltoken(so_inh);
490 * Save completed queue and incompleted queue
492 TAILQ_CONCAT(&comp, &so->so_comp, so_list);
496 TAILQ_CONCAT(&incomp, &so->so_incomp, so_list);
497 incqlen = so->so_incqlen;
501 * Append the saved completed queue and incompleted
502 * queue to the socket inherits them.
505 * This may temporarily break the inheriting socket's
508 TAILQ_FOREACH(sp, &comp, so_list) {
509 sp->so_head = so_inh;
511 sp->so_cred = crhold(so_inh->so_cred);
514 TAILQ_FOREACH(sp, &incomp, so_list) {
515 sp->so_head = so_inh;
517 sp->so_cred = crhold(so_inh->so_cred);
520 TAILQ_CONCAT(&so_inh->so_comp, &comp, so_list);
521 so_inh->so_qlen += qlen;
523 TAILQ_CONCAT(&so_inh->so_incomp, &incomp, so_list);
524 so_inh->so_incqlen += incqlen;
526 lwkt_relpooltoken(so_inh);
527 lwkt_relpooltoken(so);
531 * "New" connections have arrived
534 wakeup(&so_inh->so_timeo);
539 soclose_sync(struct socket *so, int fflag)
543 if (so->so_pcb == NULL)
545 if (so->so_state & SS_ISCONNECTED) {
546 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
547 error = sodisconnect(so);
551 if (so->so_options & SO_LINGER) {
552 if ((so->so_state & SS_ISDISCONNECTING) &&
555 while (so->so_state & SS_ISCONNECTED) {
556 error = tsleep(&so->so_timeo, PCATCH,
557 "soclos", so->so_linger * hz);
567 error2 = so_pru_detach(so);
573 so_pru_sync(so); /* unpend async sending */
574 sofree(so); /* dispose of ref */
580 soclose_sofree_async_handler(netmsg_t msg)
582 sofree(msg->base.nm_so);
586 soclose_sofree_async(struct socket *so)
588 struct netmsg_base *base = &so->so_clomsg;
590 netmsg_init(base, so, &netisr_apanic_rport, 0,
591 soclose_sofree_async_handler);
592 lwkt_sendmsg(so->so_port, &base->lmsg);
596 soclose_disconn_async_handler(netmsg_t msg)
598 struct socket *so = msg->base.nm_so;
600 if ((so->so_state & SS_ISCONNECTED) &&
601 (so->so_state & SS_ISDISCONNECTING) == 0)
602 so_pru_disconnect_direct(so);
605 so_pru_detach_direct(so);
612 soclose_disconn_async(struct socket *so)
614 struct netmsg_base *base = &so->so_clomsg;
616 netmsg_init(base, so, &netisr_apanic_rport, 0,
617 soclose_disconn_async_handler);
618 lwkt_sendmsg(so->so_port, &base->lmsg);
622 soclose_detach_async_handler(netmsg_t msg)
624 struct socket *so = msg->base.nm_so;
627 so_pru_detach_direct(so);
634 soclose_detach_async(struct socket *so)
636 struct netmsg_base *base = &so->so_clomsg;
638 netmsg_init(base, so, &netisr_apanic_rport, 0,
639 soclose_detach_async_handler);
640 lwkt_sendmsg(so->so_port, &base->lmsg);
644 soclose_fast(struct socket *so)
646 if (so->so_pcb == NULL)
649 if ((so->so_state & SS_ISCONNECTED) &&
650 (so->so_state & SS_ISDISCONNECTING) == 0) {
651 soclose_disconn_async(so);
656 soclose_detach_async(so);
662 soclose_sofree_async(so);
666 * Abort and destroy a socket. Only one abort can be in progress
667 * at any given moment.
670 soabort(struct socket *so)
677 soaborta(struct socket *so)
684 soabort_oncpu(struct socket *so)
687 so_pru_abort_oncpu(so);
691 * so is passed in ref'd, which becomes owned by
692 * the cleared SS_NOFDREF flag.
695 soaccept_generic(struct socket *so)
697 if ((so->so_state & SS_NOFDREF) == 0)
698 panic("soaccept: !NOFDREF");
699 soclrstate(so, SS_NOFDREF); /* owned by lack of SS_NOFDREF */
703 soaccept(struct socket *so, struct sockaddr **nam)
707 soaccept_generic(so);
708 error = so_pru_accept(so, nam);
713 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td,
718 if (so->so_options & SO_ACCEPTCONN)
721 * If protocol is connection-based, can only connect once.
722 * Otherwise, if connected, try to disconnect first.
723 * This allows user to disconnect by connecting to, e.g.,
726 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
727 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
728 (error = sodisconnect(so)))) {
732 * Prevent accumulated error from previous connection
736 if (!sync && so->so_proto->pr_usrreqs->pru_preconnect)
737 error = so_pru_connect_async(so, nam, td);
739 error = so_pru_connect(so, nam, td);
745 soconnect2(struct socket *so1, struct socket *so2)
749 error = so_pru_connect2(so1, so2);
754 sodisconnect(struct socket *so)
758 if ((so->so_state & SS_ISCONNECTED) == 0) {
762 if (so->so_state & SS_ISDISCONNECTING) {
766 error = so_pru_disconnect(so);
771 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
774 * If send must go all at once and message is larger than
775 * send buffering, then hard error.
776 * Lock against other senders.
777 * If must go all at once and not enough room now, then
778 * inform user that this would block and do nothing.
779 * Otherwise, if nonblocking, send as much as possible.
780 * The data to be sent is described by "uio" if nonzero,
781 * otherwise by the mbuf chain "top" (which must be null
782 * if uio is not). Data provided in mbuf chain must be small
783 * enough to send all at once.
785 * Returns nonzero on error, timeout or signal; callers
786 * must check for short counts if EINTR/ERESTART are returned.
787 * Data and control buffers are freed on return.
790 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
791 struct mbuf *top, struct mbuf *control, int flags,
798 int clen = 0, error, dontroute, mlen;
799 int atomic = sosendallatonce(so) || top;
803 resid = uio->uio_resid;
805 resid = (size_t)top->m_pkthdr.len;
808 for (m = top; m; m = m->m_next)
810 KKASSERT(top->m_pkthdr.len == len);
815 * WARNING! resid is unsigned, space and len are signed. space
816 * can wind up negative if the sockbuf is overcommitted.
818 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
819 * type sockets since that's an error.
821 if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
827 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
828 (so->so_proto->pr_flags & PR_ATOMIC);
829 if (td->td_lwp != NULL)
830 td->td_lwp->lwp_ru.ru_msgsnd++;
832 clen = control->m_len;
833 #define gotoerr(errcode) { error = errcode; goto release; }
836 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
841 if (so->so_state & SS_CANTSENDMORE)
844 error = so->so_error;
848 if ((so->so_state & SS_ISCONNECTED) == 0) {
850 * `sendto' and `sendmsg' is allowed on a connection-
851 * based socket if it supports implied connect.
852 * Return ENOTCONN if not connected and no address is
855 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
856 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
857 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
858 !(resid == 0 && clen != 0))
860 } else if (addr == NULL)
861 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
862 ENOTCONN : EDESTADDRREQ);
864 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
865 clen > so->so_snd.ssb_hiwat) {
868 space = ssb_space(&so->so_snd);
871 if ((space < 0 || (size_t)space < resid + clen) && uio &&
872 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
873 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
874 gotoerr(EWOULDBLOCK);
875 ssb_unlock(&so->so_snd);
876 error = ssb_wait(&so->so_snd);
886 * Data is prepackaged in "top".
890 top->m_flags |= M_EOR;
894 m = m_getl((int)resid, MB_WAIT, MT_DATA,
895 top == NULL ? M_PKTHDR : 0, &mlen);
898 m->m_pkthdr.rcvif = NULL;
900 len = imin((int)szmin(mlen, resid), space);
901 if (resid < MINCLSIZE) {
903 * For datagram protocols, leave room
904 * for protocol headers in first mbuf.
906 if (atomic && top == NULL && len < mlen)
910 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
911 resid = uio->uio_resid;
914 top->m_pkthdr.len += len;
920 top->m_flags |= M_EOR;
923 } while (space > 0 && atomic);
925 so->so_options |= SO_DONTROUTE;
926 if (flags & MSG_OOB) {
927 pru_flags = PRUS_OOB;
928 } else if ((flags & MSG_EOF) &&
929 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
932 * If the user set MSG_EOF, the protocol
933 * understands this flag and nothing left to
934 * send then use PRU_SEND_EOF instead of PRU_SEND.
936 pru_flags = PRUS_EOF;
937 } else if (resid > 0 && space > 0) {
938 /* If there is more to send, set PRUS_MORETOCOME */
939 pru_flags = PRUS_MORETOCOME;
944 * XXX all the SS_CANTSENDMORE checks previously
945 * done could be out of date. We could have recieved
946 * a reset packet in an interrupt or maybe we slept
947 * while doing page faults in uiomove() etc. We could
948 * probably recheck again inside the splnet() protection
949 * here, but there are probably other places that this
950 * also happens. We must rethink this.
952 error = so_pru_send(so, pru_flags, top, addr, control, td);
954 so->so_options &= ~SO_DONTROUTE;
961 } while (resid && space > 0);
965 ssb_unlock(&so->so_snd);
976 * A specialization of sosend() for UDP based on protocol-specific knowledge:
977 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
978 * sosendallatonce() returns true,
979 * the "atomic" variable is true,
980 * and sosendudp() blocks until space is available for the entire send.
981 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
982 * PR_IMPLOPCL flags set.
983 * UDP has no out-of-band data.
984 * UDP has no control data.
985 * UDP does not support MSG_EOR.
988 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
989 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
992 int error, pru_flags = 0;
995 if (td->td_lwp != NULL)
996 td->td_lwp->lwp_ru.ru_msgsnd++;
1000 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
1001 resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
1004 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1008 if (so->so_state & SS_CANTSENDMORE)
1011 error = so->so_error;
1015 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
1016 gotoerr(EDESTADDRREQ);
1017 if (resid > so->so_snd.ssb_hiwat)
1019 space = ssb_space(&so->so_snd);
1020 if (uio && (space < 0 || (size_t)space < resid)) {
1021 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1022 gotoerr(EWOULDBLOCK);
1023 ssb_unlock(&so->so_snd);
1024 error = ssb_wait(&so->so_snd);
1031 int hdrlen = max_hdr;
1034 * We try to optimize out the additional mbuf
1035 * allocations in M_PREPEND() on output path, e.g.
1036 * - udp_output(), when it tries to prepend protocol
1038 * - Link layer output function, when it tries to
1039 * prepend link layer header.
1041 * This probably will not benefit any data that will
1042 * be fragmented, so this optimization is only performed
1043 * when the size of data and max size of protocol+link
1044 * headers fit into one mbuf cluster.
1046 if (uio->uio_resid > MCLBYTES - hdrlen ||
1047 !udp_sosend_prepend) {
1048 top = m_uiomove(uio);
1054 top = m_getl(uio->uio_resid + hdrlen, MB_WAIT,
1055 MT_DATA, M_PKTHDR, &nsize);
1056 KASSERT(nsize >= uio->uio_resid + hdrlen,
1057 ("sosendudp invalid nsize %d, "
1058 "resid %zu, hdrlen %d",
1059 nsize, uio->uio_resid, hdrlen));
1061 top->m_len = uio->uio_resid;
1062 top->m_pkthdr.len = uio->uio_resid;
1063 top->m_data += hdrlen;
1065 error = uiomove(mtod(top, caddr_t), top->m_len, uio);
1071 if (flags & MSG_DONTROUTE)
1072 pru_flags |= PRUS_DONTROUTE;
1074 if (udp_sosend_async && (flags & MSG_SYNC) == 0) {
1075 so_pru_send_async(so, pru_flags, top, addr, NULL, td);
1078 error = so_pru_send(so, pru_flags, top, addr, NULL, td);
1080 top = NULL; /* sent or freed in lower layer */
1083 ssb_unlock(&so->so_snd);
1091 sosendtcp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1092 struct mbuf *top, struct mbuf *control, int flags,
1104 KKASSERT(top == NULL);
1106 resid = uio->uio_resid;
1109 resid = (size_t)top->m_pkthdr.len;
1112 for (m = top; m; m = m->m_next)
1114 KKASSERT(top->m_pkthdr.len == len);
1119 * WARNING! resid is unsigned, space and len are signed. space
1120 * can wind up negative if the sockbuf is overcommitted.
1122 * Also check to make sure that MSG_EOR isn't used on TCP
1124 if (flags & MSG_EOR) {
1130 /* TCP doesn't do control messages (rights, creds, etc) */
1131 if (control->m_len) {
1135 m_freem(control); /* empty control, just free it */
1139 if (td->td_lwp != NULL)
1140 td->td_lwp->lwp_ru.ru_msgsnd++;
1142 #define gotoerr(errcode) { error = errcode; goto release; }
1145 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1150 if (so->so_state & SS_CANTSENDMORE)
1153 error = so->so_error;
1157 if ((so->so_state & SS_ISCONNECTED) == 0 &&
1158 (so->so_state & SS_ISCONFIRMING) == 0)
1160 if (allatonce && resid > so->so_snd.ssb_hiwat)
1163 space = ssb_space_prealloc(&so->so_snd);
1164 if (flags & MSG_OOB)
1166 if ((space < 0 || (size_t)space < resid) && !allatonce &&
1167 space < so->so_snd.ssb_lowat) {
1168 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1169 gotoerr(EWOULDBLOCK);
1170 ssb_unlock(&so->so_snd);
1171 error = ssb_wait(&so->so_snd);
1178 int cnt = 0, async = 0;
1182 * Data is prepackaged in "top".
1186 if (resid > INT_MAX)
1188 if (tcp_sosend_jcluster) {
1189 m = m_getlj((int)resid, MB_WAIT, MT_DATA,
1190 top == NULL ? M_PKTHDR : 0, &mlen);
1192 m = m_getl((int)resid, MB_WAIT, MT_DATA,
1193 top == NULL ? M_PKTHDR : 0, &mlen);
1196 m->m_pkthdr.len = 0;
1197 m->m_pkthdr.rcvif = NULL;
1199 len = imin((int)szmin(mlen, resid), space);
1201 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
1202 resid = uio->uio_resid;
1205 top->m_pkthdr.len += len;
1212 } while (space > 0 && cnt < tcp_sosend_agglim);
1214 if (tcp_sosend_async)
1217 if (flags & MSG_OOB) {
1218 pru_flags = PRUS_OOB;
1220 } else if ((flags & MSG_EOF) && resid == 0) {
1221 pru_flags = PRUS_EOF;
1222 } else if (resid > 0 && space > 0) {
1223 /* If there is more to send, set PRUS_MORETOCOME */
1224 pru_flags = PRUS_MORETOCOME;
1230 if (flags & MSG_SYNC)
1234 * XXX all the SS_CANTSENDMORE checks previously
1235 * done could be out of date. We could have recieved
1236 * a reset packet in an interrupt or maybe we slept
1237 * while doing page faults in uiomove() etc. We could
1238 * probably recheck again inside the splnet() protection
1239 * here, but there are probably other places that this
1240 * also happens. We must rethink this.
1242 for (m = top; m; m = m->m_next)
1243 ssb_preallocstream(&so->so_snd, m);
1245 error = so_pru_send(so, pru_flags, top,
1248 so_pru_send_async(so, pru_flags, top,
1257 } while (resid && space > 0);
1261 ssb_unlock(&so->so_snd);
1272 * Implement receive operations on a socket.
1274 * We depend on the way that records are added to the signalsockbuf
1275 * by sbappend*. In particular, each record (mbufs linked through m_next)
1276 * must begin with an address if the protocol so specifies,
1277 * followed by an optional mbuf or mbufs containing ancillary data,
1278 * and then zero or more mbufs of data.
1280 * Although the signalsockbuf is locked, new data may still be appended.
1281 * A token inside the ssb_lock deals with MP issues and still allows
1282 * the network to access the socket if we block in a uio.
1284 * The caller may receive the data as a single mbuf chain by supplying
1285 * an mbuf **mp0 for use in returning the chain. The uio is then used
1286 * only for the count in uio_resid.
1289 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1290 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1293 struct mbuf *free_chain = NULL;
1294 int flags, len, error, offset;
1295 struct protosw *pr = so->so_proto;
1297 size_t resid, orig_resid;
1300 resid = uio->uio_resid;
1302 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1310 flags = *flagsp &~ MSG_EOR;
1313 if (flags & MSG_OOB) {
1314 m = m_get(MB_WAIT, MT_DATA);
1317 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1323 KKASSERT(resid >= (size_t)m->m_len);
1324 resid -= (size_t)m->m_len;
1325 } while (resid > 0 && m);
1328 uio->uio_resid = resid;
1329 error = uiomove(mtod(m, caddr_t),
1330 (int)szmin(resid, m->m_len),
1332 resid = uio->uio_resid;
1334 } while (uio->uio_resid && error == 0 && m);
1341 if ((so->so_state & SS_ISCONFIRMING) && resid)
1345 * The token interlocks against the protocol thread while
1346 * ssb_lock is a blocking lock against other userland entities.
1348 lwkt_gettoken(&so->so_rcv.ssb_token);
1350 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1354 m = so->so_rcv.ssb_mb;
1356 * If we have less data than requested, block awaiting more
1357 * (subject to any timeout) if:
1358 * 1. the current count is less than the low water mark, or
1359 * 2. MSG_WAITALL is set, and it is possible to do the entire
1360 * receive operation at once if we block (resid <= hiwat).
1361 * 3. MSG_DONTWAIT is not set
1362 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1363 * we have to do the receive in sections, and thus risk returning
1364 * a short count if a timeout or signal occurs after we start.
1366 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1367 (size_t)so->so_rcv.ssb_cc < resid) &&
1368 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1369 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
1370 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1371 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1375 error = so->so_error;
1376 if ((flags & MSG_PEEK) == 0)
1380 if (so->so_state & SS_CANTRCVMORE) {
1386 for (; m; m = m->m_next) {
1387 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1388 m = so->so_rcv.ssb_mb;
1392 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1393 (pr->pr_flags & PR_CONNREQUIRED)) {
1399 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1400 error = EWOULDBLOCK;
1403 ssb_unlock(&so->so_rcv);
1404 error = ssb_wait(&so->so_rcv);
1410 if (uio && uio->uio_td && uio->uio_td->td_proc)
1411 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1414 * note: m should be == sb_mb here. Cache the next record while
1415 * cleaning up. Note that calling m_free*() will break out critical
1418 KKASSERT(m == so->so_rcv.ssb_mb);
1421 * Skip any address mbufs prepending the record.
1423 if (pr->pr_flags & PR_ADDR) {
1424 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
1427 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1428 if (flags & MSG_PEEK)
1431 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1435 * Skip any control mbufs prepending the record.
1438 if (pr->pr_flags & PR_ADDR_OPT) {
1440 * For SCTP we may be getting a
1441 * whole message OR a partial delivery.
1443 if (m && m->m_type == MT_SONAME) {
1446 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1447 if (flags & MSG_PEEK)
1450 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1454 while (m && m->m_type == MT_CONTROL && error == 0) {
1455 if (flags & MSG_PEEK) {
1457 *controlp = m_copy(m, 0, m->m_len);
1458 m = m->m_next; /* XXX race */
1461 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1462 if (pr->pr_domain->dom_externalize &&
1463 mtod(m, struct cmsghdr *)->cmsg_type ==
1465 error = (*pr->pr_domain->dom_externalize)(m);
1469 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1472 if (controlp && *controlp) {
1474 controlp = &(*controlp)->m_next;
1483 if (type == MT_OOBDATA)
1488 * Copy to the UIO or mbuf return chain (*mp).
1492 while (m && resid > 0 && error == 0) {
1493 if (m->m_type == MT_OOBDATA) {
1494 if (type != MT_OOBDATA)
1496 } else if (type == MT_OOBDATA)
1499 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1501 soclrstate(so, SS_RCVATMARK);
1502 len = (resid > INT_MAX) ? INT_MAX : resid;
1503 if (so->so_oobmark && len > so->so_oobmark - offset)
1504 len = so->so_oobmark - offset;
1505 if (len > m->m_len - moff)
1506 len = m->m_len - moff;
1509 * Copy out to the UIO or pass the mbufs back to the SIO.
1510 * The SIO is dealt with when we eat the mbuf, but deal
1511 * with the resid here either way.
1514 uio->uio_resid = resid;
1515 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1516 resid = uio->uio_resid;
1520 resid -= (size_t)len;
1524 * Eat the entire mbuf or just a piece of it
1526 if (len == m->m_len - moff) {
1527 if (m->m_flags & M_EOR)
1530 if (m->m_flags & M_NOTIFICATION)
1531 flags |= MSG_NOTIFICATION;
1533 if (flags & MSG_PEEK) {
1538 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1542 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1546 if (flags & MSG_PEEK) {
1550 n = m_copym(m, 0, len, MB_WAIT);
1556 so->so_rcv.ssb_cc -= len;
1559 if (so->so_oobmark) {
1560 if ((flags & MSG_PEEK) == 0) {
1561 so->so_oobmark -= len;
1562 if (so->so_oobmark == 0) {
1563 sosetstate(so, SS_RCVATMARK);
1568 if (offset == so->so_oobmark)
1572 if (flags & MSG_EOR)
1575 * If the MSG_WAITALL flag is set (for non-atomic socket),
1576 * we must not quit until resid == 0 or an error
1577 * termination. If a signal/timeout occurs, return
1578 * with a short count but without error.
1579 * Keep signalsockbuf locked against other readers.
1581 while ((flags & MSG_WAITALL) && m == NULL &&
1582 resid > 0 && !sosendallatonce(so) &&
1583 so->so_rcv.ssb_mb == NULL) {
1584 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1587 * The window might have closed to zero, make
1588 * sure we send an ack now that we've drained
1589 * the buffer or we might end up blocking until
1590 * the idle takes over (5 seconds).
1592 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1593 so_pru_rcvd(so, flags);
1594 error = ssb_wait(&so->so_rcv);
1596 ssb_unlock(&so->so_rcv);
1600 m = so->so_rcv.ssb_mb;
1605 * If an atomic read was requested but unread data still remains
1606 * in the record, set MSG_TRUNC.
1608 if (m && pr->pr_flags & PR_ATOMIC)
1612 * Cleanup. If an atomic read was requested drop any unread data.
1614 if ((flags & MSG_PEEK) == 0) {
1615 if (m && (pr->pr_flags & PR_ATOMIC))
1616 sbdroprecord(&so->so_rcv.sb);
1617 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1618 so_pru_rcvd(so, flags);
1621 if (orig_resid == resid && orig_resid &&
1622 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1623 ssb_unlock(&so->so_rcv);
1630 ssb_unlock(&so->so_rcv);
1632 lwkt_reltoken(&so->so_rcv.ssb_token);
1634 m_freem(free_chain);
1639 sorecvtcp(struct socket *so, struct sockaddr **psa, struct uio *uio,
1640 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1643 struct mbuf *free_chain = NULL;
1644 int flags, len, error, offset;
1645 struct protosw *pr = so->so_proto;
1647 size_t resid, orig_resid;
1650 resid = uio->uio_resid;
1652 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1660 flags = *flagsp &~ MSG_EOR;
1663 if (flags & MSG_OOB) {
1664 m = m_get(MB_WAIT, MT_DATA);
1667 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1673 KKASSERT(resid >= (size_t)m->m_len);
1674 resid -= (size_t)m->m_len;
1675 } while (resid > 0 && m);
1678 uio->uio_resid = resid;
1679 error = uiomove(mtod(m, caddr_t),
1680 (int)szmin(resid, m->m_len),
1682 resid = uio->uio_resid;
1684 } while (uio->uio_resid && error == 0 && m);
1693 * The token interlocks against the protocol thread while
1694 * ssb_lock is a blocking lock against other userland entities.
1696 lwkt_gettoken(&so->so_rcv.ssb_token);
1698 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1702 m = so->so_rcv.ssb_mb;
1704 * If we have less data than requested, block awaiting more
1705 * (subject to any timeout) if:
1706 * 1. the current count is less than the low water mark, or
1707 * 2. MSG_WAITALL is set, and it is possible to do the entire
1708 * receive operation at once if we block (resid <= hiwat).
1709 * 3. MSG_DONTWAIT is not set
1710 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1711 * we have to do the receive in sections, and thus risk returning
1712 * a short count if a timeout or signal occurs after we start.
1714 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1715 (size_t)so->so_rcv.ssb_cc < resid) &&
1716 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1717 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)))) {
1718 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1722 error = so->so_error;
1723 if ((flags & MSG_PEEK) == 0)
1727 if (so->so_state & SS_CANTRCVMORE) {
1733 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1734 (pr->pr_flags & PR_CONNREQUIRED)) {
1740 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1741 error = EWOULDBLOCK;
1744 ssb_unlock(&so->so_rcv);
1745 error = ssb_wait(&so->so_rcv);
1751 if (uio && uio->uio_td && uio->uio_td->td_proc)
1752 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1755 * note: m should be == sb_mb here. Cache the next record while
1756 * cleaning up. Note that calling m_free*() will break out critical
1759 KKASSERT(m == so->so_rcv.ssb_mb);
1762 * Copy to the UIO or mbuf return chain (*mp).
1766 while (m && resid > 0 && error == 0) {
1767 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1770 soclrstate(so, SS_RCVATMARK);
1771 len = (resid > INT_MAX) ? INT_MAX : resid;
1772 if (so->so_oobmark && len > so->so_oobmark - offset)
1773 len = so->so_oobmark - offset;
1774 if (len > m->m_len - moff)
1775 len = m->m_len - moff;
1778 * Copy out to the UIO or pass the mbufs back to the SIO.
1779 * The SIO is dealt with when we eat the mbuf, but deal
1780 * with the resid here either way.
1783 uio->uio_resid = resid;
1784 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1785 resid = uio->uio_resid;
1789 resid -= (size_t)len;
1793 * Eat the entire mbuf or just a piece of it
1795 if (len == m->m_len - moff) {
1796 if (flags & MSG_PEEK) {
1801 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1805 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1809 if (flags & MSG_PEEK) {
1813 n = m_copym(m, 0, len, MB_WAIT);
1819 so->so_rcv.ssb_cc -= len;
1822 if (so->so_oobmark) {
1823 if ((flags & MSG_PEEK) == 0) {
1824 so->so_oobmark -= len;
1825 if (so->so_oobmark == 0) {
1826 sosetstate(so, SS_RCVATMARK);
1831 if (offset == so->so_oobmark)
1836 * If the MSG_WAITALL flag is set (for non-atomic socket),
1837 * we must not quit until resid == 0 or an error
1838 * termination. If a signal/timeout occurs, return
1839 * with a short count but without error.
1840 * Keep signalsockbuf locked against other readers.
1842 while ((flags & MSG_WAITALL) && m == NULL &&
1843 resid > 0 && !sosendallatonce(so) &&
1844 so->so_rcv.ssb_mb == NULL) {
1845 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1848 * The window might have closed to zero, make
1849 * sure we send an ack now that we've drained
1850 * the buffer or we might end up blocking until
1851 * the idle takes over (5 seconds).
1854 so_pru_rcvd_async(so);
1855 error = ssb_wait(&so->so_rcv);
1857 ssb_unlock(&so->so_rcv);
1861 m = so->so_rcv.ssb_mb;
1866 * Cleanup. If an atomic read was requested drop any unread data.
1868 if ((flags & MSG_PEEK) == 0) {
1870 so_pru_rcvd_async(so);
1873 if (orig_resid == resid && orig_resid &&
1874 (so->so_state & SS_CANTRCVMORE) == 0) {
1875 ssb_unlock(&so->so_rcv);
1882 ssb_unlock(&so->so_rcv);
1884 lwkt_reltoken(&so->so_rcv.ssb_token);
1886 m_freem(free_chain);
1891 * Shut a socket down. Note that we do not get a frontend lock as we
1892 * want to be able to shut the socket down even if another thread is
1893 * blocked in a read(), thus waking it up.
1896 soshutdown(struct socket *so, int how)
1898 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1901 if (how != SHUT_WR) {
1902 /*ssb_lock(&so->so_rcv, M_WAITOK);*/
1904 /*ssb_unlock(&so->so_rcv);*/
1907 return (so_pru_shutdown(so));
1912 sorflush(struct socket *so)
1914 struct signalsockbuf *ssb = &so->so_rcv;
1915 struct protosw *pr = so->so_proto;
1916 struct signalsockbuf asb;
1918 atomic_set_int(&ssb->ssb_flags, SSB_NOINTR);
1920 lwkt_gettoken(&ssb->ssb_token);
1925 * Can't just blow up the ssb structure here
1927 bzero(&ssb->sb, sizeof(ssb->sb));
1932 atomic_clear_int(&ssb->ssb_flags, SSB_CLEAR_MASK);
1934 if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose)
1935 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1936 ssb_release(&asb, so);
1938 lwkt_reltoken(&ssb->ssb_token);
1943 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1945 struct accept_filter_arg *afap = NULL;
1946 struct accept_filter *afp;
1947 struct so_accf *af = so->so_accf;
1950 /* do not set/remove accept filters on non listen sockets */
1951 if ((so->so_options & SO_ACCEPTCONN) == 0) {
1956 /* removing the filter */
1959 if (af->so_accept_filter != NULL &&
1960 af->so_accept_filter->accf_destroy != NULL) {
1961 af->so_accept_filter->accf_destroy(so);
1963 if (af->so_accept_filter_str != NULL) {
1964 kfree(af->so_accept_filter_str, M_ACCF);
1969 so->so_options &= ~SO_ACCEPTFILTER;
1972 /* adding a filter */
1973 /* must remove previous filter first */
1978 /* don't put large objects on the kernel stack */
1979 afap = kmalloc(sizeof(*afap), M_TEMP, M_WAITOK);
1980 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1981 afap->af_name[sizeof(afap->af_name)-1] = '\0';
1982 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1985 afp = accept_filt_get(afap->af_name);
1990 af = kmalloc(sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1991 if (afp->accf_create != NULL) {
1992 if (afap->af_name[0] != '\0') {
1993 int len = strlen(afap->af_name) + 1;
1995 af->so_accept_filter_str = kmalloc(len, M_ACCF,
1997 strcpy(af->so_accept_filter_str, afap->af_name);
1999 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
2000 if (af->so_accept_filter_arg == NULL) {
2001 kfree(af->so_accept_filter_str, M_ACCF);
2008 af->so_accept_filter = afp;
2010 so->so_options |= SO_ACCEPTFILTER;
2013 kfree(afap, M_TEMP);
2019 * Perhaps this routine, and sooptcopyout(), below, ought to come in
2020 * an additional variant to handle the case where the option value needs
2021 * to be some kind of integer, but not a specific size.
2022 * In addition to their use here, these functions are also called by the
2023 * protocol-level pr_ctloutput() routines.
2026 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2028 return soopt_to_kbuf(sopt, buf, len, minlen);
2032 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2036 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2037 KKASSERT(kva_p(buf));
2040 * If the user gives us more than we wanted, we ignore it,
2041 * but if we don't get the minimum length the caller
2042 * wants, we return EINVAL. On success, sopt->sopt_valsize
2043 * is set to however much we actually retrieved.
2045 if ((valsize = sopt->sopt_valsize) < minlen)
2048 sopt->sopt_valsize = valsize = len;
2050 bcopy(sopt->sopt_val, buf, valsize);
2056 sosetopt(struct socket *so, struct sockopt *sopt)
2062 struct signalsockbuf *sotmp;
2065 sopt->sopt_dir = SOPT_SET;
2066 if (sopt->sopt_level != SOL_SOCKET) {
2067 if (so->so_proto && so->so_proto->pr_ctloutput) {
2068 return (so_pr_ctloutput(so, sopt));
2070 error = ENOPROTOOPT;
2072 switch (sopt->sopt_name) {
2074 case SO_ACCEPTFILTER:
2075 error = do_setopt_accept_filter(so, sopt);
2081 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2085 so->so_linger = l.l_linger;
2087 so->so_options |= SO_LINGER;
2089 so->so_options &= ~SO_LINGER;
2095 case SO_USELOOPBACK:
2102 error = sooptcopyin(sopt, &optval, sizeof optval,
2107 so->so_options |= sopt->sopt_name;
2109 so->so_options &= ~sopt->sopt_name;
2116 error = sooptcopyin(sopt, &optval, sizeof optval,
2122 * Values < 1 make no sense for any of these
2123 * options, so disallow them.
2130 switch (sopt->sopt_name) {
2133 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
2134 &so->so_snd : &so->so_rcv, (u_long)optval,
2136 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
2140 sotmp = (sopt->sopt_name == SO_SNDBUF) ?
2141 &so->so_snd : &so->so_rcv;
2142 atomic_clear_int(&sotmp->ssb_flags,
2147 * Make sure the low-water is never greater than
2151 so->so_snd.ssb_lowat =
2152 (optval > so->so_snd.ssb_hiwat) ?
2153 so->so_snd.ssb_hiwat : optval;
2154 atomic_clear_int(&so->so_snd.ssb_flags,
2158 so->so_rcv.ssb_lowat =
2159 (optval > so->so_rcv.ssb_hiwat) ?
2160 so->so_rcv.ssb_hiwat : optval;
2161 atomic_clear_int(&so->so_rcv.ssb_flags,
2169 error = sooptcopyin(sopt, &tv, sizeof tv,
2174 /* assert(hz > 0); */
2175 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2176 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2180 /* assert(tick > 0); */
2181 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2182 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
2183 if (val > INT_MAX) {
2187 if (val == 0 && tv.tv_usec != 0)
2190 switch (sopt->sopt_name) {
2192 so->so_snd.ssb_timeo = val;
2195 so->so_rcv.ssb_timeo = val;
2200 error = ENOPROTOOPT;
2203 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
2204 (void) so_pr_ctloutput(so, sopt);
2211 /* Helper routine for getsockopt */
2213 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2215 soopt_from_kbuf(sopt, buf, len);
2220 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
2225 sopt->sopt_valsize = 0;
2229 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2230 KKASSERT(kva_p(buf));
2233 * Documented get behavior is that we always return a value,
2234 * possibly truncated to fit in the user's buffer.
2235 * Traditional behavior is that we always tell the user
2236 * precisely how much we copied, rather than something useful
2237 * like the total amount we had available for her.
2238 * Note that this interface is not idempotent; the entire answer must
2239 * generated ahead of time.
2241 valsize = szmin(len, sopt->sopt_valsize);
2242 sopt->sopt_valsize = valsize;
2243 if (sopt->sopt_val != 0) {
2244 bcopy(buf, sopt->sopt_val, valsize);
2249 sogetopt(struct socket *so, struct sockopt *sopt)
2256 struct accept_filter_arg *afap;
2260 sopt->sopt_dir = SOPT_GET;
2261 if (sopt->sopt_level != SOL_SOCKET) {
2262 if (so->so_proto && so->so_proto->pr_ctloutput) {
2263 return (so_pr_ctloutput(so, sopt));
2265 return (ENOPROTOOPT);
2267 switch (sopt->sopt_name) {
2269 case SO_ACCEPTFILTER:
2270 if ((so->so_options & SO_ACCEPTCONN) == 0)
2272 afap = kmalloc(sizeof(*afap), M_TEMP,
2274 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
2275 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
2276 if (so->so_accf->so_accept_filter_str != NULL)
2277 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
2279 error = sooptcopyout(sopt, afap, sizeof(*afap));
2280 kfree(afap, M_TEMP);
2285 l.l_onoff = so->so_options & SO_LINGER;
2286 l.l_linger = so->so_linger;
2287 error = sooptcopyout(sopt, &l, sizeof l);
2290 case SO_USELOOPBACK:
2300 optval = so->so_options & sopt->sopt_name;
2302 error = sooptcopyout(sopt, &optval, sizeof optval);
2306 optval = so->so_type;
2310 optval = so->so_error;
2315 optval = so->so_snd.ssb_hiwat;
2319 optval = so->so_rcv.ssb_hiwat;
2323 optval = so->so_snd.ssb_lowat;
2327 optval = so->so_rcv.ssb_lowat;
2332 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2333 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
2335 tv.tv_sec = optval / hz;
2336 tv.tv_usec = (optval % hz) * ustick;
2337 error = sooptcopyout(sopt, &tv, sizeof tv);
2341 optval_l = ssb_space(&so->so_snd);
2342 error = sooptcopyout(sopt, &optval_l, sizeof(optval_l));
2346 error = ENOPROTOOPT;
2353 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2355 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2357 struct mbuf *m, *m_prev;
2358 int sopt_size = sopt->sopt_valsize, msize;
2360 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
2364 m->m_len = min(msize, sopt_size);
2365 sopt_size -= m->m_len;
2369 while (sopt_size > 0) {
2370 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
2371 MT_DATA, 0, &msize);
2376 m->m_len = min(msize, sopt_size);
2377 sopt_size -= m->m_len;
2384 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2386 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2388 soopt_to_mbuf(sopt, m);
2393 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
2398 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2400 if (sopt->sopt_val == NULL)
2402 val = sopt->sopt_val;
2403 valsize = sopt->sopt_valsize;
2404 while (m != NULL && valsize >= m->m_len) {
2405 bcopy(val, mtod(m, char *), m->m_len);
2406 valsize -= m->m_len;
2407 val = (caddr_t)val + m->m_len;
2410 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2411 panic("ip6_sooptmcopyin");
2414 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2416 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2418 return soopt_from_mbuf(sopt, m);
2422 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
2424 struct mbuf *m0 = m;
2429 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2431 if (sopt->sopt_val == NULL)
2433 val = sopt->sopt_val;
2434 maxsize = sopt->sopt_valsize;
2435 while (m != NULL && maxsize >= m->m_len) {
2436 bcopy(mtod(m, char *), val, m->m_len);
2437 maxsize -= m->m_len;
2438 val = (caddr_t)val + m->m_len;
2439 valsize += m->m_len;
2443 /* enough soopt buffer should be given from user-land */
2447 sopt->sopt_valsize = valsize;
2452 sohasoutofband(struct socket *so)
2454 if (so->so_sigio != NULL)
2455 pgsigio(so->so_sigio, SIGURG, 0);
2456 KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
2460 sokqfilter(struct file *fp, struct knote *kn)
2462 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2463 struct signalsockbuf *ssb;
2465 switch (kn->kn_filter) {
2467 if (so->so_options & SO_ACCEPTCONN)
2468 kn->kn_fop = &solisten_filtops;
2470 kn->kn_fop = &soread_filtops;
2474 kn->kn_fop = &sowrite_filtops;
2478 kn->kn_fop = &soexcept_filtops;
2482 return (EOPNOTSUPP);
2485 knote_insert(&ssb->ssb_kq.ki_note, kn);
2486 atomic_set_int(&ssb->ssb_flags, SSB_KNOTE);
2491 filt_sordetach(struct knote *kn)
2493 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2495 knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
2496 if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
2497 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_KNOTE);
2502 filt_soread(struct knote *kn, long hint)
2504 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2506 if (kn->kn_sfflags & NOTE_OOB) {
2507 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
2508 kn->kn_fflags |= NOTE_OOB;
2513 kn->kn_data = so->so_rcv.ssb_cc;
2515 if (so->so_state & SS_CANTRCVMORE) {
2517 * Only set NODATA if all data has been exhausted.
2519 if (kn->kn_data == 0)
2520 kn->kn_flags |= EV_NODATA;
2521 kn->kn_flags |= EV_EOF;
2522 kn->kn_fflags = so->so_error;
2525 if (so->so_error) /* temporary udp error */
2527 if (kn->kn_sfflags & NOTE_LOWAT)
2528 return (kn->kn_data >= kn->kn_sdata);
2529 return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
2530 !TAILQ_EMPTY(&so->so_comp));
2534 filt_sowdetach(struct knote *kn)
2536 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2538 knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
2539 if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
2540 atomic_clear_int(&so->so_snd.ssb_flags, SSB_KNOTE);
2545 filt_sowrite(struct knote *kn, long hint)
2547 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2549 kn->kn_data = ssb_space(&so->so_snd);
2550 if (so->so_state & SS_CANTSENDMORE) {
2551 kn->kn_flags |= (EV_EOF | EV_NODATA);
2552 kn->kn_fflags = so->so_error;
2555 if (so->so_error) /* temporary udp error */
2557 if (((so->so_state & SS_ISCONNECTED) == 0) &&
2558 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2560 if (kn->kn_sfflags & NOTE_LOWAT)
2561 return (kn->kn_data >= kn->kn_sdata);
2562 return (kn->kn_data >= so->so_snd.ssb_lowat);
2567 filt_solisten(struct knote *kn, long hint)
2569 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2571 kn->kn_data = so->so_qlen;
2572 return (! TAILQ_EMPTY(&so->so_comp));