9e33a1a251e92d00861a7463189706a582c7c6ad
[dragonfly.git] / sys / kern / uipc_socket.c
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  * 
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
19  * 
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
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
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.
49  *
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
60  * SUCH DAMAGE.
61  *
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 $
64  */
65
66 #include "opt_inet.h"
67 #include "opt_sctp.h"
68
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/fcntl.h>
72 #include <sys/malloc.h>
73 #include <sys/mbuf.h>
74 #include <sys/domain.h>
75 #include <sys/file.h>                   /* for struct knote */
76 #include <sys/kernel.h>
77 #include <sys/event.h>
78 #include <sys/proc.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>
86 #include <sys/uio.h>
87 #include <sys/jail.h>
88 #include <vm/vm_zone.h>
89 #include <vm/pmap.h>
90 #include <net/netmsg2.h>
91 #include <net/netisr2.h>
92
93 #include <sys/thread2.h>
94 #include <sys/socketvar2.h>
95 #include <sys/spinlock2.h>
96
97 #include <machine/limits.h>
98
99 #ifdef INET
100 extern int tcp_sosend_agglim;
101 extern int tcp_sosend_async;
102 extern int tcp_sosend_jcluster;
103 extern int udp_sosend_async;
104 extern int udp_sosend_prepend;
105
106 static int       do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
107 #endif /* INET */
108
109 static void     filt_sordetach(struct knote *kn);
110 static int      filt_soread(struct knote *kn, long hint);
111 static void     filt_sowdetach(struct knote *kn);
112 static int      filt_sowrite(struct knote *kn, long hint);
113 static int      filt_solisten(struct knote *kn, long hint);
114
115 static int      soclose_sync(struct socket *so, int fflag);
116 static void     soclose_fast(struct socket *so);
117
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 };
126
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");
130
131
132 static int somaxconn = SOMAXCONN;
133 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
134     &somaxconn, 0, "Maximum pending socket connection queue size");
135
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");
139
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");
143
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");
147
148 int use_soconnect_async = 1;
149 SYSCTL_INT(_kern_ipc, OID_AUTO, soconnect_async, CTLFLAG_RW,
150     &use_soconnect_async, 0, "soconnect uses asynchronized pru_connect");
151
152 /*
153  * Socket operation routines.
154  * These routines are called by the routines in
155  * sys_socket.c or from a system process, and
156  * implement the semantics of socket operations by
157  * switching out to the protocol specific routines.
158  */
159
160 /*
161  * Get a socket structure, and initialize it.
162  * Note that it would probably be better to allocate socket
163  * and PCB at the same time, but I'm not convinced that all
164  * the protocols can be easily modified to do this.
165  */
166 struct socket *
167 soalloc(int waitok, struct protosw *pr)
168 {
169         struct socket *so;
170         unsigned waitmask;
171
172         waitmask = waitok ? M_WAITOK : M_NOWAIT;
173         so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
174         if (so) {
175                 /* XXX race condition for reentrant kernel */
176                 so->so_proto = pr;
177                 TAILQ_INIT(&so->so_aiojobq);
178                 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
179                 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
180                 lwkt_token_init(&so->so_rcv.ssb_token, "rcvtok");
181                 lwkt_token_init(&so->so_snd.ssb_token, "sndtok");
182                 spin_init(&so->so_rcvd_spin, "soalloc");
183                 netmsg_init(&so->so_rcvd_msg.base, so, &netisr_adone_rport,
184                     MSGF_DROPABLE | MSGF_PRIORITY,
185                     so->so_proto->pr_usrreqs->pru_rcvd);
186                 so->so_rcvd_msg.nm_pru_flags |= PRUR_ASYNC;
187                 so->so_state = SS_NOFDREF;
188                 so->so_refs = 1;
189         }
190         return so;
191 }
192
193 int
194 socreate(int dom, struct socket **aso, int type,
195         int proto, struct thread *td)
196 {
197         struct proc *p = td->td_proc;
198         struct protosw *prp;
199         struct socket *so;
200         struct pru_attach_info ai;
201         int error;
202
203         if (proto)
204                 prp = pffindproto(dom, proto, type);
205         else
206                 prp = pffindtype(dom, type);
207
208         if (prp == NULL || prp->pr_usrreqs->pru_attach == 0)
209                 return (EPROTONOSUPPORT);
210
211         if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
212             prp->pr_domain->dom_family != PF_LOCAL &&
213             prp->pr_domain->dom_family != PF_INET &&
214             prp->pr_domain->dom_family != PF_INET6 &&
215             prp->pr_domain->dom_family != PF_ROUTE) {
216                 return (EPROTONOSUPPORT);
217         }
218
219         if (prp->pr_type != type)
220                 return (EPROTOTYPE);
221         so = soalloc(p != NULL, prp);
222         if (so == NULL)
223                 return (ENOBUFS);
224
225         /*
226          * Callers of socreate() presumably will connect up a descriptor
227          * and call soclose() if they cannot.  This represents our so_refs
228          * (which should be 1) from soalloc().
229          */
230         soclrstate(so, SS_NOFDREF);
231
232         /*
233          * Set a default port for protocol processing.  No action will occur
234          * on the socket on this port until an inpcb is attached to it and
235          * is able to match incoming packets, or until the socket becomes
236          * available to userland.
237          *
238          * We normally default the socket to the protocol thread on cpu 0,
239          * if protocol does not provide its own method to initialize the
240          * default port.
241          *
242          * If PR_SYNC_PORT is set (unix domain sockets) there is no protocol
243          * thread and all pr_*()/pru_*() calls are executed synchronously.
244          */
245         if (prp->pr_flags & PR_SYNC_PORT)
246                 so->so_port = &netisr_sync_port;
247         else if (prp->pr_initport != NULL)
248                 so->so_port = prp->pr_initport();
249         else
250                 so->so_port = netisr_cpuport(0);
251
252         TAILQ_INIT(&so->so_incomp);
253         TAILQ_INIT(&so->so_comp);
254         so->so_type = type;
255         so->so_cred = crhold(p->p_ucred);
256         ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
257         ai.p_ucred = p->p_ucred;
258         ai.fd_rdir = p->p_fd->fd_rdir;
259
260         /*
261          * Auto-sizing of socket buffers is managed by the protocols and
262          * the appropriate flags must be set in the pru_attach function.
263          */
264         error = so_pru_attach(so, proto, &ai);
265         if (error) {
266                 sosetstate(so, SS_NOFDREF);
267                 sofree(so);     /* from soalloc */
268                 return error;
269         }
270
271         /*
272          * NOTE: Returns referenced socket.
273          */
274         *aso = so;
275         return (0);
276 }
277
278 int
279 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
280 {
281         int error;
282
283         error = so_pru_bind(so, nam, td);
284         return (error);
285 }
286
287 static void
288 sodealloc(struct socket *so)
289 {
290         if (so->so_rcv.ssb_hiwat)
291                 (void)chgsbsize(so->so_cred->cr_uidinfo,
292                     &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
293         if (so->so_snd.ssb_hiwat)
294                 (void)chgsbsize(so->so_cred->cr_uidinfo,
295                     &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
296 #ifdef INET
297         /* remove accept filter if present */
298         if (so->so_accf != NULL)
299                 do_setopt_accept_filter(so, NULL);
300 #endif /* INET */
301         crfree(so->so_cred);
302         if (so->so_faddr != NULL)
303                 kfree(so->so_faddr, M_SONAME);
304         kfree(so, M_SOCKET);
305 }
306
307 int
308 solisten(struct socket *so, int backlog, struct thread *td)
309 {
310         int error;
311 #ifdef SCTP
312         short oldopt, oldqlimit;
313 #endif /* SCTP */
314
315         if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))
316                 return (EINVAL);
317
318 #ifdef SCTP
319         oldopt = so->so_options;
320         oldqlimit = so->so_qlimit;
321 #endif /* SCTP */
322
323         lwkt_gettoken(&so->so_rcv.ssb_token);
324         if (TAILQ_EMPTY(&so->so_comp))
325                 so->so_options |= SO_ACCEPTCONN;
326         lwkt_reltoken(&so->so_rcv.ssb_token);
327         if (backlog < 0 || backlog > somaxconn)
328                 backlog = somaxconn;
329         so->so_qlimit = backlog;
330         /* SCTP needs to look at tweak both the inbound backlog parameter AND
331          * the so_options (UDP model both connect's and gets inbound
332          * connections .. implicitly).
333          */
334         error = so_pru_listen(so, td);
335         if (error) {
336 #ifdef SCTP
337                 /* Restore the params */
338                 so->so_options = oldopt;
339                 so->so_qlimit = oldqlimit;
340 #endif /* SCTP */
341                 return (error);
342         }
343         return (0);
344 }
345
346 /*
347  * Destroy a disconnected socket.  This routine is a NOP if entities
348  * still have a reference on the socket:
349  *
350  *      so_pcb -        The protocol stack still has a reference
351  *      SS_NOFDREF -    There is no longer a file pointer reference
352  */
353 void
354 sofree(struct socket *so)
355 {
356         struct socket *head;
357
358         /*
359          * This is a bit hackish at the moment.  We need to interlock
360          * any accept queue we are on before we potentially lose the
361          * last reference to avoid races against a re-reference from
362          * someone operating on the queue.
363          */
364         while ((head = so->so_head) != NULL) {
365                 lwkt_getpooltoken(head);
366                 if (so->so_head == head)
367                         break;
368                 lwkt_relpooltoken(head);
369         }
370
371         /*
372          * Arbitrage the last free.
373          */
374         KKASSERT(so->so_refs > 0);
375         if (atomic_fetchadd_int(&so->so_refs, -1) != 1) {
376                 if (head)
377                         lwkt_relpooltoken(head);
378                 return;
379         }
380
381         KKASSERT(so->so_pcb == NULL && (so->so_state & SS_NOFDREF));
382         KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
383
384         /*
385          * We're done, remove ourselves from the accept queue we are
386          * on, if we are on one.
387          */
388         if (head != NULL) {
389                 if (so->so_state & SS_INCOMP) {
390                         TAILQ_REMOVE(&head->so_incomp, so, so_list);
391                         head->so_incqlen--;
392                 } else if (so->so_state & SS_COMP) {
393                         /*
394                          * We must not decommission a socket that's
395                          * on the accept(2) queue.  If we do, then
396                          * accept(2) may hang after select(2) indicated
397                          * that the listening socket was ready.
398                          */
399                         lwkt_relpooltoken(head);
400                         return;
401                 } else {
402                         panic("sofree: not queued");
403                 }
404                 soclrstate(so, SS_INCOMP);
405                 so->so_head = NULL;
406                 lwkt_relpooltoken(head);
407         }
408         ssb_release(&so->so_snd, so);
409         sorflush(so);
410         sodealloc(so);
411 }
412
413 /*
414  * Close a socket on last file table reference removal.
415  * Initiate disconnect if connected.
416  * Free socket when disconnect complete.
417  */
418 int
419 soclose(struct socket *so, int fflag)
420 {
421         int error;
422
423         funsetown(&so->so_sigio);
424         sosetstate(so, SS_ISCLOSING);
425         if (!use_soclose_fast ||
426             (so->so_proto->pr_flags & PR_SYNC_PORT) ||
427             ((so->so_state & SS_ISCONNECTED) &&
428              (so->so_options & SO_LINGER))) {
429                 error = soclose_sync(so, fflag);
430         } else {
431                 soclose_fast(so);
432                 error = 0;
433         }
434         return error;
435 }
436
437 void
438 sodiscard(struct socket *so)
439 {
440         lwkt_getpooltoken(so);
441         if (so->so_options & SO_ACCEPTCONN) {
442                 struct socket *sp;
443
444                 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
445                         TAILQ_REMOVE(&so->so_incomp, sp, so_list);
446                         soclrstate(sp, SS_INCOMP);
447                         sp->so_head = NULL;
448                         so->so_incqlen--;
449                         soabort_async(sp);
450                 }
451                 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
452                         TAILQ_REMOVE(&so->so_comp, sp, so_list);
453                         soclrstate(sp, SS_COMP);
454                         sp->so_head = NULL;
455                         so->so_qlen--;
456                         soabort_async(sp);
457                 }
458         }
459         lwkt_relpooltoken(so);
460
461         if (so->so_state & SS_NOFDREF)
462                 panic("soclose: NOFDREF");
463         sosetstate(so, SS_NOFDREF);     /* take ref */
464 }
465
466 void
467 soinherit(struct socket *so, struct socket *so_inh)
468 {
469         TAILQ_HEAD(, socket) comp, incomp;
470         struct socket *sp;
471         int qlen, incqlen;
472
473         KASSERT(so->so_options & SO_ACCEPTCONN,
474             ("so does not accept connection"));
475         KASSERT(so_inh->so_options & SO_ACCEPTCONN,
476             ("so_inh does not accept connection"));
477
478         TAILQ_INIT(&comp);
479         TAILQ_INIT(&incomp);
480
481         lwkt_getpooltoken(so);
482         lwkt_getpooltoken(so_inh);
483
484         /*
485          * Save completed queue and incompleted queue
486          */
487         TAILQ_CONCAT(&comp, &so->so_comp, so_list);
488         qlen = so->so_qlen;
489         so->so_qlen = 0;
490
491         TAILQ_CONCAT(&incomp, &so->so_incomp, so_list);
492         incqlen = so->so_incqlen;
493         so->so_incqlen = 0;
494
495         /*
496          * Append the saved completed queue and incompleted
497          * queue to the socket inherits them.
498          *
499          * XXX
500          * This may temporarily break the inheriting socket's
501          * so_qlimit.
502          */
503         TAILQ_FOREACH(sp, &comp, so_list) {
504                 sp->so_head = so_inh;
505                 crfree(sp->so_cred);
506                 sp->so_cred = crhold(so_inh->so_cred);
507         }
508
509         TAILQ_FOREACH(sp, &incomp, so_list) {
510                 sp->so_head = so_inh;
511                 crfree(sp->so_cred);
512                 sp->so_cred = crhold(so_inh->so_cred);
513         }
514
515         TAILQ_CONCAT(&so_inh->so_comp, &comp, so_list);
516         so_inh->so_qlen += qlen;
517
518         TAILQ_CONCAT(&so_inh->so_incomp, &incomp, so_list);
519         so_inh->so_incqlen += incqlen;
520
521         lwkt_relpooltoken(so_inh);
522         lwkt_relpooltoken(so);
523
524         if (qlen) {
525                 /*
526                  * "New" connections have arrived
527                  */
528                 sorwakeup(so_inh);
529                 wakeup(&so_inh->so_timeo);
530         }
531 }
532
533 static int
534 soclose_sync(struct socket *so, int fflag)
535 {
536         int error = 0;
537
538         if (so->so_pcb == NULL)
539                 goto discard;
540         if (so->so_state & SS_ISCONNECTED) {
541                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
542                         error = sodisconnect(so);
543                         if (error)
544                                 goto drop;
545                 }
546                 if (so->so_options & SO_LINGER) {
547                         if ((so->so_state & SS_ISDISCONNECTING) &&
548                             (fflag & FNONBLOCK))
549                                 goto drop;
550                         while (so->so_state & SS_ISCONNECTED) {
551                                 error = tsleep(&so->so_timeo, PCATCH,
552                                                "soclos", so->so_linger * hz);
553                                 if (error)
554                                         break;
555                         }
556                 }
557         }
558 drop:
559         if (so->so_pcb) {
560                 int error2;
561
562                 error2 = so_pru_detach(so);
563                 if (error2 == EJUSTRETURN) {
564                         /*
565                          * Protocol will call sodiscard()
566                          * and sofree() for us.
567                          */
568                         return error;
569                 }
570                 if (error == 0)
571                         error = error2;
572         }
573 discard:
574         sodiscard(so);
575         so_pru_sync(so);        /* unpend async sending */
576         sofree(so);             /* dispose of ref */
577
578         return (error);
579 }
580
581 static void
582 soclose_sofree_async_handler(netmsg_t msg)
583 {
584         sofree(msg->base.nm_so);
585 }
586
587 static void
588 soclose_sofree_async(struct socket *so)
589 {
590         struct netmsg_base *base = &so->so_clomsg;
591
592         netmsg_init(base, so, &netisr_apanic_rport, 0,
593             soclose_sofree_async_handler);
594         lwkt_sendmsg(so->so_port, &base->lmsg);
595 }
596
597 static void
598 soclose_disconn_async_handler(netmsg_t msg)
599 {
600         struct socket *so = msg->base.nm_so;
601
602         if ((so->so_state & SS_ISCONNECTED) &&
603             (so->so_state & SS_ISDISCONNECTING) == 0)
604                 so_pru_disconnect_direct(so);
605
606         if (so->so_pcb) {
607                 int error;
608
609                 error = so_pru_detach_direct(so);
610                 if (error == EJUSTRETURN) {
611                         /*
612                          * Protocol will call sodiscard()
613                          * and sofree() for us.
614                          */
615                         return;
616                 }
617         }
618
619         sodiscard(so);
620         sofree(so);
621 }
622
623 static void
624 soclose_disconn_async(struct socket *so)
625 {
626         struct netmsg_base *base = &so->so_clomsg;
627
628         netmsg_init(base, so, &netisr_apanic_rport, 0,
629             soclose_disconn_async_handler);
630         lwkt_sendmsg(so->so_port, &base->lmsg);
631 }
632
633 static void
634 soclose_detach_async_handler(netmsg_t msg)
635 {
636         struct socket *so = msg->base.nm_so;
637
638         if (so->so_pcb) {
639                 int error;
640
641                 error = so_pru_detach_direct(so);
642                 if (error == EJUSTRETURN) {
643                         /*
644                          * Protocol will call sodiscard()
645                          * and sofree() for us.
646                          */
647                         return;
648                 }
649         }
650
651         sodiscard(so);
652         sofree(so);
653 }
654
655 static void
656 soclose_detach_async(struct socket *so)
657 {
658         struct netmsg_base *base = &so->so_clomsg;
659
660         netmsg_init(base, so, &netisr_apanic_rport, 0,
661             soclose_detach_async_handler);
662         lwkt_sendmsg(so->so_port, &base->lmsg);
663 }
664
665 static void
666 soclose_fast(struct socket *so)
667 {
668         if (so->so_pcb == NULL)
669                 goto discard;
670
671         if ((so->so_state & SS_ISCONNECTED) &&
672             (so->so_state & SS_ISDISCONNECTING) == 0) {
673                 soclose_disconn_async(so);
674                 return;
675         }
676
677         if (so->so_pcb) {
678                 soclose_detach_async(so);
679                 return;
680         }
681
682 discard:
683         sodiscard(so);
684         soclose_sofree_async(so);
685 }
686
687 /*
688  * Abort and destroy a socket.  Only one abort can be in progress
689  * at any given moment.
690  */
691 void
692 soabort(struct socket *so)
693 {
694         soreference(so);
695         so_pru_abort(so);
696 }
697
698 void
699 soabort_async(struct socket *so)
700 {
701         soreference(so);
702         so_pru_abort_async(so);
703 }
704
705 void
706 soabort_oncpu(struct socket *so)
707 {
708         soreference(so);
709         so_pru_abort_direct(so);
710 }
711
712 /*
713  * so is passed in ref'd, which becomes owned by
714  * the cleared SS_NOFDREF flag.
715  */
716 void
717 soaccept_generic(struct socket *so)
718 {
719         if ((so->so_state & SS_NOFDREF) == 0)
720                 panic("soaccept: !NOFDREF");
721         soclrstate(so, SS_NOFDREF);     /* owned by lack of SS_NOFDREF */
722 }
723
724 int
725 soaccept(struct socket *so, struct sockaddr **nam)
726 {
727         int error;
728
729         soaccept_generic(so);
730         error = so_pru_accept(so, nam);
731         return (error);
732 }
733
734 int
735 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td,
736     boolean_t sync)
737 {
738         int error;
739
740         if (so->so_options & SO_ACCEPTCONN)
741                 return (EOPNOTSUPP);
742         /*
743          * If protocol is connection-based, can only connect once.
744          * Otherwise, if connected, try to disconnect first.
745          * This allows user to disconnect by connecting to, e.g.,
746          * a null address.
747          */
748         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
749             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
750             (error = sodisconnect(so)))) {
751                 error = EISCONN;
752         } else {
753                 /*
754                  * Prevent accumulated error from previous connection
755                  * from biting us.
756                  */
757                 so->so_error = 0;
758                 if (!sync && so->so_proto->pr_usrreqs->pru_preconnect)
759                         error = so_pru_connect_async(so, nam, td);
760                 else
761                         error = so_pru_connect(so, nam, td);
762         }
763         return (error);
764 }
765
766 int
767 soconnect2(struct socket *so1, struct socket *so2)
768 {
769         int error;
770
771         error = so_pru_connect2(so1, so2);
772         return (error);
773 }
774
775 int
776 sodisconnect(struct socket *so)
777 {
778         int error;
779
780         if ((so->so_state & SS_ISCONNECTED) == 0) {
781                 error = ENOTCONN;
782                 goto bad;
783         }
784         if (so->so_state & SS_ISDISCONNECTING) {
785                 error = EALREADY;
786                 goto bad;
787         }
788         error = so_pru_disconnect(so);
789 bad:
790         return (error);
791 }
792
793 #define SBLOCKWAIT(f)   (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
794 /*
795  * Send on a socket.
796  * If send must go all at once and message is larger than
797  * send buffering, then hard error.
798  * Lock against other senders.
799  * If must go all at once and not enough room now, then
800  * inform user that this would block and do nothing.
801  * Otherwise, if nonblocking, send as much as possible.
802  * The data to be sent is described by "uio" if nonzero,
803  * otherwise by the mbuf chain "top" (which must be null
804  * if uio is not).  Data provided in mbuf chain must be small
805  * enough to send all at once.
806  *
807  * Returns nonzero on error, timeout or signal; callers
808  * must check for short counts if EINTR/ERESTART are returned.
809  * Data and control buffers are freed on return.
810  */
811 int
812 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
813         struct mbuf *top, struct mbuf *control, int flags,
814         struct thread *td)
815 {
816         struct mbuf **mp;
817         struct mbuf *m;
818         size_t resid;
819         int space, len;
820         int clen = 0, error, dontroute, mlen;
821         int atomic = sosendallatonce(so) || top;
822         int pru_flags;
823
824         if (uio) {
825                 resid = uio->uio_resid;
826         } else {
827                 resid = (size_t)top->m_pkthdr.len;
828 #ifdef INVARIANTS
829                 len = 0;
830                 for (m = top; m; m = m->m_next)
831                         len += m->m_len;
832                 KKASSERT(top->m_pkthdr.len == len);
833 #endif
834         }
835
836         /*
837          * WARNING!  resid is unsigned, space and len are signed.  space
838          *           can wind up negative if the sockbuf is overcommitted.
839          *
840          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
841          * type sockets since that's an error.
842          */
843         if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
844                 error = EINVAL;
845                 goto out;
846         }
847
848         dontroute =
849             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
850             (so->so_proto->pr_flags & PR_ATOMIC);
851         if (td->td_lwp != NULL)
852                 td->td_lwp->lwp_ru.ru_msgsnd++;
853         if (control)
854                 clen = control->m_len;
855 #define gotoerr(errcode)        { error = errcode; goto release; }
856
857 restart:
858         error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
859         if (error)
860                 goto out;
861
862         do {
863                 if (so->so_state & SS_CANTSENDMORE)
864                         gotoerr(EPIPE);
865                 if (so->so_error) {
866                         error = so->so_error;
867                         so->so_error = 0;
868                         goto release;
869                 }
870                 if ((so->so_state & SS_ISCONNECTED) == 0) {
871                         /*
872                          * `sendto' and `sendmsg' is allowed on a connection-
873                          * based socket if it supports implied connect.
874                          * Return ENOTCONN if not connected and no address is
875                          * supplied.
876                          */
877                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
878                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
879                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
880                                     !(resid == 0 && clen != 0))
881                                         gotoerr(ENOTCONN);
882                         } else if (addr == NULL)
883                             gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
884                                    ENOTCONN : EDESTADDRREQ);
885                 }
886                 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
887                     clen > so->so_snd.ssb_hiwat) {
888                         gotoerr(EMSGSIZE);
889                 }
890                 space = ssb_space(&so->so_snd);
891                 if (flags & MSG_OOB)
892                         space += 1024;
893                 if ((space < 0 || (size_t)space < resid + clen) && uio &&
894                     (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
895                         if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
896                                 gotoerr(EWOULDBLOCK);
897                         ssb_unlock(&so->so_snd);
898                         error = ssb_wait(&so->so_snd);
899                         if (error)
900                                 goto out;
901                         goto restart;
902                 }
903                 mp = &top;
904                 space -= clen;
905                 do {
906                     if (uio == NULL) {
907                         /*
908                          * Data is prepackaged in "top".
909                          */
910                         resid = 0;
911                         if (flags & MSG_EOR)
912                                 top->m_flags |= M_EOR;
913                     } else do {
914                         if (resid > INT_MAX)
915                                 resid = INT_MAX;
916                         m = m_getl((int)resid, MB_WAIT, MT_DATA,
917                                    top == NULL ? M_PKTHDR : 0, &mlen);
918                         if (top == NULL) {
919                                 m->m_pkthdr.len = 0;
920                                 m->m_pkthdr.rcvif = NULL;
921                         }
922                         len = imin((int)szmin(mlen, resid), space);
923                         if (resid < MINCLSIZE) {
924                                 /*
925                                  * For datagram protocols, leave room
926                                  * for protocol headers in first mbuf.
927                                  */
928                                 if (atomic && top == NULL && len < mlen)
929                                         MH_ALIGN(m, len);
930                         }
931                         space -= len;
932                         error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
933                         resid = uio->uio_resid;
934                         m->m_len = len;
935                         *mp = m;
936                         top->m_pkthdr.len += len;
937                         if (error)
938                                 goto release;
939                         mp = &m->m_next;
940                         if (resid == 0) {
941                                 if (flags & MSG_EOR)
942                                         top->m_flags |= M_EOR;
943                                 break;
944                         }
945                     } while (space > 0 && atomic);
946                     if (dontroute)
947                             so->so_options |= SO_DONTROUTE;
948                     if (flags & MSG_OOB) {
949                             pru_flags = PRUS_OOB;
950                     } else if ((flags & MSG_EOF) &&
951                                (so->so_proto->pr_flags & PR_IMPLOPCL) &&
952                                (resid == 0)) {
953                             /*
954                              * If the user set MSG_EOF, the protocol
955                              * understands this flag and nothing left to
956                              * send then use PRU_SEND_EOF instead of PRU_SEND.
957                              */
958                             pru_flags = PRUS_EOF;
959                     } else if (resid > 0 && space > 0) {
960                             /* If there is more to send, set PRUS_MORETOCOME */
961                             pru_flags = PRUS_MORETOCOME;
962                     } else {
963                             pru_flags = 0;
964                     }
965                     /*
966                      * XXX all the SS_CANTSENDMORE checks previously
967                      * done could be out of date.  We could have recieved
968                      * a reset packet in an interrupt or maybe we slept
969                      * while doing page faults in uiomove() etc. We could
970                      * probably recheck again inside the splnet() protection
971                      * here, but there are probably other places that this
972                      * also happens.  We must rethink this.
973                      */
974                     error = so_pru_send(so, pru_flags, top, addr, control, td);
975                     if (dontroute)
976                             so->so_options &= ~SO_DONTROUTE;
977                     clen = 0;
978                     control = NULL;
979                     top = NULL;
980                     mp = &top;
981                     if (error)
982                             goto release;
983                 } while (resid && space > 0);
984         } while (resid);
985
986 release:
987         ssb_unlock(&so->so_snd);
988 out:
989         if (top)
990                 m_freem(top);
991         if (control)
992                 m_freem(control);
993         return (error);
994 }
995
996 #ifdef INET
997 /*
998  * A specialization of sosend() for UDP based on protocol-specific knowledge:
999  *   so->so_proto->pr_flags has the PR_ATOMIC field set.  This means that
1000  *      sosendallatonce() returns true,
1001  *      the "atomic" variable is true,
1002  *      and sosendudp() blocks until space is available for the entire send.
1003  *   so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
1004  *      PR_IMPLOPCL flags set.
1005  *   UDP has no out-of-band data.
1006  *   UDP has no control data.
1007  *   UDP does not support MSG_EOR.
1008  */
1009 int
1010 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1011           struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1012 {
1013         size_t resid;
1014         int error, pru_flags = 0;
1015         int space;
1016
1017         if (td->td_lwp != NULL)
1018                 td->td_lwp->lwp_ru.ru_msgsnd++;
1019         if (control)
1020                 m_freem(control);
1021
1022         KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
1023         resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
1024
1025 restart:
1026         error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1027         if (error)
1028                 goto out;
1029
1030         if (so->so_state & SS_CANTSENDMORE)
1031                 gotoerr(EPIPE);
1032         if (so->so_error) {
1033                 error = so->so_error;
1034                 so->so_error = 0;
1035                 goto release;
1036         }
1037         if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
1038                 gotoerr(EDESTADDRREQ);
1039         if (resid > so->so_snd.ssb_hiwat)
1040                 gotoerr(EMSGSIZE);
1041         space = ssb_space(&so->so_snd);
1042         if (uio && (space < 0 || (size_t)space < resid)) {
1043                 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1044                         gotoerr(EWOULDBLOCK);
1045                 ssb_unlock(&so->so_snd);
1046                 error = ssb_wait(&so->so_snd);
1047                 if (error)
1048                         goto out;
1049                 goto restart;
1050         }
1051
1052         if (uio) {
1053                 int hdrlen = max_hdr;
1054
1055                 /*
1056                  * We try to optimize out the additional mbuf
1057                  * allocations in M_PREPEND() on output path, e.g.
1058                  * - udp_output(), when it tries to prepend protocol
1059                  *   headers.
1060                  * - Link layer output function, when it tries to
1061                  *   prepend link layer header.
1062                  *
1063                  * This probably will not benefit any data that will
1064                  * be fragmented, so this optimization is only performed
1065                  * when the size of data and max size of protocol+link
1066                  * headers fit into one mbuf cluster.
1067                  */
1068                 if (uio->uio_resid > MCLBYTES - hdrlen ||
1069                     !udp_sosend_prepend) {
1070                         top = m_uiomove(uio);
1071                         if (top == NULL)
1072                                 goto release;
1073                 } else {
1074                         int nsize;
1075
1076                         top = m_getl(uio->uio_resid + hdrlen, MB_WAIT,
1077                             MT_DATA, M_PKTHDR, &nsize);
1078                         KASSERT(nsize >= uio->uio_resid + hdrlen,
1079                             ("sosendudp invalid nsize %d, "
1080                              "resid %zu, hdrlen %d",
1081                              nsize, uio->uio_resid, hdrlen));
1082
1083                         top->m_len = uio->uio_resid;
1084                         top->m_pkthdr.len = uio->uio_resid;
1085                         top->m_data += hdrlen;
1086
1087                         error = uiomove(mtod(top, caddr_t), top->m_len, uio);
1088                         if (error)
1089                                 goto out;
1090                 }
1091         }
1092
1093         if (flags & MSG_DONTROUTE)
1094                 pru_flags |= PRUS_DONTROUTE;
1095
1096         if (udp_sosend_async && (flags & MSG_SYNC) == 0) {
1097                 so_pru_send_async(so, pru_flags, top, addr, NULL, td);
1098                 error = 0;
1099         } else {
1100                 error = so_pru_send(so, pru_flags, top, addr, NULL, td);
1101         }
1102         top = NULL;             /* sent or freed in lower layer */
1103
1104 release:
1105         ssb_unlock(&so->so_snd);
1106 out:
1107         if (top)
1108                 m_freem(top);
1109         return (error);
1110 }
1111
1112 int
1113 sosendtcp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1114         struct mbuf *top, struct mbuf *control, int flags,
1115         struct thread *td)
1116 {
1117         struct mbuf **mp;
1118         struct mbuf *m;
1119         size_t resid;
1120         int space, len;
1121         int error, mlen;
1122         int allatonce;
1123         int pru_flags;
1124
1125         if (uio) {
1126                 KKASSERT(top == NULL);
1127                 allatonce = 0;
1128                 resid = uio->uio_resid;
1129         } else {
1130                 allatonce = 1;
1131                 resid = (size_t)top->m_pkthdr.len;
1132 #ifdef INVARIANTS
1133                 len = 0;
1134                 for (m = top; m; m = m->m_next)
1135                         len += m->m_len;
1136                 KKASSERT(top->m_pkthdr.len == len);
1137 #endif
1138         }
1139
1140         /*
1141          * WARNING!  resid is unsigned, space and len are signed.  space
1142          *           can wind up negative if the sockbuf is overcommitted.
1143          *
1144          * Also check to make sure that MSG_EOR isn't used on TCP
1145          */
1146         if (flags & MSG_EOR) {
1147                 error = EINVAL;
1148                 goto out;
1149         }
1150
1151         if (control) {
1152                 /* TCP doesn't do control messages (rights, creds, etc) */
1153                 if (control->m_len) {
1154                         error = EINVAL;
1155                         goto out;
1156                 }
1157                 m_freem(control);       /* empty control, just free it */
1158                 control = NULL;
1159         }
1160
1161         if (td->td_lwp != NULL)
1162                 td->td_lwp->lwp_ru.ru_msgsnd++;
1163
1164 #define gotoerr(errcode)        { error = errcode; goto release; }
1165
1166 restart:
1167         error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
1168         if (error)
1169                 goto out;
1170
1171         do {
1172                 if (so->so_state & SS_CANTSENDMORE)
1173                         gotoerr(EPIPE);
1174                 if (so->so_error) {
1175                         error = so->so_error;
1176                         so->so_error = 0;
1177                         goto release;
1178                 }
1179                 if ((so->so_state & SS_ISCONNECTED) == 0 &&
1180                     (so->so_state & SS_ISCONFIRMING) == 0)
1181                         gotoerr(ENOTCONN);
1182                 if (allatonce && resid > so->so_snd.ssb_hiwat)
1183                         gotoerr(EMSGSIZE);
1184
1185                 space = ssb_space_prealloc(&so->so_snd);
1186                 if (flags & MSG_OOB)
1187                         space += 1024;
1188                 if ((space < 0 || (size_t)space < resid) && !allatonce &&
1189                     space < so->so_snd.ssb_lowat) {
1190                         if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
1191                                 gotoerr(EWOULDBLOCK);
1192                         ssb_unlock(&so->so_snd);
1193                         error = ssb_wait(&so->so_snd);
1194                         if (error)
1195                                 goto out;
1196                         goto restart;
1197                 }
1198                 mp = &top;
1199                 do {
1200                     int cnt = 0, async = 0;
1201
1202                     if (uio == NULL) {
1203                         /*
1204                          * Data is prepackaged in "top".
1205                          */
1206                         resid = 0;
1207                     } else do {
1208                         if (resid > INT_MAX)
1209                                 resid = INT_MAX;
1210                         if (tcp_sosend_jcluster) {
1211                                 m = m_getlj((int)resid, MB_WAIT, MT_DATA,
1212                                            top == NULL ? M_PKTHDR : 0, &mlen);
1213                         } else {
1214                                 m = m_getl((int)resid, MB_WAIT, MT_DATA,
1215                                            top == NULL ? M_PKTHDR : 0, &mlen);
1216                         }
1217                         if (top == NULL) {
1218                                 m->m_pkthdr.len = 0;
1219                                 m->m_pkthdr.rcvif = NULL;
1220                         }
1221                         len = imin((int)szmin(mlen, resid), space);
1222                         space -= len;
1223                         error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
1224                         resid = uio->uio_resid;
1225                         m->m_len = len;
1226                         *mp = m;
1227                         top->m_pkthdr.len += len;
1228                         if (error)
1229                                 goto release;
1230                         mp = &m->m_next;
1231                         if (resid == 0)
1232                                 break;
1233                         ++cnt;
1234                     } while (space > 0 && cnt < tcp_sosend_agglim);
1235
1236                     if (tcp_sosend_async)
1237                             async = 1;
1238
1239                     if (flags & MSG_OOB) {
1240                             pru_flags = PRUS_OOB;
1241                             async = 0;
1242                     } else if ((flags & MSG_EOF) && resid == 0) {
1243                             pru_flags = PRUS_EOF;
1244                     } else if (resid > 0 && space > 0) {
1245                             /* If there is more to send, set PRUS_MORETOCOME */
1246                             pru_flags = PRUS_MORETOCOME;
1247                             async = 1;
1248                     } else {
1249                             pru_flags = 0;
1250                     }
1251
1252                     if (flags & MSG_SYNC)
1253                             async = 0;
1254
1255                     /*
1256                      * XXX all the SS_CANTSENDMORE checks previously
1257                      * done could be out of date.  We could have recieved
1258                      * a reset packet in an interrupt or maybe we slept
1259                      * while doing page faults in uiomove() etc. We could
1260                      * probably recheck again inside the splnet() protection
1261                      * here, but there are probably other places that this
1262                      * also happens.  We must rethink this.
1263                      */
1264                     for (m = top; m; m = m->m_next)
1265                             ssb_preallocstream(&so->so_snd, m);
1266                     if (!async) {
1267                             error = so_pru_send(so, pru_flags, top,
1268                                 NULL, NULL, td);
1269                     } else {
1270                             so_pru_send_async(so, pru_flags, top,
1271                                 NULL, NULL, td);
1272                             error = 0;
1273                     }
1274
1275                     top = NULL;
1276                     mp = &top;
1277                     if (error)
1278                             goto release;
1279                 } while (resid && space > 0);
1280         } while (resid);
1281
1282 release:
1283         ssb_unlock(&so->so_snd);
1284 out:
1285         if (top)
1286                 m_freem(top);
1287         if (control)
1288                 m_freem(control);
1289         return (error);
1290 }
1291 #endif
1292
1293 /*
1294  * Implement receive operations on a socket.
1295  *
1296  * We depend on the way that records are added to the signalsockbuf
1297  * by sbappend*.  In particular, each record (mbufs linked through m_next)
1298  * must begin with an address if the protocol so specifies,
1299  * followed by an optional mbuf or mbufs containing ancillary data,
1300  * and then zero or more mbufs of data.
1301  *
1302  * Although the signalsockbuf is locked, new data may still be appended.
1303  * A token inside the ssb_lock deals with MP issues and still allows
1304  * the network to access the socket if we block in a uio.
1305  *
1306  * The caller may receive the data as a single mbuf chain by supplying
1307  * an mbuf **mp0 for use in returning the chain.  The uio is then used
1308  * only for the count in uio_resid.
1309  */
1310 int
1311 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1312           struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1313 {
1314         struct mbuf *m, *n;
1315         struct mbuf *free_chain = NULL;
1316         int flags, len, error, offset;
1317         struct protosw *pr = so->so_proto;
1318         int moff, type = 0;
1319         size_t resid, orig_resid;
1320
1321         if (uio)
1322                 resid = uio->uio_resid;
1323         else
1324                 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1325         orig_resid = resid;
1326
1327         if (psa)
1328                 *psa = NULL;
1329         if (controlp)
1330                 *controlp = NULL;
1331         if (flagsp)
1332                 flags = *flagsp &~ MSG_EOR;
1333         else
1334                 flags = 0;
1335         if (flags & MSG_OOB) {
1336                 m = m_get(MB_WAIT, MT_DATA);
1337                 if (m == NULL)
1338                         return (ENOBUFS);
1339                 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1340                 if (error)
1341                         goto bad;
1342                 if (sio) {
1343                         do {
1344                                 sbappend(sio, m);
1345                                 KKASSERT(resid >= (size_t)m->m_len);
1346                                 resid -= (size_t)m->m_len;
1347                         } while (resid > 0 && m);
1348                 } else {
1349                         do {
1350                                 uio->uio_resid = resid;
1351                                 error = uiomove(mtod(m, caddr_t),
1352                                                 (int)szmin(resid, m->m_len),
1353                                                 uio);
1354                                 resid = uio->uio_resid;
1355                                 m = m_free(m);
1356                         } while (uio->uio_resid && error == 0 && m);
1357                 }
1358 bad:
1359                 if (m)
1360                         m_freem(m);
1361                 return (error);
1362         }
1363         if ((so->so_state & SS_ISCONFIRMING) && resid)
1364                 so_pru_rcvd(so, 0);
1365
1366         /*
1367          * The token interlocks against the protocol thread while
1368          * ssb_lock is a blocking lock against other userland entities.
1369          */
1370         lwkt_gettoken(&so->so_rcv.ssb_token);
1371 restart:
1372         error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1373         if (error)
1374                 goto done;
1375
1376         m = so->so_rcv.ssb_mb;
1377         /*
1378          * If we have less data than requested, block awaiting more
1379          * (subject to any timeout) if:
1380          *   1. the current count is less than the low water mark, or
1381          *   2. MSG_WAITALL is set, and it is possible to do the entire
1382          *      receive operation at once if we block (resid <= hiwat).
1383          *   3. MSG_DONTWAIT is not set
1384          * If MSG_WAITALL is set but resid is larger than the receive buffer,
1385          * we have to do the receive in sections, and thus risk returning
1386          * a short count if a timeout or signal occurs after we start.
1387          */
1388         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1389             (size_t)so->so_rcv.ssb_cc < resid) &&
1390             (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1391             ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
1392             m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1393                 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1394                 if (so->so_error) {
1395                         if (m)
1396                                 goto dontblock;
1397                         error = so->so_error;
1398                         if ((flags & MSG_PEEK) == 0)
1399                                 so->so_error = 0;
1400                         goto release;
1401                 }
1402                 if (so->so_state & SS_CANTRCVMORE) {
1403                         if (m)
1404                                 goto dontblock;
1405                         else
1406                                 goto release;
1407                 }
1408                 for (; m; m = m->m_next) {
1409                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1410                                 m = so->so_rcv.ssb_mb;
1411                                 goto dontblock;
1412                         }
1413                 }
1414                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1415                     (pr->pr_flags & PR_CONNREQUIRED)) {
1416                         error = ENOTCONN;
1417                         goto release;
1418                 }
1419                 if (resid == 0)
1420                         goto release;
1421                 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1422                         error = EWOULDBLOCK;
1423                         goto release;
1424                 }
1425                 ssb_unlock(&so->so_rcv);
1426                 error = ssb_wait(&so->so_rcv);
1427                 if (error)
1428                         goto done;
1429                 goto restart;
1430         }
1431 dontblock:
1432         if (uio && uio->uio_td && uio->uio_td->td_proc)
1433                 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1434
1435         /*
1436          * note: m should be == sb_mb here.  Cache the next record while
1437          * cleaning up.  Note that calling m_free*() will break out critical
1438          * section.
1439          */
1440         KKASSERT(m == so->so_rcv.ssb_mb);
1441
1442         /*
1443          * Skip any address mbufs prepending the record.
1444          */
1445         if (pr->pr_flags & PR_ADDR) {
1446                 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
1447                 orig_resid = 0;
1448                 if (psa)
1449                         *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1450                 if (flags & MSG_PEEK)
1451                         m = m->m_next;
1452                 else
1453                         m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1454         }
1455
1456         /*
1457          * Skip any control mbufs prepending the record.
1458          */
1459 #ifdef SCTP
1460         if (pr->pr_flags & PR_ADDR_OPT) {
1461                 /*
1462                  * For SCTP we may be getting a
1463                  * whole message OR a partial delivery.
1464                  */
1465                 if (m && m->m_type == MT_SONAME) {
1466                         orig_resid = 0;
1467                         if (psa)
1468                                 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1469                         if (flags & MSG_PEEK)
1470                                 m = m->m_next;
1471                         else
1472                                 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1473                 }
1474         }
1475 #endif /* SCTP */
1476         while (m && m->m_type == MT_CONTROL && error == 0) {
1477                 if (flags & MSG_PEEK) {
1478                         if (controlp)
1479                                 *controlp = m_copy(m, 0, m->m_len);
1480                         m = m->m_next;  /* XXX race */
1481                 } else {
1482                         if (controlp) {
1483                                 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1484                                 if (pr->pr_domain->dom_externalize &&
1485                                     mtod(m, struct cmsghdr *)->cmsg_type ==
1486                                     SCM_RIGHTS)
1487                                    error = (*pr->pr_domain->dom_externalize)(m);
1488                                 *controlp = m;
1489                                 m = n;
1490                         } else {
1491                                 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1492                         }
1493                 }
1494                 if (controlp && *controlp) {
1495                         orig_resid = 0;
1496                         controlp = &(*controlp)->m_next;
1497                 }
1498         }
1499
1500         /*
1501          * flag OOB data.
1502          */
1503         if (m) {
1504                 type = m->m_type;
1505                 if (type == MT_OOBDATA)
1506                         flags |= MSG_OOB;
1507         }
1508
1509         /*
1510          * Copy to the UIO or mbuf return chain (*mp).
1511          */
1512         moff = 0;
1513         offset = 0;
1514         while (m && resid > 0 && error == 0) {
1515                 if (m->m_type == MT_OOBDATA) {
1516                         if (type != MT_OOBDATA)
1517                                 break;
1518                 } else if (type == MT_OOBDATA)
1519                         break;
1520                 else
1521                     KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1522                         ("receive 3"));
1523                 soclrstate(so, SS_RCVATMARK);
1524                 len = (resid > INT_MAX) ? INT_MAX : resid;
1525                 if (so->so_oobmark && len > so->so_oobmark - offset)
1526                         len = so->so_oobmark - offset;
1527                 if (len > m->m_len - moff)
1528                         len = m->m_len - moff;
1529
1530                 /*
1531                  * Copy out to the UIO or pass the mbufs back to the SIO.
1532                  * The SIO is dealt with when we eat the mbuf, but deal
1533                  * with the resid here either way.
1534                  */
1535                 if (uio) {
1536                         uio->uio_resid = resid;
1537                         error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1538                         resid = uio->uio_resid;
1539                         if (error)
1540                                 goto release;
1541                 } else {
1542                         resid -= (size_t)len;
1543                 }
1544
1545                 /*
1546                  * Eat the entire mbuf or just a piece of it
1547                  */
1548                 if (len == m->m_len - moff) {
1549                         if (m->m_flags & M_EOR)
1550                                 flags |= MSG_EOR;
1551 #ifdef SCTP
1552                         if (m->m_flags & M_NOTIFICATION)
1553                                 flags |= MSG_NOTIFICATION;
1554 #endif /* SCTP */
1555                         if (flags & MSG_PEEK) {
1556                                 m = m->m_next;
1557                                 moff = 0;
1558                         } else {
1559                                 if (sio) {
1560                                         n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1561                                         sbappend(sio, m);
1562                                         m = n;
1563                                 } else {
1564                                         m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1565                                 }
1566                         }
1567                 } else {
1568                         if (flags & MSG_PEEK) {
1569                                 moff += len;
1570                         } else {
1571                                 if (sio) {
1572                                         n = m_copym(m, 0, len, MB_WAIT);
1573                                         if (n)
1574                                                 sbappend(sio, n);
1575                                 }
1576                                 m->m_data += len;
1577                                 m->m_len -= len;
1578                                 so->so_rcv.ssb_cc -= len;
1579                         }
1580                 }
1581                 if (so->so_oobmark) {
1582                         if ((flags & MSG_PEEK) == 0) {
1583                                 so->so_oobmark -= len;
1584                                 if (so->so_oobmark == 0) {
1585                                         sosetstate(so, SS_RCVATMARK);
1586                                         break;
1587                                 }
1588                         } else {
1589                                 offset += len;
1590                                 if (offset == so->so_oobmark)
1591                                         break;
1592                         }
1593                 }
1594                 if (flags & MSG_EOR)
1595                         break;
1596                 /*
1597                  * If the MSG_WAITALL flag is set (for non-atomic socket),
1598                  * we must not quit until resid == 0 or an error
1599                  * termination.  If a signal/timeout occurs, return
1600                  * with a short count but without error.
1601                  * Keep signalsockbuf locked against other readers.
1602                  */
1603                 while ((flags & MSG_WAITALL) && m == NULL && 
1604                        resid > 0 && !sosendallatonce(so) && 
1605                        so->so_rcv.ssb_mb == NULL) {
1606                         if (so->so_error || so->so_state & SS_CANTRCVMORE)
1607                                 break;
1608                         /*
1609                          * The window might have closed to zero, make
1610                          * sure we send an ack now that we've drained
1611                          * the buffer or we might end up blocking until
1612                          * the idle takes over (5 seconds).
1613                          */
1614                         if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1615                                 so_pru_rcvd(so, flags);
1616                         error = ssb_wait(&so->so_rcv);
1617                         if (error) {
1618                                 ssb_unlock(&so->so_rcv);
1619                                 error = 0;
1620                                 goto done;
1621                         }
1622                         m = so->so_rcv.ssb_mb;
1623                 }
1624         }
1625
1626         /*
1627          * If an atomic read was requested but unread data still remains
1628          * in the record, set MSG_TRUNC.
1629          */
1630         if (m && pr->pr_flags & PR_ATOMIC)
1631                 flags |= MSG_TRUNC;
1632
1633         /*
1634          * Cleanup.  If an atomic read was requested drop any unread data.
1635          */
1636         if ((flags & MSG_PEEK) == 0) {
1637                 if (m && (pr->pr_flags & PR_ATOMIC))
1638                         sbdroprecord(&so->so_rcv.sb);
1639                 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1640                         so_pru_rcvd(so, flags);
1641         }
1642
1643         if (orig_resid == resid && orig_resid &&
1644             (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1645                 ssb_unlock(&so->so_rcv);
1646                 goto restart;
1647         }
1648
1649         if (flagsp)
1650                 *flagsp |= flags;
1651 release:
1652         ssb_unlock(&so->so_rcv);
1653 done:
1654         lwkt_reltoken(&so->so_rcv.ssb_token);
1655         if (free_chain)
1656                 m_freem(free_chain);
1657         return (error);
1658 }
1659
1660 int
1661 sorecvtcp(struct socket *so, struct sockaddr **psa, struct uio *uio,
1662           struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1663 {
1664         struct mbuf *m, *n;
1665         struct mbuf *free_chain = NULL;
1666         int flags, len, error, offset;
1667         struct protosw *pr = so->so_proto;
1668         int moff;
1669         int didoob;
1670         size_t resid, orig_resid, restmp;
1671
1672         if (uio)
1673                 resid = uio->uio_resid;
1674         else
1675                 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1676         orig_resid = resid;
1677
1678         if (psa)
1679                 *psa = NULL;
1680         if (controlp)
1681                 *controlp = NULL;
1682         if (flagsp)
1683                 flags = *flagsp &~ MSG_EOR;
1684         else
1685                 flags = 0;
1686         if (flags & MSG_OOB) {
1687                 m = m_get(MB_WAIT, MT_DATA);
1688                 if (m == NULL)
1689                         return (ENOBUFS);
1690                 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1691                 if (error)
1692                         goto bad;
1693                 if (sio) {
1694                         do {
1695                                 sbappend(sio, m);
1696                                 KKASSERT(resid >= (size_t)m->m_len);
1697                                 resid -= (size_t)m->m_len;
1698                         } while (resid > 0 && m);
1699                 } else {
1700                         do {
1701                                 uio->uio_resid = resid;
1702                                 error = uiomove(mtod(m, caddr_t),
1703                                                 (int)szmin(resid, m->m_len),
1704                                                 uio);
1705                                 resid = uio->uio_resid;
1706                                 m = m_free(m);
1707                         } while (uio->uio_resid && error == 0 && m);
1708                 }
1709 bad:
1710                 if (m)
1711                         m_freem(m);
1712                 return (error);
1713         }
1714
1715         /*
1716          * The token interlocks against the protocol thread while
1717          * ssb_lock is a blocking lock against other userland entities.
1718          *
1719          * Lock a limited number of mbufs (not all, so sbcompress() still
1720          * works well).  The token is used as an interlock for sbwait() so
1721          * release it afterwords.
1722          */
1723 restart:
1724         error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1725         if (error)
1726                 goto done;
1727
1728         lwkt_gettoken(&so->so_rcv.ssb_token);
1729         m = so->so_rcv.ssb_mb;
1730
1731         /*
1732          * If we have less data than requested, block awaiting more
1733          * (subject to any timeout) if:
1734          *   1. the current count is less than the low water mark, or
1735          *   2. MSG_WAITALL is set, and it is possible to do the entire
1736          *      receive operation at once if we block (resid <= hiwat).
1737          *   3. MSG_DONTWAIT is not set
1738          * If MSG_WAITALL is set but resid is larger than the receive buffer,
1739          * we have to do the receive in sections, and thus risk returning
1740          * a short count if a timeout or signal occurs after we start.
1741          */
1742         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1743             (size_t)so->so_rcv.ssb_cc < resid) &&
1744             (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1745            ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)))) {
1746                 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1747                 if (so->so_error) {
1748                         if (m)
1749                                 goto dontblock;
1750                         lwkt_reltoken(&so->so_rcv.ssb_token);
1751                         error = so->so_error;
1752                         if ((flags & MSG_PEEK) == 0)
1753                                 so->so_error = 0;
1754                         goto release;
1755                 }
1756                 if (so->so_state & SS_CANTRCVMORE) {
1757                         if (m)
1758                                 goto dontblock;
1759                         lwkt_reltoken(&so->so_rcv.ssb_token);
1760                         goto release;
1761                 }
1762                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1763                     (pr->pr_flags & PR_CONNREQUIRED)) {
1764                         lwkt_reltoken(&so->so_rcv.ssb_token);
1765                         error = ENOTCONN;
1766                         goto release;
1767                 }
1768                 if (resid == 0) {
1769                         lwkt_reltoken(&so->so_rcv.ssb_token);
1770                         goto release;
1771                 }
1772                 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1773                         lwkt_reltoken(&so->so_rcv.ssb_token);
1774                         error = EWOULDBLOCK;
1775                         goto release;
1776                 }
1777                 ssb_unlock(&so->so_rcv);
1778                 error = ssb_wait(&so->so_rcv);
1779                 lwkt_reltoken(&so->so_rcv.ssb_token);
1780                 if (error)
1781                         goto done;
1782                 goto restart;
1783         }
1784
1785         /*
1786          * Token still held
1787          */
1788 dontblock:
1789         n = m;
1790         restmp = 0;
1791         while (n && restmp < resid) {
1792                 n->m_flags |= M_SOLOCKED;
1793                 restmp += n->m_len;
1794                 if (n->m_next == NULL)
1795                         n = n->m_nextpkt;
1796                 else
1797                         n = n->m_next;
1798         }
1799
1800         /*
1801          * Release token for loop
1802          */
1803         lwkt_reltoken(&so->so_rcv.ssb_token);
1804         if (uio && uio->uio_td && uio->uio_td->td_proc)
1805                 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1806
1807         /*
1808          * note: m should be == sb_mb here.  Cache the next record while
1809          * cleaning up.  Note that calling m_free*() will break out critical
1810          * section.
1811          */
1812         KKASSERT(m == so->so_rcv.ssb_mb);
1813
1814         /*
1815          * Copy to the UIO or mbuf return chain (*mp).
1816          *
1817          * NOTE: Token is not held for loop
1818          */
1819         moff = 0;
1820         offset = 0;
1821         didoob = 0;
1822
1823         while (m && (m->m_flags & M_SOLOCKED) && resid > 0 && error == 0) {
1824                 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1825                     ("receive 3"));
1826
1827                 soclrstate(so, SS_RCVATMARK);
1828                 len = (resid > INT_MAX) ? INT_MAX : resid;
1829                 if (so->so_oobmark && len > so->so_oobmark - offset)
1830                         len = so->so_oobmark - offset;
1831                 if (len > m->m_len - moff)
1832                         len = m->m_len - moff;
1833
1834                 /*
1835                  * Copy out to the UIO or pass the mbufs back to the SIO.
1836                  * The SIO is dealt with when we eat the mbuf, but deal
1837                  * with the resid here either way.
1838                  */
1839                 if (uio) {
1840                         uio->uio_resid = resid;
1841                         error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1842                         resid = uio->uio_resid;
1843                         if (error)
1844                                 goto release;
1845                 } else {
1846                         resid -= (size_t)len;
1847                 }
1848
1849                 /*
1850                  * Eat the entire mbuf or just a piece of it
1851                  */
1852                 offset += len;
1853                 if (len == m->m_len - moff) {
1854                         m = m->m_next;
1855                         moff = 0;
1856                 } else {
1857                         moff += len;
1858                 }
1859
1860                 /*
1861                  * Check oobmark
1862                  */
1863                 if (so->so_oobmark && offset == so->so_oobmark) {
1864                         didoob = 1;
1865                         break;
1866                 }
1867         }
1868
1869         /*
1870          * Synchronize sockbuf with data we read.
1871          *
1872          * NOTE: (m) is junk on entry (it could be left over from the
1873          *       previous loop).
1874          */
1875         if ((flags & MSG_PEEK) == 0) {
1876                 lwkt_gettoken(&so->so_rcv.ssb_token);
1877                 m = so->so_rcv.ssb_mb;
1878                 while (m && offset >= m->m_len) {
1879                         if (so->so_oobmark) {
1880                                 so->so_oobmark -= m->m_len;
1881                                 if (so->so_oobmark == 0) {
1882                                         sosetstate(so, SS_RCVATMARK);
1883                                         didoob = 1;
1884                                 }
1885                         }
1886                         offset -= m->m_len;
1887                         if (sio) {
1888                                 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1889                                 sbappend(sio, m);
1890                                 m = n;
1891                         } else {
1892                                 m = sbunlinkmbuf(&so->so_rcv.sb,
1893                                                  m, &free_chain);
1894                         }
1895                 }
1896                 if (offset) {
1897                         KKASSERT(m);
1898                         if (sio) {
1899                                 n = m_copym(m, 0, offset, MB_WAIT);
1900                                 if (n)
1901                                         sbappend(sio, n);
1902                         }
1903                         m->m_data += offset;
1904                         m->m_len -= offset;
1905                         so->so_rcv.ssb_cc -= offset;
1906                         if (so->so_oobmark) {
1907                                 so->so_oobmark -= offset;
1908                                 if (so->so_oobmark == 0) {
1909                                         sosetstate(so, SS_RCVATMARK);
1910                                         didoob = 1;
1911                                 }
1912                         }
1913                         offset = 0;
1914                 }
1915                 lwkt_reltoken(&so->so_rcv.ssb_token);
1916         }
1917
1918         /*
1919          * If the MSG_WAITALL flag is set (for non-atomic socket),
1920          * we must not quit until resid == 0 or an error termination.
1921          *
1922          * If a signal/timeout occurs, return with a short count but without
1923          * error.
1924          *
1925          * Keep signalsockbuf locked against other readers.
1926          *
1927          * XXX if MSG_PEEK we currently do quit.
1928          */
1929         if ((flags & MSG_WAITALL) && !(flags & MSG_PEEK) &&
1930             didoob == 0 && resid > 0 &&
1931             !sosendallatonce(so)) {
1932                 lwkt_gettoken(&so->so_rcv.ssb_token);
1933                 error = 0;
1934                 while ((m = so->so_rcv.ssb_mb) == NULL) {
1935                         if (so->so_error || (so->so_state & SS_CANTRCVMORE)) {
1936                                 error = so->so_error;
1937                                 break;
1938                         }
1939                         /*
1940                          * The window might have closed to zero, make
1941                          * sure we send an ack now that we've drained
1942                          * the buffer or we might end up blocking until
1943                          * the idle takes over (5 seconds).
1944                          */
1945                         if (so->so_pcb)
1946                                 so_pru_rcvd_async(so);
1947                         if (so->so_rcv.ssb_mb == NULL)
1948                                 error = ssb_wait(&so->so_rcv);
1949                         if (error) {
1950                                 lwkt_reltoken(&so->so_rcv.ssb_token);
1951                                 ssb_unlock(&so->so_rcv);
1952                                 error = 0;
1953                                 goto done;
1954                         }
1955                 }
1956                 if (m && error == 0)
1957                         goto dontblock;
1958                 lwkt_reltoken(&so->so_rcv.ssb_token);
1959         }
1960
1961         /*
1962          * Token not held here.
1963          *
1964          * Cleanup.  If an atomic read was requested drop any unread data XXX
1965          */
1966         if ((flags & MSG_PEEK) == 0) {
1967                 if (so->so_pcb)
1968                         so_pru_rcvd_async(so);
1969         }
1970
1971         if (orig_resid == resid && orig_resid &&
1972             (so->so_state & SS_CANTRCVMORE) == 0) {
1973                 ssb_unlock(&so->so_rcv);
1974                 goto restart;
1975         }
1976
1977         if (flagsp)
1978                 *flagsp |= flags;
1979 release:
1980         ssb_unlock(&so->so_rcv);
1981 done:
1982         if (free_chain)
1983                 m_freem(free_chain);
1984         return (error);
1985 }
1986
1987 /*
1988  * Shut a socket down.  Note that we do not get a frontend lock as we
1989  * want to be able to shut the socket down even if another thread is
1990  * blocked in a read(), thus waking it up.
1991  */
1992 int
1993 soshutdown(struct socket *so, int how)
1994 {
1995         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1996                 return (EINVAL);
1997
1998         if (how != SHUT_WR) {
1999                 /*ssb_lock(&so->so_rcv, M_WAITOK);*/
2000                 sorflush(so);
2001                 /*ssb_unlock(&so->so_rcv);*/
2002         }
2003         if (how != SHUT_RD)
2004                 return (so_pru_shutdown(so));
2005         return (0);
2006 }
2007
2008 void
2009 sorflush(struct socket *so)
2010 {
2011         struct signalsockbuf *ssb = &so->so_rcv;
2012         struct protosw *pr = so->so_proto;
2013         struct signalsockbuf asb;
2014
2015         atomic_set_int(&ssb->ssb_flags, SSB_NOINTR);
2016
2017         lwkt_gettoken(&ssb->ssb_token);
2018         socantrcvmore(so);
2019         asb = *ssb;
2020
2021         /*
2022          * Can't just blow up the ssb structure here
2023          */
2024         bzero(&ssb->sb, sizeof(ssb->sb));
2025         ssb->ssb_timeo = 0;
2026         ssb->ssb_lowat = 0;
2027         ssb->ssb_hiwat = 0;
2028         ssb->ssb_mbmax = 0;
2029         atomic_clear_int(&ssb->ssb_flags, SSB_CLEAR_MASK);
2030
2031         if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose)
2032                 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
2033         ssb_release(&asb, so);
2034
2035         lwkt_reltoken(&ssb->ssb_token);
2036 }
2037
2038 #ifdef INET
2039 static int
2040 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
2041 {
2042         struct accept_filter_arg        *afap = NULL;
2043         struct accept_filter    *afp;
2044         struct so_accf  *af = so->so_accf;
2045         int     error = 0;
2046
2047         /* do not set/remove accept filters on non listen sockets */
2048         if ((so->so_options & SO_ACCEPTCONN) == 0) {
2049                 error = EINVAL;
2050                 goto out;
2051         }
2052
2053         /* removing the filter */
2054         if (sopt == NULL) {
2055                 if (af != NULL) {
2056                         if (af->so_accept_filter != NULL && 
2057                                 af->so_accept_filter->accf_destroy != NULL) {
2058                                 af->so_accept_filter->accf_destroy(so);
2059                         }
2060                         if (af->so_accept_filter_str != NULL) {
2061                                 kfree(af->so_accept_filter_str, M_ACCF);
2062                         }
2063                         kfree(af, M_ACCF);
2064                         so->so_accf = NULL;
2065                 }
2066                 so->so_options &= ~SO_ACCEPTFILTER;
2067                 return (0);
2068         }
2069         /* adding a filter */
2070         /* must remove previous filter first */
2071         if (af != NULL) {
2072                 error = EINVAL;
2073                 goto out;
2074         }
2075         /* don't put large objects on the kernel stack */
2076         afap = kmalloc(sizeof(*afap), M_TEMP, M_WAITOK);
2077         error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
2078         afap->af_name[sizeof(afap->af_name)-1] = '\0';
2079         afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
2080         if (error)
2081                 goto out;
2082         afp = accept_filt_get(afap->af_name);
2083         if (afp == NULL) {
2084                 error = ENOENT;
2085                 goto out;
2086         }
2087         af = kmalloc(sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
2088         if (afp->accf_create != NULL) {
2089                 if (afap->af_name[0] != '\0') {
2090                         int len = strlen(afap->af_name) + 1;
2091
2092                         af->so_accept_filter_str = kmalloc(len, M_ACCF,
2093                                                            M_WAITOK);
2094                         strcpy(af->so_accept_filter_str, afap->af_name);
2095                 }
2096                 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
2097                 if (af->so_accept_filter_arg == NULL) {
2098                         kfree(af->so_accept_filter_str, M_ACCF);
2099                         kfree(af, M_ACCF);
2100                         so->so_accf = NULL;
2101                         error = EINVAL;
2102                         goto out;
2103                 }
2104         }
2105         af->so_accept_filter = afp;
2106         so->so_accf = af;
2107         so->so_options |= SO_ACCEPTFILTER;
2108 out:
2109         if (afap != NULL)
2110                 kfree(afap, M_TEMP);
2111         return (error);
2112 }
2113 #endif /* INET */
2114
2115 /*
2116  * Perhaps this routine, and sooptcopyout(), below, ought to come in
2117  * an additional variant to handle the case where the option value needs
2118  * to be some kind of integer, but not a specific size.
2119  * In addition to their use here, these functions are also called by the
2120  * protocol-level pr_ctloutput() routines.
2121  */
2122 int
2123 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2124 {
2125         return soopt_to_kbuf(sopt, buf, len, minlen);
2126 }
2127
2128 int
2129 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2130 {
2131         size_t  valsize;
2132
2133         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2134         KKASSERT(kva_p(buf));
2135
2136         /*
2137          * If the user gives us more than we wanted, we ignore it,
2138          * but if we don't get the minimum length the caller
2139          * wants, we return EINVAL.  On success, sopt->sopt_valsize
2140          * is set to however much we actually retrieved.
2141          */
2142         if ((valsize = sopt->sopt_valsize) < minlen)
2143                 return EINVAL;
2144         if (valsize > len)
2145                 sopt->sopt_valsize = valsize = len;
2146
2147         bcopy(sopt->sopt_val, buf, valsize);
2148         return 0;
2149 }
2150
2151
2152 int
2153 sosetopt(struct socket *so, struct sockopt *sopt)
2154 {
2155         int     error, optval;
2156         struct  linger l;
2157         struct  timeval tv;
2158         u_long  val;
2159         struct signalsockbuf *sotmp;
2160
2161         error = 0;
2162         sopt->sopt_dir = SOPT_SET;
2163         if (sopt->sopt_level != SOL_SOCKET) {
2164                 if (so->so_proto && so->so_proto->pr_ctloutput) {
2165                         return (so_pr_ctloutput(so, sopt));
2166                 }
2167                 error = ENOPROTOOPT;
2168         } else {
2169                 switch (sopt->sopt_name) {
2170 #ifdef INET
2171                 case SO_ACCEPTFILTER:
2172                         error = do_setopt_accept_filter(so, sopt);
2173                         if (error)
2174                                 goto bad;
2175                         break;
2176 #endif /* INET */
2177                 case SO_LINGER:
2178                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2179                         if (error)
2180                                 goto bad;
2181
2182                         so->so_linger = l.l_linger;
2183                         if (l.l_onoff)
2184                                 so->so_options |= SO_LINGER;
2185                         else
2186                                 so->so_options &= ~SO_LINGER;
2187                         break;
2188
2189                 case SO_DEBUG:
2190                 case SO_KEEPALIVE:
2191                 case SO_DONTROUTE:
2192                 case SO_USELOOPBACK:
2193                 case SO_BROADCAST:
2194                 case SO_REUSEADDR:
2195                 case SO_REUSEPORT:
2196                 case SO_OOBINLINE:
2197                 case SO_TIMESTAMP:
2198                 case SO_NOSIGPIPE:
2199                         error = sooptcopyin(sopt, &optval, sizeof optval,
2200                                             sizeof optval);
2201                         if (error)
2202                                 goto bad;
2203                         if (optval)
2204                                 so->so_options |= sopt->sopt_name;
2205                         else
2206                                 so->so_options &= ~sopt->sopt_name;
2207                         break;
2208
2209                 case SO_SNDBUF:
2210                 case SO_RCVBUF:
2211                 case SO_SNDLOWAT:
2212                 case SO_RCVLOWAT:
2213                         error = sooptcopyin(sopt, &optval, sizeof optval,
2214                                             sizeof optval);
2215                         if (error)
2216                                 goto bad;
2217
2218                         /*
2219                          * Values < 1 make no sense for any of these
2220                          * options, so disallow them.
2221                          */
2222                         if (optval < 1) {
2223                                 error = EINVAL;
2224                                 goto bad;
2225                         }
2226
2227                         switch (sopt->sopt_name) {
2228                         case SO_SNDBUF:
2229                         case SO_RCVBUF:
2230                                 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
2231                                     &so->so_snd : &so->so_rcv, (u_long)optval,
2232                                     so,
2233                                     &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
2234                                         error = ENOBUFS;
2235                                         goto bad;
2236                                 }
2237                                 sotmp = (sopt->sopt_name == SO_SNDBUF) ?
2238                                                 &so->so_snd : &so->so_rcv;
2239                                 atomic_clear_int(&sotmp->ssb_flags,
2240                                                  SSB_AUTOSIZE);
2241                                 break;
2242
2243                         /*
2244                          * Make sure the low-water is never greater than
2245                          * the high-water.
2246                          */
2247                         case SO_SNDLOWAT:
2248                                 so->so_snd.ssb_lowat =
2249                                     (optval > so->so_snd.ssb_hiwat) ?
2250                                     so->so_snd.ssb_hiwat : optval;
2251                                 atomic_clear_int(&so->so_snd.ssb_flags,
2252                                                  SSB_AUTOLOWAT);
2253                                 break;
2254                         case SO_RCVLOWAT:
2255                                 so->so_rcv.ssb_lowat =
2256                                     (optval > so->so_rcv.ssb_hiwat) ?
2257                                     so->so_rcv.ssb_hiwat : optval;
2258                                 atomic_clear_int(&so->so_rcv.ssb_flags,
2259                                                  SSB_AUTOLOWAT);
2260                                 break;
2261                         }
2262                         break;
2263
2264                 case SO_SNDTIMEO:
2265                 case SO_RCVTIMEO:
2266                         error = sooptcopyin(sopt, &tv, sizeof tv,
2267                                             sizeof tv);
2268                         if (error)
2269                                 goto bad;
2270
2271                         /* assert(hz > 0); */
2272                         if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2273                             tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2274                                 error = EDOM;
2275                                 goto bad;
2276                         }
2277                         /* assert(tick > 0); */
2278                         /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2279                         val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
2280                         if (val > INT_MAX) {
2281                                 error = EDOM;
2282                                 goto bad;
2283                         }
2284                         if (val == 0 && tv.tv_usec != 0)
2285                                 val = 1;
2286
2287                         switch (sopt->sopt_name) {
2288                         case SO_SNDTIMEO:
2289                                 so->so_snd.ssb_timeo = val;
2290                                 break;
2291                         case SO_RCVTIMEO:
2292                                 so->so_rcv.ssb_timeo = val;
2293                                 break;
2294                         }
2295                         break;
2296                 default:
2297                         error = ENOPROTOOPT;
2298                         break;
2299                 }
2300                 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
2301                         (void) so_pr_ctloutput(so, sopt);
2302                 }
2303         }
2304 bad:
2305         return (error);
2306 }
2307
2308 /* Helper routine for getsockopt */
2309 int
2310 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2311 {
2312         soopt_from_kbuf(sopt, buf, len);
2313         return 0;
2314 }
2315
2316 void
2317 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
2318 {
2319         size_t  valsize;
2320
2321         if (len == 0) {
2322                 sopt->sopt_valsize = 0;
2323                 return;
2324         }
2325
2326         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2327         KKASSERT(kva_p(buf));
2328
2329         /*
2330          * Documented get behavior is that we always return a value,
2331          * possibly truncated to fit in the user's buffer.
2332          * Traditional behavior is that we always tell the user
2333          * precisely how much we copied, rather than something useful
2334          * like the total amount we had available for her.
2335          * Note that this interface is not idempotent; the entire answer must
2336          * generated ahead of time.
2337          */
2338         valsize = szmin(len, sopt->sopt_valsize);
2339         sopt->sopt_valsize = valsize;
2340         if (sopt->sopt_val != 0) {
2341                 bcopy(buf, sopt->sopt_val, valsize);
2342         }
2343 }
2344
2345 int
2346 sogetopt(struct socket *so, struct sockopt *sopt)
2347 {
2348         int     error, optval;
2349         long    optval_l;
2350         struct  linger l;
2351         struct  timeval tv;
2352 #ifdef INET
2353         struct accept_filter_arg *afap;
2354 #endif
2355
2356         error = 0;
2357         sopt->sopt_dir = SOPT_GET;
2358         if (sopt->sopt_level != SOL_SOCKET) {
2359                 if (so->so_proto && so->so_proto->pr_ctloutput) {
2360                         return (so_pr_ctloutput(so, sopt));
2361                 } else
2362                         return (ENOPROTOOPT);
2363         } else {
2364                 switch (sopt->sopt_name) {
2365 #ifdef INET
2366                 case SO_ACCEPTFILTER:
2367                         if ((so->so_options & SO_ACCEPTCONN) == 0)
2368                                 return (EINVAL);
2369                         afap = kmalloc(sizeof(*afap), M_TEMP,
2370                                        M_WAITOK | M_ZERO);
2371                         if ((so->so_options & SO_ACCEPTFILTER) != 0) {
2372                                 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
2373                                 if (so->so_accf->so_accept_filter_str != NULL)
2374                                         strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
2375                         }
2376                         error = sooptcopyout(sopt, afap, sizeof(*afap));
2377                         kfree(afap, M_TEMP);
2378                         break;
2379 #endif /* INET */
2380                         
2381                 case SO_LINGER:
2382                         l.l_onoff = so->so_options & SO_LINGER;
2383                         l.l_linger = so->so_linger;
2384                         error = sooptcopyout(sopt, &l, sizeof l);
2385                         break;
2386
2387                 case SO_USELOOPBACK:
2388                 case SO_DONTROUTE:
2389                 case SO_DEBUG:
2390                 case SO_KEEPALIVE:
2391                 case SO_REUSEADDR:
2392                 case SO_REUSEPORT:
2393                 case SO_BROADCAST:
2394                 case SO_OOBINLINE:
2395                 case SO_TIMESTAMP:
2396                 case SO_NOSIGPIPE:
2397                         optval = so->so_options & sopt->sopt_name;
2398 integer:
2399                         error = sooptcopyout(sopt, &optval, sizeof optval);
2400                         break;
2401
2402                 case SO_TYPE:
2403                         optval = so->so_type;
2404                         goto integer;
2405
2406                 case SO_ERROR:
2407                         optval = so->so_error;
2408                         so->so_error = 0;
2409                         goto integer;
2410
2411                 case SO_SNDBUF:
2412                         optval = so->so_snd.ssb_hiwat;
2413                         goto integer;
2414
2415                 case SO_RCVBUF:
2416                         optval = so->so_rcv.ssb_hiwat;
2417                         goto integer;
2418
2419                 case SO_SNDLOWAT:
2420                         optval = so->so_snd.ssb_lowat;
2421                         goto integer;
2422
2423                 case SO_RCVLOWAT:
2424                         optval = so->so_rcv.ssb_lowat;
2425                         goto integer;
2426
2427                 case SO_SNDTIMEO:
2428                 case SO_RCVTIMEO:
2429                         optval = (sopt->sopt_name == SO_SNDTIMEO ?
2430                                   so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
2431
2432                         tv.tv_sec = optval / hz;
2433                         tv.tv_usec = (optval % hz) * ustick;
2434                         error = sooptcopyout(sopt, &tv, sizeof tv);
2435                         break;                  
2436
2437                 case SO_SNDSPACE:
2438                         optval_l = ssb_space(&so->so_snd);
2439                         error = sooptcopyout(sopt, &optval_l, sizeof(optval_l));
2440                         break;
2441
2442                 case SO_CPUHINT:
2443                         optval = -1; /* no hint */
2444                         goto integer;
2445
2446                 default:
2447                         error = ENOPROTOOPT;
2448                         break;
2449                 }
2450                 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput)
2451                         so_pr_ctloutput(so, sopt);
2452                 return (error);
2453         }
2454 }
2455
2456 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2457 int
2458 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2459 {
2460         struct mbuf *m, *m_prev;
2461         int sopt_size = sopt->sopt_valsize, msize;
2462
2463         m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
2464                    0, &msize);
2465         if (m == NULL)
2466                 return (ENOBUFS);
2467         m->m_len = min(msize, sopt_size);
2468         sopt_size -= m->m_len;
2469         *mp = m;
2470         m_prev = m;
2471
2472         while (sopt_size > 0) {
2473                 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
2474                            MT_DATA, 0, &msize);
2475                 if (m == NULL) {
2476                         m_freem(*mp);
2477                         return (ENOBUFS);
2478                 }
2479                 m->m_len = min(msize, sopt_size);
2480                 sopt_size -= m->m_len;
2481                 m_prev->m_next = m;
2482                 m_prev = m;
2483         }
2484         return (0);
2485 }
2486
2487 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2488 int
2489 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2490 {
2491         soopt_to_mbuf(sopt, m);
2492         return 0;
2493 }
2494
2495 void
2496 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
2497 {
2498         size_t valsize;
2499         void *val;
2500
2501         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2502         KKASSERT(kva_p(m));
2503         if (sopt->sopt_val == NULL)
2504                 return;
2505         val = sopt->sopt_val;
2506         valsize = sopt->sopt_valsize;
2507         while (m != NULL && valsize >= m->m_len) {
2508                 bcopy(val, mtod(m, char *), m->m_len);
2509                 valsize -= m->m_len;
2510                 val = (caddr_t)val + m->m_len;
2511                 m = m->m_next;
2512         }
2513         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2514                 panic("ip6_sooptmcopyin");
2515 }
2516
2517 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2518 int
2519 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2520 {
2521         return soopt_from_mbuf(sopt, m);
2522 }
2523
2524 int
2525 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
2526 {
2527         struct mbuf *m0 = m;
2528         size_t valsize = 0;
2529         size_t maxsize;
2530         void *val;
2531
2532         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
2533         KKASSERT(kva_p(m));
2534         if (sopt->sopt_val == NULL)
2535                 return 0;
2536         val = sopt->sopt_val;
2537         maxsize = sopt->sopt_valsize;
2538         while (m != NULL && maxsize >= m->m_len) {
2539                 bcopy(mtod(m, char *), val, m->m_len);
2540                maxsize -= m->m_len;
2541                val = (caddr_t)val + m->m_len;
2542                valsize += m->m_len;
2543                m = m->m_next;
2544         }
2545         if (m != NULL) {
2546                 /* enough soopt buffer should be given from user-land */
2547                 m_freem(m0);
2548                 return (EINVAL);
2549         }
2550         sopt->sopt_valsize = valsize;
2551         return 0;
2552 }
2553
2554 void
2555 sohasoutofband(struct socket *so)
2556 {
2557         if (so->so_sigio != NULL)
2558                 pgsigio(so->so_sigio, SIGURG, 0);
2559         KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
2560 }
2561
2562 int
2563 sokqfilter(struct file *fp, struct knote *kn)
2564 {
2565         struct socket *so = (struct socket *)kn->kn_fp->f_data;
2566         struct signalsockbuf *ssb;
2567
2568         switch (kn->kn_filter) {
2569         case EVFILT_READ:
2570                 if (so->so_options & SO_ACCEPTCONN)
2571                         kn->kn_fop = &solisten_filtops;
2572                 else
2573                         kn->kn_fop = &soread_filtops;
2574                 ssb = &so->so_rcv;
2575                 break;
2576         case EVFILT_WRITE:
2577                 kn->kn_fop = &sowrite_filtops;
2578                 ssb = &so->so_snd;
2579                 break;
2580         case EVFILT_EXCEPT:
2581                 kn->kn_fop = &soexcept_filtops;
2582                 ssb = &so->so_rcv;
2583                 break;
2584         default:
2585                 return (EOPNOTSUPP);
2586         }
2587
2588         knote_insert(&ssb->ssb_kq.ki_note, kn);
2589         atomic_set_int(&ssb->ssb_flags, SSB_KNOTE);
2590         return (0);
2591 }
2592
2593 static void
2594 filt_sordetach(struct knote *kn)
2595 {
2596         struct socket *so = (struct socket *)kn->kn_fp->f_data;
2597
2598         knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
2599         if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
2600                 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_KNOTE);
2601 }
2602
2603 /*ARGSUSED*/
2604 static int
2605 filt_soread(struct knote *kn, long hint)
2606 {
2607         struct socket *so = (struct socket *)kn->kn_fp->f_data;
2608
2609         if (kn->kn_sfflags & NOTE_OOB) {
2610                 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
2611                         kn->kn_fflags |= NOTE_OOB;
2612                         return (1);
2613                 }
2614                 return (0);
2615         }
2616         kn->kn_data = so->so_rcv.ssb_cc;
2617
2618         if (so->so_state & SS_CANTRCVMORE) {
2619                 /*
2620                  * Only set NODATA if all data has been exhausted.
2621                  */
2622                 if (kn->kn_data == 0)
2623                         kn->kn_flags |= EV_NODATA;
2624                 kn->kn_flags |= EV_EOF; 
2625                 kn->kn_fflags = so->so_error;
2626                 return (1);
2627         }
2628         if (so->so_error)       /* temporary udp error */
2629                 return (1);
2630         if (kn->kn_sfflags & NOTE_LOWAT)
2631                 return (kn->kn_data >= kn->kn_sdata);
2632         return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
2633                 !TAILQ_EMPTY(&so->so_comp));
2634 }
2635
2636 static void
2637 filt_sowdetach(struct knote *kn)
2638 {
2639         struct socket *so = (struct socket *)kn->kn_fp->f_data;
2640
2641         knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
2642         if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
2643                 atomic_clear_int(&so->so_snd.ssb_flags, SSB_KNOTE);
2644 }
2645
2646 /*ARGSUSED*/
2647 static int
2648 filt_sowrite(struct knote *kn, long hint)
2649 {
2650         struct socket *so = (struct socket *)kn->kn_fp->f_data;
2651
2652         kn->kn_data = ssb_space(&so->so_snd);
2653         if (so->so_state & SS_CANTSENDMORE) {
2654                 kn->kn_flags |= (EV_EOF | EV_NODATA);
2655                 kn->kn_fflags = so->so_error;
2656                 return (1);
2657         }
2658         if (so->so_error)       /* temporary udp error */
2659                 return (1);
2660         if (((so->so_state & SS_ISCONNECTED) == 0) &&
2661             (so->so_proto->pr_flags & PR_CONNREQUIRED))
2662                 return (0);
2663         if (kn->kn_sfflags & NOTE_LOWAT)
2664                 return (kn->kn_data >= kn->kn_sdata);
2665         return (kn->kn_data >= so->so_snd.ssb_lowat);
2666 }
2667
2668 /*ARGSUSED*/
2669 static int
2670 filt_solisten(struct knote *kn, long hint)
2671 {
2672         struct socket *so = (struct socket *)kn->kn_fp->f_data;
2673
2674         kn->kn_data = so->so_qlen;
2675         return (! TAILQ_EMPTY(&so->so_comp));
2676 }