Remove some duplicate includes in sys/kern.
[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. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      @(#)uipc_socket.c       8.3 (Berkeley) 4/15/94
67  * $FreeBSD: src/sys/kern/uipc_socket.c,v 1.68.2.24 2003/11/11 17:18:18 silby Exp $
68  */
69
70 #include "opt_inet.h"
71 #include "opt_sctp.h"
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/fcntl.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/domain.h>
79 #include <sys/file.h>                   /* for struct knote */
80 #include <sys/kernel.h>
81 #include <sys/event.h>
82 #include <sys/proc.h>
83 #include <sys/protosw.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/socketops.h>
87 #include <sys/resourcevar.h>
88 #include <sys/signalvar.h>
89 #include <sys/sysctl.h>
90 #include <sys/uio.h>
91 #include <sys/jail.h>
92 #include <vm/vm_zone.h>
93 #include <vm/pmap.h>
94
95 #include <sys/thread2.h>
96 #include <sys/socketvar2.h>
97
98 #include <machine/limits.h>
99
100 #ifdef INET
101 static int       do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
102 #endif /* INET */
103
104 static void     filt_sordetach(struct knote *kn);
105 static int      filt_soread(struct knote *kn, long hint);
106 static void     filt_sowdetach(struct knote *kn);
107 static int      filt_sowrite(struct knote *kn, long hint);
108 static int      filt_solisten(struct knote *kn, long hint);
109
110 static struct filterops solisten_filtops = 
111         { FILTEROP_ISFD, NULL, filt_sordetach, filt_solisten };
112 static struct filterops soread_filtops =
113         { FILTEROP_ISFD, NULL, filt_sordetach, filt_soread };
114 static struct filterops sowrite_filtops = 
115         { FILTEROP_ISFD, NULL, filt_sowdetach, filt_sowrite };
116 static struct filterops soexcept_filtops =
117         { FILTEROP_ISFD, NULL, filt_sordetach, filt_soread };
118
119 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
120 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
121 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
122
123
124 static int somaxconn = SOMAXCONN;
125 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
126     &somaxconn, 0, "Maximum pending socket connection queue size");
127
128 /*
129  * Socket operation routines.
130  * These routines are called by the routines in
131  * sys_socket.c or from a system process, and
132  * implement the semantics of socket operations by
133  * switching out to the protocol specific routines.
134  */
135
136 /*
137  * Get a socket structure, and initialize it.
138  * Note that it would probably be better to allocate socket
139  * and PCB at the same time, but I'm not convinced that all
140  * the protocols can be easily modified to do this.
141  */
142 struct socket *
143 soalloc(int waitok)
144 {
145         struct socket *so;
146         unsigned waitmask;
147
148         waitmask = waitok ? M_WAITOK : M_NOWAIT;
149         so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
150         if (so) {
151                 /* XXX race condition for reentrant kernel */
152                 TAILQ_INIT(&so->so_aiojobq);
153                 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
154                 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
155                 lwkt_token_init(&so->so_rcv.ssb_token, "rcvtok");
156                 lwkt_token_init(&so->so_snd.ssb_token, "sndtok");
157                 so->so_state = SS_NOFDREF;
158                 so->so_refs = 1;
159         }
160         return so;
161 }
162
163 int
164 socreate(int dom, struct socket **aso, int type,
165         int proto, struct thread *td)
166 {
167         struct proc *p = td->td_proc;
168         struct protosw *prp;
169         struct socket *so;
170         struct pru_attach_info ai;
171         int error;
172
173         if (proto)
174                 prp = pffindproto(dom, proto, type);
175         else
176                 prp = pffindtype(dom, type);
177
178         if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
179                 return (EPROTONOSUPPORT);
180
181         if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
182             prp->pr_domain->dom_family != PF_LOCAL &&
183             prp->pr_domain->dom_family != PF_INET &&
184             prp->pr_domain->dom_family != PF_INET6 &&
185             prp->pr_domain->dom_family != PF_ROUTE) {
186                 return (EPROTONOSUPPORT);
187         }
188
189         if (prp->pr_type != type)
190                 return (EPROTOTYPE);
191         so = soalloc(p != 0);
192         if (so == NULL)
193                 return (ENOBUFS);
194
195         /*
196          * Callers of socreate() presumably will connect up a descriptor
197          * and call soclose() if they cannot.  This represents our so_refs
198          * (which should be 1) from soalloc().
199          */
200         soclrstate(so, SS_NOFDREF);
201
202         /*
203          * Set a default port for protocol processing.  No action will occur
204          * on the socket on this port until an inpcb is attached to it and
205          * is able to match incoming packets, or until the socket becomes
206          * available to userland.
207          *
208          * We normally default the socket to the protocol thread on cpu 0.
209          * If PR_SYNC_PORT is set (unix domain sockets) there is no protocol
210          * thread and all pr_*()/pru_*() calls are executed synchronously.
211          */
212         if (prp->pr_flags & PR_SYNC_PORT)
213                 so->so_port = &netisr_sync_port;
214         else
215                 so->so_port = cpu_portfn(0);
216
217         TAILQ_INIT(&so->so_incomp);
218         TAILQ_INIT(&so->so_comp);
219         so->so_type = type;
220         so->so_cred = crhold(p->p_ucred);
221         so->so_proto = prp;
222         ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
223         ai.p_ucred = p->p_ucred;
224         ai.fd_rdir = p->p_fd->fd_rdir;
225
226         /*
227          * Auto-sizing of socket buffers is managed by the protocols and
228          * the appropriate flags must be set in the pru_attach function.
229          */
230         error = so_pru_attach(so, proto, &ai);
231         if (error) {
232                 sosetstate(so, SS_NOFDREF);
233                 sofree(so);     /* from soalloc */
234                 return error;
235         }
236
237         /*
238          * NOTE: Returns referenced socket.
239          */
240         *aso = so;
241         return (0);
242 }
243
244 int
245 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
246 {
247         int error;
248
249         error = so_pru_bind(so, nam, td);
250         return (error);
251 }
252
253 static void
254 sodealloc(struct socket *so)
255 {
256         if (so->so_rcv.ssb_hiwat)
257                 (void)chgsbsize(so->so_cred->cr_uidinfo,
258                     &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
259         if (so->so_snd.ssb_hiwat)
260                 (void)chgsbsize(so->so_cred->cr_uidinfo,
261                     &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
262 #ifdef INET
263         /* remove accept filter if present */
264         if (so->so_accf != NULL)
265                 do_setopt_accept_filter(so, NULL);
266 #endif /* INET */
267         crfree(so->so_cred);
268         kfree(so, M_SOCKET);
269 }
270
271 int
272 solisten(struct socket *so, int backlog, struct thread *td)
273 {
274         int error;
275 #ifdef SCTP
276         short oldopt, oldqlimit;
277 #endif /* SCTP */
278
279         if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))
280                 return (EINVAL);
281
282 #ifdef SCTP
283         oldopt = so->so_options;
284         oldqlimit = so->so_qlimit;
285 #endif /* SCTP */
286
287         lwkt_gettoken(&so->so_rcv.ssb_token);
288         if (TAILQ_EMPTY(&so->so_comp))
289                 so->so_options |= SO_ACCEPTCONN;
290         lwkt_reltoken(&so->so_rcv.ssb_token);
291         if (backlog < 0 || backlog > somaxconn)
292                 backlog = somaxconn;
293         so->so_qlimit = backlog;
294         /* SCTP needs to look at tweak both the inbound backlog parameter AND
295          * the so_options (UDP model both connect's and gets inbound
296          * connections .. implicitly).
297          */
298         error = so_pru_listen(so, td);
299         if (error) {
300 #ifdef SCTP
301                 /* Restore the params */
302                 so->so_options = oldopt;
303                 so->so_qlimit = oldqlimit;
304 #endif /* SCTP */
305                 return (error);
306         }
307         return (0);
308 }
309
310 /*
311  * Destroy a disconnected socket.  This routine is a NOP if entities
312  * still have a reference on the socket:
313  *
314  *      so_pcb -        The protocol stack still has a reference
315  *      SS_NOFDREF -    There is no longer a file pointer reference
316  */
317 void
318 sofree(struct socket *so)
319 {
320         struct socket *head;
321
322         /*
323          * This is a bit hackish at the moment.  We need to interlock
324          * any accept queue we are on before we potentially lose the
325          * last reference to avoid races against a re-reference from
326          * someone operating on the queue.
327          */
328         while ((head = so->so_head) != NULL) {
329                 lwkt_getpooltoken(head);
330                 if (so->so_head == head)
331                         break;
332                 lwkt_relpooltoken(head);
333         }
334
335         /*
336          * Arbitrage the last free.
337          */
338         KKASSERT(so->so_refs > 0);
339         if (atomic_fetchadd_int(&so->so_refs, -1) != 1) {
340                 if (head)
341                         lwkt_relpooltoken(head);
342                 return;
343         }
344
345         KKASSERT(so->so_pcb == NULL && (so->so_state & SS_NOFDREF));
346         KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
347
348         /*
349          * We're done, remove ourselves from the accept queue we are
350          * on, if we are on one.
351          */
352         if (head != NULL) {
353                 if (so->so_state & SS_INCOMP) {
354                         TAILQ_REMOVE(&head->so_incomp, so, so_list);
355                         head->so_incqlen--;
356                 } else if (so->so_state & SS_COMP) {
357                         /*
358                          * We must not decommission a socket that's
359                          * on the accept(2) queue.  If we do, then
360                          * accept(2) may hang after select(2) indicated
361                          * that the listening socket was ready.
362                          */
363                         lwkt_relpooltoken(head);
364                         return;
365                 } else {
366                         panic("sofree: not queued");
367                 }
368                 soclrstate(so, SS_INCOMP);
369                 so->so_head = NULL;
370                 lwkt_relpooltoken(head);
371         }
372         ssb_release(&so->so_snd, so);
373         sorflush(so);
374         sodealloc(so);
375 }
376
377 /*
378  * Close a socket on last file table reference removal.
379  * Initiate disconnect if connected.
380  * Free socket when disconnect complete.
381  */
382 int
383 soclose(struct socket *so, int fflag)
384 {
385         int error = 0;
386
387         funsetown(&so->so_sigio);
388         if (so->so_pcb == NULL)
389                 goto discard;
390         if (so->so_state & SS_ISCONNECTED) {
391                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
392                         error = sodisconnect(so);
393                         if (error)
394                                 goto drop;
395                 }
396                 if (so->so_options & SO_LINGER) {
397                         if ((so->so_state & SS_ISDISCONNECTING) &&
398                             (fflag & FNONBLOCK))
399                                 goto drop;
400                         while (so->so_state & SS_ISCONNECTED) {
401                                 error = tsleep(&so->so_timeo, PCATCH,
402                                                "soclos", so->so_linger * hz);
403                                 if (error)
404                                         break;
405                         }
406                 }
407         }
408 drop:
409         if (so->so_pcb) {
410                 int error2;
411
412                 error2 = so_pru_detach(so);
413                 if (error == 0)
414                         error = error2;
415         }
416 discard:
417         lwkt_getpooltoken(so);
418         if (so->so_options & SO_ACCEPTCONN) {
419                 struct socket *sp;
420
421                 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
422                         TAILQ_REMOVE(&so->so_incomp, sp, so_list);
423                         soclrstate(sp, SS_INCOMP);
424                         sp->so_head = NULL;
425                         so->so_incqlen--;
426                         soaborta(sp);
427                 }
428                 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
429                         TAILQ_REMOVE(&so->so_comp, sp, so_list);
430                         soclrstate(sp, SS_COMP);
431                         sp->so_head = NULL;
432                         so->so_qlen--;
433                         soaborta(sp);
434                 }
435         }
436         lwkt_relpooltoken(so);
437         if (so->so_state & SS_NOFDREF)
438                 panic("soclose: NOFDREF");
439         sosetstate(so, SS_NOFDREF);     /* take ref */
440         sofree(so);                     /* dispose of ref */
441         return (error);
442 }
443
444 /*
445  * Abort and destroy a socket.  Only one abort can be in progress
446  * at any given moment.
447  */
448 void
449 soabort(struct socket *so)
450 {
451         soreference(so);
452         so_pru_abort(so);
453 }
454
455 void
456 soaborta(struct socket *so)
457 {
458         soreference(so);
459         so_pru_aborta(so);
460 }
461
462 void
463 soabort_oncpu(struct socket *so)
464 {
465         soreference(so);
466         so_pru_abort_oncpu(so);
467 }
468
469 /*
470  * so is passed in ref'd, which becomes owned by
471  * the cleared SS_NOFDREF flag.
472  */
473 int
474 soaccept(struct socket *so, struct sockaddr **nam)
475 {
476         int error;
477
478         if ((so->so_state & SS_NOFDREF) == 0)
479                 panic("soaccept: !NOFDREF");
480         soclrstate(so, SS_NOFDREF);     /* owned by lack of SS_NOFDREF */
481         error = so_pru_accept_direct(so, nam);
482         return (error);
483 }
484
485 int
486 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
487 {
488         int error;
489
490         if (so->so_options & SO_ACCEPTCONN)
491                 return (EOPNOTSUPP);
492         /*
493          * If protocol is connection-based, can only connect once.
494          * Otherwise, if connected, try to disconnect first.
495          * This allows user to disconnect by connecting to, e.g.,
496          * a null address.
497          */
498         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
499             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
500             (error = sodisconnect(so)))) {
501                 error = EISCONN;
502         } else {
503                 /*
504                  * Prevent accumulated error from previous connection
505                  * from biting us.
506                  */
507                 so->so_error = 0;
508                 error = so_pru_connect(so, nam, td);
509         }
510         return (error);
511 }
512
513 int
514 soconnect2(struct socket *so1, struct socket *so2)
515 {
516         int error;
517
518         error = so_pru_connect2(so1, so2);
519         return (error);
520 }
521
522 int
523 sodisconnect(struct socket *so)
524 {
525         int error;
526
527         if ((so->so_state & SS_ISCONNECTED) == 0) {
528                 error = ENOTCONN;
529                 goto bad;
530         }
531         if (so->so_state & SS_ISDISCONNECTING) {
532                 error = EALREADY;
533                 goto bad;
534         }
535         error = so_pru_disconnect(so);
536 bad:
537         return (error);
538 }
539
540 #define SBLOCKWAIT(f)   (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
541 /*
542  * Send on a socket.
543  * If send must go all at once and message is larger than
544  * send buffering, then hard error.
545  * Lock against other senders.
546  * If must go all at once and not enough room now, then
547  * inform user that this would block and do nothing.
548  * Otherwise, if nonblocking, send as much as possible.
549  * The data to be sent is described by "uio" if nonzero,
550  * otherwise by the mbuf chain "top" (which must be null
551  * if uio is not).  Data provided in mbuf chain must be small
552  * enough to send all at once.
553  *
554  * Returns nonzero on error, timeout or signal; callers
555  * must check for short counts if EINTR/ERESTART are returned.
556  * Data and control buffers are freed on return.
557  */
558 int
559 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
560         struct mbuf *top, struct mbuf *control, int flags,
561         struct thread *td)
562 {
563         struct mbuf **mp;
564         struct mbuf *m;
565         size_t resid;
566         int space, len;
567         int clen = 0, error, dontroute, mlen;
568         int atomic = sosendallatonce(so) || top;
569         int pru_flags;
570
571         if (uio) {
572                 resid = uio->uio_resid;
573         } else {
574                 resid = (size_t)top->m_pkthdr.len;
575 #ifdef INVARIANTS
576                 len = 0;
577                 for (m = top; m; m = m->m_next)
578                         len += m->m_len;
579                 KKASSERT(top->m_pkthdr.len == len);
580 #endif
581         }
582
583         /*
584          * WARNING!  resid is unsigned, space and len are signed.  space
585          *           can wind up negative if the sockbuf is overcommitted.
586          *
587          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
588          * type sockets since that's an error.
589          */
590         if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
591                 error = EINVAL;
592                 goto out;
593         }
594
595         dontroute =
596             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
597             (so->so_proto->pr_flags & PR_ATOMIC);
598         if (td->td_lwp != NULL)
599                 td->td_lwp->lwp_ru.ru_msgsnd++;
600         if (control)
601                 clen = control->m_len;
602 #define gotoerr(errcode)        { error = errcode; goto release; }
603
604 restart:
605         error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
606         if (error)
607                 goto out;
608
609         do {
610                 if (so->so_state & SS_CANTSENDMORE)
611                         gotoerr(EPIPE);
612                 if (so->so_error) {
613                         error = so->so_error;
614                         so->so_error = 0;
615                         goto release;
616                 }
617                 if ((so->so_state & SS_ISCONNECTED) == 0) {
618                         /*
619                          * `sendto' and `sendmsg' is allowed on a connection-
620                          * based socket if it supports implied connect.
621                          * Return ENOTCONN if not connected and no address is
622                          * supplied.
623                          */
624                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
625                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
626                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
627                                     !(resid == 0 && clen != 0))
628                                         gotoerr(ENOTCONN);
629                         } else if (addr == 0)
630                             gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
631                                    ENOTCONN : EDESTADDRREQ);
632                 }
633                 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
634                     clen > so->so_snd.ssb_hiwat) {
635                         gotoerr(EMSGSIZE);
636                 }
637                 space = ssb_space(&so->so_snd);
638                 if (flags & MSG_OOB)
639                         space += 1024;
640                 if ((space < 0 || (size_t)space < resid + clen) && uio &&
641                     (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
642                         if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
643                                 gotoerr(EWOULDBLOCK);
644                         ssb_unlock(&so->so_snd);
645                         error = ssb_wait(&so->so_snd);
646                         if (error)
647                                 goto out;
648                         goto restart;
649                 }
650                 mp = &top;
651                 space -= clen;
652                 do {
653                     if (uio == NULL) {
654                         /*
655                          * Data is prepackaged in "top".
656                          */
657                         resid = 0;
658                         if (flags & MSG_EOR)
659                                 top->m_flags |= M_EOR;
660                     } else do {
661                         if (resid > INT_MAX)
662                                 resid = INT_MAX;
663                         m = m_getl((int)resid, MB_WAIT, MT_DATA,
664                                    top == NULL ? M_PKTHDR : 0, &mlen);
665                         if (top == NULL) {
666                                 m->m_pkthdr.len = 0;
667                                 m->m_pkthdr.rcvif = NULL;
668                         }
669                         len = imin((int)szmin(mlen, resid), space);
670                         if (resid < MINCLSIZE) {
671                                 /*
672                                  * For datagram protocols, leave room
673                                  * for protocol headers in first mbuf.
674                                  */
675                                 if (atomic && top == 0 && len < mlen)
676                                         MH_ALIGN(m, len);
677                         }
678                         space -= len;
679                         error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
680                         resid = uio->uio_resid;
681                         m->m_len = len;
682                         *mp = m;
683                         top->m_pkthdr.len += len;
684                         if (error)
685                                 goto release;
686                         mp = &m->m_next;
687                         if (resid == 0) {
688                                 if (flags & MSG_EOR)
689                                         top->m_flags |= M_EOR;
690                                 break;
691                         }
692                     } while (space > 0 && atomic);
693                     if (dontroute)
694                             so->so_options |= SO_DONTROUTE;
695                     if (flags & MSG_OOB) {
696                             pru_flags = PRUS_OOB;
697                     } else if ((flags & MSG_EOF) &&
698                                (so->so_proto->pr_flags & PR_IMPLOPCL) &&
699                                (resid == 0)) {
700                             /*
701                              * If the user set MSG_EOF, the protocol
702                              * understands this flag and nothing left to
703                              * send then use PRU_SEND_EOF instead of PRU_SEND.
704                              */
705                             pru_flags = PRUS_EOF;
706                     } else if (resid > 0 && space > 0) {
707                             /* If there is more to send, set PRUS_MORETOCOME */
708                             pru_flags = PRUS_MORETOCOME;
709                     } else {
710                             pru_flags = 0;
711                     }
712                     /*
713                      * XXX all the SS_CANTSENDMORE checks previously
714                      * done could be out of date.  We could have recieved
715                      * a reset packet in an interrupt or maybe we slept
716                      * while doing page faults in uiomove() etc. We could
717                      * probably recheck again inside the splnet() protection
718                      * here, but there are probably other places that this
719                      * also happens.  We must rethink this.
720                      */
721                     error = so_pru_send(so, pru_flags, top, addr, control, td);
722                     if (dontroute)
723                             so->so_options &= ~SO_DONTROUTE;
724                     clen = 0;
725                     control = 0;
726                     top = NULL;
727                     mp = &top;
728                     if (error)
729                             goto release;
730                 } while (resid && space > 0);
731         } while (resid);
732
733 release:
734         ssb_unlock(&so->so_snd);
735 out:
736         if (top)
737                 m_freem(top);
738         if (control)
739                 m_freem(control);
740         return (error);
741 }
742
743 /*
744  * A specialization of sosend() for UDP based on protocol-specific knowledge:
745  *   so->so_proto->pr_flags has the PR_ATOMIC field set.  This means that
746  *      sosendallatonce() returns true,
747  *      the "atomic" variable is true,
748  *      and sosendudp() blocks until space is available for the entire send.
749  *   so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
750  *      PR_IMPLOPCL flags set.
751  *   UDP has no out-of-band data.
752  *   UDP has no control data.
753  *   UDP does not support MSG_EOR.
754  */
755 int
756 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
757           struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
758 {
759         boolean_t dontroute;            /* temporary SO_DONTROUTE setting */
760         size_t resid;
761         int error;
762         int space;
763
764         if (td->td_lwp != NULL)
765                 td->td_lwp->lwp_ru.ru_msgsnd++;
766         if (control)
767                 m_freem(control);
768
769         KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
770         resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
771
772 restart:
773         error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
774         if (error)
775                 goto out;
776
777         if (so->so_state & SS_CANTSENDMORE)
778                 gotoerr(EPIPE);
779         if (so->so_error) {
780                 error = so->so_error;
781                 so->so_error = 0;
782                 goto release;
783         }
784         if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
785                 gotoerr(EDESTADDRREQ);
786         if (resid > so->so_snd.ssb_hiwat)
787                 gotoerr(EMSGSIZE);
788         space = ssb_space(&so->so_snd);
789         if (uio && (space < 0 || (size_t)space < resid)) {
790                 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
791                         gotoerr(EWOULDBLOCK);
792                 ssb_unlock(&so->so_snd);
793                 error = ssb_wait(&so->so_snd);
794                 if (error)
795                         goto out;
796                 goto restart;
797         }
798
799         if (uio) {
800                 top = m_uiomove(uio);
801                 if (top == NULL)
802                         goto release;
803         }
804
805         dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
806         if (dontroute)
807                 so->so_options |= SO_DONTROUTE;
808
809         error = so_pru_send(so, 0, top, addr, NULL, td);
810         top = NULL;             /* sent or freed in lower layer */
811
812         if (dontroute)
813                 so->so_options &= ~SO_DONTROUTE;
814
815 release:
816         ssb_unlock(&so->so_snd);
817 out:
818         if (top)
819                 m_freem(top);
820         return (error);
821 }
822
823 /*
824  * Implement receive operations on a socket.
825  *
826  * We depend on the way that records are added to the signalsockbuf
827  * by sbappend*.  In particular, each record (mbufs linked through m_next)
828  * must begin with an address if the protocol so specifies,
829  * followed by an optional mbuf or mbufs containing ancillary data,
830  * and then zero or more mbufs of data.
831  *
832  * Although the signalsockbuf is locked, new data may still be appended.
833  * A token inside the ssb_lock deals with MP issues and still allows
834  * the network to access the socket if we block in a uio.
835  *
836  * The caller may receive the data as a single mbuf chain by supplying
837  * an mbuf **mp0 for use in returning the chain.  The uio is then used
838  * only for the count in uio_resid.
839  */
840 int
841 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
842           struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
843 {
844         struct mbuf *m, *n;
845         struct mbuf *free_chain = NULL;
846         int flags, len, error, offset;
847         struct protosw *pr = so->so_proto;
848         int moff, type = 0;
849         size_t resid, orig_resid;
850
851         if (uio)
852                 resid = uio->uio_resid;
853         else
854                 resid = (size_t)(sio->sb_climit - sio->sb_cc);
855         orig_resid = resid;
856
857         if (psa)
858                 *psa = NULL;
859         if (controlp)
860                 *controlp = NULL;
861         if (flagsp)
862                 flags = *flagsp &~ MSG_EOR;
863         else
864                 flags = 0;
865         if (flags & MSG_OOB) {
866                 m = m_get(MB_WAIT, MT_DATA);
867                 if (m == NULL)
868                         return (ENOBUFS);
869                 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
870                 if (error)
871                         goto bad;
872                 if (sio) {
873                         do {
874                                 sbappend(sio, m);
875                                 KKASSERT(resid >= (size_t)m->m_len);
876                                 resid -= (size_t)m->m_len;
877                         } while (resid > 0 && m);
878                 } else {
879                         do {
880                                 uio->uio_resid = resid;
881                                 error = uiomove(mtod(m, caddr_t),
882                                                 (int)szmin(resid, m->m_len),
883                                                 uio);
884                                 resid = uio->uio_resid;
885                                 m = m_free(m);
886                         } while (uio->uio_resid && error == 0 && m);
887                 }
888 bad:
889                 if (m)
890                         m_freem(m);
891                 return (error);
892         }
893         if ((so->so_state & SS_ISCONFIRMING) && resid)
894                 so_pru_rcvd(so, 0);
895
896         /*
897          * The token interlocks against the protocol thread while
898          * ssb_lock is a blocking lock against other userland entities.
899          */
900         lwkt_gettoken(&so->so_rcv.ssb_token);
901 restart:
902         error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
903         if (error)
904                 goto done;
905
906         m = so->so_rcv.ssb_mb;
907         /*
908          * If we have less data than requested, block awaiting more
909          * (subject to any timeout) if:
910          *   1. the current count is less than the low water mark, or
911          *   2. MSG_WAITALL is set, and it is possible to do the entire
912          *      receive operation at once if we block (resid <= hiwat).
913          *   3. MSG_DONTWAIT is not set
914          * If MSG_WAITALL is set but resid is larger than the receive buffer,
915          * we have to do the receive in sections, and thus risk returning
916          * a short count if a timeout or signal occurs after we start.
917          */
918         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
919             (size_t)so->so_rcv.ssb_cc < resid) &&
920             (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
921             ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
922             m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
923                 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
924                 if (so->so_error) {
925                         if (m)
926                                 goto dontblock;
927                         error = so->so_error;
928                         if ((flags & MSG_PEEK) == 0)
929                                 so->so_error = 0;
930                         goto release;
931                 }
932                 if (so->so_state & SS_CANTRCVMORE) {
933                         if (m)
934                                 goto dontblock;
935                         else
936                                 goto release;
937                 }
938                 for (; m; m = m->m_next) {
939                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
940                                 m = so->so_rcv.ssb_mb;
941                                 goto dontblock;
942                         }
943                 }
944                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
945                     (pr->pr_flags & PR_CONNREQUIRED)) {
946                         error = ENOTCONN;
947                         goto release;
948                 }
949                 if (resid == 0)
950                         goto release;
951                 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
952                         error = EWOULDBLOCK;
953                         goto release;
954                 }
955                 ssb_unlock(&so->so_rcv);
956                 error = ssb_wait(&so->so_rcv);
957                 if (error)
958                         goto done;
959                 goto restart;
960         }
961 dontblock:
962         if (uio && uio->uio_td && uio->uio_td->td_proc)
963                 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
964
965         /*
966          * note: m should be == sb_mb here.  Cache the next record while
967          * cleaning up.  Note that calling m_free*() will break out critical
968          * section.
969          */
970         KKASSERT(m == so->so_rcv.ssb_mb);
971
972         /*
973          * Skip any address mbufs prepending the record.
974          */
975         if (pr->pr_flags & PR_ADDR) {
976                 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
977                 orig_resid = 0;
978                 if (psa)
979                         *psa = dup_sockaddr(mtod(m, struct sockaddr *));
980                 if (flags & MSG_PEEK)
981                         m = m->m_next;
982                 else
983                         m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
984         }
985
986         /*
987          * Skip any control mbufs prepending the record.
988          */
989 #ifdef SCTP
990         if (pr->pr_flags & PR_ADDR_OPT) {
991                 /*
992                  * For SCTP we may be getting a
993                  * whole message OR a partial delivery.
994                  */
995                 if (m && m->m_type == MT_SONAME) {
996                         orig_resid = 0;
997                         if (psa)
998                                 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
999                         if (flags & MSG_PEEK)
1000                                 m = m->m_next;
1001                         else
1002                                 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1003                 }
1004         }
1005 #endif /* SCTP */
1006         while (m && m->m_type == MT_CONTROL && error == 0) {
1007                 if (flags & MSG_PEEK) {
1008                         if (controlp)
1009                                 *controlp = m_copy(m, 0, m->m_len);
1010                         m = m->m_next;  /* XXX race */
1011                 } else {
1012                         if (controlp) {
1013                                 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1014                                 if (pr->pr_domain->dom_externalize &&
1015                                     mtod(m, struct cmsghdr *)->cmsg_type ==
1016                                     SCM_RIGHTS)
1017                                    error = (*pr->pr_domain->dom_externalize)(m);
1018                                 *controlp = m;
1019                                 m = n;
1020                         } else {
1021                                 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1022                         }
1023                 }
1024                 if (controlp && *controlp) {
1025                         orig_resid = 0;
1026                         controlp = &(*controlp)->m_next;
1027                 }
1028         }
1029
1030         /*
1031          * flag OOB data.
1032          */
1033         if (m) {
1034                 type = m->m_type;
1035                 if (type == MT_OOBDATA)
1036                         flags |= MSG_OOB;
1037         }
1038
1039         /*
1040          * Copy to the UIO or mbuf return chain (*mp).
1041          */
1042         moff = 0;
1043         offset = 0;
1044         while (m && resid > 0 && error == 0) {
1045                 if (m->m_type == MT_OOBDATA) {
1046                         if (type != MT_OOBDATA)
1047                                 break;
1048                 } else if (type == MT_OOBDATA)
1049                         break;
1050                 else
1051                     KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1052                         ("receive 3"));
1053                 soclrstate(so, SS_RCVATMARK);
1054                 len = (resid > INT_MAX) ? INT_MAX : resid;
1055                 if (so->so_oobmark && len > so->so_oobmark - offset)
1056                         len = so->so_oobmark - offset;
1057                 if (len > m->m_len - moff)
1058                         len = m->m_len - moff;
1059
1060                 /*
1061                  * Copy out to the UIO or pass the mbufs back to the SIO.
1062                  * The SIO is dealt with when we eat the mbuf, but deal
1063                  * with the resid here either way.
1064                  */
1065                 if (uio) {
1066                         uio->uio_resid = resid;
1067                         error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1068                         resid = uio->uio_resid;
1069                         if (error)
1070                                 goto release;
1071                 } else {
1072                         resid -= (size_t)len;
1073                 }
1074
1075                 /*
1076                  * Eat the entire mbuf or just a piece of it
1077                  */
1078                 if (len == m->m_len - moff) {
1079                         if (m->m_flags & M_EOR)
1080                                 flags |= MSG_EOR;
1081 #ifdef SCTP
1082                         if (m->m_flags & M_NOTIFICATION)
1083                                 flags |= MSG_NOTIFICATION;
1084 #endif /* SCTP */
1085                         if (flags & MSG_PEEK) {
1086                                 m = m->m_next;
1087                                 moff = 0;
1088                         } else {
1089                                 if (sio) {
1090                                         n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1091                                         sbappend(sio, m);
1092                                         m = n;
1093                                 } else {
1094                                         m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1095                                 }
1096                         }
1097                 } else {
1098                         if (flags & MSG_PEEK) {
1099                                 moff += len;
1100                         } else {
1101                                 if (sio) {
1102                                         n = m_copym(m, 0, len, MB_WAIT);
1103                                         if (n)
1104                                                 sbappend(sio, n);
1105                                 }
1106                                 m->m_data += len;
1107                                 m->m_len -= len;
1108                                 so->so_rcv.ssb_cc -= len;
1109                         }
1110                 }
1111                 if (so->so_oobmark) {
1112                         if ((flags & MSG_PEEK) == 0) {
1113                                 so->so_oobmark -= len;
1114                                 if (so->so_oobmark == 0) {
1115                                         sosetstate(so, SS_RCVATMARK);
1116                                         break;
1117                                 }
1118                         } else {
1119                                 offset += len;
1120                                 if (offset == so->so_oobmark)
1121                                         break;
1122                         }
1123                 }
1124                 if (flags & MSG_EOR)
1125                         break;
1126                 /*
1127                  * If the MSG_WAITALL flag is set (for non-atomic socket),
1128                  * we must not quit until resid == 0 or an error
1129                  * termination.  If a signal/timeout occurs, return
1130                  * with a short count but without error.
1131                  * Keep signalsockbuf locked against other readers.
1132                  */
1133                 while ((flags & MSG_WAITALL) && m == NULL && 
1134                        resid > 0 && !sosendallatonce(so) && 
1135                        so->so_rcv.ssb_mb == NULL) {
1136                         if (so->so_error || so->so_state & SS_CANTRCVMORE)
1137                                 break;
1138                         /*
1139                          * The window might have closed to zero, make
1140                          * sure we send an ack now that we've drained
1141                          * the buffer or we might end up blocking until
1142                          * the idle takes over (5 seconds).
1143                          */
1144                         if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1145                                 so_pru_rcvd(so, flags);
1146                         error = ssb_wait(&so->so_rcv);
1147                         if (error) {
1148                                 ssb_unlock(&so->so_rcv);
1149                                 error = 0;
1150                                 goto done;
1151                         }
1152                         m = so->so_rcv.ssb_mb;
1153                 }
1154         }
1155
1156         /*
1157          * If an atomic read was requested but unread data still remains
1158          * in the record, set MSG_TRUNC.
1159          */
1160         if (m && pr->pr_flags & PR_ATOMIC)
1161                 flags |= MSG_TRUNC;
1162
1163         /*
1164          * Cleanup.  If an atomic read was requested drop any unread data.
1165          */
1166         if ((flags & MSG_PEEK) == 0) {
1167                 if (m && (pr->pr_flags & PR_ATOMIC))
1168                         sbdroprecord(&so->so_rcv.sb);
1169                 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1170                         so_pru_rcvd(so, flags);
1171         }
1172
1173         if (orig_resid == resid && orig_resid &&
1174             (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1175                 ssb_unlock(&so->so_rcv);
1176                 goto restart;
1177         }
1178
1179         if (flagsp)
1180                 *flagsp |= flags;
1181 release:
1182         ssb_unlock(&so->so_rcv);
1183 done:
1184         lwkt_reltoken(&so->so_rcv.ssb_token);
1185         if (free_chain)
1186                 m_freem(free_chain);
1187         return (error);
1188 }
1189
1190 /*
1191  * Shut a socket down.  Note that we do not get a frontend lock as we
1192  * want to be able to shut the socket down even if another thread is
1193  * blocked in a read(), thus waking it up.
1194  */
1195 int
1196 soshutdown(struct socket *so, int how)
1197 {
1198         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1199                 return (EINVAL);
1200
1201         if (how != SHUT_WR) {
1202                 /*ssb_lock(&so->so_rcv, M_WAITOK);*/
1203                 sorflush(so);
1204                 /*ssb_unlock(&so->so_rcv);*/
1205         }
1206         if (how != SHUT_RD)
1207                 return (so_pru_shutdown(so));
1208         return (0);
1209 }
1210
1211 void
1212 sorflush(struct socket *so)
1213 {
1214         struct signalsockbuf *ssb = &so->so_rcv;
1215         struct protosw *pr = so->so_proto;
1216         struct signalsockbuf asb;
1217
1218         atomic_set_int(&ssb->ssb_flags, SSB_NOINTR);
1219
1220         lwkt_gettoken(&ssb->ssb_token);
1221         socantrcvmore(so);
1222         asb = *ssb;
1223
1224         /*
1225          * Can't just blow up the ssb structure here
1226          */
1227         bzero(&ssb->sb, sizeof(ssb->sb));
1228         ssb->ssb_timeo = 0;
1229         ssb->ssb_lowat = 0;
1230         ssb->ssb_hiwat = 0;
1231         ssb->ssb_mbmax = 0;
1232         atomic_clear_int(&ssb->ssb_flags, SSB_CLEAR_MASK);
1233
1234         if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose)
1235                 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1236         ssb_release(&asb, so);
1237
1238         lwkt_reltoken(&ssb->ssb_token);
1239 }
1240
1241 #ifdef INET
1242 static int
1243 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1244 {
1245         struct accept_filter_arg        *afap = NULL;
1246         struct accept_filter    *afp;
1247         struct so_accf  *af = so->so_accf;
1248         int     error = 0;
1249
1250         /* do not set/remove accept filters on non listen sockets */
1251         if ((so->so_options & SO_ACCEPTCONN) == 0) {
1252                 error = EINVAL;
1253                 goto out;
1254         }
1255
1256         /* removing the filter */
1257         if (sopt == NULL) {
1258                 if (af != NULL) {
1259                         if (af->so_accept_filter != NULL && 
1260                                 af->so_accept_filter->accf_destroy != NULL) {
1261                                 af->so_accept_filter->accf_destroy(so);
1262                         }
1263                         if (af->so_accept_filter_str != NULL) {
1264                                 FREE(af->so_accept_filter_str, M_ACCF);
1265                         }
1266                         FREE(af, M_ACCF);
1267                         so->so_accf = NULL;
1268                 }
1269                 so->so_options &= ~SO_ACCEPTFILTER;
1270                 return (0);
1271         }
1272         /* adding a filter */
1273         /* must remove previous filter first */
1274         if (af != NULL) {
1275                 error = EINVAL;
1276                 goto out;
1277         }
1278         /* don't put large objects on the kernel stack */
1279         MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1280         error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1281         afap->af_name[sizeof(afap->af_name)-1] = '\0';
1282         afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1283         if (error)
1284                 goto out;
1285         afp = accept_filt_get(afap->af_name);
1286         if (afp == NULL) {
1287                 error = ENOENT;
1288                 goto out;
1289         }
1290         MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1291         if (afp->accf_create != NULL) {
1292                 if (afap->af_name[0] != '\0') {
1293                         int len = strlen(afap->af_name) + 1;
1294
1295                         MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1296                         strcpy(af->so_accept_filter_str, afap->af_name);
1297                 }
1298                 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1299                 if (af->so_accept_filter_arg == NULL) {
1300                         FREE(af->so_accept_filter_str, M_ACCF);
1301                         FREE(af, M_ACCF);
1302                         so->so_accf = NULL;
1303                         error = EINVAL;
1304                         goto out;
1305                 }
1306         }
1307         af->so_accept_filter = afp;
1308         so->so_accf = af;
1309         so->so_options |= SO_ACCEPTFILTER;
1310 out:
1311         if (afap != NULL)
1312                 FREE(afap, M_TEMP);
1313         return (error);
1314 }
1315 #endif /* INET */
1316
1317 /*
1318  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1319  * an additional variant to handle the case where the option value needs
1320  * to be some kind of integer, but not a specific size.
1321  * In addition to their use here, these functions are also called by the
1322  * protocol-level pr_ctloutput() routines.
1323  */
1324 int
1325 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1326 {
1327         return soopt_to_kbuf(sopt, buf, len, minlen);
1328 }
1329
1330 int
1331 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1332 {
1333         size_t  valsize;
1334
1335         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1336         KKASSERT(kva_p(buf));
1337
1338         /*
1339          * If the user gives us more than we wanted, we ignore it,
1340          * but if we don't get the minimum length the caller
1341          * wants, we return EINVAL.  On success, sopt->sopt_valsize
1342          * is set to however much we actually retrieved.
1343          */
1344         if ((valsize = sopt->sopt_valsize) < minlen)
1345                 return EINVAL;
1346         if (valsize > len)
1347                 sopt->sopt_valsize = valsize = len;
1348
1349         bcopy(sopt->sopt_val, buf, valsize);
1350         return 0;
1351 }
1352
1353
1354 int
1355 sosetopt(struct socket *so, struct sockopt *sopt)
1356 {
1357         int     error, optval;
1358         struct  linger l;
1359         struct  timeval tv;
1360         u_long  val;
1361         struct signalsockbuf *sotmp;
1362
1363         error = 0;
1364         sopt->sopt_dir = SOPT_SET;
1365         if (sopt->sopt_level != SOL_SOCKET) {
1366                 if (so->so_proto && so->so_proto->pr_ctloutput) {
1367                         return (so_pr_ctloutput(so, sopt));
1368                 }
1369                 error = ENOPROTOOPT;
1370         } else {
1371                 switch (sopt->sopt_name) {
1372 #ifdef INET
1373                 case SO_ACCEPTFILTER:
1374                         error = do_setopt_accept_filter(so, sopt);
1375                         if (error)
1376                                 goto bad;
1377                         break;
1378 #endif /* INET */
1379                 case SO_LINGER:
1380                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1381                         if (error)
1382                                 goto bad;
1383
1384                         so->so_linger = l.l_linger;
1385                         if (l.l_onoff)
1386                                 so->so_options |= SO_LINGER;
1387                         else
1388                                 so->so_options &= ~SO_LINGER;
1389                         break;
1390
1391                 case SO_DEBUG:
1392                 case SO_KEEPALIVE:
1393                 case SO_DONTROUTE:
1394                 case SO_USELOOPBACK:
1395                 case SO_BROADCAST:
1396                 case SO_REUSEADDR:
1397                 case SO_REUSEPORT:
1398                 case SO_OOBINLINE:
1399                 case SO_TIMESTAMP:
1400                         error = sooptcopyin(sopt, &optval, sizeof optval,
1401                                             sizeof optval);
1402                         if (error)
1403                                 goto bad;
1404                         if (optval)
1405                                 so->so_options |= sopt->sopt_name;
1406                         else
1407                                 so->so_options &= ~sopt->sopt_name;
1408                         break;
1409
1410                 case SO_SNDBUF:
1411                 case SO_RCVBUF:
1412                 case SO_SNDLOWAT:
1413                 case SO_RCVLOWAT:
1414                         error = sooptcopyin(sopt, &optval, sizeof optval,
1415                                             sizeof optval);
1416                         if (error)
1417                                 goto bad;
1418
1419                         /*
1420                          * Values < 1 make no sense for any of these
1421                          * options, so disallow them.
1422                          */
1423                         if (optval < 1) {
1424                                 error = EINVAL;
1425                                 goto bad;
1426                         }
1427
1428                         switch (sopt->sopt_name) {
1429                         case SO_SNDBUF:
1430                         case SO_RCVBUF:
1431                                 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
1432                                     &so->so_snd : &so->so_rcv, (u_long)optval,
1433                                     so,
1434                                     &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1435                                         error = ENOBUFS;
1436                                         goto bad;
1437                                 }
1438                                 sotmp = (sopt->sopt_name == SO_SNDBUF) ?
1439                                                 &so->so_snd : &so->so_rcv;
1440                                 atomic_clear_int(&sotmp->ssb_flags,
1441                                                  SSB_AUTOSIZE);
1442                                 break;
1443
1444                         /*
1445                          * Make sure the low-water is never greater than
1446                          * the high-water.
1447                          */
1448                         case SO_SNDLOWAT:
1449                                 so->so_snd.ssb_lowat =
1450                                     (optval > so->so_snd.ssb_hiwat) ?
1451                                     so->so_snd.ssb_hiwat : optval;
1452                                 atomic_clear_int(&so->so_snd.ssb_flags,
1453                                                  SSB_AUTOLOWAT);
1454                                 break;
1455                         case SO_RCVLOWAT:
1456                                 so->so_rcv.ssb_lowat =
1457                                     (optval > so->so_rcv.ssb_hiwat) ?
1458                                     so->so_rcv.ssb_hiwat : optval;
1459                                 atomic_clear_int(&so->so_rcv.ssb_flags,
1460                                                  SSB_AUTOLOWAT);
1461                                 break;
1462                         }
1463                         break;
1464
1465                 case SO_SNDTIMEO:
1466                 case SO_RCVTIMEO:
1467                         error = sooptcopyin(sopt, &tv, sizeof tv,
1468                                             sizeof tv);
1469                         if (error)
1470                                 goto bad;
1471
1472                         /* assert(hz > 0); */
1473                         if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
1474                             tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1475                                 error = EDOM;
1476                                 goto bad;
1477                         }
1478                         /* assert(tick > 0); */
1479                         /* assert(ULONG_MAX - INT_MAX >= 1000000); */
1480                         val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
1481                         if (val > INT_MAX) {
1482                                 error = EDOM;
1483                                 goto bad;
1484                         }
1485                         if (val == 0 && tv.tv_usec != 0)
1486                                 val = 1;
1487
1488                         switch (sopt->sopt_name) {
1489                         case SO_SNDTIMEO:
1490                                 so->so_snd.ssb_timeo = val;
1491                                 break;
1492                         case SO_RCVTIMEO:
1493                                 so->so_rcv.ssb_timeo = val;
1494                                 break;
1495                         }
1496                         break;
1497                 default:
1498                         error = ENOPROTOOPT;
1499                         break;
1500                 }
1501                 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1502                         (void) so_pr_ctloutput(so, sopt);
1503                 }
1504         }
1505 bad:
1506         return (error);
1507 }
1508
1509 /* Helper routine for getsockopt */
1510 int
1511 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1512 {
1513         soopt_from_kbuf(sopt, buf, len);
1514         return 0;
1515 }
1516
1517 void
1518 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
1519 {
1520         size_t  valsize;
1521
1522         if (len == 0) {
1523                 sopt->sopt_valsize = 0;
1524                 return;
1525         }
1526
1527         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1528         KKASSERT(kva_p(buf));
1529
1530         /*
1531          * Documented get behavior is that we always return a value,
1532          * possibly truncated to fit in the user's buffer.
1533          * Traditional behavior is that we always tell the user
1534          * precisely how much we copied, rather than something useful
1535          * like the total amount we had available for her.
1536          * Note that this interface is not idempotent; the entire answer must
1537          * generated ahead of time.
1538          */
1539         valsize = szmin(len, sopt->sopt_valsize);
1540         sopt->sopt_valsize = valsize;
1541         if (sopt->sopt_val != 0) {
1542                 bcopy(buf, sopt->sopt_val, valsize);
1543         }
1544 }
1545
1546 int
1547 sogetopt(struct socket *so, struct sockopt *sopt)
1548 {
1549         int     error, optval;
1550         long    optval_l;
1551         struct  linger l;
1552         struct  timeval tv;
1553 #ifdef INET
1554         struct accept_filter_arg *afap;
1555 #endif
1556
1557         error = 0;
1558         sopt->sopt_dir = SOPT_GET;
1559         if (sopt->sopt_level != SOL_SOCKET) {
1560                 if (so->so_proto && so->so_proto->pr_ctloutput) {
1561                         return (so_pr_ctloutput(so, sopt));
1562                 } else
1563                         return (ENOPROTOOPT);
1564         } else {
1565                 switch (sopt->sopt_name) {
1566 #ifdef INET
1567                 case SO_ACCEPTFILTER:
1568                         if ((so->so_options & SO_ACCEPTCONN) == 0)
1569                                 return (EINVAL);
1570                         MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1571                                 M_TEMP, M_WAITOK | M_ZERO);
1572                         if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1573                                 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1574                                 if (so->so_accf->so_accept_filter_str != NULL)
1575                                         strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1576                         }
1577                         error = sooptcopyout(sopt, afap, sizeof(*afap));
1578                         FREE(afap, M_TEMP);
1579                         break;
1580 #endif /* INET */
1581                         
1582                 case SO_LINGER:
1583                         l.l_onoff = so->so_options & SO_LINGER;
1584                         l.l_linger = so->so_linger;
1585                         error = sooptcopyout(sopt, &l, sizeof l);
1586                         break;
1587
1588                 case SO_USELOOPBACK:
1589                 case SO_DONTROUTE:
1590                 case SO_DEBUG:
1591                 case SO_KEEPALIVE:
1592                 case SO_REUSEADDR:
1593                 case SO_REUSEPORT:
1594                 case SO_BROADCAST:
1595                 case SO_OOBINLINE:
1596                 case SO_TIMESTAMP:
1597                         optval = so->so_options & sopt->sopt_name;
1598 integer:
1599                         error = sooptcopyout(sopt, &optval, sizeof optval);
1600                         break;
1601
1602                 case SO_TYPE:
1603                         optval = so->so_type;
1604                         goto integer;
1605
1606                 case SO_ERROR:
1607                         optval = so->so_error;
1608                         so->so_error = 0;
1609                         goto integer;
1610
1611                 case SO_SNDBUF:
1612                         optval = so->so_snd.ssb_hiwat;
1613                         goto integer;
1614
1615                 case SO_RCVBUF:
1616                         optval = so->so_rcv.ssb_hiwat;
1617                         goto integer;
1618
1619                 case SO_SNDLOWAT:
1620                         optval = so->so_snd.ssb_lowat;
1621                         goto integer;
1622
1623                 case SO_RCVLOWAT:
1624                         optval = so->so_rcv.ssb_lowat;
1625                         goto integer;
1626
1627                 case SO_SNDTIMEO:
1628                 case SO_RCVTIMEO:
1629                         optval = (sopt->sopt_name == SO_SNDTIMEO ?
1630                                   so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
1631
1632                         tv.tv_sec = optval / hz;
1633                         tv.tv_usec = (optval % hz) * ustick;
1634                         error = sooptcopyout(sopt, &tv, sizeof tv);
1635                         break;                  
1636
1637                 case SO_SNDSPACE:
1638                         optval_l = ssb_space(&so->so_snd);
1639                         error = sooptcopyout(sopt, &optval_l, sizeof(optval_l));
1640                         break;
1641
1642                 default:
1643                         error = ENOPROTOOPT;
1644                         break;
1645                 }
1646                 return (error);
1647         }
1648 }
1649
1650 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1651 int
1652 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1653 {
1654         struct mbuf *m, *m_prev;
1655         int sopt_size = sopt->sopt_valsize, msize;
1656
1657         m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1658                    0, &msize);
1659         if (m == NULL)
1660                 return (ENOBUFS);
1661         m->m_len = min(msize, sopt_size);
1662         sopt_size -= m->m_len;
1663         *mp = m;
1664         m_prev = m;
1665
1666         while (sopt_size > 0) {
1667                 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1668                            MT_DATA, 0, &msize);
1669                 if (m == NULL) {
1670                         m_freem(*mp);
1671                         return (ENOBUFS);
1672                 }
1673                 m->m_len = min(msize, sopt_size);
1674                 sopt_size -= m->m_len;
1675                 m_prev->m_next = m;
1676                 m_prev = m;
1677         }
1678         return (0);
1679 }
1680
1681 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1682 int
1683 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1684 {
1685         soopt_to_mbuf(sopt, m);
1686         return 0;
1687 }
1688
1689 void
1690 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
1691 {
1692         size_t valsize;
1693         void *val;
1694
1695         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1696         KKASSERT(kva_p(m));
1697         if (sopt->sopt_val == NULL)
1698                 return;
1699         val = sopt->sopt_val;
1700         valsize = sopt->sopt_valsize;
1701         while (m != NULL && valsize >= m->m_len) {
1702                 bcopy(val, mtod(m, char *), m->m_len);
1703                 valsize -= m->m_len;
1704                 val = (caddr_t)val + m->m_len;
1705                 m = m->m_next;
1706         }
1707         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1708                 panic("ip6_sooptmcopyin");
1709 }
1710
1711 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1712 int
1713 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1714 {
1715         return soopt_from_mbuf(sopt, m);
1716 }
1717
1718 int
1719 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
1720 {
1721         struct mbuf *m0 = m;
1722         size_t valsize = 0;
1723         size_t maxsize;
1724         void *val;
1725
1726         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1727         KKASSERT(kva_p(m));
1728         if (sopt->sopt_val == NULL)
1729                 return 0;
1730         val = sopt->sopt_val;
1731         maxsize = sopt->sopt_valsize;
1732         while (m != NULL && maxsize >= m->m_len) {
1733                 bcopy(mtod(m, char *), val, m->m_len);
1734                maxsize -= m->m_len;
1735                val = (caddr_t)val + m->m_len;
1736                valsize += m->m_len;
1737                m = m->m_next;
1738         }
1739         if (m != NULL) {
1740                 /* enough soopt buffer should be given from user-land */
1741                 m_freem(m0);
1742                 return (EINVAL);
1743         }
1744         sopt->sopt_valsize = valsize;
1745         return 0;
1746 }
1747
1748 void
1749 sohasoutofband(struct socket *so)
1750 {
1751         if (so->so_sigio != NULL)
1752                 pgsigio(so->so_sigio, SIGURG, 0);
1753         KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
1754 }
1755
1756 int
1757 sokqfilter(struct file *fp, struct knote *kn)
1758 {
1759         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1760         struct signalsockbuf *ssb;
1761
1762         switch (kn->kn_filter) {
1763         case EVFILT_READ:
1764                 if (so->so_options & SO_ACCEPTCONN)
1765                         kn->kn_fop = &solisten_filtops;
1766                 else
1767                         kn->kn_fop = &soread_filtops;
1768                 ssb = &so->so_rcv;
1769                 break;
1770         case EVFILT_WRITE:
1771                 kn->kn_fop = &sowrite_filtops;
1772                 ssb = &so->so_snd;
1773                 break;
1774         case EVFILT_EXCEPT:
1775                 kn->kn_fop = &soexcept_filtops;
1776                 ssb = &so->so_rcv;
1777                 break;
1778         default:
1779                 return (EOPNOTSUPP);
1780         }
1781
1782         knote_insert(&ssb->ssb_kq.ki_note, kn);
1783         atomic_set_int(&ssb->ssb_flags, SSB_KNOTE);
1784         return (0);
1785 }
1786
1787 static void
1788 filt_sordetach(struct knote *kn)
1789 {
1790         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1791
1792         knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
1793         if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
1794                 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_KNOTE);
1795 }
1796
1797 /*ARGSUSED*/
1798 static int
1799 filt_soread(struct knote *kn, long hint)
1800 {
1801         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1802
1803         if (kn->kn_sfflags & NOTE_OOB) {
1804                 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
1805                         kn->kn_fflags |= NOTE_OOB;
1806                         return (1);
1807                 }
1808                 return (0);
1809         }
1810         kn->kn_data = so->so_rcv.ssb_cc;
1811
1812         if (so->so_state & SS_CANTRCVMORE) {
1813                 /*
1814                  * Only set NODATA if all data has been exhausted.
1815                  */
1816                 if (kn->kn_data == 0)
1817                         kn->kn_flags |= EV_NODATA;
1818                 kn->kn_flags |= EV_EOF; 
1819                 kn->kn_fflags = so->so_error;
1820                 return (1);
1821         }
1822         if (so->so_error)       /* temporary udp error */
1823                 return (1);
1824         if (kn->kn_sfflags & NOTE_LOWAT)
1825                 return (kn->kn_data >= kn->kn_sdata);
1826         return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
1827                 !TAILQ_EMPTY(&so->so_comp));
1828 }
1829
1830 static void
1831 filt_sowdetach(struct knote *kn)
1832 {
1833         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1834
1835         knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
1836         if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
1837                 atomic_clear_int(&so->so_snd.ssb_flags, SSB_KNOTE);
1838 }
1839
1840 /*ARGSUSED*/
1841 static int
1842 filt_sowrite(struct knote *kn, long hint)
1843 {
1844         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1845
1846         kn->kn_data = ssb_space(&so->so_snd);
1847         if (so->so_state & SS_CANTSENDMORE) {
1848                 kn->kn_flags |= (EV_EOF | EV_NODATA);
1849                 kn->kn_fflags = so->so_error;
1850                 return (1);
1851         }
1852         if (so->so_error)       /* temporary udp error */
1853                 return (1);
1854         if (((so->so_state & SS_ISCONNECTED) == 0) &&
1855             (so->so_proto->pr_flags & PR_CONNREQUIRED))
1856                 return (0);
1857         if (kn->kn_sfflags & NOTE_LOWAT)
1858                 return (kn->kn_data >= kn->kn_sdata);
1859         return (kn->kn_data >= so->so_snd.ssb_lowat);
1860 }
1861
1862 /*ARGSUSED*/
1863 static int
1864 filt_solisten(struct knote *kn, long hint)
1865 {
1866         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1867
1868         kn->kn_data = so->so_qlen;
1869         return (! TAILQ_EMPTY(&so->so_comp));
1870 }