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