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