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