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