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