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