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 int soclose_sync(struct socket *so, int fflag);
116 static void soclose_fast(struct socket *so);
118 static struct filterops solisten_filtops =
119 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_solisten };
120 static struct filterops soread_filtops =
121 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_soread };
122 static struct filterops sowrite_filtops =
123 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sowdetach, filt_sowrite };
124 static struct filterops soexcept_filtops =
125 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_soread };
127 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
128 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
129 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
132 static int somaxconn = SOMAXCONN;
133 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
134 &somaxconn, 0, "Maximum pending socket connection queue size");
136 static int use_soclose_fast = 1;
137 SYSCTL_INT(_kern_ipc, OID_AUTO, soclose_fast, CTLFLAG_RW,
138 &use_soclose_fast, 0, "Fast socket close");
140 int use_soaccept_pred_fast = 1;
141 SYSCTL_INT(_kern_ipc, OID_AUTO, soaccept_pred_fast, CTLFLAG_RW,
142 &use_soaccept_pred_fast, 0, "Fast socket accept predication");
144 int use_sendfile_async = 1;
145 SYSCTL_INT(_kern_ipc, OID_AUTO, sendfile_async, CTLFLAG_RW,
146 &use_sendfile_async, 0, "sendfile uses asynchronized pru_send");
148 int use_soconnect_async = 1;
149 SYSCTL_INT(_kern_ipc, OID_AUTO, soconnect_async, CTLFLAG_RW,
150 &use_soconnect_async, 0, "soconnect uses asynchronized pru_connect");
153 * Socket operation routines.
154 * These routines are called by the routines in
155 * sys_socket.c or from a system process, and
156 * implement the semantics of socket operations by
157 * switching out to the protocol specific routines.
161 * Get a socket structure, and initialize it.
162 * Note that it would probably be better to allocate socket
163 * and PCB at the same time, but I'm not convinced that all
164 * the protocols can be easily modified to do this.
167 soalloc(int waitok, struct protosw *pr)
172 waitmask = waitok ? M_WAITOK : M_NOWAIT;
173 so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
175 /* XXX race condition for reentrant kernel */
177 TAILQ_INIT(&so->so_aiojobq);
178 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
179 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
180 lwkt_token_init(&so->so_rcv.ssb_token, "rcvtok");
181 lwkt_token_init(&so->so_snd.ssb_token, "sndtok");
182 spin_init(&so->so_rcvd_spin, "soalloc");
183 netmsg_init(&so->so_rcvd_msg.base, so, &netisr_adone_rport,
184 MSGF_DROPABLE | MSGF_PRIORITY,
185 so->so_proto->pr_usrreqs->pru_rcvd);
186 so->so_rcvd_msg.nm_pru_flags |= PRUR_ASYNC;
187 so->so_state = SS_NOFDREF;
194 socreate(int dom, struct socket **aso, int type,
195 int proto, struct thread *td)
197 struct proc *p = td->td_proc;
200 struct pru_attach_info ai;
204 prp = pffindproto(dom, proto, type);
206 prp = pffindtype(dom, type);
208 if (prp == NULL || prp->pr_usrreqs->pru_attach == 0)
209 return (EPROTONOSUPPORT);
211 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
212 prp->pr_domain->dom_family != PF_LOCAL &&
213 prp->pr_domain->dom_family != PF_INET &&
214 prp->pr_domain->dom_family != PF_INET6 &&
215 prp->pr_domain->dom_family != PF_ROUTE) {
216 return (EPROTONOSUPPORT);
219 if (prp->pr_type != type)
221 so = soalloc(p != NULL, prp);
226 * Callers of socreate() presumably will connect up a descriptor
227 * and call soclose() if they cannot. This represents our so_refs
228 * (which should be 1) from soalloc().
230 soclrstate(so, SS_NOFDREF);
233 * Set a default port for protocol processing. No action will occur
234 * on the socket on this port until an inpcb is attached to it and
235 * is able to match incoming packets, or until the socket becomes
236 * available to userland.
238 * We normally default the socket to the protocol thread on cpu 0,
239 * if protocol does not provide its own method to initialize the
242 * If PR_SYNC_PORT is set (unix domain sockets) there is no protocol
243 * thread and all pr_*()/pru_*() calls are executed synchronously.
245 if (prp->pr_flags & PR_SYNC_PORT)
246 so->so_port = &netisr_sync_port;
247 else if (prp->pr_initport != NULL)
248 so->so_port = prp->pr_initport();
250 so->so_port = netisr_cpuport(0);
252 TAILQ_INIT(&so->so_incomp);
253 TAILQ_INIT(&so->so_comp);
255 so->so_cred = crhold(p->p_ucred);
256 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
257 ai.p_ucred = p->p_ucred;
258 ai.fd_rdir = p->p_fd->fd_rdir;
261 * Auto-sizing of socket buffers is managed by the protocols and
262 * the appropriate flags must be set in the pru_attach function.
264 error = so_pru_attach(so, proto, &ai);
266 sosetstate(so, SS_NOFDREF);
267 sofree(so); /* from soalloc */
272 * NOTE: Returns referenced socket.
279 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
283 error = so_pru_bind(so, nam, td);
288 sodealloc(struct socket *so)
290 if (so->so_rcv.ssb_hiwat)
291 (void)chgsbsize(so->so_cred->cr_uidinfo,
292 &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
293 if (so->so_snd.ssb_hiwat)
294 (void)chgsbsize(so->so_cred->cr_uidinfo,
295 &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
297 /* remove accept filter if present */
298 if (so->so_accf != NULL)
299 do_setopt_accept_filter(so, NULL);
302 if (so->so_faddr != NULL)
303 kfree(so->so_faddr, M_SONAME);
308 solisten(struct socket *so, int backlog, struct thread *td)
312 short oldopt, oldqlimit;
315 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))
319 oldopt = so->so_options;
320 oldqlimit = so->so_qlimit;
323 lwkt_gettoken(&so->so_rcv.ssb_token);
324 if (TAILQ_EMPTY(&so->so_comp))
325 so->so_options |= SO_ACCEPTCONN;
326 lwkt_reltoken(&so->so_rcv.ssb_token);
327 if (backlog < 0 || backlog > somaxconn)
329 so->so_qlimit = backlog;
330 /* SCTP needs to look at tweak both the inbound backlog parameter AND
331 * the so_options (UDP model both connect's and gets inbound
332 * connections .. implicitly).
334 error = so_pru_listen(so, td);
337 /* Restore the params */
338 so->so_options = oldopt;
339 so->so_qlimit = oldqlimit;
347 * Destroy a disconnected socket. This routine is a NOP if entities
348 * still have a reference on the socket:
350 * so_pcb - The protocol stack still has a reference
351 * SS_NOFDREF - There is no longer a file pointer reference
354 sofree(struct socket *so)
359 * This is a bit hackish at the moment. We need to interlock
360 * any accept queue we are on before we potentially lose the
361 * last reference to avoid races against a re-reference from
362 * someone operating on the queue.
364 while ((head = so->so_head) != NULL) {
365 lwkt_getpooltoken(head);
366 if (so->so_head == head)
368 lwkt_relpooltoken(head);
372 * Arbitrage the last free.
374 KKASSERT(so->so_refs > 0);
375 if (atomic_fetchadd_int(&so->so_refs, -1) != 1) {
377 lwkt_relpooltoken(head);
381 KKASSERT(so->so_pcb == NULL && (so->so_state & SS_NOFDREF));
382 KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
385 * We're done, remove ourselves from the accept queue we are
386 * on, if we are on one.
389 if (so->so_state & SS_INCOMP) {
390 TAILQ_REMOVE(&head->so_incomp, so, so_list);
392 } else if (so->so_state & SS_COMP) {
394 * We must not decommission a socket that's
395 * on the accept(2) queue. If we do, then
396 * accept(2) may hang after select(2) indicated
397 * that the listening socket was ready.
399 lwkt_relpooltoken(head);
402 panic("sofree: not queued");
404 soclrstate(so, SS_INCOMP);
406 lwkt_relpooltoken(head);
408 ssb_release(&so->so_snd, so);
414 * Close a socket on last file table reference removal.
415 * Initiate disconnect if connected.
416 * Free socket when disconnect complete.
419 soclose(struct socket *so, int fflag)
423 funsetown(&so->so_sigio);
424 sosetstate(so, SS_ISCLOSING);
425 if (!use_soclose_fast ||
426 (so->so_proto->pr_flags & PR_SYNC_PORT) ||
427 ((so->so_state & SS_ISCONNECTED) &&
428 (so->so_options & SO_LINGER))) {
429 error = soclose_sync(so, fflag);
438 sodiscard(struct socket *so)
440 lwkt_getpooltoken(so);
441 if (so->so_options & SO_ACCEPTCONN) {
444 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
445 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
446 soclrstate(sp, SS_INCOMP);
451 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
452 TAILQ_REMOVE(&so->so_comp, sp, so_list);
453 soclrstate(sp, SS_COMP);
459 lwkt_relpooltoken(so);
461 if (so->so_state & SS_NOFDREF)
462 panic("soclose: NOFDREF");
463 sosetstate(so, SS_NOFDREF); /* take ref */
467 soinherit(struct socket *so, struct socket *so_inh)
469 TAILQ_HEAD(, socket) comp, incomp;
473 KASSERT(so->so_options & SO_ACCEPTCONN,
474 ("so does not accept connection"));
475 KASSERT(so_inh->so_options & SO_ACCEPTCONN,
476 ("so_inh does not accept connection"));
481 lwkt_getpooltoken(so);
482 lwkt_getpooltoken(so_inh);
485 * Save completed queue and incompleted queue
487 TAILQ_CONCAT(&comp, &so->so_comp, so_list);
491 TAILQ_CONCAT(&incomp, &so->so_incomp, so_list);
492 incqlen = so->so_incqlen;
496 * Append the saved completed queue and incompleted
497 * queue to the socket inherits them.
500 * This may temporarily break the inheriting socket's
503 TAILQ_FOREACH(sp, &comp, so_list) {
504 sp->so_head = so_inh;
506 sp->so_cred = crhold(so_inh->so_cred);
509 TAILQ_FOREACH(sp, &incomp, so_list) {
510 sp->so_head = so_inh;
512 sp->so_cred = crhold(so_inh->so_cred);
515 TAILQ_CONCAT(&so_inh->so_comp, &comp, so_list);
516 so_inh->so_qlen += qlen;
518 TAILQ_CONCAT(&so_inh->so_incomp, &incomp, so_list);
519 so_inh->so_incqlen += incqlen;
521 lwkt_relpooltoken(so_inh);
522 lwkt_relpooltoken(so);
526 * "New" connections have arrived
529 wakeup(&so_inh->so_timeo);
534 soclose_sync(struct socket *so, int fflag)
538 if (so->so_pcb == NULL)
540 if (so->so_state & SS_ISCONNECTED) {
541 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
542 error = sodisconnect(so);
546 if (so->so_options & SO_LINGER) {
547 if ((so->so_state & SS_ISDISCONNECTING) &&
550 while (so->so_state & SS_ISCONNECTED) {
551 error = tsleep(&so->so_timeo, PCATCH,
552 "soclos", so->so_linger * hz);
562 error2 = so_pru_detach(so);
563 if (error2 == EJUSTRETURN) {
565 * Protocol will call sodiscard()
566 * and sofree() for us.
575 so_pru_sync(so); /* unpend async sending */
576 sofree(so); /* dispose of ref */
582 soclose_sofree_async_handler(netmsg_t msg)
584 sofree(msg->base.nm_so);
588 soclose_sofree_async(struct socket *so)
590 struct netmsg_base *base = &so->so_clomsg;
592 netmsg_init(base, so, &netisr_apanic_rport, 0,
593 soclose_sofree_async_handler);
594 lwkt_sendmsg(so->so_port, &base->lmsg);
598 soclose_disconn_async_handler(netmsg_t msg)
600 struct socket *so = msg->base.nm_so;
602 if ((so->so_state & SS_ISCONNECTED) &&
603 (so->so_state & SS_ISDISCONNECTING) == 0)
604 so_pru_disconnect_direct(so);
609 error = so_pru_detach_direct(so);
610 if (error == EJUSTRETURN) {
612 * Protocol will call sodiscard()
613 * and sofree() for us.
624 soclose_disconn_async(struct socket *so)
626 struct netmsg_base *base = &so->so_clomsg;
628 netmsg_init(base, so, &netisr_apanic_rport, 0,
629 soclose_disconn_async_handler);
630 lwkt_sendmsg(so->so_port, &base->lmsg);
634 soclose_detach_async_handler(netmsg_t msg)
636 struct socket *so = msg->base.nm_so;
641 error = so_pru_detach_direct(so);
642 if (error == EJUSTRETURN) {
644 * Protocol will call sodiscard()
645 * and sofree() for us.
656 soclose_detach_async(struct socket *so)
658 struct netmsg_base *base = &so->so_clomsg;
660 netmsg_init(base, so, &netisr_apanic_rport, 0,
661 soclose_detach_async_handler);
662 lwkt_sendmsg(so->so_port, &base->lmsg);
666 soclose_fast(struct socket *so)
668 if (so->so_pcb == NULL)
671 if ((so->so_state & SS_ISCONNECTED) &&
672 (so->so_state & SS_ISDISCONNECTING) == 0) {
673 soclose_disconn_async(so);
678 soclose_detach_async(so);
684 soclose_sofree_async(so);
688 * Abort and destroy a socket. Only one abort can be in progress
689 * at any given moment.
692 soabort(struct socket *so)
699 soabort_async(struct socket *so)
702 so_pru_abort_async(so);
706 soabort_oncpu(struct socket *so)
709 so_pru_abort_direct(so);
713 * so is passed in ref'd, which becomes owned by
714 * the cleared SS_NOFDREF flag.
717 soaccept_generic(struct socket *so)
719 if ((so->so_state & SS_NOFDREF) == 0)
720 panic("soaccept: !NOFDREF");
721 soclrstate(so, SS_NOFDREF); /* owned by lack of SS_NOFDREF */
725 soaccept(struct socket *so, struct sockaddr **nam)
729 soaccept_generic(so);
730 error = so_pru_accept(so, nam);
735 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td,
740 if (so->so_options & SO_ACCEPTCONN)
743 * If protocol is connection-based, can only connect once.
744 * Otherwise, if connected, try to disconnect first.
745 * This allows user to disconnect by connecting to, e.g.,
748 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
749 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
750 (error = sodisconnect(so)))) {
754 * Prevent accumulated error from previous connection
758 if (!sync && so->so_proto->pr_usrreqs->pru_preconnect)
759 error = so_pru_connect_async(so, nam, td);
761 error = so_pru_connect(so, nam, td);
767 soconnect2(struct socket *so1, struct socket *so2)
771 error = so_pru_connect2(so1, so2);
776 sodisconnect(struct socket *so)
780 if ((so->so_state & SS_ISCONNECTED) == 0) {
784 if (so->so_state & SS_ISDISCONNECTING) {
788 error = so_pru_disconnect(so);
793 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
796 * If send must go all at once and message is larger than
797 * send buffering, then hard error.
798 * Lock against other senders.
799 * If must go all at once and not enough room now, then
800 * inform user that this would block and do nothing.
801 * Otherwise, if nonblocking, send as much as possible.
802 * The data to be sent is described by "uio" if nonzero,
803 * otherwise by the mbuf chain "top" (which must be null
804 * if uio is not). Data provided in mbuf chain must be small
805 * enough to send all at once.
807 * Returns nonzero on error, timeout or signal; callers
808 * must check for short counts if EINTR/ERESTART are returned.
809 * Data and control buffers are freed on return.
812 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
813 struct mbuf *top, struct mbuf *control, int flags,
820 int clen = 0, error, dontroute, mlen;
821 int atomic = sosendallatonce(so) || top;
825 resid = uio->uio_resid;
827 resid = (size_t)top->m_pkthdr.len;
830 for (m = top; m; m = m->m_next)
832 KKASSERT(top->m_pkthdr.len == len);
837 * WARNING! resid is unsigned, space and len are signed. space
838 * can wind up negative if the sockbuf is overcommitted.
840 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
841 * type sockets since that's an error.
843 if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
849 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
850 (so->so_proto->pr_flags & PR_ATOMIC);
851 if (td->td_lwp != NULL)
852 td->td_lwp->lwp_ru.ru_msgsnd++;
854 clen = control->m_len;
855 #define gotoerr(errcode) { error = errcode; goto release; }
858 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
863 if (so->so_state & SS_CANTSENDMORE)
866 error = so->so_error;
870 if ((so->so_state & SS_ISCONNECTED) == 0) {
872 * `sendto' and `sendmsg' is allowed on a connection-
873 * based socket if it supports implied connect.
874 * Return ENOTCONN if not connected and no address is
877 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
878 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
879 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
880 !(resid == 0 && clen != 0))
882 } else if (addr == NULL)
883 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
884 ENOTCONN : EDESTADDRREQ);
886 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
887 clen > so->so_snd.ssb_hiwat) {
890 space = ssb_space(&so->so_snd);
893 if ((space < 0 || (size_t)space < resid + clen) && uio &&
894 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
895 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
896 gotoerr(EWOULDBLOCK);
897 ssb_unlock(&so->so_snd);
898 error = ssb_wait(&so->so_snd);
908 * Data is prepackaged in "top".
912 top->m_flags |= M_EOR;
916 m = m_getl((int)resid, MB_WAIT, MT_DATA,
917 top == NULL ? M_PKTHDR : 0, &mlen);
920 m->m_pkthdr.rcvif = NULL;
922 len = imin((int)szmin(mlen, resid), space);
923 if (resid < MINCLSIZE) {
925 * For datagram protocols, leave room
926 * for protocol headers in first mbuf.
928 if (atomic && top == NULL && len < mlen)
932 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
933 resid = uio->uio_resid;
936 top->m_pkthdr.len += len;
942 top->m_flags |= M_EOR;
945 } while (space > 0 && atomic);
947 so->so_options |= SO_DONTROUTE;
948 if (flags & MSG_OOB) {
949 pru_flags = PRUS_OOB;
950 } else if ((flags & MSG_EOF) &&
951 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
954 * If the user set MSG_EOF, the protocol
955 * understands this flag and nothing left to
956 * send then use PRU_SEND_EOF instead of PRU_SEND.
958 pru_flags = PRUS_EOF;
959 } else if (resid > 0 && space > 0) {
960 /* If there is more to send, set PRUS_MORETOCOME */
961 pru_flags = PRUS_MORETOCOME;
966 * XXX all the SS_CANTSENDMORE checks previously
967 * done could be out of date. We could have recieved
968 * a reset packet in an interrupt or maybe we slept
969 * while doing page faults in uiomove() etc. We could
970 * probably recheck again inside the splnet() protection
971 * here, but there are probably other places that this
972 * also happens. We must rethink this.
974 error = so_pru_send(so, pru_flags, top, addr, control, td);
976 so->so_options &= ~SO_DONTROUTE;
983 } while (resid && space > 0);
987 ssb_unlock(&so->so_snd);
998 * A specialization of sosend() for UDP based on protocol-specific knowledge:
999 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
1000 * sosendallatonce() returns true,
1001 * the "atomic" variable is true,
1002 * and sosendudp() blocks until space is available for the entire send.
1003 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
1004 * PR_IMPLOPCL flags set.
1005 * UDP has no out-of-band data.
1006 * UDP has no control data.
1007 * UDP does not support MSG_EOR.
1010 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1011 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1014 int error, pru_flags = 0;
1017 if (td->td_lwp != NULL)
1018 td->td_lwp->lwp_ru.ru_msgsnd++;
1022 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
1023 resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
1026 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1030 if (so->so_state & SS_CANTSENDMORE)
1033 error = so->so_error;
1037 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
1038 gotoerr(EDESTADDRREQ);
1039 if (resid > so->so_snd.ssb_hiwat)
1041 space = ssb_space(&so->so_snd);
1042 if (uio && (space < 0 || (size_t)space < resid)) {
1043 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1044 gotoerr(EWOULDBLOCK);
1045 ssb_unlock(&so->so_snd);
1046 error = ssb_wait(&so->so_snd);
1053 int hdrlen = max_hdr;
1056 * We try to optimize out the additional mbuf
1057 * allocations in M_PREPEND() on output path, e.g.
1058 * - udp_output(), when it tries to prepend protocol
1060 * - Link layer output function, when it tries to
1061 * prepend link layer header.
1063 * This probably will not benefit any data that will
1064 * be fragmented, so this optimization is only performed
1065 * when the size of data and max size of protocol+link
1066 * headers fit into one mbuf cluster.
1068 if (uio->uio_resid > MCLBYTES - hdrlen ||
1069 !udp_sosend_prepend) {
1070 top = m_uiomove(uio);
1076 top = m_getl(uio->uio_resid + hdrlen, MB_WAIT,
1077 MT_DATA, M_PKTHDR, &nsize);
1078 KASSERT(nsize >= uio->uio_resid + hdrlen,
1079 ("sosendudp invalid nsize %d, "
1080 "resid %zu, hdrlen %d",
1081 nsize, uio->uio_resid, hdrlen));
1083 top->m_len = uio->uio_resid;
1084 top->m_pkthdr.len = uio->uio_resid;
1085 top->m_data += hdrlen;
1087 error = uiomove(mtod(top, caddr_t), top->m_len, uio);
1093 if (flags & MSG_DONTROUTE)
1094 pru_flags |= PRUS_DONTROUTE;
1096 if (udp_sosend_async && (flags & MSG_SYNC) == 0) {
1097 so_pru_send_async(so, pru_flags, top, addr, NULL, td);
1100 error = so_pru_send(so, pru_flags, top, addr, NULL, td);
1102 top = NULL; /* sent or freed in lower layer */
1105 ssb_unlock(&so->so_snd);
1113 sosendtcp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1114 struct mbuf *top, struct mbuf *control, int flags,
1126 KKASSERT(top == NULL);
1128 resid = uio->uio_resid;
1131 resid = (size_t)top->m_pkthdr.len;
1134 for (m = top; m; m = m->m_next)
1136 KKASSERT(top->m_pkthdr.len == len);
1141 * WARNING! resid is unsigned, space and len are signed. space
1142 * can wind up negative if the sockbuf is overcommitted.
1144 * Also check to make sure that MSG_EOR isn't used on TCP
1146 if (flags & MSG_EOR) {
1152 /* TCP doesn't do control messages (rights, creds, etc) */
1153 if (control->m_len) {
1157 m_freem(control); /* empty control, just free it */
1161 if (td->td_lwp != NULL)
1162 td->td_lwp->lwp_ru.ru_msgsnd++;
1164 #define gotoerr(errcode) { error = errcode; goto release; }
1167 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1172 if (so->so_state & SS_CANTSENDMORE)
1175 error = so->so_error;
1179 if ((so->so_state & SS_ISCONNECTED) == 0 &&
1180 (so->so_state & SS_ISCONFIRMING) == 0)
1182 if (allatonce && resid > so->so_snd.ssb_hiwat)
1185 space = ssb_space_prealloc(&so->so_snd);
1186 if (flags & MSG_OOB)
1188 if ((space < 0 || (size_t)space < resid) && !allatonce &&
1189 space < so->so_snd.ssb_lowat) {
1190 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1191 gotoerr(EWOULDBLOCK);
1192 ssb_unlock(&so->so_snd);
1193 error = ssb_wait(&so->so_snd);
1200 int cnt = 0, async = 0;
1204 * Data is prepackaged in "top".
1208 if (resid > INT_MAX)
1210 if (tcp_sosend_jcluster) {
1211 m = m_getlj((int)resid, MB_WAIT, MT_DATA,
1212 top == NULL ? M_PKTHDR : 0, &mlen);
1214 m = m_getl((int)resid, MB_WAIT, MT_DATA,
1215 top == NULL ? M_PKTHDR : 0, &mlen);
1218 m->m_pkthdr.len = 0;
1219 m->m_pkthdr.rcvif = NULL;
1221 len = imin((int)szmin(mlen, resid), space);
1223 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
1224 resid = uio->uio_resid;
1227 top->m_pkthdr.len += len;
1234 } while (space > 0 && cnt < tcp_sosend_agglim);
1236 if (tcp_sosend_async)
1239 if (flags & MSG_OOB) {
1240 pru_flags = PRUS_OOB;
1242 } else if ((flags & MSG_EOF) && resid == 0) {
1243 pru_flags = PRUS_EOF;
1244 } else if (resid > 0 && space > 0) {
1245 /* If there is more to send, set PRUS_MORETOCOME */
1246 pru_flags = PRUS_MORETOCOME;
1252 if (flags & MSG_SYNC)
1256 * XXX all the SS_CANTSENDMORE checks previously
1257 * done could be out of date. We could have recieved
1258 * a reset packet in an interrupt or maybe we slept
1259 * while doing page faults in uiomove() etc. We could
1260 * probably recheck again inside the splnet() protection
1261 * here, but there are probably other places that this
1262 * also happens. We must rethink this.
1264 for (m = top; m; m = m->m_next)
1265 ssb_preallocstream(&so->so_snd, m);
1267 error = so_pru_send(so, pru_flags, top,
1270 so_pru_send_async(so, pru_flags, top,
1279 } while (resid && space > 0);
1283 ssb_unlock(&so->so_snd);
1294 * Implement receive operations on a socket.
1296 * We depend on the way that records are added to the signalsockbuf
1297 * by sbappend*. In particular, each record (mbufs linked through m_next)
1298 * must begin with an address if the protocol so specifies,
1299 * followed by an optional mbuf or mbufs containing ancillary data,
1300 * and then zero or more mbufs of data.
1302 * Although the signalsockbuf is locked, new data may still be appended.
1303 * A token inside the ssb_lock deals with MP issues and still allows
1304 * the network to access the socket if we block in a uio.
1306 * The caller may receive the data as a single mbuf chain by supplying
1307 * an mbuf **mp0 for use in returning the chain. The uio is then used
1308 * only for the count in uio_resid.
1311 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1312 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1315 struct mbuf *free_chain = NULL;
1316 int flags, len, error, offset;
1317 struct protosw *pr = so->so_proto;
1319 size_t resid, orig_resid;
1322 resid = uio->uio_resid;
1324 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1332 flags = *flagsp &~ MSG_EOR;
1335 if (flags & MSG_OOB) {
1336 m = m_get(MB_WAIT, MT_DATA);
1339 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1345 KKASSERT(resid >= (size_t)m->m_len);
1346 resid -= (size_t)m->m_len;
1347 } while (resid > 0 && m);
1350 uio->uio_resid = resid;
1351 error = uiomove(mtod(m, caddr_t),
1352 (int)szmin(resid, m->m_len),
1354 resid = uio->uio_resid;
1356 } while (uio->uio_resid && error == 0 && m);
1363 if ((so->so_state & SS_ISCONFIRMING) && resid)
1367 * The token interlocks against the protocol thread while
1368 * ssb_lock is a blocking lock against other userland entities.
1370 lwkt_gettoken(&so->so_rcv.ssb_token);
1372 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1376 m = so->so_rcv.ssb_mb;
1378 * If we have less data than requested, block awaiting more
1379 * (subject to any timeout) if:
1380 * 1. the current count is less than the low water mark, or
1381 * 2. MSG_WAITALL is set, and it is possible to do the entire
1382 * receive operation at once if we block (resid <= hiwat).
1383 * 3. MSG_DONTWAIT is not set
1384 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1385 * we have to do the receive in sections, and thus risk returning
1386 * a short count if a timeout or signal occurs after we start.
1388 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1389 (size_t)so->so_rcv.ssb_cc < resid) &&
1390 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1391 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
1392 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1393 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1397 error = so->so_error;
1398 if ((flags & MSG_PEEK) == 0)
1402 if (so->so_state & SS_CANTRCVMORE) {
1408 for (; m; m = m->m_next) {
1409 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1410 m = so->so_rcv.ssb_mb;
1414 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1415 (pr->pr_flags & PR_CONNREQUIRED)) {
1421 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1422 error = EWOULDBLOCK;
1425 ssb_unlock(&so->so_rcv);
1426 error = ssb_wait(&so->so_rcv);
1432 if (uio && uio->uio_td && uio->uio_td->td_proc)
1433 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1436 * note: m should be == sb_mb here. Cache the next record while
1437 * cleaning up. Note that calling m_free*() will break out critical
1440 KKASSERT(m == so->so_rcv.ssb_mb);
1443 * Skip any address mbufs prepending the record.
1445 if (pr->pr_flags & PR_ADDR) {
1446 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
1449 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1450 if (flags & MSG_PEEK)
1453 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1457 * Skip any control mbufs prepending the record.
1460 if (pr->pr_flags & PR_ADDR_OPT) {
1462 * For SCTP we may be getting a
1463 * whole message OR a partial delivery.
1465 if (m && m->m_type == MT_SONAME) {
1468 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1469 if (flags & MSG_PEEK)
1472 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1476 while (m && m->m_type == MT_CONTROL && error == 0) {
1477 if (flags & MSG_PEEK) {
1479 *controlp = m_copy(m, 0, m->m_len);
1480 m = m->m_next; /* XXX race */
1483 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1484 if (pr->pr_domain->dom_externalize &&
1485 mtod(m, struct cmsghdr *)->cmsg_type ==
1487 error = (*pr->pr_domain->dom_externalize)(m);
1491 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1494 if (controlp && *controlp) {
1496 controlp = &(*controlp)->m_next;
1505 if (type == MT_OOBDATA)
1510 * Copy to the UIO or mbuf return chain (*mp).
1514 while (m && resid > 0 && error == 0) {
1515 if (m->m_type == MT_OOBDATA) {
1516 if (type != MT_OOBDATA)
1518 } else if (type == MT_OOBDATA)
1521 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1523 soclrstate(so, SS_RCVATMARK);
1524 len = (resid > INT_MAX) ? INT_MAX : resid;
1525 if (so->so_oobmark && len > so->so_oobmark - offset)
1526 len = so->so_oobmark - offset;
1527 if (len > m->m_len - moff)
1528 len = m->m_len - moff;
1531 * Copy out to the UIO or pass the mbufs back to the SIO.
1532 * The SIO is dealt with when we eat the mbuf, but deal
1533 * with the resid here either way.
1536 uio->uio_resid = resid;
1537 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1538 resid = uio->uio_resid;
1542 resid -= (size_t)len;
1546 * Eat the entire mbuf or just a piece of it
1548 if (len == m->m_len - moff) {
1549 if (m->m_flags & M_EOR)
1552 if (m->m_flags & M_NOTIFICATION)
1553 flags |= MSG_NOTIFICATION;
1555 if (flags & MSG_PEEK) {
1560 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1564 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1568 if (flags & MSG_PEEK) {
1572 n = m_copym(m, 0, len, MB_WAIT);
1578 so->so_rcv.ssb_cc -= len;
1581 if (so->so_oobmark) {
1582 if ((flags & MSG_PEEK) == 0) {
1583 so->so_oobmark -= len;
1584 if (so->so_oobmark == 0) {
1585 sosetstate(so, SS_RCVATMARK);
1590 if (offset == so->so_oobmark)
1594 if (flags & MSG_EOR)
1597 * If the MSG_WAITALL flag is set (for non-atomic socket),
1598 * we must not quit until resid == 0 or an error
1599 * termination. If a signal/timeout occurs, return
1600 * with a short count but without error.
1601 * Keep signalsockbuf locked against other readers.
1603 while ((flags & MSG_WAITALL) && m == NULL &&
1604 resid > 0 && !sosendallatonce(so) &&
1605 so->so_rcv.ssb_mb == NULL) {
1606 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1609 * The window might have closed to zero, make
1610 * sure we send an ack now that we've drained
1611 * the buffer or we might end up blocking until
1612 * the idle takes over (5 seconds).
1614 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1615 so_pru_rcvd(so, flags);
1616 error = ssb_wait(&so->so_rcv);
1618 ssb_unlock(&so->so_rcv);
1622 m = so->so_rcv.ssb_mb;
1627 * If an atomic read was requested but unread data still remains
1628 * in the record, set MSG_TRUNC.
1630 if (m && pr->pr_flags & PR_ATOMIC)
1634 * Cleanup. If an atomic read was requested drop any unread data.
1636 if ((flags & MSG_PEEK) == 0) {
1637 if (m && (pr->pr_flags & PR_ATOMIC))
1638 sbdroprecord(&so->so_rcv.sb);
1639 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1640 so_pru_rcvd(so, flags);
1643 if (orig_resid == resid && orig_resid &&
1644 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1645 ssb_unlock(&so->so_rcv);
1652 ssb_unlock(&so->so_rcv);
1654 lwkt_reltoken(&so->so_rcv.ssb_token);
1656 m_freem(free_chain);
1661 sorecvtcp(struct socket *so, struct sockaddr **psa, struct uio *uio,
1662 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1665 struct mbuf *free_chain = NULL;
1666 int flags, len, error, offset;
1667 struct protosw *pr = so->so_proto;
1670 size_t resid, orig_resid, restmp;
1673 resid = uio->uio_resid;
1675 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1683 flags = *flagsp &~ MSG_EOR;
1686 if (flags & MSG_OOB) {
1687 m = m_get(MB_WAIT, MT_DATA);
1690 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1696 KKASSERT(resid >= (size_t)m->m_len);
1697 resid -= (size_t)m->m_len;
1698 } while (resid > 0 && m);
1701 uio->uio_resid = resid;
1702 error = uiomove(mtod(m, caddr_t),
1703 (int)szmin(resid, m->m_len),
1705 resid = uio->uio_resid;
1707 } while (uio->uio_resid && error == 0 && m);
1716 * The token interlocks against the protocol thread while
1717 * ssb_lock is a blocking lock against other userland entities.
1719 * Lock a limited number of mbufs (not all, so sbcompress() still
1720 * works well). The token is used as an interlock for sbwait() so
1721 * release it afterwords.
1724 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1728 lwkt_gettoken(&so->so_rcv.ssb_token);
1729 m = so->so_rcv.ssb_mb;
1732 * If we have less data than requested, block awaiting more
1733 * (subject to any timeout) if:
1734 * 1. the current count is less than the low water mark, or
1735 * 2. MSG_WAITALL is set, and it is possible to do the entire
1736 * receive operation at once if we block (resid <= hiwat).
1737 * 3. MSG_DONTWAIT is not set
1738 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1739 * we have to do the receive in sections, and thus risk returning
1740 * a short count if a timeout or signal occurs after we start.
1742 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1743 (size_t)so->so_rcv.ssb_cc < resid) &&
1744 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1745 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)))) {
1746 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1750 lwkt_reltoken(&so->so_rcv.ssb_token);
1751 error = so->so_error;
1752 if ((flags & MSG_PEEK) == 0)
1756 if (so->so_state & SS_CANTRCVMORE) {
1759 lwkt_reltoken(&so->so_rcv.ssb_token);
1762 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1763 (pr->pr_flags & PR_CONNREQUIRED)) {
1764 lwkt_reltoken(&so->so_rcv.ssb_token);
1769 lwkt_reltoken(&so->so_rcv.ssb_token);
1772 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1773 lwkt_reltoken(&so->so_rcv.ssb_token);
1774 error = EWOULDBLOCK;
1777 ssb_unlock(&so->so_rcv);
1778 error = ssb_wait(&so->so_rcv);
1779 lwkt_reltoken(&so->so_rcv.ssb_token);
1791 while (n && restmp < resid) {
1792 n->m_flags |= M_SOLOCKED;
1794 if (n->m_next == NULL)
1801 * Release token for loop
1803 lwkt_reltoken(&so->so_rcv.ssb_token);
1804 if (uio && uio->uio_td && uio->uio_td->td_proc)
1805 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1808 * note: m should be == sb_mb here. Cache the next record while
1809 * cleaning up. Note that calling m_free*() will break out critical
1812 KKASSERT(m == so->so_rcv.ssb_mb);
1815 * Copy to the UIO or mbuf return chain (*mp).
1817 * NOTE: Token is not held for loop
1823 while (m && (m->m_flags & M_SOLOCKED) && resid > 0 && error == 0) {
1824 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1827 soclrstate(so, SS_RCVATMARK);
1828 len = (resid > INT_MAX) ? INT_MAX : resid;
1829 if (so->so_oobmark && len > so->so_oobmark - offset)
1830 len = so->so_oobmark - offset;
1831 if (len > m->m_len - moff)
1832 len = m->m_len - moff;
1835 * Copy out to the UIO or pass the mbufs back to the SIO.
1836 * The SIO is dealt with when we eat the mbuf, but deal
1837 * with the resid here either way.
1840 uio->uio_resid = resid;
1841 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1842 resid = uio->uio_resid;
1846 resid -= (size_t)len;
1850 * Eat the entire mbuf or just a piece of it
1853 if (len == m->m_len - moff) {
1863 if (so->so_oobmark && offset == so->so_oobmark) {
1870 * Synchronize sockbuf with data we read.
1872 * NOTE: (m) is junk on entry (it could be left over from the
1875 if ((flags & MSG_PEEK) == 0) {
1876 lwkt_gettoken(&so->so_rcv.ssb_token);
1877 m = so->so_rcv.ssb_mb;
1878 while (m && offset >= m->m_len) {
1879 if (so->so_oobmark) {
1880 so->so_oobmark -= m->m_len;
1881 if (so->so_oobmark == 0) {
1882 sosetstate(so, SS_RCVATMARK);
1888 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1892 m = sbunlinkmbuf(&so->so_rcv.sb,
1899 n = m_copym(m, 0, offset, MB_WAIT);
1903 m->m_data += offset;
1905 so->so_rcv.ssb_cc -= offset;
1906 if (so->so_oobmark) {
1907 so->so_oobmark -= offset;
1908 if (so->so_oobmark == 0) {
1909 sosetstate(so, SS_RCVATMARK);
1915 lwkt_reltoken(&so->so_rcv.ssb_token);
1919 * If the MSG_WAITALL flag is set (for non-atomic socket),
1920 * we must not quit until resid == 0 or an error termination.
1922 * If a signal/timeout occurs, return with a short count but without
1925 * Keep signalsockbuf locked against other readers.
1927 * XXX if MSG_PEEK we currently do quit.
1929 if ((flags & MSG_WAITALL) && !(flags & MSG_PEEK) &&
1930 didoob == 0 && resid > 0 &&
1931 !sosendallatonce(so)) {
1932 lwkt_gettoken(&so->so_rcv.ssb_token);
1934 while ((m = so->so_rcv.ssb_mb) == NULL) {
1935 if (so->so_error || (so->so_state & SS_CANTRCVMORE)) {
1936 error = so->so_error;
1940 * The window might have closed to zero, make
1941 * sure we send an ack now that we've drained
1942 * the buffer or we might end up blocking until
1943 * the idle takes over (5 seconds).
1946 so_pru_rcvd_async(so);
1947 if (so->so_rcv.ssb_mb == NULL)
1948 error = ssb_wait(&so->so_rcv);
1950 lwkt_reltoken(&so->so_rcv.ssb_token);
1951 ssb_unlock(&so->so_rcv);
1956 if (m && error == 0)
1958 lwkt_reltoken(&so->so_rcv.ssb_token);
1962 * Token not held here.
1964 * Cleanup. If an atomic read was requested drop any unread data XXX
1966 if ((flags & MSG_PEEK) == 0) {
1968 so_pru_rcvd_async(so);
1971 if (orig_resid == resid && orig_resid &&
1972 (so->so_state & SS_CANTRCVMORE) == 0) {
1973 ssb_unlock(&so->so_rcv);
1980 ssb_unlock(&so->so_rcv);
1983 m_freem(free_chain);
1988 * Shut a socket down. Note that we do not get a frontend lock as we
1989 * want to be able to shut the socket down even if another thread is
1990 * blocked in a read(), thus waking it up.
1993 soshutdown(struct socket *so, int how)
1995 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1998 if (how != SHUT_WR) {
1999 /*ssb_lock(&so->so_rcv, M_WAITOK);*/
2001 /*ssb_unlock(&so->so_rcv);*/
2004 return (so_pru_shutdown(so));
2009 sorflush(struct socket *so)
2011 struct signalsockbuf *ssb = &so->so_rcv;
2012 struct protosw *pr = so->so_proto;
2013 struct signalsockbuf asb;
2015 atomic_set_int(&ssb->ssb_flags, SSB_NOINTR);
2017 lwkt_gettoken(&ssb->ssb_token);
2022 * Can't just blow up the ssb structure here
2024 bzero(&ssb->sb, sizeof(ssb->sb));
2029 atomic_clear_int(&ssb->ssb_flags, SSB_CLEAR_MASK);
2031 if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose)
2032 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
2033 ssb_release(&asb, so);
2035 lwkt_reltoken(&ssb->ssb_token);
2040 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
2042 struct accept_filter_arg *afap = NULL;
2043 struct accept_filter *afp;
2044 struct so_accf *af = so->so_accf;
2047 /* do not set/remove accept filters on non listen sockets */
2048 if ((so->so_options & SO_ACCEPTCONN) == 0) {
2053 /* removing the filter */
2056 if (af->so_accept_filter != NULL &&
2057 af->so_accept_filter->accf_destroy != NULL) {
2058 af->so_accept_filter->accf_destroy(so);
2060 if (af->so_accept_filter_str != NULL) {
2061 kfree(af->so_accept_filter_str, M_ACCF);
2066 so->so_options &= ~SO_ACCEPTFILTER;
2069 /* adding a filter */
2070 /* must remove previous filter first */
2075 /* don't put large objects on the kernel stack */
2076 afap = kmalloc(sizeof(*afap), M_TEMP, M_WAITOK);
2077 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
2078 afap->af_name[sizeof(afap->af_name)-1] = '\0';
2079 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
2082 afp = accept_filt_get(afap->af_name);
2087 af = kmalloc(sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
2088 if (afp->accf_create != NULL) {
2089 if (afap->af_name[0] != '\0') {
2090 int len = strlen(afap->af_name) + 1;
2092 af->so_accept_filter_str = kmalloc(len, M_ACCF,
2094 strcpy(af->so_accept_filter_str, afap->af_name);
2096 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
2097 if (af->so_accept_filter_arg == NULL) {
2098 kfree(af->so_accept_filter_str, M_ACCF);
2105 af->so_accept_filter = afp;
2107 so->so_options |= SO_ACCEPTFILTER;
2110 kfree(afap, M_TEMP);
2116 * Perhaps this routine, and sooptcopyout(), below, ought to come in
2117 * an additional variant to handle the case where the option value needs
2118 * to be some kind of integer, but not a specific size.
2119 * In addition to their use here, these functions are also called by the
2120 * protocol-level pr_ctloutput() routines.
2123 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2125 return soopt_to_kbuf(sopt, buf, len, minlen);
2129 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2133 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2134 KKASSERT(kva_p(buf));
2137 * If the user gives us more than we wanted, we ignore it,
2138 * but if we don't get the minimum length the caller
2139 * wants, we return EINVAL. On success, sopt->sopt_valsize
2140 * is set to however much we actually retrieved.
2142 if ((valsize = sopt->sopt_valsize) < minlen)
2145 sopt->sopt_valsize = valsize = len;
2147 bcopy(sopt->sopt_val, buf, valsize);
2153 sosetopt(struct socket *so, struct sockopt *sopt)
2159 struct signalsockbuf *sotmp;
2162 sopt->sopt_dir = SOPT_SET;
2163 if (sopt->sopt_level != SOL_SOCKET) {
2164 if (so->so_proto && so->so_proto->pr_ctloutput) {
2165 return (so_pr_ctloutput(so, sopt));
2167 error = ENOPROTOOPT;
2169 switch (sopt->sopt_name) {
2171 case SO_ACCEPTFILTER:
2172 error = do_setopt_accept_filter(so, sopt);
2178 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2182 so->so_linger = l.l_linger;
2184 so->so_options |= SO_LINGER;
2186 so->so_options &= ~SO_LINGER;
2192 case SO_USELOOPBACK:
2199 error = sooptcopyin(sopt, &optval, sizeof optval,
2204 so->so_options |= sopt->sopt_name;
2206 so->so_options &= ~sopt->sopt_name;
2213 error = sooptcopyin(sopt, &optval, sizeof optval,
2219 * Values < 1 make no sense for any of these
2220 * options, so disallow them.
2227 switch (sopt->sopt_name) {
2230 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
2231 &so->so_snd : &so->so_rcv, (u_long)optval,
2233 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
2237 sotmp = (sopt->sopt_name == SO_SNDBUF) ?
2238 &so->so_snd : &so->so_rcv;
2239 atomic_clear_int(&sotmp->ssb_flags,
2244 * Make sure the low-water is never greater than
2248 so->so_snd.ssb_lowat =
2249 (optval > so->so_snd.ssb_hiwat) ?
2250 so->so_snd.ssb_hiwat : optval;
2251 atomic_clear_int(&so->so_snd.ssb_flags,
2255 so->so_rcv.ssb_lowat =
2256 (optval > so->so_rcv.ssb_hiwat) ?
2257 so->so_rcv.ssb_hiwat : optval;
2258 atomic_clear_int(&so->so_rcv.ssb_flags,
2266 error = sooptcopyin(sopt, &tv, sizeof tv,
2271 /* assert(hz > 0); */
2272 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2273 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2277 /* assert(tick > 0); */
2278 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2279 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
2280 if (val > INT_MAX) {
2284 if (val == 0 && tv.tv_usec != 0)
2287 switch (sopt->sopt_name) {
2289 so->so_snd.ssb_timeo = val;
2292 so->so_rcv.ssb_timeo = val;
2297 error = ENOPROTOOPT;
2300 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
2301 (void) so_pr_ctloutput(so, sopt);
2308 /* Helper routine for getsockopt */
2310 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2312 soopt_from_kbuf(sopt, buf, len);
2317 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
2322 sopt->sopt_valsize = 0;
2326 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2327 KKASSERT(kva_p(buf));
2330 * Documented get behavior is that we always return a value,
2331 * possibly truncated to fit in the user's buffer.
2332 * Traditional behavior is that we always tell the user
2333 * precisely how much we copied, rather than something useful
2334 * like the total amount we had available for her.
2335 * Note that this interface is not idempotent; the entire answer must
2336 * generated ahead of time.
2338 valsize = szmin(len, sopt->sopt_valsize);
2339 sopt->sopt_valsize = valsize;
2340 if (sopt->sopt_val != 0) {
2341 bcopy(buf, sopt->sopt_val, valsize);
2346 sogetopt(struct socket *so, struct sockopt *sopt)
2353 struct accept_filter_arg *afap;
2357 sopt->sopt_dir = SOPT_GET;
2358 if (sopt->sopt_level != SOL_SOCKET) {
2359 if (so->so_proto && so->so_proto->pr_ctloutput) {
2360 return (so_pr_ctloutput(so, sopt));
2362 return (ENOPROTOOPT);
2364 switch (sopt->sopt_name) {
2366 case SO_ACCEPTFILTER:
2367 if ((so->so_options & SO_ACCEPTCONN) == 0)
2369 afap = kmalloc(sizeof(*afap), M_TEMP,
2371 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
2372 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
2373 if (so->so_accf->so_accept_filter_str != NULL)
2374 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
2376 error = sooptcopyout(sopt, afap, sizeof(*afap));
2377 kfree(afap, M_TEMP);
2382 l.l_onoff = so->so_options & SO_LINGER;
2383 l.l_linger = so->so_linger;
2384 error = sooptcopyout(sopt, &l, sizeof l);
2387 case SO_USELOOPBACK:
2397 optval = so->so_options & sopt->sopt_name;
2399 error = sooptcopyout(sopt, &optval, sizeof optval);
2403 optval = so->so_type;
2407 optval = so->so_error;
2412 optval = so->so_snd.ssb_hiwat;
2416 optval = so->so_rcv.ssb_hiwat;
2420 optval = so->so_snd.ssb_lowat;
2424 optval = so->so_rcv.ssb_lowat;
2429 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2430 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
2432 tv.tv_sec = optval / hz;
2433 tv.tv_usec = (optval % hz) * ustick;
2434 error = sooptcopyout(sopt, &tv, sizeof tv);
2438 optval_l = ssb_space(&so->so_snd);
2439 error = sooptcopyout(sopt, &optval_l, sizeof(optval_l));
2443 optval = -1; /* no hint */
2447 error = ENOPROTOOPT;
2450 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput)
2451 so_pr_ctloutput(so, sopt);
2456 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2458 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2460 struct mbuf *m, *m_prev;
2461 int sopt_size = sopt->sopt_valsize, msize;
2463 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
2467 m->m_len = min(msize, sopt_size);
2468 sopt_size -= m->m_len;
2472 while (sopt_size > 0) {
2473 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
2474 MT_DATA, 0, &msize);
2479 m->m_len = min(msize, sopt_size);
2480 sopt_size -= m->m_len;
2487 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2489 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2491 soopt_to_mbuf(sopt, m);
2496 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
2501 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2503 if (sopt->sopt_val == NULL)
2505 val = sopt->sopt_val;
2506 valsize = sopt->sopt_valsize;
2507 while (m != NULL && valsize >= m->m_len) {
2508 bcopy(val, mtod(m, char *), m->m_len);
2509 valsize -= m->m_len;
2510 val = (caddr_t)val + m->m_len;
2513 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2514 panic("ip6_sooptmcopyin");
2517 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2519 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2521 return soopt_from_mbuf(sopt, m);
2525 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
2527 struct mbuf *m0 = m;
2532 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2534 if (sopt->sopt_val == NULL)
2536 val = sopt->sopt_val;
2537 maxsize = sopt->sopt_valsize;
2538 while (m != NULL && maxsize >= m->m_len) {
2539 bcopy(mtod(m, char *), val, m->m_len);
2540 maxsize -= m->m_len;
2541 val = (caddr_t)val + m->m_len;
2542 valsize += m->m_len;
2546 /* enough soopt buffer should be given from user-land */
2550 sopt->sopt_valsize = valsize;
2555 sohasoutofband(struct socket *so)
2557 if (so->so_sigio != NULL)
2558 pgsigio(so->so_sigio, SIGURG, 0);
2559 KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
2563 sokqfilter(struct file *fp, struct knote *kn)
2565 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2566 struct signalsockbuf *ssb;
2568 switch (kn->kn_filter) {
2570 if (so->so_options & SO_ACCEPTCONN)
2571 kn->kn_fop = &solisten_filtops;
2573 kn->kn_fop = &soread_filtops;
2577 kn->kn_fop = &sowrite_filtops;
2581 kn->kn_fop = &soexcept_filtops;
2585 return (EOPNOTSUPP);
2588 knote_insert(&ssb->ssb_kq.ki_note, kn);
2589 atomic_set_int(&ssb->ssb_flags, SSB_KNOTE);
2594 filt_sordetach(struct knote *kn)
2596 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2598 knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
2599 if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
2600 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_KNOTE);
2605 filt_soread(struct knote *kn, long hint)
2607 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2609 if (kn->kn_sfflags & NOTE_OOB) {
2610 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
2611 kn->kn_fflags |= NOTE_OOB;
2616 kn->kn_data = so->so_rcv.ssb_cc;
2618 if (so->so_state & SS_CANTRCVMORE) {
2620 * Only set NODATA if all data has been exhausted.
2622 if (kn->kn_data == 0)
2623 kn->kn_flags |= EV_NODATA;
2624 kn->kn_flags |= EV_EOF;
2625 kn->kn_fflags = so->so_error;
2628 if (so->so_error) /* temporary udp error */
2630 if (kn->kn_sfflags & NOTE_LOWAT)
2631 return (kn->kn_data >= kn->kn_sdata);
2632 return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
2633 !TAILQ_EMPTY(&so->so_comp));
2637 filt_sowdetach(struct knote *kn)
2639 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2641 knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
2642 if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
2643 atomic_clear_int(&so->so_snd.ssb_flags, SSB_KNOTE);
2648 filt_sowrite(struct knote *kn, long hint)
2650 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2652 kn->kn_data = ssb_space(&so->so_snd);
2653 if (so->so_state & SS_CANTSENDMORE) {
2654 kn->kn_flags |= (EV_EOF | EV_NODATA);
2655 kn->kn_fflags = so->so_error;
2658 if (so->so_error) /* temporary udp error */
2660 if (((so->so_state & SS_ISCONNECTED) == 0) &&
2661 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2663 if (kn->kn_sfflags & NOTE_LOWAT)
2664 return (kn->kn_data >= kn->kn_sdata);
2665 return (kn->kn_data >= so->so_snd.ssb_lowat);
2670 filt_solisten(struct knote *kn, long hint)
2672 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2674 kn->kn_data = so->so_qlen;
2675 return (! TAILQ_EMPTY(&so->so_comp));