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 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 void sodiscard(struct socket *so);
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");
149 * Socket operation routines.
150 * These routines are called by the routines in
151 * sys_socket.c or from a system process, and
152 * implement the semantics of socket operations by
153 * switching out to the protocol specific routines.
157 * Get a socket structure, and initialize it.
158 * Note that it would probably be better to allocate socket
159 * and PCB at the same time, but I'm not convinced that all
160 * the protocols can be easily modified to do this.
163 soalloc(int waitok, struct protosw *pr)
168 waitmask = waitok ? M_WAITOK : M_NOWAIT;
169 so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
171 /* XXX race condition for reentrant kernel */
173 TAILQ_INIT(&so->so_aiojobq);
174 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
175 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
176 lwkt_token_init(&so->so_rcv.ssb_token, "rcvtok");
177 lwkt_token_init(&so->so_snd.ssb_token, "sndtok");
178 spin_init(&so->so_rcvd_spin);
179 netmsg_init(&so->so_rcvd_msg.base, so, &netisr_adone_rport,
180 MSGF_DROPABLE | MSGF_PRIORITY,
181 so->so_proto->pr_usrreqs->pru_rcvd);
182 so->so_rcvd_msg.nm_pru_flags |= PRUR_ASYNC;
183 so->so_state = SS_NOFDREF;
190 socreate(int dom, struct socket **aso, int type,
191 int proto, struct thread *td)
193 struct proc *p = td->td_proc;
196 struct pru_attach_info ai;
200 prp = pffindproto(dom, proto, type);
202 prp = pffindtype(dom, type);
204 if (prp == NULL || prp->pr_usrreqs->pru_attach == 0)
205 return (EPROTONOSUPPORT);
207 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
208 prp->pr_domain->dom_family != PF_LOCAL &&
209 prp->pr_domain->dom_family != PF_INET &&
210 prp->pr_domain->dom_family != PF_INET6 &&
211 prp->pr_domain->dom_family != PF_ROUTE) {
212 return (EPROTONOSUPPORT);
215 if (prp->pr_type != type)
217 so = soalloc(p != NULL, prp);
222 * Callers of socreate() presumably will connect up a descriptor
223 * and call soclose() if they cannot. This represents our so_refs
224 * (which should be 1) from soalloc().
226 soclrstate(so, SS_NOFDREF);
229 * Set a default port for protocol processing. No action will occur
230 * on the socket on this port until an inpcb is attached to it and
231 * is able to match incoming packets, or until the socket becomes
232 * available to userland.
234 * We normally default the socket to the protocol thread on cpu 0.
235 * If PR_SYNC_PORT is set (unix domain sockets) there is no protocol
236 * thread and all pr_*()/pru_*() calls are executed synchronously.
238 if (prp->pr_flags & PR_SYNC_PORT)
239 so->so_port = &netisr_sync_port;
241 so->so_port = netisr_cpuport(0);
243 TAILQ_INIT(&so->so_incomp);
244 TAILQ_INIT(&so->so_comp);
246 so->so_cred = crhold(p->p_ucred);
247 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
248 ai.p_ucred = p->p_ucred;
249 ai.fd_rdir = p->p_fd->fd_rdir;
252 * Auto-sizing of socket buffers is managed by the protocols and
253 * the appropriate flags must be set in the pru_attach function.
255 error = so_pru_attach(so, proto, &ai);
257 sosetstate(so, SS_NOFDREF);
258 sofree(so); /* from soalloc */
263 * NOTE: Returns referenced socket.
270 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
274 error = so_pru_bind(so, nam, td);
279 sodealloc(struct socket *so)
281 if (so->so_rcv.ssb_hiwat)
282 (void)chgsbsize(so->so_cred->cr_uidinfo,
283 &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
284 if (so->so_snd.ssb_hiwat)
285 (void)chgsbsize(so->so_cred->cr_uidinfo,
286 &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
288 /* remove accept filter if present */
289 if (so->so_accf != NULL)
290 do_setopt_accept_filter(so, NULL);
293 if (so->so_faddr != NULL)
294 kfree(so->so_faddr, M_SONAME);
299 solisten(struct socket *so, int backlog, struct thread *td)
303 short oldopt, oldqlimit;
306 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))
310 oldopt = so->so_options;
311 oldqlimit = so->so_qlimit;
314 lwkt_gettoken(&so->so_rcv.ssb_token);
315 if (TAILQ_EMPTY(&so->so_comp))
316 so->so_options |= SO_ACCEPTCONN;
317 lwkt_reltoken(&so->so_rcv.ssb_token);
318 if (backlog < 0 || backlog > somaxconn)
320 so->so_qlimit = backlog;
321 /* SCTP needs to look at tweak both the inbound backlog parameter AND
322 * the so_options (UDP model both connect's and gets inbound
323 * connections .. implicitly).
325 error = so_pru_listen(so, td);
328 /* Restore the params */
329 so->so_options = oldopt;
330 so->so_qlimit = oldqlimit;
338 * Destroy a disconnected socket. This routine is a NOP if entities
339 * still have a reference on the socket:
341 * so_pcb - The protocol stack still has a reference
342 * SS_NOFDREF - There is no longer a file pointer reference
345 sofree(struct socket *so)
350 * This is a bit hackish at the moment. We need to interlock
351 * any accept queue we are on before we potentially lose the
352 * last reference to avoid races against a re-reference from
353 * someone operating on the queue.
355 while ((head = so->so_head) != NULL) {
356 lwkt_getpooltoken(head);
357 if (so->so_head == head)
359 lwkt_relpooltoken(head);
363 * Arbitrage the last free.
365 KKASSERT(so->so_refs > 0);
366 if (atomic_fetchadd_int(&so->so_refs, -1) != 1) {
368 lwkt_relpooltoken(head);
372 KKASSERT(so->so_pcb == NULL && (so->so_state & SS_NOFDREF));
373 KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
376 * We're done, remove ourselves from the accept queue we are
377 * on, if we are on one.
380 if (so->so_state & SS_INCOMP) {
381 TAILQ_REMOVE(&head->so_incomp, so, so_list);
383 } else if (so->so_state & SS_COMP) {
385 * We must not decommission a socket that's
386 * on the accept(2) queue. If we do, then
387 * accept(2) may hang after select(2) indicated
388 * that the listening socket was ready.
390 lwkt_relpooltoken(head);
393 panic("sofree: not queued");
395 soclrstate(so, SS_INCOMP);
397 lwkt_relpooltoken(head);
399 ssb_release(&so->so_snd, so);
405 * Close a socket on last file table reference removal.
406 * Initiate disconnect if connected.
407 * Free socket when disconnect complete.
410 soclose(struct socket *so, int fflag)
414 funsetown(&so->so_sigio);
415 if (!use_soclose_fast ||
416 (so->so_proto->pr_flags & PR_SYNC_PORT) ||
417 (so->so_options & SO_LINGER)) {
418 error = soclose_sync(so, fflag);
427 sodiscard(struct socket *so)
429 lwkt_getpooltoken(so);
430 if (so->so_options & SO_ACCEPTCONN) {
433 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
434 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
435 soclrstate(sp, SS_INCOMP);
440 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
441 TAILQ_REMOVE(&so->so_comp, sp, so_list);
442 soclrstate(sp, SS_COMP);
448 lwkt_relpooltoken(so);
450 if (so->so_state & SS_NOFDREF)
451 panic("soclose: NOFDREF");
452 sosetstate(so, SS_NOFDREF); /* take ref */
456 soinherit(struct socket *so, struct socket *so_inh)
458 TAILQ_HEAD(, socket) comp, incomp;
462 KASSERT(so->so_options & SO_ACCEPTCONN,
463 ("so does not accept connection"));
464 KASSERT(so_inh->so_options & SO_ACCEPTCONN,
465 ("so_inh does not accept connection"));
470 lwkt_getpooltoken(so);
471 lwkt_getpooltoken(so_inh);
474 * Save completed queue and incompleted queue
476 TAILQ_CONCAT(&comp, &so->so_comp, so_list);
480 TAILQ_CONCAT(&incomp, &so->so_incomp, so_list);
481 incqlen = so->so_incqlen;
485 * Append the saved completed queue and incompleted
486 * queue to the socket inherits them.
489 * This may temporarily break the inheriting socket's
492 TAILQ_FOREACH(sp, &comp, so_list) {
493 sp->so_head = so_inh;
495 sp->so_cred = crhold(so_inh->so_cred);
498 TAILQ_FOREACH(sp, &incomp, so_list) {
499 sp->so_head = so_inh;
501 sp->so_cred = crhold(so_inh->so_cred);
504 TAILQ_CONCAT(&so_inh->so_comp, &comp, so_list);
505 so_inh->so_qlen += qlen;
507 TAILQ_CONCAT(&so_inh->so_incomp, &incomp, so_list);
508 so_inh->so_incqlen += incqlen;
510 lwkt_relpooltoken(so_inh);
511 lwkt_relpooltoken(so);
515 * "New" connections have arrived
518 wakeup(&so_inh->so_timeo);
523 soclose_sync(struct socket *so, int fflag)
527 if (so->so_pcb == NULL)
529 if (so->so_state & SS_ISCONNECTED) {
530 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
531 error = sodisconnect(so);
535 if (so->so_options & SO_LINGER) {
536 if ((so->so_state & SS_ISDISCONNECTING) &&
539 while (so->so_state & SS_ISCONNECTED) {
540 error = tsleep(&so->so_timeo, PCATCH,
541 "soclos", so->so_linger * hz);
551 error2 = so_pru_detach(so);
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);
589 so_pru_detach_direct(so);
596 soclose_disconn_async(struct socket *so)
598 struct netmsg_base *base = &so->so_clomsg;
600 netmsg_init(base, so, &netisr_apanic_rport, 0,
601 soclose_disconn_async_handler);
602 lwkt_sendmsg(so->so_port, &base->lmsg);
606 soclose_detach_async_handler(netmsg_t msg)
608 struct socket *so = msg->base.nm_so;
611 so_pru_detach_direct(so);
618 soclose_detach_async(struct socket *so)
620 struct netmsg_base *base = &so->so_clomsg;
622 netmsg_init(base, so, &netisr_apanic_rport, 0,
623 soclose_detach_async_handler);
624 lwkt_sendmsg(so->so_port, &base->lmsg);
628 soclose_fast(struct socket *so)
630 if (so->so_pcb == NULL)
633 if ((so->so_state & SS_ISCONNECTED) &&
634 (so->so_state & SS_ISDISCONNECTING) == 0) {
635 soclose_disconn_async(so);
640 soclose_detach_async(so);
646 soclose_sofree_async(so);
650 * Abort and destroy a socket. Only one abort can be in progress
651 * at any given moment.
654 soabort(struct socket *so)
661 soaborta(struct socket *so)
668 soabort_oncpu(struct socket *so)
671 so_pru_abort_oncpu(so);
675 * so is passed in ref'd, which becomes owned by
676 * the cleared SS_NOFDREF flag.
679 soaccept_generic(struct socket *so)
681 if ((so->so_state & SS_NOFDREF) == 0)
682 panic("soaccept: !NOFDREF");
683 soclrstate(so, SS_NOFDREF); /* owned by lack of SS_NOFDREF */
687 soaccept(struct socket *so, struct sockaddr **nam)
691 soaccept_generic(so);
692 error = so_pru_accept(so, nam);
697 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
701 if (so->so_options & SO_ACCEPTCONN)
704 * If protocol is connection-based, can only connect once.
705 * Otherwise, if connected, try to disconnect first.
706 * This allows user to disconnect by connecting to, e.g.,
709 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
710 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
711 (error = sodisconnect(so)))) {
715 * Prevent accumulated error from previous connection
719 error = so_pru_connect(so, nam, td);
725 soconnect2(struct socket *so1, struct socket *so2)
729 error = so_pru_connect2(so1, so2);
734 sodisconnect(struct socket *so)
738 if ((so->so_state & SS_ISCONNECTED) == 0) {
742 if (so->so_state & SS_ISDISCONNECTING) {
746 error = so_pru_disconnect(so);
751 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
754 * If send must go all at once and message is larger than
755 * send buffering, then hard error.
756 * Lock against other senders.
757 * If must go all at once and not enough room now, then
758 * inform user that this would block and do nothing.
759 * Otherwise, if nonblocking, send as much as possible.
760 * The data to be sent is described by "uio" if nonzero,
761 * otherwise by the mbuf chain "top" (which must be null
762 * if uio is not). Data provided in mbuf chain must be small
763 * enough to send all at once.
765 * Returns nonzero on error, timeout or signal; callers
766 * must check for short counts if EINTR/ERESTART are returned.
767 * Data and control buffers are freed on return.
770 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
771 struct mbuf *top, struct mbuf *control, int flags,
778 int clen = 0, error, dontroute, mlen;
779 int atomic = sosendallatonce(so) || top;
783 resid = uio->uio_resid;
785 resid = (size_t)top->m_pkthdr.len;
788 for (m = top; m; m = m->m_next)
790 KKASSERT(top->m_pkthdr.len == len);
795 * WARNING! resid is unsigned, space and len are signed. space
796 * can wind up negative if the sockbuf is overcommitted.
798 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
799 * type sockets since that's an error.
801 if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
807 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
808 (so->so_proto->pr_flags & PR_ATOMIC);
809 if (td->td_lwp != NULL)
810 td->td_lwp->lwp_ru.ru_msgsnd++;
812 clen = control->m_len;
813 #define gotoerr(errcode) { error = errcode; goto release; }
816 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
821 if (so->so_state & SS_CANTSENDMORE)
824 error = so->so_error;
828 if ((so->so_state & SS_ISCONNECTED) == 0) {
830 * `sendto' and `sendmsg' is allowed on a connection-
831 * based socket if it supports implied connect.
832 * Return ENOTCONN if not connected and no address is
835 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
836 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
837 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
838 !(resid == 0 && clen != 0))
840 } else if (addr == NULL)
841 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
842 ENOTCONN : EDESTADDRREQ);
844 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
845 clen > so->so_snd.ssb_hiwat) {
848 space = ssb_space(&so->so_snd);
851 if ((space < 0 || (size_t)space < resid + clen) && uio &&
852 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
853 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
854 gotoerr(EWOULDBLOCK);
855 ssb_unlock(&so->so_snd);
856 error = ssb_wait(&so->so_snd);
866 * Data is prepackaged in "top".
870 top->m_flags |= M_EOR;
874 m = m_getl((int)resid, MB_WAIT, MT_DATA,
875 top == NULL ? M_PKTHDR : 0, &mlen);
878 m->m_pkthdr.rcvif = NULL;
880 len = imin((int)szmin(mlen, resid), space);
881 if (resid < MINCLSIZE) {
883 * For datagram protocols, leave room
884 * for protocol headers in first mbuf.
886 if (atomic && top == NULL && len < mlen)
890 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
891 resid = uio->uio_resid;
894 top->m_pkthdr.len += len;
900 top->m_flags |= M_EOR;
903 } while (space > 0 && atomic);
905 so->so_options |= SO_DONTROUTE;
906 if (flags & MSG_OOB) {
907 pru_flags = PRUS_OOB;
908 } else if ((flags & MSG_EOF) &&
909 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
912 * If the user set MSG_EOF, the protocol
913 * understands this flag and nothing left to
914 * send then use PRU_SEND_EOF instead of PRU_SEND.
916 pru_flags = PRUS_EOF;
917 } else if (resid > 0 && space > 0) {
918 /* If there is more to send, set PRUS_MORETOCOME */
919 pru_flags = PRUS_MORETOCOME;
924 * XXX all the SS_CANTSENDMORE checks previously
925 * done could be out of date. We could have recieved
926 * a reset packet in an interrupt or maybe we slept
927 * while doing page faults in uiomove() etc. We could
928 * probably recheck again inside the splnet() protection
929 * here, but there are probably other places that this
930 * also happens. We must rethink this.
932 error = so_pru_send(so, pru_flags, top, addr, control, td);
934 so->so_options &= ~SO_DONTROUTE;
941 } while (resid && space > 0);
945 ssb_unlock(&so->so_snd);
956 * A specialization of sosend() for UDP based on protocol-specific knowledge:
957 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
958 * sosendallatonce() returns true,
959 * the "atomic" variable is true,
960 * and sosendudp() blocks until space is available for the entire send.
961 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
962 * PR_IMPLOPCL flags set.
963 * UDP has no out-of-band data.
964 * UDP has no control data.
965 * UDP does not support MSG_EOR.
968 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
969 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
972 int error, pru_flags = 0;
975 if (td->td_lwp != NULL)
976 td->td_lwp->lwp_ru.ru_msgsnd++;
980 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
981 resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
984 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
988 if (so->so_state & SS_CANTSENDMORE)
991 error = so->so_error;
995 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
996 gotoerr(EDESTADDRREQ);
997 if (resid > so->so_snd.ssb_hiwat)
999 space = ssb_space(&so->so_snd);
1000 if (uio && (space < 0 || (size_t)space < resid)) {
1001 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1002 gotoerr(EWOULDBLOCK);
1003 ssb_unlock(&so->so_snd);
1004 error = ssb_wait(&so->so_snd);
1011 int hdrlen = max_hdr;
1014 * We try to optimize out the additional mbuf
1015 * allocations in M_PREPEND() on output path, e.g.
1016 * - udp_output(), when it tries to prepend protocol
1018 * - Link layer output function, when it tries to
1019 * prepend link layer header.
1021 * This probably will not benefit any data that will
1022 * be fragmented, so this optimization is only performed
1023 * when the size of data and max size of protocol+link
1024 * headers fit into one mbuf cluster.
1026 if (uio->uio_resid > MCLBYTES - hdrlen ||
1027 !udp_sosend_prepend) {
1028 top = m_uiomove(uio);
1034 top = m_getl(uio->uio_resid + hdrlen, MB_WAIT,
1035 MT_DATA, M_PKTHDR, &nsize);
1036 KASSERT(nsize >= uio->uio_resid + hdrlen,
1037 ("sosendudp invalid nsize %d, "
1038 "resid %zu, hdrlen %d",
1039 nsize, uio->uio_resid, hdrlen));
1041 top->m_len = uio->uio_resid;
1042 top->m_pkthdr.len = uio->uio_resid;
1043 top->m_data += hdrlen;
1045 error = uiomove(mtod(top, caddr_t), top->m_len, uio);
1051 if (flags & MSG_DONTROUTE)
1052 pru_flags |= PRUS_DONTROUTE;
1054 if (udp_sosend_async && (flags & MSG_SYNC) == 0) {
1055 so_pru_send_async(so, pru_flags, top, addr, NULL, td);
1058 error = so_pru_send(so, pru_flags, top, addr, NULL, td);
1060 top = NULL; /* sent or freed in lower layer */
1063 ssb_unlock(&so->so_snd);
1071 sosendtcp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1072 struct mbuf *top, struct mbuf *control, int flags,
1084 KKASSERT(top == NULL);
1086 resid = uio->uio_resid;
1089 resid = (size_t)top->m_pkthdr.len;
1092 for (m = top; m; m = m->m_next)
1094 KKASSERT(top->m_pkthdr.len == len);
1099 * WARNING! resid is unsigned, space and len are signed. space
1100 * can wind up negative if the sockbuf is overcommitted.
1102 * Also check to make sure that MSG_EOR isn't used on TCP
1104 if (flags & MSG_EOR) {
1110 /* TCP doesn't do control messages (rights, creds, etc) */
1111 if (control->m_len) {
1115 m_freem(control); /* empty control, just free it */
1119 if (td->td_lwp != NULL)
1120 td->td_lwp->lwp_ru.ru_msgsnd++;
1122 #define gotoerr(errcode) { error = errcode; goto release; }
1125 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1130 if (so->so_state & SS_CANTSENDMORE)
1133 error = so->so_error;
1137 if ((so->so_state & SS_ISCONNECTED) == 0 &&
1138 (so->so_state & SS_ISCONFIRMING) == 0)
1140 if (allatonce && resid > so->so_snd.ssb_hiwat)
1143 space = ssb_space_prealloc(&so->so_snd);
1144 if (flags & MSG_OOB)
1146 if ((space < 0 || (size_t)space < resid) && !allatonce &&
1147 space < so->so_snd.ssb_lowat) {
1148 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1149 gotoerr(EWOULDBLOCK);
1150 ssb_unlock(&so->so_snd);
1151 error = ssb_wait(&so->so_snd);
1158 int cnt = 0, async = 0;
1162 * Data is prepackaged in "top".
1166 if (resid > INT_MAX)
1168 m = m_getl((int)resid, MB_WAIT, MT_DATA,
1169 top == NULL ? M_PKTHDR : 0, &mlen);
1171 m->m_pkthdr.len = 0;
1172 m->m_pkthdr.rcvif = NULL;
1174 len = imin((int)szmin(mlen, resid), space);
1176 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
1177 resid = uio->uio_resid;
1180 top->m_pkthdr.len += len;
1187 } while (space > 0 && cnt < tcp_sosend_agglim);
1189 if (tcp_sosend_async)
1192 if (flags & MSG_OOB) {
1193 pru_flags = PRUS_OOB;
1195 } else if ((flags & MSG_EOF) && resid == 0) {
1196 pru_flags = PRUS_EOF;
1197 } else if (resid > 0 && space > 0) {
1198 /* If there is more to send, set PRUS_MORETOCOME */
1199 pru_flags = PRUS_MORETOCOME;
1205 if (flags & MSG_SYNC)
1209 * XXX all the SS_CANTSENDMORE checks previously
1210 * done could be out of date. We could have recieved
1211 * a reset packet in an interrupt or maybe we slept
1212 * while doing page faults in uiomove() etc. We could
1213 * probably recheck again inside the splnet() protection
1214 * here, but there are probably other places that this
1215 * also happens. We must rethink this.
1217 for (m = top; m; m = m->m_next)
1218 ssb_preallocstream(&so->so_snd, m);
1220 error = so_pru_send(so, pru_flags, top,
1223 so_pru_send_async(so, pru_flags, top,
1232 } while (resid && space > 0);
1236 ssb_unlock(&so->so_snd);
1247 * Implement receive operations on a socket.
1249 * We depend on the way that records are added to the signalsockbuf
1250 * by sbappend*. In particular, each record (mbufs linked through m_next)
1251 * must begin with an address if the protocol so specifies,
1252 * followed by an optional mbuf or mbufs containing ancillary data,
1253 * and then zero or more mbufs of data.
1255 * Although the signalsockbuf is locked, new data may still be appended.
1256 * A token inside the ssb_lock deals with MP issues and still allows
1257 * the network to access the socket if we block in a uio.
1259 * The caller may receive the data as a single mbuf chain by supplying
1260 * an mbuf **mp0 for use in returning the chain. The uio is then used
1261 * only for the count in uio_resid.
1264 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1265 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1268 struct mbuf *free_chain = NULL;
1269 int flags, len, error, offset;
1270 struct protosw *pr = so->so_proto;
1272 size_t resid, orig_resid;
1275 resid = uio->uio_resid;
1277 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1285 flags = *flagsp &~ MSG_EOR;
1288 if (flags & MSG_OOB) {
1289 m = m_get(MB_WAIT, MT_DATA);
1292 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1298 KKASSERT(resid >= (size_t)m->m_len);
1299 resid -= (size_t)m->m_len;
1300 } while (resid > 0 && m);
1303 uio->uio_resid = resid;
1304 error = uiomove(mtod(m, caddr_t),
1305 (int)szmin(resid, m->m_len),
1307 resid = uio->uio_resid;
1309 } while (uio->uio_resid && error == 0 && m);
1316 if ((so->so_state & SS_ISCONFIRMING) && resid)
1320 * The token interlocks against the protocol thread while
1321 * ssb_lock is a blocking lock against other userland entities.
1323 lwkt_gettoken(&so->so_rcv.ssb_token);
1325 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1329 m = so->so_rcv.ssb_mb;
1331 * If we have less data than requested, block awaiting more
1332 * (subject to any timeout) if:
1333 * 1. the current count is less than the low water mark, or
1334 * 2. MSG_WAITALL is set, and it is possible to do the entire
1335 * receive operation at once if we block (resid <= hiwat).
1336 * 3. MSG_DONTWAIT is not set
1337 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1338 * we have to do the receive in sections, and thus risk returning
1339 * a short count if a timeout or signal occurs after we start.
1341 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1342 (size_t)so->so_rcv.ssb_cc < resid) &&
1343 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1344 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
1345 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1346 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1350 error = so->so_error;
1351 if ((flags & MSG_PEEK) == 0)
1355 if (so->so_state & SS_CANTRCVMORE) {
1361 for (; m; m = m->m_next) {
1362 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1363 m = so->so_rcv.ssb_mb;
1367 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1368 (pr->pr_flags & PR_CONNREQUIRED)) {
1374 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1375 error = EWOULDBLOCK;
1378 ssb_unlock(&so->so_rcv);
1379 error = ssb_wait(&so->so_rcv);
1385 if (uio && uio->uio_td && uio->uio_td->td_proc)
1386 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1389 * note: m should be == sb_mb here. Cache the next record while
1390 * cleaning up. Note that calling m_free*() will break out critical
1393 KKASSERT(m == so->so_rcv.ssb_mb);
1396 * Skip any address mbufs prepending the record.
1398 if (pr->pr_flags & PR_ADDR) {
1399 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
1402 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1403 if (flags & MSG_PEEK)
1406 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1410 * Skip any control mbufs prepending the record.
1413 if (pr->pr_flags & PR_ADDR_OPT) {
1415 * For SCTP we may be getting a
1416 * whole message OR a partial delivery.
1418 if (m && m->m_type == MT_SONAME) {
1421 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1422 if (flags & MSG_PEEK)
1425 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1429 while (m && m->m_type == MT_CONTROL && error == 0) {
1430 if (flags & MSG_PEEK) {
1432 *controlp = m_copy(m, 0, m->m_len);
1433 m = m->m_next; /* XXX race */
1436 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1437 if (pr->pr_domain->dom_externalize &&
1438 mtod(m, struct cmsghdr *)->cmsg_type ==
1440 error = (*pr->pr_domain->dom_externalize)(m);
1444 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1447 if (controlp && *controlp) {
1449 controlp = &(*controlp)->m_next;
1458 if (type == MT_OOBDATA)
1463 * Copy to the UIO or mbuf return chain (*mp).
1467 while (m && resid > 0 && error == 0) {
1468 if (m->m_type == MT_OOBDATA) {
1469 if (type != MT_OOBDATA)
1471 } else if (type == MT_OOBDATA)
1474 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1476 soclrstate(so, SS_RCVATMARK);
1477 len = (resid > INT_MAX) ? INT_MAX : resid;
1478 if (so->so_oobmark && len > so->so_oobmark - offset)
1479 len = so->so_oobmark - offset;
1480 if (len > m->m_len - moff)
1481 len = m->m_len - moff;
1484 * Copy out to the UIO or pass the mbufs back to the SIO.
1485 * The SIO is dealt with when we eat the mbuf, but deal
1486 * with the resid here either way.
1489 uio->uio_resid = resid;
1490 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1491 resid = uio->uio_resid;
1495 resid -= (size_t)len;
1499 * Eat the entire mbuf or just a piece of it
1501 if (len == m->m_len - moff) {
1502 if (m->m_flags & M_EOR)
1505 if (m->m_flags & M_NOTIFICATION)
1506 flags |= MSG_NOTIFICATION;
1508 if (flags & MSG_PEEK) {
1513 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1517 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1521 if (flags & MSG_PEEK) {
1525 n = m_copym(m, 0, len, MB_WAIT);
1531 so->so_rcv.ssb_cc -= len;
1534 if (so->so_oobmark) {
1535 if ((flags & MSG_PEEK) == 0) {
1536 so->so_oobmark -= len;
1537 if (so->so_oobmark == 0) {
1538 sosetstate(so, SS_RCVATMARK);
1543 if (offset == so->so_oobmark)
1547 if (flags & MSG_EOR)
1550 * If the MSG_WAITALL flag is set (for non-atomic socket),
1551 * we must not quit until resid == 0 or an error
1552 * termination. If a signal/timeout occurs, return
1553 * with a short count but without error.
1554 * Keep signalsockbuf locked against other readers.
1556 while ((flags & MSG_WAITALL) && m == NULL &&
1557 resid > 0 && !sosendallatonce(so) &&
1558 so->so_rcv.ssb_mb == NULL) {
1559 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1562 * The window might have closed to zero, make
1563 * sure we send an ack now that we've drained
1564 * the buffer or we might end up blocking until
1565 * the idle takes over (5 seconds).
1567 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1568 so_pru_rcvd(so, flags);
1569 error = ssb_wait(&so->so_rcv);
1571 ssb_unlock(&so->so_rcv);
1575 m = so->so_rcv.ssb_mb;
1580 * If an atomic read was requested but unread data still remains
1581 * in the record, set MSG_TRUNC.
1583 if (m && pr->pr_flags & PR_ATOMIC)
1587 * Cleanup. If an atomic read was requested drop any unread data.
1589 if ((flags & MSG_PEEK) == 0) {
1590 if (m && (pr->pr_flags & PR_ATOMIC))
1591 sbdroprecord(&so->so_rcv.sb);
1592 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1593 so_pru_rcvd(so, flags);
1596 if (orig_resid == resid && orig_resid &&
1597 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1598 ssb_unlock(&so->so_rcv);
1605 ssb_unlock(&so->so_rcv);
1607 lwkt_reltoken(&so->so_rcv.ssb_token);
1609 m_freem(free_chain);
1614 sorecvtcp(struct socket *so, struct sockaddr **psa, struct uio *uio,
1615 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1618 struct mbuf *free_chain = NULL;
1619 int flags, len, error, offset;
1620 struct protosw *pr = so->so_proto;
1622 size_t resid, orig_resid;
1625 resid = uio->uio_resid;
1627 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1635 flags = *flagsp &~ MSG_EOR;
1638 if (flags & MSG_OOB) {
1639 m = m_get(MB_WAIT, MT_DATA);
1642 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1648 KKASSERT(resid >= (size_t)m->m_len);
1649 resid -= (size_t)m->m_len;
1650 } while (resid > 0 && m);
1653 uio->uio_resid = resid;
1654 error = uiomove(mtod(m, caddr_t),
1655 (int)szmin(resid, m->m_len),
1657 resid = uio->uio_resid;
1659 } while (uio->uio_resid && error == 0 && m);
1668 * The token interlocks against the protocol thread while
1669 * ssb_lock is a blocking lock against other userland entities.
1671 lwkt_gettoken(&so->so_rcv.ssb_token);
1673 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1677 m = so->so_rcv.ssb_mb;
1679 * If we have less data than requested, block awaiting more
1680 * (subject to any timeout) if:
1681 * 1. the current count is less than the low water mark, or
1682 * 2. MSG_WAITALL is set, and it is possible to do the entire
1683 * receive operation at once if we block (resid <= hiwat).
1684 * 3. MSG_DONTWAIT is not set
1685 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1686 * we have to do the receive in sections, and thus risk returning
1687 * a short count if a timeout or signal occurs after we start.
1689 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1690 (size_t)so->so_rcv.ssb_cc < resid) &&
1691 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1692 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)))) {
1693 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1697 error = so->so_error;
1698 if ((flags & MSG_PEEK) == 0)
1702 if (so->so_state & SS_CANTRCVMORE) {
1708 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1709 (pr->pr_flags & PR_CONNREQUIRED)) {
1715 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1716 error = EWOULDBLOCK;
1719 ssb_unlock(&so->so_rcv);
1720 error = ssb_wait(&so->so_rcv);
1726 if (uio && uio->uio_td && uio->uio_td->td_proc)
1727 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1730 * note: m should be == sb_mb here. Cache the next record while
1731 * cleaning up. Note that calling m_free*() will break out critical
1734 KKASSERT(m == so->so_rcv.ssb_mb);
1737 * Copy to the UIO or mbuf return chain (*mp).
1741 while (m && resid > 0 && error == 0) {
1742 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1745 soclrstate(so, SS_RCVATMARK);
1746 len = (resid > INT_MAX) ? INT_MAX : resid;
1747 if (so->so_oobmark && len > so->so_oobmark - offset)
1748 len = so->so_oobmark - offset;
1749 if (len > m->m_len - moff)
1750 len = m->m_len - moff;
1753 * Copy out to the UIO or pass the mbufs back to the SIO.
1754 * The SIO is dealt with when we eat the mbuf, but deal
1755 * with the resid here either way.
1758 uio->uio_resid = resid;
1759 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1760 resid = uio->uio_resid;
1764 resid -= (size_t)len;
1768 * Eat the entire mbuf or just a piece of it
1770 if (len == m->m_len - moff) {
1771 if (flags & MSG_PEEK) {
1776 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1780 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1784 if (flags & MSG_PEEK) {
1788 n = m_copym(m, 0, len, MB_WAIT);
1794 so->so_rcv.ssb_cc -= len;
1797 if (so->so_oobmark) {
1798 if ((flags & MSG_PEEK) == 0) {
1799 so->so_oobmark -= len;
1800 if (so->so_oobmark == 0) {
1801 sosetstate(so, SS_RCVATMARK);
1806 if (offset == so->so_oobmark)
1811 * If the MSG_WAITALL flag is set (for non-atomic socket),
1812 * we must not quit until resid == 0 or an error
1813 * termination. If a signal/timeout occurs, return
1814 * with a short count but without error.
1815 * Keep signalsockbuf locked against other readers.
1817 while ((flags & MSG_WAITALL) && m == NULL &&
1818 resid > 0 && !sosendallatonce(so) &&
1819 so->so_rcv.ssb_mb == NULL) {
1820 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1823 * The window might have closed to zero, make
1824 * sure we send an ack now that we've drained
1825 * the buffer or we might end up blocking until
1826 * the idle takes over (5 seconds).
1829 so_pru_rcvd_async(so);
1830 error = ssb_wait(&so->so_rcv);
1832 ssb_unlock(&so->so_rcv);
1836 m = so->so_rcv.ssb_mb;
1841 * Cleanup. If an atomic read was requested drop any unread data.
1843 if ((flags & MSG_PEEK) == 0) {
1845 so_pru_rcvd_async(so);
1848 if (orig_resid == resid && orig_resid &&
1849 (so->so_state & SS_CANTRCVMORE) == 0) {
1850 ssb_unlock(&so->so_rcv);
1857 ssb_unlock(&so->so_rcv);
1859 lwkt_reltoken(&so->so_rcv.ssb_token);
1861 m_freem(free_chain);
1866 * Shut a socket down. Note that we do not get a frontend lock as we
1867 * want to be able to shut the socket down even if another thread is
1868 * blocked in a read(), thus waking it up.
1871 soshutdown(struct socket *so, int how)
1873 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1876 if (how != SHUT_WR) {
1877 /*ssb_lock(&so->so_rcv, M_WAITOK);*/
1879 /*ssb_unlock(&so->so_rcv);*/
1882 return (so_pru_shutdown(so));
1887 sorflush(struct socket *so)
1889 struct signalsockbuf *ssb = &so->so_rcv;
1890 struct protosw *pr = so->so_proto;
1891 struct signalsockbuf asb;
1893 atomic_set_int(&ssb->ssb_flags, SSB_NOINTR);
1895 lwkt_gettoken(&ssb->ssb_token);
1900 * Can't just blow up the ssb structure here
1902 bzero(&ssb->sb, sizeof(ssb->sb));
1907 atomic_clear_int(&ssb->ssb_flags, SSB_CLEAR_MASK);
1909 if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose)
1910 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1911 ssb_release(&asb, so);
1913 lwkt_reltoken(&ssb->ssb_token);
1918 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1920 struct accept_filter_arg *afap = NULL;
1921 struct accept_filter *afp;
1922 struct so_accf *af = so->so_accf;
1925 /* do not set/remove accept filters on non listen sockets */
1926 if ((so->so_options & SO_ACCEPTCONN) == 0) {
1931 /* removing the filter */
1934 if (af->so_accept_filter != NULL &&
1935 af->so_accept_filter->accf_destroy != NULL) {
1936 af->so_accept_filter->accf_destroy(so);
1938 if (af->so_accept_filter_str != NULL) {
1939 kfree(af->so_accept_filter_str, M_ACCF);
1944 so->so_options &= ~SO_ACCEPTFILTER;
1947 /* adding a filter */
1948 /* must remove previous filter first */
1953 /* don't put large objects on the kernel stack */
1954 afap = kmalloc(sizeof(*afap), M_TEMP, M_WAITOK);
1955 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1956 afap->af_name[sizeof(afap->af_name)-1] = '\0';
1957 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1960 afp = accept_filt_get(afap->af_name);
1965 af = kmalloc(sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1966 if (afp->accf_create != NULL) {
1967 if (afap->af_name[0] != '\0') {
1968 int len = strlen(afap->af_name) + 1;
1970 af->so_accept_filter_str = kmalloc(len, M_ACCF,
1972 strcpy(af->so_accept_filter_str, afap->af_name);
1974 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1975 if (af->so_accept_filter_arg == NULL) {
1976 kfree(af->so_accept_filter_str, M_ACCF);
1983 af->so_accept_filter = afp;
1985 so->so_options |= SO_ACCEPTFILTER;
1988 kfree(afap, M_TEMP);
1994 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1995 * an additional variant to handle the case where the option value needs
1996 * to be some kind of integer, but not a specific size.
1997 * In addition to their use here, these functions are also called by the
1998 * protocol-level pr_ctloutput() routines.
2001 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2003 return soopt_to_kbuf(sopt, buf, len, minlen);
2007 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2011 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2012 KKASSERT(kva_p(buf));
2015 * If the user gives us more than we wanted, we ignore it,
2016 * but if we don't get the minimum length the caller
2017 * wants, we return EINVAL. On success, sopt->sopt_valsize
2018 * is set to however much we actually retrieved.
2020 if ((valsize = sopt->sopt_valsize) < minlen)
2023 sopt->sopt_valsize = valsize = len;
2025 bcopy(sopt->sopt_val, buf, valsize);
2031 sosetopt(struct socket *so, struct sockopt *sopt)
2037 struct signalsockbuf *sotmp;
2040 sopt->sopt_dir = SOPT_SET;
2041 if (sopt->sopt_level != SOL_SOCKET) {
2042 if (so->so_proto && so->so_proto->pr_ctloutput) {
2043 return (so_pr_ctloutput(so, sopt));
2045 error = ENOPROTOOPT;
2047 switch (sopt->sopt_name) {
2049 case SO_ACCEPTFILTER:
2050 error = do_setopt_accept_filter(so, sopt);
2056 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2060 so->so_linger = l.l_linger;
2062 so->so_options |= SO_LINGER;
2064 so->so_options &= ~SO_LINGER;
2070 case SO_USELOOPBACK:
2077 error = sooptcopyin(sopt, &optval, sizeof optval,
2082 so->so_options |= sopt->sopt_name;
2084 so->so_options &= ~sopt->sopt_name;
2091 error = sooptcopyin(sopt, &optval, sizeof optval,
2097 * Values < 1 make no sense for any of these
2098 * options, so disallow them.
2105 switch (sopt->sopt_name) {
2108 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
2109 &so->so_snd : &so->so_rcv, (u_long)optval,
2111 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
2115 sotmp = (sopt->sopt_name == SO_SNDBUF) ?
2116 &so->so_snd : &so->so_rcv;
2117 atomic_clear_int(&sotmp->ssb_flags,
2122 * Make sure the low-water is never greater than
2126 so->so_snd.ssb_lowat =
2127 (optval > so->so_snd.ssb_hiwat) ?
2128 so->so_snd.ssb_hiwat : optval;
2129 atomic_clear_int(&so->so_snd.ssb_flags,
2133 so->so_rcv.ssb_lowat =
2134 (optval > so->so_rcv.ssb_hiwat) ?
2135 so->so_rcv.ssb_hiwat : optval;
2136 atomic_clear_int(&so->so_rcv.ssb_flags,
2144 error = sooptcopyin(sopt, &tv, sizeof tv,
2149 /* assert(hz > 0); */
2150 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2151 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2155 /* assert(tick > 0); */
2156 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2157 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
2158 if (val > INT_MAX) {
2162 if (val == 0 && tv.tv_usec != 0)
2165 switch (sopt->sopt_name) {
2167 so->so_snd.ssb_timeo = val;
2170 so->so_rcv.ssb_timeo = val;
2175 error = ENOPROTOOPT;
2178 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
2179 (void) so_pr_ctloutput(so, sopt);
2186 /* Helper routine for getsockopt */
2188 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2190 soopt_from_kbuf(sopt, buf, len);
2195 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
2200 sopt->sopt_valsize = 0;
2204 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2205 KKASSERT(kva_p(buf));
2208 * Documented get behavior is that we always return a value,
2209 * possibly truncated to fit in the user's buffer.
2210 * Traditional behavior is that we always tell the user
2211 * precisely how much we copied, rather than something useful
2212 * like the total amount we had available for her.
2213 * Note that this interface is not idempotent; the entire answer must
2214 * generated ahead of time.
2216 valsize = szmin(len, sopt->sopt_valsize);
2217 sopt->sopt_valsize = valsize;
2218 if (sopt->sopt_val != 0) {
2219 bcopy(buf, sopt->sopt_val, valsize);
2224 sogetopt(struct socket *so, struct sockopt *sopt)
2231 struct accept_filter_arg *afap;
2235 sopt->sopt_dir = SOPT_GET;
2236 if (sopt->sopt_level != SOL_SOCKET) {
2237 if (so->so_proto && so->so_proto->pr_ctloutput) {
2238 return (so_pr_ctloutput(so, sopt));
2240 return (ENOPROTOOPT);
2242 switch (sopt->sopt_name) {
2244 case SO_ACCEPTFILTER:
2245 if ((so->so_options & SO_ACCEPTCONN) == 0)
2247 afap = kmalloc(sizeof(*afap), M_TEMP,
2249 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
2250 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
2251 if (so->so_accf->so_accept_filter_str != NULL)
2252 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
2254 error = sooptcopyout(sopt, afap, sizeof(*afap));
2255 kfree(afap, M_TEMP);
2260 l.l_onoff = so->so_options & SO_LINGER;
2261 l.l_linger = so->so_linger;
2262 error = sooptcopyout(sopt, &l, sizeof l);
2265 case SO_USELOOPBACK:
2275 optval = so->so_options & sopt->sopt_name;
2277 error = sooptcopyout(sopt, &optval, sizeof optval);
2281 optval = so->so_type;
2285 optval = so->so_error;
2290 optval = so->so_snd.ssb_hiwat;
2294 optval = so->so_rcv.ssb_hiwat;
2298 optval = so->so_snd.ssb_lowat;
2302 optval = so->so_rcv.ssb_lowat;
2307 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2308 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
2310 tv.tv_sec = optval / hz;
2311 tv.tv_usec = (optval % hz) * ustick;
2312 error = sooptcopyout(sopt, &tv, sizeof tv);
2316 optval_l = ssb_space(&so->so_snd);
2317 error = sooptcopyout(sopt, &optval_l, sizeof(optval_l));
2321 error = ENOPROTOOPT;
2328 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2330 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2332 struct mbuf *m, *m_prev;
2333 int sopt_size = sopt->sopt_valsize, msize;
2335 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
2339 m->m_len = min(msize, sopt_size);
2340 sopt_size -= m->m_len;
2344 while (sopt_size > 0) {
2345 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
2346 MT_DATA, 0, &msize);
2351 m->m_len = min(msize, sopt_size);
2352 sopt_size -= m->m_len;
2359 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2361 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2363 soopt_to_mbuf(sopt, m);
2368 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
2373 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2375 if (sopt->sopt_val == NULL)
2377 val = sopt->sopt_val;
2378 valsize = sopt->sopt_valsize;
2379 while (m != NULL && valsize >= m->m_len) {
2380 bcopy(val, mtod(m, char *), m->m_len);
2381 valsize -= m->m_len;
2382 val = (caddr_t)val + m->m_len;
2385 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2386 panic("ip6_sooptmcopyin");
2389 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2391 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2393 return soopt_from_mbuf(sopt, m);
2397 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
2399 struct mbuf *m0 = m;
2404 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2406 if (sopt->sopt_val == NULL)
2408 val = sopt->sopt_val;
2409 maxsize = sopt->sopt_valsize;
2410 while (m != NULL && maxsize >= m->m_len) {
2411 bcopy(mtod(m, char *), val, m->m_len);
2412 maxsize -= m->m_len;
2413 val = (caddr_t)val + m->m_len;
2414 valsize += m->m_len;
2418 /* enough soopt buffer should be given from user-land */
2422 sopt->sopt_valsize = valsize;
2427 sohasoutofband(struct socket *so)
2429 if (so->so_sigio != NULL)
2430 pgsigio(so->so_sigio, SIGURG, 0);
2431 KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
2435 sokqfilter(struct file *fp, struct knote *kn)
2437 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2438 struct signalsockbuf *ssb;
2440 switch (kn->kn_filter) {
2442 if (so->so_options & SO_ACCEPTCONN)
2443 kn->kn_fop = &solisten_filtops;
2445 kn->kn_fop = &soread_filtops;
2449 kn->kn_fop = &sowrite_filtops;
2453 kn->kn_fop = &soexcept_filtops;
2457 return (EOPNOTSUPP);
2460 knote_insert(&ssb->ssb_kq.ki_note, kn);
2461 atomic_set_int(&ssb->ssb_flags, SSB_KNOTE);
2466 filt_sordetach(struct knote *kn)
2468 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2470 knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
2471 if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
2472 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_KNOTE);
2477 filt_soread(struct knote *kn, long hint)
2479 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2481 if (kn->kn_sfflags & NOTE_OOB) {
2482 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
2483 kn->kn_fflags |= NOTE_OOB;
2488 kn->kn_data = so->so_rcv.ssb_cc;
2490 if (so->so_state & SS_CANTRCVMORE) {
2492 * Only set NODATA if all data has been exhausted.
2494 if (kn->kn_data == 0)
2495 kn->kn_flags |= EV_NODATA;
2496 kn->kn_flags |= EV_EOF;
2497 kn->kn_fflags = so->so_error;
2500 if (so->so_error) /* temporary udp error */
2502 if (kn->kn_sfflags & NOTE_LOWAT)
2503 return (kn->kn_data >= kn->kn_sdata);
2504 return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
2505 !TAILQ_EMPTY(&so->so_comp));
2509 filt_sowdetach(struct knote *kn)
2511 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2513 knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
2514 if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
2515 atomic_clear_int(&so->so_snd.ssb_flags, SSB_KNOTE);
2520 filt_sowrite(struct knote *kn, long hint)
2522 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2524 kn->kn_data = ssb_space(&so->so_snd);
2525 if (so->so_state & SS_CANTSENDMORE) {
2526 kn->kn_flags |= (EV_EOF | EV_NODATA);
2527 kn->kn_fflags = so->so_error;
2530 if (so->so_error) /* temporary udp error */
2532 if (((so->so_state & SS_ISCONNECTED) == 0) &&
2533 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2535 if (kn->kn_sfflags & NOTE_LOWAT)
2536 return (kn->kn_data >= kn->kn_sdata);
2537 return (kn->kn_data >= so->so_snd.ssb_lowat);
2542 filt_solisten(struct knote *kn, long hint)
2544 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2546 kn->kn_data = so->so_qlen;
2547 return (! TAILQ_EMPTY(&so->so_comp));