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