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