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");
151 static int use_socreate_fast = 1;
152 SYSCTL_INT(_kern_ipc, OID_AUTO, socreate_fast, CTLFLAG_RW,
153 &use_socreate_fast, 0, "Fast socket creation");
156 * Socket operation routines.
157 * These routines are called by the routines in
158 * sys_socket.c or from a system process, and
159 * implement the semantics of socket operations by
160 * switching out to the protocol specific routines.
164 * Get a socket structure, and initialize it.
165 * Note that it would probably be better to allocate socket
166 * and PCB at the same time, but I'm not convinced that all
167 * the protocols can be easily modified to do this.
170 soalloc(int waitok, struct protosw *pr)
175 waitmask = waitok ? M_WAITOK : M_NOWAIT;
176 so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
178 /* XXX race condition for reentrant kernel */
180 TAILQ_INIT(&so->so_aiojobq);
181 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
182 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
183 lwkt_token_init(&so->so_rcv.ssb_token, "rcvtok");
184 lwkt_token_init(&so->so_snd.ssb_token, "sndtok");
185 spin_init(&so->so_rcvd_spin, "soalloc");
186 netmsg_init(&so->so_rcvd_msg.base, so, &netisr_adone_rport,
187 MSGF_DROPABLE | MSGF_PRIORITY,
188 so->so_proto->pr_usrreqs->pru_rcvd);
189 so->so_rcvd_msg.nm_pru_flags |= PRUR_ASYNC;
190 so->so_state = SS_NOFDREF;
197 socreate(int dom, struct socket **aso, int type,
198 int proto, struct thread *td)
200 struct proc *p = td->td_proc;
203 struct pru_attach_info ai;
207 prp = pffindproto(dom, proto, type);
209 prp = pffindtype(dom, type);
211 if (prp == NULL || prp->pr_usrreqs->pru_attach == 0)
212 return (EPROTONOSUPPORT);
214 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
215 prp->pr_domain->dom_family != PF_LOCAL &&
216 prp->pr_domain->dom_family != PF_INET &&
217 prp->pr_domain->dom_family != PF_INET6 &&
218 prp->pr_domain->dom_family != PF_ROUTE) {
219 return (EPROTONOSUPPORT);
222 if (prp->pr_type != type)
224 so = soalloc(p != NULL, prp);
229 * Callers of socreate() presumably will connect up a descriptor
230 * and call soclose() if they cannot. This represents our so_refs
231 * (which should be 1) from soalloc().
233 soclrstate(so, SS_NOFDREF);
236 * Set a default port for protocol processing. No action will occur
237 * on the socket on this port until an inpcb is attached to it and
238 * is able to match incoming packets, or until the socket becomes
239 * available to userland.
241 * We normally default the socket to the protocol thread on cpu 0,
242 * if protocol does not provide its own method to initialize the
245 * If PR_SYNC_PORT is set (unix domain sockets) there is no protocol
246 * thread and all pr_*()/pru_*() calls are executed synchronously.
248 if (prp->pr_flags & PR_SYNC_PORT)
249 so->so_port = &netisr_sync_port;
250 else if (prp->pr_initport != NULL)
251 so->so_port = prp->pr_initport();
253 so->so_port = netisr_cpuport(0);
255 TAILQ_INIT(&so->so_incomp);
256 TAILQ_INIT(&so->so_comp);
258 so->so_cred = crhold(p->p_ucred);
259 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
260 ai.p_ucred = p->p_ucred;
261 ai.fd_rdir = p->p_fd->fd_rdir;
264 * Auto-sizing of socket buffers is managed by the protocols and
265 * the appropriate flags must be set in the pru_attach function.
267 if (use_socreate_fast && prp->pr_usrreqs->pru_preattach)
268 error = so_pru_attach_fast(so, proto, &ai);
270 error = so_pru_attach(so, proto, &ai);
272 sosetstate(so, SS_NOFDREF);
273 sofree(so); /* from soalloc */
278 * NOTE: Returns referenced socket.
285 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
289 error = so_pru_bind(so, nam, td);
294 sodealloc(struct socket *so)
296 KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) == 0);
297 /* TODO: assert accept queues are empty, after unix socket is fixed */
299 if (so->so_rcv.ssb_hiwat)
300 (void)chgsbsize(so->so_cred->cr_uidinfo,
301 &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
302 if (so->so_snd.ssb_hiwat)
303 (void)chgsbsize(so->so_cred->cr_uidinfo,
304 &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
306 /* remove accept filter if present */
307 if (so->so_accf != NULL)
308 do_setopt_accept_filter(so, NULL);
311 if (so->so_faddr != NULL)
312 kfree(so->so_faddr, M_SONAME);
317 solisten(struct socket *so, int backlog, struct thread *td)
319 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))
322 lwkt_gettoken(&so->so_rcv.ssb_token);
323 if (TAILQ_EMPTY(&so->so_comp))
324 so->so_options |= SO_ACCEPTCONN;
325 lwkt_reltoken(&so->so_rcv.ssb_token);
326 if (backlog < 0 || backlog > somaxconn)
328 so->so_qlimit = backlog;
329 return so_pru_listen(so, td);
333 soqflush(struct socket *so)
335 lwkt_getpooltoken(so);
336 if (so->so_options & SO_ACCEPTCONN) {
339 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
340 KKASSERT((sp->so_state & (SS_INCOMP | SS_COMP)) ==
342 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
344 soclrstate(sp, SS_INCOMP);
345 soabort_async(sp, TRUE);
347 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
348 KKASSERT((sp->so_state & (SS_INCOMP | SS_COMP)) ==
350 TAILQ_REMOVE(&so->so_comp, sp, so_list);
352 soclrstate(sp, SS_COMP);
353 soabort_async(sp, TRUE);
356 lwkt_relpooltoken(so);
360 * Destroy a disconnected socket. This routine is a NOP if entities
361 * still have a reference on the socket:
363 * so_pcb - The protocol stack still has a reference
364 * SS_NOFDREF - There is no longer a file pointer reference
367 sofree(struct socket *so)
372 * This is a bit hackish at the moment. We need to interlock
373 * any accept queue we are on before we potentially lose the
374 * last reference to avoid races against a re-reference from
375 * someone operating on the queue.
377 while ((head = so->so_head) != NULL) {
378 lwkt_getpooltoken(head);
379 if (so->so_head == head)
381 lwkt_relpooltoken(head);
385 * Arbitrage the last free.
387 KKASSERT(so->so_refs > 0);
388 if (atomic_fetchadd_int(&so->so_refs, -1) != 1) {
390 lwkt_relpooltoken(head);
394 KKASSERT(so->so_pcb == NULL && (so->so_state & SS_NOFDREF));
395 KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
399 * We're done, remove ourselves from the accept queue we are
400 * on, if we are on one.
402 if (so->so_state & SS_INCOMP) {
403 KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) ==
405 TAILQ_REMOVE(&head->so_incomp, so, so_list);
407 } else if (so->so_state & SS_COMP) {
409 * We must not decommission a socket that's
410 * on the accept(2) queue. If we do, then
411 * accept(2) may hang after select(2) indicated
412 * that the listening socket was ready.
414 KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) ==
416 lwkt_relpooltoken(head);
419 panic("sofree: not queued");
421 soclrstate(so, SS_INCOMP);
423 lwkt_relpooltoken(head);
425 /* Flush accept queues, if we are accepting. */
428 ssb_release(&so->so_snd, so);
434 * Close a socket on last file table reference removal.
435 * Initiate disconnect if connected.
436 * Free socket when disconnect complete.
439 soclose(struct socket *so, int fflag)
443 funsetown(&so->so_sigio);
444 sosetstate(so, SS_ISCLOSING);
445 if (!use_soclose_fast ||
446 (so->so_proto->pr_flags & PR_SYNC_PORT) ||
447 ((so->so_state & SS_ISCONNECTED) &&
448 (so->so_options & SO_LINGER))) {
449 error = soclose_sync(so, fflag);
458 sodiscard(struct socket *so)
460 if (so->so_state & SS_NOFDREF)
461 panic("soclose: NOFDREF");
462 sosetstate(so, SS_NOFDREF); /* take ref */
466 * Append the completed queue of head to head_inh (inherting listen socket).
469 soinherit(struct socket *head, struct socket *head_inh)
471 boolean_t do_wakeup = FALSE;
473 KASSERT(head->so_options & SO_ACCEPTCONN,
474 ("head does not accept connection"));
475 KASSERT(head_inh->so_options & SO_ACCEPTCONN,
476 ("head_inh does not accept connection"));
478 lwkt_getpooltoken(head);
479 lwkt_getpooltoken(head_inh);
481 if (head->so_qlen > 0)
484 while (!TAILQ_EMPTY(&head->so_comp)) {
485 struct ucred *old_cr;
488 sp = TAILQ_FIRST(&head->so_comp);
489 KKASSERT((sp->so_state & (SS_INCOMP | SS_COMP)) == SS_COMP);
492 * Remove this socket from the current listen socket
495 TAILQ_REMOVE(&head->so_comp, sp, so_list);
498 /* Save the old ucred for later free. */
499 old_cr = sp->so_cred;
502 * Install this socket to the inheriting listen socket
505 sp->so_cred = crhold(head_inh->so_cred); /* non-blocking */
506 sp->so_head = head_inh;
508 TAILQ_INSERT_TAIL(&head_inh->so_comp, sp, so_list);
513 * crfree() may block and release the tokens temporarily.
514 * However, we are fine here, since the transition is done.
519 lwkt_relpooltoken(head_inh);
520 lwkt_relpooltoken(head);
524 * "New" connections have arrived
527 wakeup(&head_inh->so_timeo);
532 soclose_sync(struct socket *so, int fflag)
536 if ((so->so_proto->pr_flags & PR_SYNC_PORT) == 0)
537 so_pru_sync(so); /* unpend async prus */
539 if (so->so_pcb == NULL)
542 if (so->so_state & SS_ISCONNECTED) {
543 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
544 error = sodisconnect(so);
548 if (so->so_options & SO_LINGER) {
549 if ((so->so_state & SS_ISDISCONNECTING) &&
552 while (so->so_state & SS_ISCONNECTED) {
553 error = tsleep(&so->so_timeo, PCATCH,
554 "soclos", so->so_linger * hz);
564 error2 = so_pru_detach(so);
565 if (error2 == EJUSTRETURN) {
567 * Protocol will call sodiscard()
568 * and sofree() for us.
577 sofree(so); /* dispose of ref */
583 soclose_fast_handler(netmsg_t msg)
585 struct socket *so = msg->base.nm_so;
587 if (so->so_pcb == NULL)
590 if ((so->so_state & SS_ISCONNECTED) &&
591 (so->so_state & SS_ISDISCONNECTING) == 0)
592 so_pru_disconnect_direct(so);
597 error = so_pru_detach_direct(so);
598 if (error == EJUSTRETURN) {
600 * Protocol will call sodiscard()
601 * and sofree() for us.
612 soclose_fast(struct socket *so)
614 struct netmsg_base *base = &so->so_clomsg;
616 netmsg_init(base, so, &netisr_apanic_rport, 0,
617 soclose_fast_handler);
618 lwkt_sendmsg(so->so_port, &base->lmsg);
622 * Abort and destroy a socket. Only one abort can be in progress
623 * at any given moment.
626 soabort_async(struct socket *so, boolean_t clr_head)
629 * Keep a reference before clearing the so_head
630 * to avoid racing socket close in netisr.
635 so_pru_abort_async(so);
639 soabort_direct(struct socket *so)
642 so_pru_abort_direct(so);
646 * so is passed in ref'd, which becomes owned by
647 * the cleared SS_NOFDREF flag.
650 soaccept_generic(struct socket *so)
652 if ((so->so_state & SS_NOFDREF) == 0)
653 panic("soaccept: !NOFDREF");
654 soclrstate(so, SS_NOFDREF); /* owned by lack of SS_NOFDREF */
658 soaccept(struct socket *so, struct sockaddr **nam)
662 soaccept_generic(so);
663 error = so_pru_accept(so, nam);
668 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td,
673 if (so->so_options & SO_ACCEPTCONN)
676 * If protocol is connection-based, can only connect once.
677 * Otherwise, if connected, try to disconnect first.
678 * This allows user to disconnect by connecting to, e.g.,
681 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
682 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
683 (error = sodisconnect(so)))) {
687 * Prevent accumulated error from previous connection
691 if (!sync && so->so_proto->pr_usrreqs->pru_preconnect)
692 error = so_pru_connect_async(so, nam, td);
694 error = so_pru_connect(so, nam, td);
700 soconnect2(struct socket *so1, struct socket *so2)
704 error = so_pru_connect2(so1, so2);
709 sodisconnect(struct socket *so)
713 if ((so->so_state & SS_ISCONNECTED) == 0) {
717 if (so->so_state & SS_ISDISCONNECTING) {
721 error = so_pru_disconnect(so);
726 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
729 * If send must go all at once and message is larger than
730 * send buffering, then hard error.
731 * Lock against other senders.
732 * If must go all at once and not enough room now, then
733 * inform user that this would block and do nothing.
734 * Otherwise, if nonblocking, send as much as possible.
735 * The data to be sent is described by "uio" if nonzero,
736 * otherwise by the mbuf chain "top" (which must be null
737 * if uio is not). Data provided in mbuf chain must be small
738 * enough to send all at once.
740 * Returns nonzero on error, timeout or signal; callers
741 * must check for short counts if EINTR/ERESTART are returned.
742 * Data and control buffers are freed on return.
745 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
746 struct mbuf *top, struct mbuf *control, int flags,
753 int clen = 0, error, dontroute, mlen;
754 int atomic = sosendallatonce(so) || top;
758 resid = uio->uio_resid;
760 resid = (size_t)top->m_pkthdr.len;
763 for (m = top; m; m = m->m_next)
765 KKASSERT(top->m_pkthdr.len == len);
770 * WARNING! resid is unsigned, space and len are signed. space
771 * can wind up negative if the sockbuf is overcommitted.
773 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
774 * type sockets since that's an error.
776 if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
782 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
783 (so->so_proto->pr_flags & PR_ATOMIC);
784 if (td->td_lwp != NULL)
785 td->td_lwp->lwp_ru.ru_msgsnd++;
787 clen = control->m_len;
788 #define gotoerr(errcode) { error = errcode; goto release; }
791 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
796 if (so->so_state & SS_CANTSENDMORE)
799 error = so->so_error;
803 if ((so->so_state & SS_ISCONNECTED) == 0) {
805 * `sendto' and `sendmsg' is allowed on a connection-
806 * based socket if it supports implied connect.
807 * Return ENOTCONN if not connected and no address is
810 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
811 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
812 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
813 !(resid == 0 && clen != 0))
815 } else if (addr == NULL)
816 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
817 ENOTCONN : EDESTADDRREQ);
819 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
820 clen > so->so_snd.ssb_hiwat) {
823 space = ssb_space(&so->so_snd);
826 if ((space < 0 || (size_t)space < resid + clen) && uio &&
827 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
828 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
829 gotoerr(EWOULDBLOCK);
830 ssb_unlock(&so->so_snd);
831 error = ssb_wait(&so->so_snd);
841 * Data is prepackaged in "top".
845 top->m_flags |= M_EOR;
849 m = m_getl((int)resid, M_WAITOK, MT_DATA,
850 top == NULL ? M_PKTHDR : 0, &mlen);
853 m->m_pkthdr.rcvif = NULL;
855 len = imin((int)szmin(mlen, resid), space);
856 if (resid < MINCLSIZE) {
858 * For datagram protocols, leave room
859 * for protocol headers in first mbuf.
861 if (atomic && top == NULL && len < mlen)
865 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
866 resid = uio->uio_resid;
869 top->m_pkthdr.len += len;
875 top->m_flags |= M_EOR;
878 } while (space > 0 && atomic);
880 so->so_options |= SO_DONTROUTE;
881 if (flags & MSG_OOB) {
882 pru_flags = PRUS_OOB;
883 } else if ((flags & MSG_EOF) &&
884 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
887 * If the user set MSG_EOF, the protocol
888 * understands this flag and nothing left to
889 * send then use PRU_SEND_EOF instead of PRU_SEND.
891 pru_flags = PRUS_EOF;
892 } else if (resid > 0 && space > 0) {
893 /* If there is more to send, set PRUS_MORETOCOME */
894 pru_flags = PRUS_MORETOCOME;
899 * XXX all the SS_CANTSENDMORE checks previously
900 * done could be out of date. We could have recieved
901 * a reset packet in an interrupt or maybe we slept
902 * while doing page faults in uiomove() etc. We could
903 * probably recheck again inside the splnet() protection
904 * here, but there are probably other places that this
905 * also happens. We must rethink this.
907 error = so_pru_send(so, pru_flags, top, addr, control, td);
909 so->so_options &= ~SO_DONTROUTE;
916 } while (resid && space > 0);
920 ssb_unlock(&so->so_snd);
931 * A specialization of sosend() for UDP based on protocol-specific knowledge:
932 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
933 * sosendallatonce() returns true,
934 * the "atomic" variable is true,
935 * and sosendudp() blocks until space is available for the entire send.
936 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
937 * PR_IMPLOPCL flags set.
938 * UDP has no out-of-band data.
939 * UDP has no control data.
940 * UDP does not support MSG_EOR.
943 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
944 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
947 int error, pru_flags = 0;
950 if (td->td_lwp != NULL)
951 td->td_lwp->lwp_ru.ru_msgsnd++;
955 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
956 resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
959 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
963 if (so->so_state & SS_CANTSENDMORE)
966 error = so->so_error;
970 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
971 gotoerr(EDESTADDRREQ);
972 if (resid > so->so_snd.ssb_hiwat)
974 space = ssb_space(&so->so_snd);
975 if (uio && (space < 0 || (size_t)space < resid)) {
976 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
977 gotoerr(EWOULDBLOCK);
978 ssb_unlock(&so->so_snd);
979 error = ssb_wait(&so->so_snd);
986 int hdrlen = max_hdr;
989 * We try to optimize out the additional mbuf
990 * allocations in M_PREPEND() on output path, e.g.
991 * - udp_output(), when it tries to prepend protocol
993 * - Link layer output function, when it tries to
994 * prepend link layer header.
996 * This probably will not benefit any data that will
997 * be fragmented, so this optimization is only performed
998 * when the size of data and max size of protocol+link
999 * headers fit into one mbuf cluster.
1001 if (uio->uio_resid > MCLBYTES - hdrlen ||
1002 !udp_sosend_prepend) {
1003 top = m_uiomove(uio);
1009 top = m_getl(uio->uio_resid + hdrlen, M_WAITOK,
1010 MT_DATA, M_PKTHDR, &nsize);
1011 KASSERT(nsize >= uio->uio_resid + hdrlen,
1012 ("sosendudp invalid nsize %d, "
1013 "resid %zu, hdrlen %d",
1014 nsize, uio->uio_resid, hdrlen));
1016 top->m_len = uio->uio_resid;
1017 top->m_pkthdr.len = uio->uio_resid;
1018 top->m_data += hdrlen;
1020 error = uiomove(mtod(top, caddr_t), top->m_len, uio);
1026 if (flags & MSG_DONTROUTE)
1027 pru_flags |= PRUS_DONTROUTE;
1029 if (udp_sosend_async && (flags & MSG_SYNC) == 0) {
1030 so_pru_send_async(so, pru_flags, top, addr, NULL, td);
1033 error = so_pru_send(so, pru_flags, top, addr, NULL, td);
1035 top = NULL; /* sent or freed in lower layer */
1038 ssb_unlock(&so->so_snd);
1046 sosendtcp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1047 struct mbuf *top, struct mbuf *control, int flags,
1059 KKASSERT(top == NULL);
1061 resid = uio->uio_resid;
1064 resid = (size_t)top->m_pkthdr.len;
1067 for (m = top; m; m = m->m_next)
1069 KKASSERT(top->m_pkthdr.len == len);
1074 * WARNING! resid is unsigned, space and len are signed. space
1075 * can wind up negative if the sockbuf is overcommitted.
1077 * Also check to make sure that MSG_EOR isn't used on TCP
1079 if (flags & MSG_EOR) {
1085 /* TCP doesn't do control messages (rights, creds, etc) */
1086 if (control->m_len) {
1090 m_freem(control); /* empty control, just free it */
1094 if (td->td_lwp != NULL)
1095 td->td_lwp->lwp_ru.ru_msgsnd++;
1097 #define gotoerr(errcode) { error = errcode; goto release; }
1100 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1105 if (so->so_state & SS_CANTSENDMORE)
1108 error = so->so_error;
1112 if ((so->so_state & SS_ISCONNECTED) == 0 &&
1113 (so->so_state & SS_ISCONFIRMING) == 0)
1115 if (allatonce && resid > so->so_snd.ssb_hiwat)
1118 space = ssb_space_prealloc(&so->so_snd);
1119 if (flags & MSG_OOB)
1121 if ((space < 0 || (size_t)space < resid) && !allatonce &&
1122 space < so->so_snd.ssb_lowat) {
1123 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1124 gotoerr(EWOULDBLOCK);
1125 ssb_unlock(&so->so_snd);
1126 error = ssb_wait(&so->so_snd);
1133 int cnt = 0, async = 0;
1137 * Data is prepackaged in "top".
1141 if (resid > INT_MAX)
1143 if (tcp_sosend_jcluster) {
1144 m = m_getlj((int)resid, M_WAITOK, MT_DATA,
1145 top == NULL ? M_PKTHDR : 0, &mlen);
1147 m = m_getl((int)resid, M_WAITOK, MT_DATA,
1148 top == NULL ? M_PKTHDR : 0, &mlen);
1151 m->m_pkthdr.len = 0;
1152 m->m_pkthdr.rcvif = NULL;
1154 len = imin((int)szmin(mlen, resid), space);
1156 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
1157 resid = uio->uio_resid;
1160 top->m_pkthdr.len += len;
1167 } while (space > 0 && cnt < tcp_sosend_agglim);
1169 if (tcp_sosend_async)
1172 if (flags & MSG_OOB) {
1173 pru_flags = PRUS_OOB;
1175 } else if ((flags & MSG_EOF) && resid == 0) {
1176 pru_flags = PRUS_EOF;
1177 } else if (resid > 0 && space > 0) {
1178 /* If there is more to send, set PRUS_MORETOCOME */
1179 pru_flags = PRUS_MORETOCOME;
1185 if (flags & MSG_SYNC)
1189 * XXX all the SS_CANTSENDMORE checks previously
1190 * done could be out of date. We could have recieved
1191 * a reset packet in an interrupt or maybe we slept
1192 * while doing page faults in uiomove() etc. We could
1193 * probably recheck again inside the splnet() protection
1194 * here, but there are probably other places that this
1195 * also happens. We must rethink this.
1197 for (m = top; m; m = m->m_next)
1198 ssb_preallocstream(&so->so_snd, m);
1200 error = so_pru_send(so, pru_flags, top,
1203 so_pru_send_async(so, pru_flags, top,
1212 } while (resid && space > 0);
1216 ssb_unlock(&so->so_snd);
1227 * Implement receive operations on a socket.
1229 * We depend on the way that records are added to the signalsockbuf
1230 * by sbappend*. In particular, each record (mbufs linked through m_next)
1231 * must begin with an address if the protocol so specifies,
1232 * followed by an optional mbuf or mbufs containing ancillary data,
1233 * and then zero or more mbufs of data.
1235 * Although the signalsockbuf is locked, new data may still be appended.
1236 * A token inside the ssb_lock deals with MP issues and still allows
1237 * the network to access the socket if we block in a uio.
1239 * The caller may receive the data as a single mbuf chain by supplying
1240 * an mbuf **mp0 for use in returning the chain. The uio is then used
1241 * only for the count in uio_resid.
1244 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1245 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1248 struct mbuf *free_chain = NULL;
1249 int flags, len, error, offset;
1250 struct protosw *pr = so->so_proto;
1252 size_t resid, orig_resid;
1253 boolean_t free_rights = FALSE;
1256 resid = uio->uio_resid;
1258 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1266 flags = *flagsp &~ MSG_EOR;
1269 if (flags & MSG_OOB) {
1270 m = m_get(M_WAITOK, MT_DATA);
1273 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1279 KKASSERT(resid >= (size_t)m->m_len);
1280 resid -= (size_t)m->m_len;
1281 } while (resid > 0 && m);
1284 uio->uio_resid = resid;
1285 error = uiomove(mtod(m, caddr_t),
1286 (int)szmin(resid, m->m_len),
1288 resid = uio->uio_resid;
1290 } while (uio->uio_resid && error == 0 && m);
1297 if ((so->so_state & SS_ISCONFIRMING) && resid)
1301 * The token interlocks against the protocol thread while
1302 * ssb_lock is a blocking lock against other userland entities.
1304 lwkt_gettoken(&so->so_rcv.ssb_token);
1306 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1310 m = so->so_rcv.ssb_mb;
1312 * If we have less data than requested, block awaiting more
1313 * (subject to any timeout) if:
1314 * 1. the current count is less than the low water mark, or
1315 * 2. MSG_WAITALL is set, and it is possible to do the entire
1316 * receive operation at once if we block (resid <= hiwat).
1317 * 3. MSG_DONTWAIT is not set
1318 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1319 * we have to do the receive in sections, and thus risk returning
1320 * a short count if a timeout or signal occurs after we start.
1322 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1323 (size_t)so->so_rcv.ssb_cc < resid) &&
1324 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1325 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
1326 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1327 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1331 error = so->so_error;
1332 if ((flags & MSG_PEEK) == 0)
1336 if (so->so_state & SS_CANTRCVMORE) {
1342 for (; m; m = m->m_next) {
1343 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1344 m = so->so_rcv.ssb_mb;
1348 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1349 (pr->pr_flags & PR_CONNREQUIRED)) {
1355 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1356 error = EWOULDBLOCK;
1359 ssb_unlock(&so->so_rcv);
1360 error = ssb_wait(&so->so_rcv);
1366 if (uio && uio->uio_td && uio->uio_td->td_proc)
1367 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1370 * note: m should be == sb_mb here. Cache the next record while
1371 * cleaning up. Note that calling m_free*() will break out critical
1374 KKASSERT(m == so->so_rcv.ssb_mb);
1377 * Skip any address mbufs prepending the record.
1379 if (pr->pr_flags & PR_ADDR) {
1380 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
1383 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1384 if (flags & MSG_PEEK)
1387 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1391 * Skip any control mbufs prepending the record.
1393 while (m && m->m_type == MT_CONTROL && error == 0) {
1394 if (flags & MSG_PEEK) {
1396 *controlp = m_copy(m, 0, m->m_len);
1397 m = m->m_next; /* XXX race */
1399 const struct cmsghdr *cm = mtod(m, struct cmsghdr *);
1402 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1403 if (pr->pr_domain->dom_externalize &&
1404 cm->cmsg_level == SOL_SOCKET &&
1405 cm->cmsg_type == SCM_RIGHTS) {
1406 error = pr->pr_domain->dom_externalize
1412 if (cm->cmsg_level == SOL_SOCKET &&
1413 cm->cmsg_type == SCM_RIGHTS)
1415 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1418 if (controlp && *controlp) {
1420 controlp = &(*controlp)->m_next;
1429 if (type == MT_OOBDATA)
1434 * Copy to the UIO or mbuf return chain (*mp).
1438 while (m && resid > 0 && error == 0) {
1439 if (m->m_type == MT_OOBDATA) {
1440 if (type != MT_OOBDATA)
1442 } else if (type == MT_OOBDATA)
1445 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1447 soclrstate(so, SS_RCVATMARK);
1448 len = (resid > INT_MAX) ? INT_MAX : resid;
1449 if (so->so_oobmark && len > so->so_oobmark - offset)
1450 len = so->so_oobmark - offset;
1451 if (len > m->m_len - moff)
1452 len = m->m_len - moff;
1455 * Copy out to the UIO or pass the mbufs back to the SIO.
1456 * The SIO is dealt with when we eat the mbuf, but deal
1457 * with the resid here either way.
1460 uio->uio_resid = resid;
1461 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1462 resid = uio->uio_resid;
1466 resid -= (size_t)len;
1470 * Eat the entire mbuf or just a piece of it
1472 if (len == m->m_len - moff) {
1473 if (m->m_flags & M_EOR)
1475 if (flags & MSG_PEEK) {
1480 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1484 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1488 if (flags & MSG_PEEK) {
1492 n = m_copym(m, 0, len, M_WAITOK);
1498 so->so_rcv.ssb_cc -= len;
1501 if (so->so_oobmark) {
1502 if ((flags & MSG_PEEK) == 0) {
1503 so->so_oobmark -= len;
1504 if (so->so_oobmark == 0) {
1505 sosetstate(so, SS_RCVATMARK);
1510 if (offset == so->so_oobmark)
1514 if (flags & MSG_EOR)
1517 * If the MSG_WAITALL flag is set (for non-atomic socket),
1518 * we must not quit until resid == 0 or an error
1519 * termination. If a signal/timeout occurs, return
1520 * with a short count but without error.
1521 * Keep signalsockbuf locked against other readers.
1523 while ((flags & MSG_WAITALL) && m == NULL &&
1524 resid > 0 && !sosendallatonce(so) &&
1525 so->so_rcv.ssb_mb == NULL) {
1526 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1529 * The window might have closed to zero, make
1530 * sure we send an ack now that we've drained
1531 * the buffer or we might end up blocking until
1532 * the idle takes over (5 seconds).
1534 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1535 so_pru_rcvd(so, flags);
1536 error = ssb_wait(&so->so_rcv);
1538 ssb_unlock(&so->so_rcv);
1542 m = so->so_rcv.ssb_mb;
1547 * If an atomic read was requested but unread data still remains
1548 * in the record, set MSG_TRUNC.
1550 if (m && pr->pr_flags & PR_ATOMIC)
1554 * Cleanup. If an atomic read was requested drop any unread data.
1556 if ((flags & MSG_PEEK) == 0) {
1557 if (m && (pr->pr_flags & PR_ATOMIC))
1558 sbdroprecord(&so->so_rcv.sb);
1559 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1560 so_pru_rcvd(so, flags);
1563 if (orig_resid == resid && orig_resid &&
1564 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1565 ssb_unlock(&so->so_rcv);
1572 ssb_unlock(&so->so_rcv);
1574 lwkt_reltoken(&so->so_rcv.ssb_token);
1576 if (free_rights && (pr->pr_flags & PR_RIGHTS) &&
1577 pr->pr_domain->dom_dispose)
1578 pr->pr_domain->dom_dispose(free_chain);
1579 m_freem(free_chain);
1585 sorecvtcp(struct socket *so, struct sockaddr **psa, struct uio *uio,
1586 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1589 struct mbuf *free_chain = NULL;
1590 int flags, len, error, offset;
1591 struct protosw *pr = so->so_proto;
1594 size_t resid, orig_resid, restmp;
1597 resid = uio->uio_resid;
1599 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1607 flags = *flagsp &~ MSG_EOR;
1610 if (flags & MSG_OOB) {
1611 m = m_get(M_WAITOK, MT_DATA);
1614 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1620 KKASSERT(resid >= (size_t)m->m_len);
1621 resid -= (size_t)m->m_len;
1622 } while (resid > 0 && m);
1625 uio->uio_resid = resid;
1626 error = uiomove(mtod(m, caddr_t),
1627 (int)szmin(resid, m->m_len),
1629 resid = uio->uio_resid;
1631 } while (uio->uio_resid && error == 0 && m);
1640 * The token interlocks against the protocol thread while
1641 * ssb_lock is a blocking lock against other userland entities.
1643 * Lock a limited number of mbufs (not all, so sbcompress() still
1644 * works well). The token is used as an interlock for sbwait() so
1645 * release it afterwords.
1648 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1652 lwkt_gettoken(&so->so_rcv.ssb_token);
1653 m = so->so_rcv.ssb_mb;
1656 * If we have less data than requested, block awaiting more
1657 * (subject to any timeout) if:
1658 * 1. the current count is less than the low water mark, or
1659 * 2. MSG_WAITALL is set, and it is possible to do the entire
1660 * receive operation at once if we block (resid <= hiwat).
1661 * 3. MSG_DONTWAIT is not set
1662 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1663 * we have to do the receive in sections, and thus risk returning
1664 * a short count if a timeout or signal occurs after we start.
1666 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1667 (size_t)so->so_rcv.ssb_cc < resid) &&
1668 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1669 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)))) {
1670 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1674 lwkt_reltoken(&so->so_rcv.ssb_token);
1675 error = so->so_error;
1676 if ((flags & MSG_PEEK) == 0)
1680 if (so->so_state & SS_CANTRCVMORE) {
1683 lwkt_reltoken(&so->so_rcv.ssb_token);
1686 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1687 (pr->pr_flags & PR_CONNREQUIRED)) {
1688 lwkt_reltoken(&so->so_rcv.ssb_token);
1693 lwkt_reltoken(&so->so_rcv.ssb_token);
1696 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1697 lwkt_reltoken(&so->so_rcv.ssb_token);
1698 error = EWOULDBLOCK;
1701 ssb_unlock(&so->so_rcv);
1702 error = ssb_wait(&so->so_rcv);
1703 lwkt_reltoken(&so->so_rcv.ssb_token);
1715 while (n && restmp < resid) {
1716 n->m_flags |= M_SOLOCKED;
1718 if (n->m_next == NULL)
1725 * Release token for loop
1727 lwkt_reltoken(&so->so_rcv.ssb_token);
1728 if (uio && uio->uio_td && uio->uio_td->td_proc)
1729 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1732 * note: m should be == sb_mb here. Cache the next record while
1733 * cleaning up. Note that calling m_free*() will break out critical
1736 KKASSERT(m == so->so_rcv.ssb_mb);
1739 * Copy to the UIO or mbuf return chain (*mp).
1741 * NOTE: Token is not held for loop
1747 while (m && (m->m_flags & M_SOLOCKED) && resid > 0 && error == 0) {
1748 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1751 soclrstate(so, SS_RCVATMARK);
1752 len = (resid > INT_MAX) ? INT_MAX : resid;
1753 if (so->so_oobmark && len > so->so_oobmark - offset)
1754 len = so->so_oobmark - offset;
1755 if (len > m->m_len - moff)
1756 len = m->m_len - moff;
1759 * Copy out to the UIO or pass the mbufs back to the SIO.
1760 * The SIO is dealt with when we eat the mbuf, but deal
1761 * with the resid here either way.
1764 uio->uio_resid = resid;
1765 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1766 resid = uio->uio_resid;
1770 resid -= (size_t)len;
1774 * Eat the entire mbuf or just a piece of it
1777 if (len == m->m_len - moff) {
1787 if (so->so_oobmark && offset == so->so_oobmark) {
1794 * Synchronize sockbuf with data we read.
1796 * NOTE: (m) is junk on entry (it could be left over from the
1799 if ((flags & MSG_PEEK) == 0) {
1800 lwkt_gettoken(&so->so_rcv.ssb_token);
1801 m = so->so_rcv.ssb_mb;
1802 while (m && offset >= m->m_len) {
1803 if (so->so_oobmark) {
1804 so->so_oobmark -= m->m_len;
1805 if (so->so_oobmark == 0) {
1806 sosetstate(so, SS_RCVATMARK);
1812 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1816 m = sbunlinkmbuf(&so->so_rcv.sb,
1823 n = m_copym(m, 0, offset, M_WAITOK);
1827 m->m_data += offset;
1829 so->so_rcv.ssb_cc -= offset;
1830 if (so->so_oobmark) {
1831 so->so_oobmark -= offset;
1832 if (so->so_oobmark == 0) {
1833 sosetstate(so, SS_RCVATMARK);
1839 lwkt_reltoken(&so->so_rcv.ssb_token);
1843 * If the MSG_WAITALL flag is set (for non-atomic socket),
1844 * we must not quit until resid == 0 or an error termination.
1846 * If a signal/timeout occurs, return with a short count but without
1849 * Keep signalsockbuf locked against other readers.
1851 * XXX if MSG_PEEK we currently do quit.
1853 if ((flags & MSG_WAITALL) && !(flags & MSG_PEEK) &&
1854 didoob == 0 && resid > 0 &&
1855 !sosendallatonce(so)) {
1856 lwkt_gettoken(&so->so_rcv.ssb_token);
1858 while ((m = so->so_rcv.ssb_mb) == NULL) {
1859 if (so->so_error || (so->so_state & SS_CANTRCVMORE)) {
1860 error = so->so_error;
1864 * The window might have closed to zero, make
1865 * sure we send an ack now that we've drained
1866 * the buffer or we might end up blocking until
1867 * the idle takes over (5 seconds).
1870 so_pru_rcvd_async(so);
1871 if (so->so_rcv.ssb_mb == NULL)
1872 error = ssb_wait(&so->so_rcv);
1874 lwkt_reltoken(&so->so_rcv.ssb_token);
1875 ssb_unlock(&so->so_rcv);
1880 if (m && error == 0)
1882 lwkt_reltoken(&so->so_rcv.ssb_token);
1886 * Token not held here.
1888 * Cleanup. If an atomic read was requested drop any unread data XXX
1890 if ((flags & MSG_PEEK) == 0) {
1892 so_pru_rcvd_async(so);
1895 if (orig_resid == resid && orig_resid &&
1896 (so->so_state & SS_CANTRCVMORE) == 0) {
1897 ssb_unlock(&so->so_rcv);
1904 ssb_unlock(&so->so_rcv);
1907 m_freem(free_chain);
1912 * Shut a socket down. Note that we do not get a frontend lock as we
1913 * want to be able to shut the socket down even if another thread is
1914 * blocked in a read(), thus waking it up.
1917 soshutdown(struct socket *so, int how)
1919 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1922 if (how != SHUT_WR) {
1923 /*ssb_lock(&so->so_rcv, M_WAITOK);*/
1925 /*ssb_unlock(&so->so_rcv);*/
1928 return (so_pru_shutdown(so));
1933 sorflush(struct socket *so)
1935 struct signalsockbuf *ssb = &so->so_rcv;
1936 struct protosw *pr = so->so_proto;
1937 struct signalsockbuf asb;
1939 atomic_set_int(&ssb->ssb_flags, SSB_NOINTR);
1941 lwkt_gettoken(&ssb->ssb_token);
1946 * Can't just blow up the ssb structure here
1948 bzero(&ssb->sb, sizeof(ssb->sb));
1953 atomic_clear_int(&ssb->ssb_flags, SSB_CLEAR_MASK);
1955 if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose)
1956 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1957 ssb_release(&asb, so);
1959 lwkt_reltoken(&ssb->ssb_token);
1964 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1966 struct accept_filter_arg *afap = NULL;
1967 struct accept_filter *afp;
1968 struct so_accf *af = so->so_accf;
1971 /* do not set/remove accept filters on non listen sockets */
1972 if ((so->so_options & SO_ACCEPTCONN) == 0) {
1977 /* removing the filter */
1980 if (af->so_accept_filter != NULL &&
1981 af->so_accept_filter->accf_destroy != NULL) {
1982 af->so_accept_filter->accf_destroy(so);
1984 if (af->so_accept_filter_str != NULL) {
1985 kfree(af->so_accept_filter_str, M_ACCF);
1990 so->so_options &= ~SO_ACCEPTFILTER;
1993 /* adding a filter */
1994 /* must remove previous filter first */
1999 /* don't put large objects on the kernel stack */
2000 afap = kmalloc(sizeof(*afap), M_TEMP, M_WAITOK);
2001 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
2002 afap->af_name[sizeof(afap->af_name)-1] = '\0';
2003 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
2006 afp = accept_filt_get(afap->af_name);
2011 af = kmalloc(sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
2012 if (afp->accf_create != NULL) {
2013 if (afap->af_name[0] != '\0') {
2014 int len = strlen(afap->af_name) + 1;
2016 af->so_accept_filter_str = kmalloc(len, M_ACCF,
2018 strcpy(af->so_accept_filter_str, afap->af_name);
2020 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
2021 if (af->so_accept_filter_arg == NULL) {
2022 kfree(af->so_accept_filter_str, M_ACCF);
2029 af->so_accept_filter = afp;
2031 so->so_options |= SO_ACCEPTFILTER;
2034 kfree(afap, M_TEMP);
2040 * Perhaps this routine, and sooptcopyout(), below, ought to come in
2041 * an additional variant to handle the case where the option value needs
2042 * to be some kind of integer, but not a specific size.
2043 * In addition to their use here, these functions are also called by the
2044 * protocol-level pr_ctloutput() routines.
2047 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2049 return soopt_to_kbuf(sopt, buf, len, minlen);
2053 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2057 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2058 KKASSERT(kva_p(buf));
2061 * If the user gives us more than we wanted, we ignore it,
2062 * but if we don't get the minimum length the caller
2063 * wants, we return EINVAL. On success, sopt->sopt_valsize
2064 * is set to however much we actually retrieved.
2066 if ((valsize = sopt->sopt_valsize) < minlen)
2069 sopt->sopt_valsize = valsize = len;
2071 bcopy(sopt->sopt_val, buf, valsize);
2077 sosetopt(struct socket *so, struct sockopt *sopt)
2083 struct signalsockbuf *sotmp;
2086 sopt->sopt_dir = SOPT_SET;
2087 if (sopt->sopt_level != SOL_SOCKET) {
2088 if (so->so_proto && so->so_proto->pr_ctloutput) {
2089 return (so_pr_ctloutput(so, sopt));
2091 error = ENOPROTOOPT;
2093 switch (sopt->sopt_name) {
2095 case SO_ACCEPTFILTER:
2096 error = do_setopt_accept_filter(so, sopt);
2102 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2106 so->so_linger = l.l_linger;
2108 so->so_options |= SO_LINGER;
2110 so->so_options &= ~SO_LINGER;
2116 case SO_USELOOPBACK:
2123 error = sooptcopyin(sopt, &optval, sizeof optval,
2128 so->so_options |= sopt->sopt_name;
2130 so->so_options &= ~sopt->sopt_name;
2137 error = sooptcopyin(sopt, &optval, sizeof optval,
2143 * Values < 1 make no sense for any of these
2144 * options, so disallow them.
2151 switch (sopt->sopt_name) {
2154 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
2155 &so->so_snd : &so->so_rcv, (u_long)optval,
2157 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
2161 sotmp = (sopt->sopt_name == SO_SNDBUF) ?
2162 &so->so_snd : &so->so_rcv;
2163 atomic_clear_int(&sotmp->ssb_flags,
2168 * Make sure the low-water is never greater than
2172 so->so_snd.ssb_lowat =
2173 (optval > so->so_snd.ssb_hiwat) ?
2174 so->so_snd.ssb_hiwat : optval;
2175 atomic_clear_int(&so->so_snd.ssb_flags,
2179 so->so_rcv.ssb_lowat =
2180 (optval > so->so_rcv.ssb_hiwat) ?
2181 so->so_rcv.ssb_hiwat : optval;
2182 atomic_clear_int(&so->so_rcv.ssb_flags,
2190 error = sooptcopyin(sopt, &tv, sizeof tv,
2195 /* assert(hz > 0); */
2196 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2197 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2201 /* assert(tick > 0); */
2202 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2203 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
2204 if (val > INT_MAX) {
2208 if (val == 0 && tv.tv_usec != 0)
2211 switch (sopt->sopt_name) {
2213 so->so_snd.ssb_timeo = val;
2216 so->so_rcv.ssb_timeo = val;
2221 error = ENOPROTOOPT;
2224 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
2225 (void) so_pr_ctloutput(so, sopt);
2232 /* Helper routine for getsockopt */
2234 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2236 soopt_from_kbuf(sopt, buf, len);
2241 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
2246 sopt->sopt_valsize = 0;
2250 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2251 KKASSERT(kva_p(buf));
2254 * Documented get behavior is that we always return a value,
2255 * possibly truncated to fit in the user's buffer.
2256 * Traditional behavior is that we always tell the user
2257 * precisely how much we copied, rather than something useful
2258 * like the total amount we had available for her.
2259 * Note that this interface is not idempotent; the entire answer must
2260 * generated ahead of time.
2262 valsize = szmin(len, sopt->sopt_valsize);
2263 sopt->sopt_valsize = valsize;
2264 if (sopt->sopt_val != 0) {
2265 bcopy(buf, sopt->sopt_val, valsize);
2270 sogetopt(struct socket *so, struct sockopt *sopt)
2277 struct accept_filter_arg *afap;
2281 sopt->sopt_dir = SOPT_GET;
2282 if (sopt->sopt_level != SOL_SOCKET) {
2283 if (so->so_proto && so->so_proto->pr_ctloutput) {
2284 return (so_pr_ctloutput(so, sopt));
2286 return (ENOPROTOOPT);
2288 switch (sopt->sopt_name) {
2290 case SO_ACCEPTFILTER:
2291 if ((so->so_options & SO_ACCEPTCONN) == 0)
2293 afap = kmalloc(sizeof(*afap), M_TEMP,
2295 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
2296 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
2297 if (so->so_accf->so_accept_filter_str != NULL)
2298 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
2300 error = sooptcopyout(sopt, afap, sizeof(*afap));
2301 kfree(afap, M_TEMP);
2306 l.l_onoff = so->so_options & SO_LINGER;
2307 l.l_linger = so->so_linger;
2308 error = sooptcopyout(sopt, &l, sizeof l);
2311 case SO_USELOOPBACK:
2321 optval = so->so_options & sopt->sopt_name;
2323 error = sooptcopyout(sopt, &optval, sizeof optval);
2327 optval = so->so_type;
2331 optval = so->so_error;
2336 optval = so->so_snd.ssb_hiwat;
2340 optval = so->so_rcv.ssb_hiwat;
2344 optval = so->so_snd.ssb_lowat;
2348 optval = so->so_rcv.ssb_lowat;
2353 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2354 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
2356 tv.tv_sec = optval / hz;
2357 tv.tv_usec = (optval % hz) * ustick;
2358 error = sooptcopyout(sopt, &tv, sizeof tv);
2362 optval_l = ssb_space(&so->so_snd);
2363 error = sooptcopyout(sopt, &optval_l, sizeof(optval_l));
2367 optval = -1; /* no hint */
2371 error = ENOPROTOOPT;
2374 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput)
2375 so_pr_ctloutput(so, sopt);
2380 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2382 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2384 struct mbuf *m, *m_prev;
2385 int sopt_size = sopt->sopt_valsize, msize;
2387 m = m_getl(sopt_size, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA,
2391 m->m_len = min(msize, sopt_size);
2392 sopt_size -= m->m_len;
2396 while (sopt_size > 0) {
2397 m = m_getl(sopt_size, sopt->sopt_td ? M_WAITOK : M_NOWAIT,
2398 MT_DATA, 0, &msize);
2403 m->m_len = min(msize, sopt_size);
2404 sopt_size -= m->m_len;
2411 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2413 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2415 soopt_to_mbuf(sopt, m);
2420 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
2425 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2427 if (sopt->sopt_val == NULL)
2429 val = sopt->sopt_val;
2430 valsize = sopt->sopt_valsize;
2431 while (m != NULL && valsize >= m->m_len) {
2432 bcopy(val, mtod(m, char *), m->m_len);
2433 valsize -= m->m_len;
2434 val = (caddr_t)val + m->m_len;
2437 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2438 panic("ip6_sooptmcopyin");
2441 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2443 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2445 return soopt_from_mbuf(sopt, m);
2449 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
2451 struct mbuf *m0 = m;
2456 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2458 if (sopt->sopt_val == NULL)
2460 val = sopt->sopt_val;
2461 maxsize = sopt->sopt_valsize;
2462 while (m != NULL && maxsize >= m->m_len) {
2463 bcopy(mtod(m, char *), val, m->m_len);
2464 maxsize -= m->m_len;
2465 val = (caddr_t)val + m->m_len;
2466 valsize += m->m_len;
2470 /* enough soopt buffer should be given from user-land */
2474 sopt->sopt_valsize = valsize;
2479 sohasoutofband(struct socket *so)
2481 if (so->so_sigio != NULL)
2482 pgsigio(so->so_sigio, SIGURG, 0);
2483 KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
2487 sokqfilter(struct file *fp, struct knote *kn)
2489 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2490 struct signalsockbuf *ssb;
2492 switch (kn->kn_filter) {
2494 if (so->so_options & SO_ACCEPTCONN)
2495 kn->kn_fop = &solisten_filtops;
2497 kn->kn_fop = &soread_filtops;
2501 kn->kn_fop = &sowrite_filtops;
2505 kn->kn_fop = &soexcept_filtops;
2509 return (EOPNOTSUPP);
2512 knote_insert(&ssb->ssb_kq.ki_note, kn);
2513 atomic_set_int(&ssb->ssb_flags, SSB_KNOTE);
2518 filt_sordetach(struct knote *kn)
2520 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2522 knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
2523 if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
2524 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_KNOTE);
2529 filt_soread(struct knote *kn, long hint)
2531 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2533 if (kn->kn_sfflags & NOTE_OOB) {
2534 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
2535 kn->kn_fflags |= NOTE_OOB;
2540 kn->kn_data = so->so_rcv.ssb_cc;
2542 if (so->so_state & SS_CANTRCVMORE) {
2544 * Only set NODATA if all data has been exhausted.
2546 if (kn->kn_data == 0)
2547 kn->kn_flags |= EV_NODATA;
2548 kn->kn_flags |= EV_EOF;
2549 kn->kn_fflags = so->so_error;
2552 if (so->so_error) /* temporary udp error */
2554 if (kn->kn_sfflags & NOTE_LOWAT)
2555 return (kn->kn_data >= kn->kn_sdata);
2556 return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
2557 !TAILQ_EMPTY(&so->so_comp));
2561 filt_sowdetach(struct knote *kn)
2563 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2565 knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
2566 if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
2567 atomic_clear_int(&so->so_snd.ssb_flags, SSB_KNOTE);
2572 filt_sowrite(struct knote *kn, long hint)
2574 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2576 kn->kn_data = ssb_space(&so->so_snd);
2577 if (so->so_state & SS_CANTSENDMORE) {
2578 kn->kn_flags |= (EV_EOF | EV_NODATA);
2579 kn->kn_fflags = so->so_error;
2582 if (so->so_error) /* temporary udp error */
2584 if (((so->so_state & SS_ISCONNECTED) == 0) &&
2585 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2587 if (kn->kn_sfflags & NOTE_LOWAT)
2588 return (kn->kn_data >= kn->kn_sdata);
2589 return (kn->kn_data >= so->so_snd.ssb_lowat);
2594 filt_solisten(struct knote *kn, long hint)
2596 struct socket *so = (struct socket *)kn->kn_fp->f_data;
2598 kn->kn_data = so->so_qlen;
2599 return (! TAILQ_EMPTY(&so->so_comp));