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