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 $
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/fcntl.h>
71 #include <sys/malloc.h>
73 #include <sys/domain.h>
74 #include <sys/file.h> /* for struct knote */
75 #include <sys/kernel.h>
76 #include <sys/event.h>
78 #include <sys/protosw.h>
79 #include <sys/socket.h>
80 #include <sys/socketvar.h>
81 #include <sys/socketops.h>
82 #include <sys/resourcevar.h>
83 #include <sys/signalvar.h>
84 #include <sys/sysctl.h>
87 #include <vm/vm_zone.h>
89 #include <net/netmsg2.h>
90 #include <net/netisr2.h>
92 #include <sys/thread2.h>
93 #include <sys/socketvar2.h>
94 #include <sys/spinlock2.h>
96 #include <machine/limits.h>
99 extern int tcp_sosend_agglim;
100 extern int tcp_sosend_async;
101 extern int tcp_sosend_jcluster;
102 extern int udp_sosend_async;
103 extern int udp_sosend_prepend;
105 static int do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
108 static void filt_sordetach(struct knote *kn);
109 static int filt_soread(struct knote *kn, long hint);
110 static void filt_sowdetach(struct knote *kn);
111 static int filt_sowrite(struct knote *kn, long hint);
112 static int filt_solisten(struct knote *kn, long hint);
114 static int soclose_sync(struct socket *so, int fflag);
115 static void soclose_fast(struct socket *so);
117 static struct filterops solisten_filtops =
118 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_solisten };
119 static struct filterops soread_filtops =
120 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_soread };
121 static struct filterops sowrite_filtops =
122 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sowdetach, filt_sowrite };
123 static struct filterops soexcept_filtops =
124 { FILTEROP_ISFD|FILTEROP_MPSAFE, NULL, filt_sordetach, filt_soread };
126 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
127 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
128 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
131 static int somaxconn = SOMAXCONN;
132 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
133 &somaxconn, 0, "Maximum pending socket connection queue size");
135 static int use_soclose_fast = 1;
136 SYSCTL_INT(_kern_ipc, OID_AUTO, soclose_fast, CTLFLAG_RW,
137 &use_soclose_fast, 0, "Fast socket close");
139 int use_soaccept_pred_fast = 1;
140 SYSCTL_INT(_kern_ipc, OID_AUTO, soaccept_pred_fast, CTLFLAG_RW,
141 &use_soaccept_pred_fast, 0, "Fast socket accept predication");
143 int use_sendfile_async = 1;
144 SYSCTL_INT(_kern_ipc, OID_AUTO, sendfile_async, CTLFLAG_RW,
145 &use_sendfile_async, 0, "sendfile uses asynchronized pru_send");
147 int use_soconnect_async = 1;
148 SYSCTL_INT(_kern_ipc, OID_AUTO, soconnect_async, CTLFLAG_RW,
149 &use_soconnect_async, 0, "soconnect uses asynchronized pru_connect");
152 * Socket operation routines.
153 * These routines are called by the routines in
154 * sys_socket.c or from a system process, and
155 * implement the semantics of socket operations by
156 * switching out to the protocol specific routines.
160 * Get a socket structure, and initialize it.
161 * Note that it would probably be better to allocate socket
162 * and PCB at the same time, but I'm not convinced that all
163 * the protocols can be easily modified to do this.
166 soalloc(int waitok, struct protosw *pr)
171 waitmask = waitok ? M_WAITOK : M_NOWAIT;
172 so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
174 /* XXX race condition for reentrant kernel */
176 TAILQ_INIT(&so->so_aiojobq);
177 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
178 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
179 lwkt_token_init(&so->so_rcv.ssb_token, "rcvtok");
180 lwkt_token_init(&so->so_snd.ssb_token, "sndtok");
181 spin_init(&so->so_rcvd_spin, "soalloc");
182 netmsg_init(&so->so_rcvd_msg.base, so, &netisr_adone_rport,
183 MSGF_DROPABLE | MSGF_PRIORITY,
184 so->so_proto->pr_usrreqs->pru_rcvd);
185 so->so_rcvd_msg.nm_pru_flags |= PRUR_ASYNC;
186 so->so_state = SS_NOFDREF;
193 socreate(int dom, struct socket **aso, int type,
194 int proto, struct thread *td)
196 struct proc *p = td->td_proc;
199 struct pru_attach_info ai;
203 prp = pffindproto(dom, proto, type);
205 prp = pffindtype(dom, type);
207 if (prp == NULL || prp->pr_usrreqs->pru_attach == 0)
208 return (EPROTONOSUPPORT);
210 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
211 prp->pr_domain->dom_family != PF_LOCAL &&
212 prp->pr_domain->dom_family != PF_INET &&
213 prp->pr_domain->dom_family != PF_INET6 &&
214 prp->pr_domain->dom_family != PF_ROUTE) {
215 return (EPROTONOSUPPORT);
218 if (prp->pr_type != type)
220 so = soalloc(p != NULL, prp);
225 * Callers of socreate() presumably will connect up a descriptor
226 * and call soclose() if they cannot. This represents our so_refs
227 * (which should be 1) from soalloc().
229 soclrstate(so, SS_NOFDREF);
232 * Set a default port for protocol processing. No action will occur
233 * on the socket on this port until an inpcb is attached to it and
234 * is able to match incoming packets, or until the socket becomes
235 * available to userland.
237 * We normally default the socket to the protocol thread on cpu 0,
238 * if protocol does not provide its own method to initialize the
241 * If PR_SYNC_PORT is set (unix domain sockets) there is no protocol
242 * thread and all pr_*()/pru_*() calls are executed synchronously.
244 if (prp->pr_flags & PR_SYNC_PORT)
245 so->so_port = &netisr_sync_port;
246 else if (prp->pr_initport != NULL)
247 so->so_port = prp->pr_initport();
249 so->so_port = netisr_cpuport(0);
251 TAILQ_INIT(&so->so_incomp);
252 TAILQ_INIT(&so->so_comp);
254 so->so_cred = crhold(p->p_ucred);
255 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
256 ai.p_ucred = p->p_ucred;
257 ai.fd_rdir = p->p_fd->fd_rdir;
260 * Auto-sizing of socket buffers is managed by the protocols and
261 * the appropriate flags must be set in the pru_attach function.
263 error = so_pru_attach(so, proto, &ai);
265 sosetstate(so, SS_NOFDREF);
266 sofree(so); /* from soalloc */
271 * NOTE: Returns referenced socket.
278 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
282 error = so_pru_bind(so, nam, td);
287 sodealloc(struct socket *so)
289 KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) == 0);
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)
310 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))
313 lwkt_gettoken(&so->so_rcv.ssb_token);
314 if (TAILQ_EMPTY(&so->so_comp))
315 so->so_options |= SO_ACCEPTCONN;
316 lwkt_reltoken(&so->so_rcv.ssb_token);
317 if (backlog < 0 || backlog > somaxconn)
319 so->so_qlimit = backlog;
320 return so_pru_listen(so, td);
324 * Destroy a disconnected socket. This routine is a NOP if entities
325 * still have a reference on the socket:
327 * so_pcb - The protocol stack still has a reference
328 * SS_NOFDREF - There is no longer a file pointer reference
331 sofree(struct socket *so)
336 * This is a bit hackish at the moment. We need to interlock
337 * any accept queue we are on before we potentially lose the
338 * last reference to avoid races against a re-reference from
339 * someone operating on the queue.
341 while ((head = so->so_head) != NULL) {
342 lwkt_getpooltoken(head);
343 if (so->so_head == head)
345 lwkt_relpooltoken(head);
349 * Arbitrage the last free.
351 KKASSERT(so->so_refs > 0);
352 if (atomic_fetchadd_int(&so->so_refs, -1) != 1) {
354 lwkt_relpooltoken(head);
358 KKASSERT(so->so_pcb == NULL && (so->so_state & SS_NOFDREF));
359 KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
362 * We're done, remove ourselves from the accept queue we are
363 * on, if we are on one.
366 if (so->so_state & SS_INCOMP) {
367 KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) ==
369 TAILQ_REMOVE(&head->so_incomp, so, so_list);
371 } else if (so->so_state & SS_COMP) {
373 * We must not decommission a socket that's
374 * on the accept(2) queue. If we do, then
375 * accept(2) may hang after select(2) indicated
376 * that the listening socket was ready.
378 KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) ==
380 lwkt_relpooltoken(head);
383 panic("sofree: not queued");
385 soclrstate(so, SS_INCOMP);
387 lwkt_relpooltoken(head);
389 ssb_release(&so->so_snd, so);
395 * Close a socket on last file table reference removal.
396 * Initiate disconnect if connected.
397 * Free socket when disconnect complete.
400 soclose(struct socket *so, int fflag)
404 funsetown(&so->so_sigio);
405 sosetstate(so, SS_ISCLOSING);
406 if (!use_soclose_fast ||
407 (so->so_proto->pr_flags & PR_SYNC_PORT) ||
408 ((so->so_state & SS_ISCONNECTED) &&
409 (so->so_options & SO_LINGER))) {
410 error = soclose_sync(so, fflag);
419 sodiscard(struct socket *so)
421 lwkt_getpooltoken(so);
422 if (so->so_options & SO_ACCEPTCONN) {
425 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
426 KKASSERT((sp->so_state & (SS_INCOMP | SS_COMP)) ==
428 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
430 soclrstate(sp, SS_INCOMP);
431 soabort_async(sp, TRUE);
433 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
434 KKASSERT((sp->so_state & (SS_INCOMP | SS_COMP)) ==
436 TAILQ_REMOVE(&so->so_comp, sp, so_list);
438 soclrstate(sp, SS_COMP);
439 soabort_async(sp, TRUE);
442 lwkt_relpooltoken(so);
444 if (so->so_state & SS_NOFDREF)
445 panic("soclose: NOFDREF");
446 sosetstate(so, SS_NOFDREF); /* take ref */
450 * Append the completed queue of head to head_inh (inherting listen socket).
453 soinherit(struct socket *head, struct socket *head_inh)
455 boolean_t do_wakeup = FALSE;
457 KASSERT(head->so_options & SO_ACCEPTCONN,
458 ("head does not accept connection"));
459 KASSERT(head_inh->so_options & SO_ACCEPTCONN,
460 ("head_inh does not accept connection"));
462 lwkt_getpooltoken(head);
463 lwkt_getpooltoken(head_inh);
465 if (head->so_qlen > 0)
468 while (!TAILQ_EMPTY(&head->so_comp)) {
469 struct ucred *old_cr;
472 sp = TAILQ_FIRST(&head->so_comp);
473 KKASSERT((sp->so_state & (SS_INCOMP | SS_COMP)) == SS_COMP);
476 * Remove this socket from the current listen socket
479 TAILQ_REMOVE(&head->so_comp, sp, so_list);
482 /* Save the old ucred for later free. */
483 old_cr = sp->so_cred;
486 * Install this socket to the inheriting listen socket
489 sp->so_cred = crhold(head_inh->so_cred); /* non-blocking */
490 sp->so_head = head_inh;
492 TAILQ_INSERT_TAIL(&head_inh->so_comp, sp, so_list);
497 * crfree() may block and release the tokens temporarily.
498 * However, we are fine here, since the transition is done.
503 lwkt_relpooltoken(head_inh);
504 lwkt_relpooltoken(head);
508 * "New" connections have arrived
511 wakeup(&head_inh->so_timeo);
516 soclose_sync(struct socket *so, int fflag)
520 if (so->so_pcb == NULL)
522 if (so->so_state & SS_ISCONNECTED) {
523 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
524 error = sodisconnect(so);
528 if (so->so_options & SO_LINGER) {
529 if ((so->so_state & SS_ISDISCONNECTING) &&
532 while (so->so_state & SS_ISCONNECTED) {
533 error = tsleep(&so->so_timeo, PCATCH,
534 "soclos", so->so_linger * hz);
544 error2 = so_pru_detach(so);
545 if (error2 == EJUSTRETURN) {
547 * Protocol will call sodiscard()
548 * and sofree() for us.
557 so_pru_sync(so); /* unpend async sending */
558 sofree(so); /* dispose of ref */
564 soclose_sofree_async_handler(netmsg_t msg)
566 sofree(msg->base.nm_so);
570 soclose_sofree_async(struct socket *so)
572 struct netmsg_base *base = &so->so_clomsg;
574 netmsg_init(base, so, &netisr_apanic_rport, 0,
575 soclose_sofree_async_handler);
576 lwkt_sendmsg(so->so_port, &base->lmsg);
580 soclose_disconn_async_handler(netmsg_t msg)
582 struct socket *so = msg->base.nm_so;
584 if ((so->so_state & SS_ISCONNECTED) &&
585 (so->so_state & SS_ISDISCONNECTING) == 0)
586 so_pru_disconnect_direct(so);
591 error = so_pru_detach_direct(so);
592 if (error == EJUSTRETURN) {
594 * Protocol will call sodiscard()
595 * and sofree() for us.
606 soclose_disconn_async(struct socket *so)
608 struct netmsg_base *base = &so->so_clomsg;
610 netmsg_init(base, so, &netisr_apanic_rport, 0,
611 soclose_disconn_async_handler);
612 lwkt_sendmsg(so->so_port, &base->lmsg);
616 soclose_detach_async_handler(netmsg_t msg)
618 struct socket *so = msg->base.nm_so;
623 error = so_pru_detach_direct(so);
624 if (error == EJUSTRETURN) {
626 * Protocol will call sodiscard()
627 * and sofree() for us.
638 soclose_detach_async(struct socket *so)
640 struct netmsg_base *base = &so->so_clomsg;
642 netmsg_init(base, so, &netisr_apanic_rport, 0,
643 soclose_detach_async_handler);
644 lwkt_sendmsg(so->so_port, &base->lmsg);
648 soclose_fast(struct socket *so)
650 if (so->so_pcb == NULL)
653 if ((so->so_state & SS_ISCONNECTED) &&
654 (so->so_state & SS_ISDISCONNECTING) == 0) {
655 soclose_disconn_async(so);
660 soclose_detach_async(so);
666 soclose_sofree_async(so);
670 * Abort and destroy a socket. Only one abort can be in progress
671 * at any given moment.
674 soabort_async(struct socket *so, boolean_t clr_head)
677 * Keep a reference before clearing the so_head
678 * to avoid racing socket close in netisr.
683 so_pru_abort_async(so);
687 soabort_oncpu(struct socket *so)
690 so_pru_abort_direct(so);
694 * so is passed in ref'd, which becomes owned by
695 * the cleared SS_NOFDREF flag.
698 soaccept_generic(struct socket *so)
700 if ((so->so_state & SS_NOFDREF) == 0)
701 panic("soaccept: !NOFDREF");
702 soclrstate(so, SS_NOFDREF); /* owned by lack of SS_NOFDREF */
706 soaccept(struct socket *so, struct sockaddr **nam)
710 soaccept_generic(so);
711 error = so_pru_accept(so, nam);
716 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td,
721 if (so->so_options & SO_ACCEPTCONN)
724 * If protocol is connection-based, can only connect once.
725 * Otherwise, if connected, try to disconnect first.
726 * This allows user to disconnect by connecting to, e.g.,
729 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
730 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
731 (error = sodisconnect(so)))) {
735 * Prevent accumulated error from previous connection
739 if (!sync && so->so_proto->pr_usrreqs->pru_preconnect)
740 error = so_pru_connect_async(so, nam, td);
742 error = so_pru_connect(so, nam, td);
748 soconnect2(struct socket *so1, struct socket *so2)
752 error = so_pru_connect2(so1, so2);
757 sodisconnect(struct socket *so)
761 if ((so->so_state & SS_ISCONNECTED) == 0) {
765 if (so->so_state & SS_ISDISCONNECTING) {
769 error = so_pru_disconnect(so);
774 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
777 * If send must go all at once and message is larger than
778 * send buffering, then hard error.
779 * Lock against other senders.
780 * If must go all at once and not enough room now, then
781 * inform user that this would block and do nothing.
782 * Otherwise, if nonblocking, send as much as possible.
783 * The data to be sent is described by "uio" if nonzero,
784 * otherwise by the mbuf chain "top" (which must be null
785 * if uio is not). Data provided in mbuf chain must be small
786 * enough to send all at once.
788 * Returns nonzero on error, timeout or signal; callers
789 * must check for short counts if EINTR/ERESTART are returned.
790 * Data and control buffers are freed on return.
793 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
794 struct mbuf *top, struct mbuf *control, int flags,
801 int clen = 0, error, dontroute, mlen;
802 int atomic = sosendallatonce(so) || top;
806 resid = uio->uio_resid;
808 resid = (size_t)top->m_pkthdr.len;
811 for (m = top; m; m = m->m_next)
813 KKASSERT(top->m_pkthdr.len == len);
818 * WARNING! resid is unsigned, space and len are signed. space
819 * can wind up negative if the sockbuf is overcommitted.
821 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
822 * type sockets since that's an error.
824 if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
830 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
831 (so->so_proto->pr_flags & PR_ATOMIC);
832 if (td->td_lwp != NULL)
833 td->td_lwp->lwp_ru.ru_msgsnd++;
835 clen = control->m_len;
836 #define gotoerr(errcode) { error = errcode; goto release; }
839 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
844 if (so->so_state & SS_CANTSENDMORE)
847 error = so->so_error;
851 if ((so->so_state & SS_ISCONNECTED) == 0) {
853 * `sendto' and `sendmsg' is allowed on a connection-
854 * based socket if it supports implied connect.
855 * Return ENOTCONN if not connected and no address is
858 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
859 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
860 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
861 !(resid == 0 && clen != 0))
863 } else if (addr == NULL)
864 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
865 ENOTCONN : EDESTADDRREQ);
867 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
868 clen > so->so_snd.ssb_hiwat) {
871 space = ssb_space(&so->so_snd);
874 if ((space < 0 || (size_t)space < resid + clen) && uio &&
875 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
876 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
877 gotoerr(EWOULDBLOCK);
878 ssb_unlock(&so->so_snd);
879 error = ssb_wait(&so->so_snd);
889 * Data is prepackaged in "top".
893 top->m_flags |= M_EOR;
897 m = m_getl((int)resid, M_WAITOK, MT_DATA,
898 top == NULL ? M_PKTHDR : 0, &mlen);
901 m->m_pkthdr.rcvif = NULL;
903 len = imin((int)szmin(mlen, resid), space);
904 if (resid < MINCLSIZE) {
906 * For datagram protocols, leave room
907 * for protocol headers in first mbuf.
909 if (atomic && top == NULL && len < mlen)
913 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
914 resid = uio->uio_resid;
917 top->m_pkthdr.len += len;
923 top->m_flags |= M_EOR;
926 } while (space > 0 && atomic);
928 so->so_options |= SO_DONTROUTE;
929 if (flags & MSG_OOB) {
930 pru_flags = PRUS_OOB;
931 } else if ((flags & MSG_EOF) &&
932 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
935 * If the user set MSG_EOF, the protocol
936 * understands this flag and nothing left to
937 * send then use PRU_SEND_EOF instead of PRU_SEND.
939 pru_flags = PRUS_EOF;
940 } else if (resid > 0 && space > 0) {
941 /* If there is more to send, set PRUS_MORETOCOME */
942 pru_flags = PRUS_MORETOCOME;
947 * XXX all the SS_CANTSENDMORE checks previously
948 * done could be out of date. We could have recieved
949 * a reset packet in an interrupt or maybe we slept
950 * while doing page faults in uiomove() etc. We could
951 * probably recheck again inside the splnet() protection
952 * here, but there are probably other places that this
953 * also happens. We must rethink this.
955 error = so_pru_send(so, pru_flags, top, addr, control, td);
957 so->so_options &= ~SO_DONTROUTE;
964 } while (resid && space > 0);
968 ssb_unlock(&so->so_snd);
979 * A specialization of sosend() for UDP based on protocol-specific knowledge:
980 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
981 * sosendallatonce() returns true,
982 * the "atomic" variable is true,
983 * and sosendudp() blocks until space is available for the entire send.
984 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
985 * PR_IMPLOPCL flags set.
986 * UDP has no out-of-band data.
987 * UDP has no control data.
988 * UDP does not support MSG_EOR.
991 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
992 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
995 int error, pru_flags = 0;
998 if (td->td_lwp != NULL)
999 td->td_lwp->lwp_ru.ru_msgsnd++;
1003 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
1004 resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
1007 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1011 if (so->so_state & SS_CANTSENDMORE)
1014 error = so->so_error;
1018 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
1019 gotoerr(EDESTADDRREQ);
1020 if (resid > so->so_snd.ssb_hiwat)
1022 space = ssb_space(&so->so_snd);
1023 if (uio && (space < 0 || (size_t)space < resid)) {
1024 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1025 gotoerr(EWOULDBLOCK);
1026 ssb_unlock(&so->so_snd);
1027 error = ssb_wait(&so->so_snd);
1034 int hdrlen = max_hdr;
1037 * We try to optimize out the additional mbuf
1038 * allocations in M_PREPEND() on output path, e.g.
1039 * - udp_output(), when it tries to prepend protocol
1041 * - Link layer output function, when it tries to
1042 * prepend link layer header.
1044 * This probably will not benefit any data that will
1045 * be fragmented, so this optimization is only performed
1046 * when the size of data and max size of protocol+link
1047 * headers fit into one mbuf cluster.
1049 if (uio->uio_resid > MCLBYTES - hdrlen ||
1050 !udp_sosend_prepend) {
1051 top = m_uiomove(uio);
1057 top = m_getl(uio->uio_resid + hdrlen, M_WAITOK,
1058 MT_DATA, M_PKTHDR, &nsize);
1059 KASSERT(nsize >= uio->uio_resid + hdrlen,
1060 ("sosendudp invalid nsize %d, "
1061 "resid %zu, hdrlen %d",
1062 nsize, uio->uio_resid, hdrlen));
1064 top->m_len = uio->uio_resid;
1065 top->m_pkthdr.len = uio->uio_resid;
1066 top->m_data += hdrlen;
1068 error = uiomove(mtod(top, caddr_t), top->m_len, uio);
1074 if (flags & MSG_DONTROUTE)
1075 pru_flags |= PRUS_DONTROUTE;
1077 if (udp_sosend_async && (flags & MSG_SYNC) == 0) {
1078 so_pru_send_async(so, pru_flags, top, addr, NULL, td);
1081 error = so_pru_send(so, pru_flags, top, addr, NULL, td);
1083 top = NULL; /* sent or freed in lower layer */
1086 ssb_unlock(&so->so_snd);
1094 sosendtcp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1095 struct mbuf *top, struct mbuf *control, int flags,
1107 KKASSERT(top == NULL);
1109 resid = uio->uio_resid;
1112 resid = (size_t)top->m_pkthdr.len;
1115 for (m = top; m; m = m->m_next)
1117 KKASSERT(top->m_pkthdr.len == len);
1122 * WARNING! resid is unsigned, space and len are signed. space
1123 * can wind up negative if the sockbuf is overcommitted.
1125 * Also check to make sure that MSG_EOR isn't used on TCP
1127 if (flags & MSG_EOR) {
1133 /* TCP doesn't do control messages (rights, creds, etc) */
1134 if (control->m_len) {
1138 m_freem(control); /* empty control, just free it */
1142 if (td->td_lwp != NULL)
1143 td->td_lwp->lwp_ru.ru_msgsnd++;
1145 #define gotoerr(errcode) { error = errcode; goto release; }
1148 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1153 if (so->so_state & SS_CANTSENDMORE)
1156 error = so->so_error;
1160 if ((so->so_state & SS_ISCONNECTED) == 0 &&
1161 (so->so_state & SS_ISCONFIRMING) == 0)
1163 if (allatonce && resid > so->so_snd.ssb_hiwat)
1166 space = ssb_space_prealloc(&so->so_snd);
1167 if (flags & MSG_OOB)
1169 if ((space < 0 || (size_t)space < resid) && !allatonce &&
1170 space < so->so_snd.ssb_lowat) {
1171 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1172 gotoerr(EWOULDBLOCK);
1173 ssb_unlock(&so->so_snd);
1174 error = ssb_wait(&so->so_snd);
1181 int cnt = 0, async = 0;
1185 * Data is prepackaged in "top".
1189 if (resid > INT_MAX)
1191 if (tcp_sosend_jcluster) {
1192 m = m_getlj((int)resid, M_WAITOK, MT_DATA,
1193 top == NULL ? M_PKTHDR : 0, &mlen);
1195 m = m_getl((int)resid, M_WAITOK, MT_DATA,
1196 top == NULL ? M_PKTHDR : 0, &mlen);
1199 m->m_pkthdr.len = 0;
1200 m->m_pkthdr.rcvif = NULL;
1202 len = imin((int)szmin(mlen, resid), space);
1204 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
1205 resid = uio->uio_resid;
1208 top->m_pkthdr.len += len;
1215 } while (space > 0 && cnt < tcp_sosend_agglim);
1217 if (tcp_sosend_async)
1220 if (flags & MSG_OOB) {
1221 pru_flags = PRUS_OOB;
1223 } else if ((flags & MSG_EOF) && resid == 0) {
1224 pru_flags = PRUS_EOF;
1225 } else if (resid > 0 && space > 0) {
1226 /* If there is more to send, set PRUS_MORETOCOME */
1227 pru_flags = PRUS_MORETOCOME;
1233 if (flags & MSG_SYNC)
1237 * XXX all the SS_CANTSENDMORE checks previously
1238 * done could be out of date. We could have recieved
1239 * a reset packet in an interrupt or maybe we slept
1240 * while doing page faults in uiomove() etc. We could
1241 * probably recheck again inside the splnet() protection
1242 * here, but there are probably other places that this
1243 * also happens. We must rethink this.
1245 for (m = top; m; m = m->m_next)
1246 ssb_preallocstream(&so->so_snd, m);
1248 error = so_pru_send(so, pru_flags, top,
1251 so_pru_send_async(so, pru_flags, top,
1260 } while (resid && space > 0);
1264 ssb_unlock(&so->so_snd);
1275 * Implement receive operations on a socket.
1277 * We depend on the way that records are added to the signalsockbuf
1278 * by sbappend*. In particular, each record (mbufs linked through m_next)
1279 * must begin with an address if the protocol so specifies,
1280 * followed by an optional mbuf or mbufs containing ancillary data,
1281 * and then zero or more mbufs of data.
1283 * Although the signalsockbuf is locked, new data may still be appended.
1284 * A token inside the ssb_lock deals with MP issues and still allows
1285 * the network to access the socket if we block in a uio.
1287 * The caller may receive the data as a single mbuf chain by supplying
1288 * an mbuf **mp0 for use in returning the chain. The uio is then used
1289 * only for the count in uio_resid.
1292 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1293 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1296 struct mbuf *free_chain = NULL;
1297 int flags, len, error, offset;
1298 struct protosw *pr = so->so_proto;
1300 size_t resid, orig_resid;
1303 resid = uio->uio_resid;
1305 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1313 flags = *flagsp &~ MSG_EOR;
1316 if (flags & MSG_OOB) {
1317 m = m_get(M_WAITOK, MT_DATA);
1320 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1326 KKASSERT(resid >= (size_t)m->m_len);
1327 resid -= (size_t)m->m_len;
1328 } while (resid > 0 && m);
1331 uio->uio_resid = resid;
1332 error = uiomove(mtod(m, caddr_t),
1333 (int)szmin(resid, m->m_len),
1335 resid = uio->uio_resid;
1337 } while (uio->uio_resid && error == 0 && m);
1344 if ((so->so_state & SS_ISCONFIRMING) && resid)
1348 * The token interlocks against the protocol thread while
1349 * ssb_lock is a blocking lock against other userland entities.
1351 lwkt_gettoken(&so->so_rcv.ssb_token);
1353 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1357 m = so->so_rcv.ssb_mb;
1359 * If we have less data than requested, block awaiting more
1360 * (subject to any timeout) if:
1361 * 1. the current count is less than the low water mark, or
1362 * 2. MSG_WAITALL is set, and it is possible to do the entire
1363 * receive operation at once if we block (resid <= hiwat).
1364 * 3. MSG_DONTWAIT is not set
1365 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1366 * we have to do the receive in sections, and thus risk returning
1367 * a short count if a timeout or signal occurs after we start.
1369 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1370 (size_t)so->so_rcv.ssb_cc < resid) &&
1371 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1372 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
1373 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1374 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1378 error = so->so_error;
1379 if ((flags & MSG_PEEK) == 0)
1383 if (so->so_state & SS_CANTRCVMORE) {
1389 for (; m; m = m->m_next) {
1390 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1391 m = so->so_rcv.ssb_mb;
1395 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1396 (pr->pr_flags & PR_CONNREQUIRED)) {
1402 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1403 error = EWOULDBLOCK;
1406 ssb_unlock(&so->so_rcv);
1407 error = ssb_wait(&so->so_rcv);
1413 if (uio && uio->uio_td && uio->uio_td->td_proc)
1414 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1417 * note: m should be == sb_mb here. Cache the next record while
1418 * cleaning up. Note that calling m_free*() will break out critical
1421 KKASSERT(m == so->so_rcv.ssb_mb);
1424 * Skip any address mbufs prepending the record.
1426 if (pr->pr_flags & PR_ADDR) {
1427 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
1430 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1431 if (flags & MSG_PEEK)
1434 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1438 * Skip any control mbufs prepending the record.
1440 while (m && m->m_type == MT_CONTROL && error == 0) {
1441 if (flags & MSG_PEEK) {
1443 *controlp = m_copy(m, 0, m->m_len);
1444 m = m->m_next; /* XXX race */
1447 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1448 if (pr->pr_domain->dom_externalize &&
1449 mtod(m, struct cmsghdr *)->cmsg_type ==
1451 error = (*pr->pr_domain->dom_externalize)(m);
1455 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1458 if (controlp && *controlp) {
1460 controlp = &(*controlp)->m_next;
1469 if (type == MT_OOBDATA)
1474 * Copy to the UIO or mbuf return chain (*mp).
1478 while (m && resid > 0 && error == 0) {
1479 if (m->m_type == MT_OOBDATA) {
1480 if (type != MT_OOBDATA)
1482 } else if (type == MT_OOBDATA)
1485 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1487 soclrstate(so, SS_RCVATMARK);
1488 len = (resid > INT_MAX) ? INT_MAX : resid;
1489 if (so->so_oobmark && len > so->so_oobmark - offset)
1490 len = so->so_oobmark - offset;
1491 if (len > m->m_len - moff)
1492 len = m->m_len - moff;
1495 * Copy out to the UIO or pass the mbufs back to the SIO.
1496 * The SIO is dealt with when we eat the mbuf, but deal
1497 * with the resid here either way.
1500 uio->uio_resid = resid;
1501 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1502 resid = uio->uio_resid;
1506 resid -= (size_t)len;
1510 * Eat the entire mbuf or just a piece of it
1512 if (len == m->m_len - moff) {
1513 if (m->m_flags & M_EOR)
1515 if (flags & MSG_PEEK) {
1520 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1524 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1528 if (flags & MSG_PEEK) {
1532 n = m_copym(m, 0, len, M_WAITOK);
1538 so->so_rcv.ssb_cc -= len;
1541 if (so->so_oobmark) {
1542 if ((flags & MSG_PEEK) == 0) {
1543 so->so_oobmark -= len;
1544 if (so->so_oobmark == 0) {
1545 sosetstate(so, SS_RCVATMARK);
1550 if (offset == so->so_oobmark)
1554 if (flags & MSG_EOR)
1557 * If the MSG_WAITALL flag is set (for non-atomic socket),
1558 * we must not quit until resid == 0 or an error
1559 * termination. If a signal/timeout occurs, return
1560 * with a short count but without error.
1561 * Keep signalsockbuf locked against other readers.
1563 while ((flags & MSG_WAITALL) && m == NULL &&
1564 resid > 0 && !sosendallatonce(so) &&
1565 so->so_rcv.ssb_mb == NULL) {
1566 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1569 * The window might have closed to zero, make
1570 * sure we send an ack now that we've drained
1571 * the buffer or we might end up blocking until
1572 * the idle takes over (5 seconds).
1574 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1575 so_pru_rcvd(so, flags);
1576 error = ssb_wait(&so->so_rcv);
1578 ssb_unlock(&so->so_rcv);
1582 m = so->so_rcv.ssb_mb;
1587 * If an atomic read was requested but unread data still remains
1588 * in the record, set MSG_TRUNC.
1590 if (m && pr->pr_flags & PR_ATOMIC)
1594 * Cleanup. If an atomic read was requested drop any unread data.
1596 if ((flags & MSG_PEEK) == 0) {
1597 if (m && (pr->pr_flags & PR_ATOMIC))
1598 sbdroprecord(&so->so_rcv.sb);
1599 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1600 so_pru_rcvd(so, flags);
1603 if (orig_resid == resid && orig_resid &&
1604 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1605 ssb_unlock(&so->so_rcv);
1612 ssb_unlock(&so->so_rcv);
1614 lwkt_reltoken(&so->so_rcv.ssb_token);
1616 m_freem(free_chain);
1621 sorecvtcp(struct socket *so, struct sockaddr **psa, struct uio *uio,
1622 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1625 struct mbuf *free_chain = NULL;
1626 int flags, len, error, offset;
1627 struct protosw *pr = so->so_proto;
1630 size_t resid, orig_resid, restmp;
1633 resid = uio->uio_resid;
1635 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1643 flags = *flagsp &~ MSG_EOR;
1646 if (flags & MSG_OOB) {
1647 m = m_get(M_WAITOK, MT_DATA);
1650 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1656 KKASSERT(resid >= (size_t)m->m_len);
1657 resid -= (size_t)m->m_len;
1658 } while (resid > 0 && m);
1661 uio->uio_resid = resid;
1662 error = uiomove(mtod(m, caddr_t),
1663 (int)szmin(resid, m->m_len),
1665 resid = uio->uio_resid;
1667 } while (uio->uio_resid && error == 0 && m);
1676 * The token interlocks against the protocol thread while
1677 * ssb_lock is a blocking lock against other userland entities.
1679 * Lock a limited number of mbufs (not all, so sbcompress() still
1680 * works well). The token is used as an interlock for sbwait() so
1681 * release it afterwords.
1684 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1688 lwkt_gettoken(&so->so_rcv.ssb_token);
1689 m = so->so_rcv.ssb_mb;
1692 * If we have less data than requested, block awaiting more
1693 * (subject to any timeout) if:
1694 * 1. the current count is less than the low water mark, or
1695 * 2. MSG_WAITALL is set, and it is possible to do the entire
1696 * receive operation at once if we block (resid <= hiwat).
1697 * 3. MSG_DONTWAIT is not set
1698 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1699 * we have to do the receive in sections, and thus risk returning
1700 * a short count if a timeout or signal occurs after we start.
1702 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1703 (size_t)so->so_rcv.ssb_cc < resid) &&
1704 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1705 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)))) {
1706 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1710 lwkt_reltoken(&so->so_rcv.ssb_token);
1711 error = so->so_error;
1712 if ((flags & MSG_PEEK) == 0)
1716 if (so->so_state & SS_CANTRCVMORE) {
1719 lwkt_reltoken(&so->so_rcv.ssb_token);
1722 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1723 (pr->pr_flags & PR_CONNREQUIRED)) {
1724 lwkt_reltoken(&so->so_rcv.ssb_token);
1729 lwkt_reltoken(&so->so_rcv.ssb_token);
1732 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1733 lwkt_reltoken(&so->so_rcv.ssb_token);
1734 error = EWOULDBLOCK;
1737 ssb_unlock(&so->so_rcv);
1738 error = ssb_wait(&so->so_rcv);
1739 lwkt_reltoken(&so->so_rcv.ssb_token);
1751 while (n && restmp < resid) {
1752 n->m_flags |= M_SOLOCKED;
1754 if (n->m_next == NULL)
1761 * Release token for loop
1763 lwkt_reltoken(&so->so_rcv.ssb_token);
1764 if (uio && uio->uio_td && uio->uio_td->td_proc)
1765 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1768 * note: m should be == sb_mb here. Cache the next record while
1769 * cleaning up. Note that calling m_free*() will break out critical
1772 KKASSERT(m == so->so_rcv.ssb_mb);
1775 * Copy to the UIO or mbuf return chain (*mp).
1777 * NOTE: Token is not held for loop
1783 while (m && (m->m_flags & M_SOLOCKED) && resid > 0 && error == 0) {
1784 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1787 soclrstate(so, SS_RCVATMARK);
1788 len = (resid > INT_MAX) ? INT_MAX : resid;
1789 if (so->so_oobmark && len > so->so_oobmark - offset)
1790 len = so->so_oobmark - offset;
1791 if (len > m->m_len - moff)
1792 len = m->m_len - moff;
1795 * Copy out to the UIO or pass the mbufs back to the SIO.
1796 * The SIO is dealt with when we eat the mbuf, but deal
1797 * with the resid here either way.
1800 uio->uio_resid = resid;
1801 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1802 resid = uio->uio_resid;
1806 resid -= (size_t)len;
1810 * Eat the entire mbuf or just a piece of it
1813 if (len == m->m_len - moff) {
1823 if (so->so_oobmark && offset == so->so_oobmark) {
1830 * Synchronize sockbuf with data we read.
1832 * NOTE: (m) is junk on entry (it could be left over from the
1835 if ((flags & MSG_PEEK) == 0) {
1836 lwkt_gettoken(&so->so_rcv.ssb_token);
1837 m = so->so_rcv.ssb_mb;
1838 while (m && offset >= m->m_len) {
1839 if (so->so_oobmark) {
1840 so->so_oobmark -= m->m_len;
1841 if (so->so_oobmark == 0) {
1842 sosetstate(so, SS_RCVATMARK);
1848 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1852 m = sbunlinkmbuf(&so->so_rcv.sb,
1859 n = m_copym(m, 0, offset, M_WAITOK);
1863 m->m_data += offset;
1865 so->so_rcv.ssb_cc -= offset;
1866 if (so->so_oobmark) {
1867 so->so_oobmark -= offset;
1868 if (so->so_oobmark == 0) {
1869 sosetstate(so, SS_RCVATMARK);
1875 lwkt_reltoken(&so->so_rcv.ssb_token);
1879 * If the MSG_WAITALL flag is set (for non-atomic socket),
1880 * we must not quit until resid == 0 or an error termination.
1882 * If a signal/timeout occurs, return with a short count but without
1885 * Keep signalsockbuf locked against other readers.
1887 * XXX if MSG_PEEK we currently do quit.
1889 if ((flags & MSG_WAITALL) && !(flags & MSG_PEEK) &&
1890 didoob == 0 && resid > 0 &&
1891 !sosendallatonce(so)) {
1892 lwkt_gettoken(&so->so_rcv.ssb_token);
1894 while ((m = so->so_rcv.ssb_mb) == NULL) {
1895 if (so->so_error || (so->so_state & SS_CANTRCVMORE)) {
1896 error = so->so_error;
1900 * The window might have closed to zero, make
1901 * sure we send an ack now that we've drained
1902 * the buffer or we might end up blocking until
1903 * the idle takes over (5 seconds).
1906 so_pru_rcvd_async(so);
1907 if (so->so_rcv.ssb_mb == NULL)
1908 error = ssb_wait(&so->so_rcv);
1910 lwkt_reltoken(&so->so_rcv.ssb_token);
1911 ssb_unlock(&so->so_rcv);
1916 if (m && error == 0)
1918 lwkt_reltoken(&so->so_rcv.ssb_token);
1922 * Token not held here.
1924 * Cleanup. If an atomic read was requested drop any unread data XXX
1926 if ((flags & MSG_PEEK) == 0) {
1928 so_pru_rcvd_async(so);
1931 if (orig_resid == resid && orig_resid &&
1932 (so->so_state & SS_CANTRCVMORE) == 0) {
1933 ssb_unlock(&so->so_rcv);
1940 ssb_unlock(&so->so_rcv);
1943 m_freem(free_chain);
1948 * Shut a socket down. Note that we do not get a frontend lock as we
1949 * want to be able to shut the socket down even if another thread is
1950 * blocked in a read(), thus waking it up.
1953 soshutdown(struct socket *so, int how)
1955 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1958 if (how != SHUT_WR) {
1959 /*ssb_lock(&so->so_rcv, M_WAITOK);*/
1961 /*ssb_unlock(&so->so_rcv);*/
1964 return (so_pru_shutdown(so));
1969 sorflush(struct socket *so)
1971 struct signalsockbuf *ssb = &so->so_rcv;
1972 struct protosw *pr = so->so_proto;
1973 struct signalsockbuf asb;
1975 atomic_set_int(&ssb->ssb_flags, SSB_NOINTR);
1977 lwkt_gettoken(&ssb->ssb_token);
1982 * Can't just blow up the ssb structure here
1984 bzero(&ssb->sb, sizeof(ssb->sb));
1989 atomic_clear_int(&ssb->ssb_flags, SSB_CLEAR_MASK);
1991 if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose)
1992 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1993 ssb_release(&asb, so);
1995 lwkt_reltoken(&ssb->ssb_token);
2000 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
2002 struct accept_filter_arg *afap = NULL;
2003 struct accept_filter *afp;
2004 struct so_accf *af = so->so_accf;
2007 /* do not set/remove accept filters on non listen sockets */
2008 if ((so->so_options & SO_ACCEPTCONN) == 0) {
2013 /* removing the filter */
2016 if (af->so_accept_filter != NULL &&
2017 af->so_accept_filter->accf_destroy != NULL) {
2018 af->so_accept_filter->accf_destroy(so);
2020 if (af->so_accept_filter_str != NULL) {
2021 kfree(af->so_accept_filter_str, M_ACCF);
2026 so->so_options &= ~SO_ACCEPTFILTER;
2029 /* adding a filter */
2030 /* must remove previous filter first */
2035 /* don't put large objects on the kernel stack */
2036 afap = kmalloc(sizeof(*afap), M_TEMP, M_WAITOK);
2037 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
2038 afap->af_name[sizeof(afap->af_name)-1] = '\0';
2039 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
2042 afp = accept_filt_get(afap->af_name);
2047 af = kmalloc(sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
2048 if (afp->accf_create != NULL) {
2049 if (afap->af_name[0] != '\0') {
2050 int len = strlen(afap->af_name) + 1;
2052 af->so_accept_filter_str = kmalloc(len, M_ACCF,
2054 strcpy(af->so_accept_filter_str, afap->af_name);
2056 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
2057 if (af->so_accept_filter_arg == NULL) {
2058 kfree(af->so_accept_filter_str, M_ACCF);
2065 af->so_accept_filter = afp;
2067 so->so_options |= SO_ACCEPTFILTER;
2070 kfree(afap, M_TEMP);
2076 * Perhaps this routine, and sooptcopyout(), below, ought to come in
2077 * an additional variant to handle the case where the option value needs
2078 * to be some kind of integer, but not a specific size.
2079 * In addition to their use here, these functions are also called by the
2080 * protocol-level pr_ctloutput() routines.
2083 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2085 return soopt_to_kbuf(sopt, buf, len, minlen);
2089 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2093 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2094 KKASSERT(kva_p(buf));
2097 * If the user gives us more than we wanted, we ignore it,
2098 * but if we don't get the minimum length the caller
2099 * wants, we return EINVAL. On success, sopt->sopt_valsize
2100 * is set to however much we actually retrieved.
2102 if ((valsize = sopt->sopt_valsize) < minlen)
2105 sopt->sopt_valsize = valsize = len;
2107 bcopy(sopt->sopt_val, buf, valsize);
2113 sosetopt(struct socket *so, struct sockopt *sopt)
2119 struct signalsockbuf *sotmp;
2122 sopt->sopt_dir = SOPT_SET;
2123 if (sopt->sopt_level != SOL_SOCKET) {
2124 if (so->so_proto && so->so_proto->pr_ctloutput) {
2125 return (so_pr_ctloutput(so, sopt));
2127 error = ENOPROTOOPT;
2129 switch (sopt->sopt_name) {
2131 case SO_ACCEPTFILTER:
2132 error = do_setopt_accept_filter(so, sopt);
2138 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2142 so->so_linger = l.l_linger;
2144 so->so_options |= SO_LINGER;
2146 so->so_options &= ~SO_LINGER;
2152 case SO_USELOOPBACK:
2159 error = sooptcopyin(sopt, &optval, sizeof optval,
2164 so->so_options |= sopt->sopt_name;
2166 so->so_options &= ~sopt->sopt_name;
2173 error = sooptcopyin(sopt, &optval, sizeof optval,
2179 * Values < 1 make no sense for any of these
2180 * options, so disallow them.
2187 switch (sopt->sopt_name) {
2190 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
2191 &so->so_snd : &so->so_rcv, (u_long)optval,
2193 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
2197 sotmp = (sopt->sopt_name == SO_SNDBUF) ?
2198 &so->so_snd : &so->so_rcv;
2199 atomic_clear_int(&sotmp->ssb_flags,
2204 * Make sure the low-water is never greater than
2208 so->so_snd.ssb_lowat =
2209 (optval > so->so_snd.ssb_hiwat) ?
2210 so->so_snd.ssb_hiwat : optval;
2211 atomic_clear_int(&so->so_snd.ssb_flags,
2215 so->so_rcv.ssb_lowat =
2216 (optval > so->so_rcv.ssb_hiwat) ?
2217 so->so_rcv.ssb_hiwat : optval;
2218 atomic_clear_int(&so->so_rcv.ssb_flags,
2226 error = sooptcopyin(sopt, &tv, sizeof tv,
2231 /* assert(hz > 0); */
2232 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2233 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2237 /* assert(tick > 0); */
2238 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2239 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
2240 if (val > INT_MAX) {
2244 if (val == 0 && tv.tv_usec != 0)
2247 switch (sopt->sopt_name) {
2249 so->so_snd.ssb_timeo = val;
2252 so->so_rcv.ssb_timeo = val;
2257 error = ENOPROTOOPT;
2260 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
2261 (void) so_pr_ctloutput(so, sopt);
2268 /* Helper routine for getsockopt */
2270 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2272 soopt_from_kbuf(sopt, buf, len);
2277 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
2282 sopt->sopt_valsize = 0;
2286 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2287 KKASSERT(kva_p(buf));
2290 * Documented get behavior is that we always return a value,
2291 * possibly truncated to fit in the user's buffer.
2292 * Traditional behavior is that we always tell the user
2293 * precisely how much we copied, rather than something useful
2294 * like the total amount we had available for her.
2295 * Note that this interface is not idempotent; the entire answer must
2296 * generated ahead of time.
2298 valsize = szmin(len, sopt->sopt_valsize);
2299 sopt->sopt_valsize = valsize;
2300 if (sopt->sopt_val != 0) {
2301 bcopy(buf, sopt->sopt_val, valsize);
2306 sogetopt(struct socket *so, struct sockopt *sopt)
2313 struct accept_filter_arg *afap;
2317 sopt->sopt_dir = SOPT_GET;
2318 if (sopt->sopt_level != SOL_SOCKET) {
2319 if (so->so_proto && so->so_proto->pr_ctloutput) {
2320 return (so_pr_ctloutput(so, sopt));
2322 return (ENOPROTOOPT);
2324 switch (sopt->sopt_name) {
2326 case SO_ACCEPTFILTER:
2327 if ((so->so_options & SO_ACCEPTCONN) == 0)
2329 afap = kmalloc(sizeof(*afap), M_TEMP,
2331 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
2332 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
2333 if (so->so_accf->so_accept_filter_str != NULL)
2334 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
2336 error = sooptcopyout(sopt, afap, sizeof(*afap));
2337 kfree(afap, M_TEMP);
2342 l.l_onoff = so->so_options & SO_LINGER;
2343 l.l_linger = so->so_linger;
2344 error = sooptcopyout(sopt, &l, sizeof l);
2347 case SO_USELOOPBACK:
2357 optval = so->so_options & sopt->sopt_name;
2359 error = sooptcopyout(sopt, &optval, sizeof optval);
2363 optval = so->so_type;
2367 optval = so->so_error;
2372 optval = so->so_snd.ssb_hiwat;
2376 optval = so->so_rcv.ssb_hiwat;
2380 optval = so->so_snd.ssb_lowat;
2384 optval = so->so_rcv.ssb_lowat;
2389 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2390 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
2392 tv.tv_sec = optval / hz;
2393 tv.tv_usec = (optval % hz) * ustick;
2394 error = sooptcopyout(sopt, &tv, sizeof tv);
2398 optval_l = ssb_space(&so->so_snd);
2399 error = sooptcopyout(sopt, &optval_l, sizeof(optval_l));
2403 optval = -1; /* no hint */
2407 error = ENOPROTOOPT;
2410 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput)
2411 so_pr_ctloutput(so, sopt);
2416 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2418 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2420 struct mbuf *m, *m_prev;
2421 int sopt_size = sopt->sopt_valsize, msize;
2423 m = m_getl(sopt_size, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA,
2427 m->m_len = min(msize, sopt_size);
2428 sopt_size -= m->m_len;
2432 while (sopt_size > 0) {
2433 m = m_getl(sopt_size, sopt->sopt_td ? M_WAITOK : M_NOWAIT,
2434 MT_DATA, 0, &msize);
2439 m->m_len = min(msize, sopt_size);
2440 sopt_size -= m->m_len;
2447 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2449 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2451 soopt_to_mbuf(sopt, m);
2456 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
2461 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2463 if (sopt->sopt_val == NULL)
2465 val = sopt->sopt_val;
2466 valsize = sopt->sopt_valsize;
2467 while (m != NULL && valsize >= m->m_len) {
2468 bcopy(val, mtod(m, char *), m->m_len);
2469 valsize -= m->m_len;
2470 val = (caddr_t)val + m->m_len;
2473 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2474 panic("ip6_sooptmcopyin");
2477 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2479 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2481 return soopt_from_mbuf(sopt, m);
2485 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
2487 struct mbuf *m0 = m;
2492 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2494 if (sopt->sopt_val == NULL)
2496 val = sopt->sopt_val;
2497 maxsize = sopt->sopt_valsize;
2498 while (m != NULL && maxsize >= m->m_len) {
2499 bcopy(mtod(m, char *), val, m->m_len);
2500 maxsize -= m->m_len;
2501 val = (caddr_t)val + m->m_len;
2502 valsize += m->m_len;
2506 /* enough soopt buffer should be given from user-land */
2510 sopt->sopt_valsize = valsize;
2515 sohasoutofband(struct socket *so)
2517 if (so->so_sigio != NULL)
2518 pgsigio(so->so_sigio, SIGURG, 0);
2519 KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
2523 sokqfilter(struct file *fp, struct knote *kn)
2525 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2526 struct signalsockbuf *ssb;
2528 switch (kn->kn_filter) {
2530 if (so->so_options & SO_ACCEPTCONN)
2531 kn->kn_fop = &solisten_filtops;
2533 kn->kn_fop = &soread_filtops;
2537 kn->kn_fop = &sowrite_filtops;
2541 kn->kn_fop = &soexcept_filtops;
2545 return (EOPNOTSUPP);
2548 knote_insert(&ssb->ssb_kq.ki_note, kn);
2549 atomic_set_int(&ssb->ssb_flags, SSB_KNOTE);
2554 filt_sordetach(struct knote *kn)
2556 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2558 knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
2559 if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
2560 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_KNOTE);
2565 filt_soread(struct knote *kn, long hint)
2567 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2569 if (kn->kn_sfflags & NOTE_OOB) {
2570 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
2571 kn->kn_fflags |= NOTE_OOB;
2576 kn->kn_data = so->so_rcv.ssb_cc;
2578 if (so->so_state & SS_CANTRCVMORE) {
2580 * Only set NODATA if all data has been exhausted.
2582 if (kn->kn_data == 0)
2583 kn->kn_flags |= EV_NODATA;
2584 kn->kn_flags |= EV_EOF;
2585 kn->kn_fflags = so->so_error;
2588 if (so->so_error) /* temporary udp error */
2590 if (kn->kn_sfflags & NOTE_LOWAT)
2591 return (kn->kn_data >= kn->kn_sdata);
2592 return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
2593 !TAILQ_EMPTY(&so->so_comp));
2597 filt_sowdetach(struct knote *kn)
2599 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2601 knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
2602 if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
2603 atomic_clear_int(&so->so_snd.ssb_flags, SSB_KNOTE);
2608 filt_sowrite(struct knote *kn, long hint)
2610 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2612 kn->kn_data = ssb_space(&so->so_snd);
2613 if (so->so_state & SS_CANTSENDMORE) {
2614 kn->kn_flags |= (EV_EOF | EV_NODATA);
2615 kn->kn_fflags = so->so_error;
2618 if (so->so_error) /* temporary udp error */
2620 if (((so->so_state & SS_ISCONNECTED) == 0) &&
2621 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2623 if (kn->kn_sfflags & NOTE_LOWAT)
2624 return (kn->kn_data >= kn->kn_sdata);
2625 return (kn->kn_data >= so->so_snd.ssb_lowat);
2630 filt_solisten(struct knote *kn, long hint)
2632 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2634 kn->kn_data = so->so_qlen;
2635 return (! TAILQ_EMPTY(&so->so_comp));