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