]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_socket.c
Import ACPICA 20090521.
[FreeBSD/FreeBSD.git] / sys / kern / uipc_socket.c
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
3  *      The Regents of the University of California.
4  * Copyright (c) 2004 The FreeBSD Foundation
5  * Copyright (c) 2004-2008 Robert N. M. Watson
6  * All rights reserved.
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      @(#)uipc_socket.c       8.3 (Berkeley) 4/15/94
33  */
34
35 /*
36  * Comments on the socket life cycle:
37  *
38  * soalloc() sets of socket layer state for a socket, called only by
39  * socreate() and sonewconn().  Socket layer private.
40  *
41  * sodealloc() tears down socket layer state for a socket, called only by
42  * sofree() and sonewconn().  Socket layer private.
43  *
44  * pru_attach() associates protocol layer state with an allocated socket;
45  * called only once, may fail, aborting socket allocation.  This is called
46  * from socreate() and sonewconn().  Socket layer private.
47  *
48  * pru_detach() disassociates protocol layer state from an attached socket,
49  * and will be called exactly once for sockets in which pru_attach() has
50  * been successfully called.  If pru_attach() returned an error,
51  * pru_detach() will not be called.  Socket layer private.
52  *
53  * pru_abort() and pru_close() notify the protocol layer that the last
54  * consumer of a socket is starting to tear down the socket, and that the
55  * protocol should terminate the connection.  Historically, pru_abort() also
56  * detached protocol state from the socket state, but this is no longer the
57  * case.
58  *
59  * socreate() creates a socket and attaches protocol state.  This is a public
60  * interface that may be used by socket layer consumers to create new
61  * sockets.
62  *
63  * sonewconn() creates a socket and attaches protocol state.  This is a
64  * public interface  that may be used by protocols to create new sockets when
65  * a new connection is received and will be available for accept() on a
66  * listen socket.
67  *
68  * soclose() destroys a socket after possibly waiting for it to disconnect.
69  * This is a public interface that socket consumers should use to close and
70  * release a socket when done with it.
71  *
72  * soabort() destroys a socket without waiting for it to disconnect (used
73  * only for incoming connections that are already partially or fully
74  * connected).  This is used internally by the socket layer when clearing
75  * listen socket queues (due to overflow or close on the listen socket), but
76  * is also a public interface protocols may use to abort connections in
77  * their incomplete listen queues should they no longer be required.  Sockets
78  * placed in completed connection listen queues should not be aborted for
79  * reasons described in the comment above the soclose() implementation.  This
80  * is not a general purpose close routine, and except in the specific
81  * circumstances described here, should not be used.
82  *
83  * sofree() will free a socket and its protocol state if all references on
84  * the socket have been released, and is the public interface to attempt to
85  * free a socket when a reference is removed.  This is a socket layer private
86  * interface.
87  *
88  * NOTE: In addition to socreate() and soclose(), which provide a single
89  * socket reference to the consumer to be managed as required, there are two
90  * calls to explicitly manage socket references, soref(), and sorele().
91  * Currently, these are generally required only when transitioning a socket
92  * from a listen queue to a file descriptor, in order to prevent garbage
93  * collection of the socket at an untimely moment.  For a number of reasons,
94  * these interfaces are not preferred, and should be avoided.
95  */
96
97 #include <sys/cdefs.h>
98 __FBSDID("$FreeBSD$");
99
100 #include "opt_inet.h"
101 #include "opt_inet6.h"
102 #include "opt_zero.h"
103 #include "opt_compat.h"
104
105 #include <sys/param.h>
106 #include <sys/systm.h>
107 #include <sys/fcntl.h>
108 #include <sys/limits.h>
109 #include <sys/lock.h>
110 #include <sys/mac.h>
111 #include <sys/malloc.h>
112 #include <sys/mbuf.h>
113 #include <sys/mutex.h>
114 #include <sys/domain.h>
115 #include <sys/file.h>                   /* for struct knote */
116 #include <sys/kernel.h>
117 #include <sys/event.h>
118 #include <sys/eventhandler.h>
119 #include <sys/poll.h>
120 #include <sys/proc.h>
121 #include <sys/protosw.h>
122 #include <sys/socket.h>
123 #include <sys/socketvar.h>
124 #include <sys/resourcevar.h>
125 #include <net/route.h>
126 #include <sys/signalvar.h>
127 #include <sys/stat.h>
128 #include <sys/sx.h>
129 #include <sys/sysctl.h>
130 #include <sys/uio.h>
131 #include <sys/jail.h>
132 #include <sys/vimage.h>
133
134 #include <security/mac/mac_framework.h>
135
136 #include <vm/uma.h>
137
138 #ifdef COMPAT_IA32
139 #include <sys/mount.h>
140 #include <sys/sysent.h>
141 #include <compat/freebsd32/freebsd32.h>
142 #endif
143
144 static int      soreceive_rcvoob(struct socket *so, struct uio *uio,
145                     int flags);
146
147 static void     filt_sordetach(struct knote *kn);
148 static int      filt_soread(struct knote *kn, long hint);
149 static void     filt_sowdetach(struct knote *kn);
150 static int      filt_sowrite(struct knote *kn, long hint);
151 static int      filt_solisten(struct knote *kn, long hint);
152
153 static struct filterops solisten_filtops =
154         { 1, NULL, filt_sordetach, filt_solisten };
155 static struct filterops soread_filtops =
156         { 1, NULL, filt_sordetach, filt_soread };
157 static struct filterops sowrite_filtops =
158         { 1, NULL, filt_sowdetach, filt_sowrite };
159
160 uma_zone_t socket_zone;
161 so_gen_t        so_gencnt;      /* generation count for sockets */
162
163 int     maxsockets;
164
165 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
166 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
167
168 static int somaxconn = SOMAXCONN;
169 static int sysctl_somaxconn(SYSCTL_HANDLER_ARGS);
170 /* XXX: we dont have SYSCTL_USHORT */
171 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
172     0, sizeof(int), sysctl_somaxconn, "I", "Maximum pending socket connection "
173     "queue size");
174 static int numopensockets;
175 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
176     &numopensockets, 0, "Number of open sockets");
177 #ifdef ZERO_COPY_SOCKETS
178 /* These aren't static because they're used in other files. */
179 int so_zero_copy_send = 1;
180 int so_zero_copy_receive = 1;
181 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
182     "Zero copy controls");
183 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
184     &so_zero_copy_receive, 0, "Enable zero copy receive");
185 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
186     &so_zero_copy_send, 0, "Enable zero copy send");
187 #endif /* ZERO_COPY_SOCKETS */
188
189 /*
190  * accept_mtx locks down per-socket fields relating to accept queues.  See
191  * socketvar.h for an annotation of the protected fields of struct socket.
192  */
193 struct mtx accept_mtx;
194 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
195
196 /*
197  * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
198  * so_gencnt field.
199  */
200 static struct mtx so_global_mtx;
201 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
202
203 /*
204  * General IPC sysctl name space, used by sockets and a variety of other IPC
205  * types.
206  */
207 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
208
209 /*
210  * Sysctl to get and set the maximum global sockets limit.  Notify protocols
211  * of the change so that they can update their dependent limits as required.
212  */
213 static int
214 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
215 {
216         int error, newmaxsockets;
217
218         newmaxsockets = maxsockets;
219         error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
220         if (error == 0 && req->newptr) {
221                 if (newmaxsockets > maxsockets) {
222                         maxsockets = newmaxsockets;
223                         if (maxsockets > ((maxfiles / 4) * 3)) {
224                                 maxfiles = (maxsockets * 5) / 4;
225                                 maxfilesperproc = (maxfiles * 9) / 10;
226                         }
227                         EVENTHANDLER_INVOKE(maxsockets_change);
228                 } else
229                         error = EINVAL;
230         }
231         return (error);
232 }
233
234 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
235     &maxsockets, 0, sysctl_maxsockets, "IU",
236     "Maximum number of sockets avaliable");
237
238 /*
239  * Initialise maxsockets.  This SYSINIT must be run after
240  * tunable_mbinit().
241  */
242 static void
243 init_maxsockets(void *ignored)
244 {
245
246         TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
247         maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
248 }
249 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
250
251 /*
252  * Socket operation routines.  These routines are called by the routines in
253  * sys_socket.c or from a system process, and implement the semantics of
254  * socket operations by switching out to the protocol specific routines.
255  */
256
257 /*
258  * Get a socket structure from our zone, and initialize it.  Note that it
259  * would probably be better to allocate socket and PCB at the same time, but
260  * I'm not convinced that all the protocols can be easily modified to do
261  * this.
262  *
263  * soalloc() returns a socket with a ref count of 0.
264  */
265 static struct socket *
266 soalloc(struct vnet *vnet)
267 {
268         struct socket *so;
269
270         so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
271         if (so == NULL)
272                 return (NULL);
273 #ifdef MAC
274         if (mac_socket_init(so, M_NOWAIT) != 0) {
275                 uma_zfree(socket_zone, so);
276                 return (NULL);
277         }
278 #endif
279         SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
280         SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
281         sx_init(&so->so_snd.sb_sx, "so_snd_sx");
282         sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
283         TAILQ_INIT(&so->so_aiojobq);
284         mtx_lock(&so_global_mtx);
285         so->so_gencnt = ++so_gencnt;
286         ++numopensockets;
287 #ifdef VIMAGE
288         ++vnet->sockcnt;        /* Locked with so_global_mtx. */
289         so->so_vnet = vnet;
290 #endif
291         mtx_unlock(&so_global_mtx);
292         return (so);
293 }
294
295 /*
296  * Free the storage associated with a socket at the socket layer, tear down
297  * locks, labels, etc.  All protocol state is assumed already to have been
298  * torn down (and possibly never set up) by the caller.
299  */
300 static void
301 sodealloc(struct socket *so)
302 {
303
304         KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
305         KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
306
307         mtx_lock(&so_global_mtx);
308         so->so_gencnt = ++so_gencnt;
309         --numopensockets;       /* Could be below, but faster here. */
310 #ifdef VIMAGE
311         --so->so_vnet->sockcnt;
312 #endif
313         mtx_unlock(&so_global_mtx);
314         if (so->so_rcv.sb_hiwat)
315                 (void)chgsbsize(so->so_cred->cr_uidinfo,
316                     &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
317         if (so->so_snd.sb_hiwat)
318                 (void)chgsbsize(so->so_cred->cr_uidinfo,
319                     &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
320 #ifdef INET
321         /* remove acccept filter if one is present. */
322         if (so->so_accf != NULL)
323                 do_setopt_accept_filter(so, NULL);
324 #endif
325 #ifdef MAC
326         mac_socket_destroy(so);
327 #endif
328         crfree(so->so_cred);
329         sx_destroy(&so->so_snd.sb_sx);
330         sx_destroy(&so->so_rcv.sb_sx);
331         SOCKBUF_LOCK_DESTROY(&so->so_snd);
332         SOCKBUF_LOCK_DESTROY(&so->so_rcv);
333         uma_zfree(socket_zone, so);
334 }
335
336 /*
337  * socreate returns a socket with a ref count of 1.  The socket should be
338  * closed with soclose().
339  */
340 int
341 socreate(int dom, struct socket **aso, int type, int proto,
342     struct ucred *cred, struct thread *td)
343 {
344         struct protosw *prp;
345         struct socket *so;
346         int error;
347
348         if (proto)
349                 prp = pffindproto(dom, proto, type);
350         else
351                 prp = pffindtype(dom, type);
352
353         if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
354             prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
355                 return (EPROTONOSUPPORT);
356
357         if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
358                 return (EPROTONOSUPPORT);
359
360         if (prp->pr_type != type)
361                 return (EPROTOTYPE);
362         so = soalloc(TD_TO_VNET(td));
363         if (so == NULL)
364                 return (ENOBUFS);
365
366         TAILQ_INIT(&so->so_incomp);
367         TAILQ_INIT(&so->so_comp);
368         so->so_type = type;
369         so->so_cred = crhold(cred);
370         if ((prp->pr_domain->dom_family == PF_INET) ||
371             (prp->pr_domain->dom_family == PF_ROUTE))
372                 so->so_fibnum = td->td_proc->p_fibnum;
373         else
374                 so->so_fibnum = 0;
375         so->so_proto = prp;
376 #ifdef MAC
377         mac_socket_create(cred, so);
378 #endif
379         knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
380             NULL, NULL, NULL);
381         knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
382             NULL, NULL, NULL);
383         so->so_count = 1;
384         /*
385          * Auto-sizing of socket buffers is managed by the protocols and
386          * the appropriate flags must be set in the pru_attach function.
387          */
388         CURVNET_SET(so->so_vnet);
389         error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
390         CURVNET_RESTORE();
391         if (error) {
392                 KASSERT(so->so_count == 1, ("socreate: so_count %d",
393                     so->so_count));
394                 so->so_count = 0;
395                 sodealloc(so);
396                 return (error);
397         }
398         *aso = so;
399         return (0);
400 }
401
402 #ifdef REGRESSION
403 static int regression_sonewconn_earlytest = 1;
404 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
405     &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
406 #endif
407
408 /*
409  * When an attempt at a new connection is noted on a socket which accepts
410  * connections, sonewconn is called.  If the connection is possible (subject
411  * to space constraints, etc.) then we allocate a new structure, propoerly
412  * linked into the data structure of the original socket, and return this.
413  * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
414  *
415  * Note: the ref count on the socket is 0 on return.
416  */
417 struct socket *
418 sonewconn(struct socket *head, int connstatus)
419 {
420         struct socket *so;
421         int over;
422
423         ACCEPT_LOCK();
424         over = (head->so_qlen > 3 * head->so_qlimit / 2);
425         ACCEPT_UNLOCK();
426 #ifdef REGRESSION
427         if (regression_sonewconn_earlytest && over)
428 #else
429         if (over)
430 #endif
431                 return (NULL);
432         VNET_ASSERT(head->so_vnet);
433         so = soalloc(head->so_vnet);
434         if (so == NULL)
435                 return (NULL);
436         if ((head->so_options & SO_ACCEPTFILTER) != 0)
437                 connstatus = 0;
438         so->so_head = head;
439         so->so_type = head->so_type;
440         so->so_options = head->so_options &~ SO_ACCEPTCONN;
441         so->so_linger = head->so_linger;
442         so->so_state = head->so_state | SS_NOFDREF;
443         so->so_proto = head->so_proto;
444         so->so_cred = crhold(head->so_cred);
445 #ifdef MAC
446         mac_socket_newconn(head, so);
447 #endif
448         knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
449             NULL, NULL, NULL);
450         knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
451             NULL, NULL, NULL);
452         if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
453             (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
454                 sodealloc(so);
455                 return (NULL);
456         }
457         so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
458         so->so_snd.sb_lowat = head->so_snd.sb_lowat;
459         so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
460         so->so_snd.sb_timeo = head->so_snd.sb_timeo;
461         so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
462         so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
463         so->so_state |= connstatus;
464         ACCEPT_LOCK();
465         if (connstatus) {
466                 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
467                 so->so_qstate |= SQ_COMP;
468                 head->so_qlen++;
469         } else {
470                 /*
471                  * Keep removing sockets from the head until there's room for
472                  * us to insert on the tail.  In pre-locking revisions, this
473                  * was a simple if(), but as we could be racing with other
474                  * threads and soabort() requires dropping locks, we must
475                  * loop waiting for the condition to be true.
476                  */
477                 while (head->so_incqlen > head->so_qlimit) {
478                         struct socket *sp;
479                         sp = TAILQ_FIRST(&head->so_incomp);
480                         TAILQ_REMOVE(&head->so_incomp, sp, so_list);
481                         head->so_incqlen--;
482                         sp->so_qstate &= ~SQ_INCOMP;
483                         sp->so_head = NULL;
484                         ACCEPT_UNLOCK();
485                         soabort(sp);
486                         ACCEPT_LOCK();
487                 }
488                 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
489                 so->so_qstate |= SQ_INCOMP;
490                 head->so_incqlen++;
491         }
492         ACCEPT_UNLOCK();
493         if (connstatus) {
494                 sorwakeup(head);
495                 wakeup_one(&head->so_timeo);
496         }
497         return (so);
498 }
499
500 int
501 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
502 {
503         int error;
504
505         CURVNET_SET(so->so_vnet);
506         error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
507         CURVNET_RESTORE();
508         return error;
509 }
510
511 /*
512  * solisten() transitions a socket from a non-listening state to a listening
513  * state, but can also be used to update the listen queue depth on an
514  * existing listen socket.  The protocol will call back into the sockets
515  * layer using solisten_proto_check() and solisten_proto() to check and set
516  * socket-layer listen state.  Call backs are used so that the protocol can
517  * acquire both protocol and socket layer locks in whatever order is required
518  * by the protocol.
519  *
520  * Protocol implementors are advised to hold the socket lock across the
521  * socket-layer test and set to avoid races at the socket layer.
522  */
523 int
524 solisten(struct socket *so, int backlog, struct thread *td)
525 {
526
527         return ((*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td));
528 }
529
530 int
531 solisten_proto_check(struct socket *so)
532 {
533
534         SOCK_LOCK_ASSERT(so);
535
536         if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
537             SS_ISDISCONNECTING))
538                 return (EINVAL);
539         return (0);
540 }
541
542 void
543 solisten_proto(struct socket *so, int backlog)
544 {
545
546         SOCK_LOCK_ASSERT(so);
547
548         if (backlog < 0 || backlog > somaxconn)
549                 backlog = somaxconn;
550         so->so_qlimit = backlog;
551         so->so_options |= SO_ACCEPTCONN;
552 }
553
554 /*
555  * Attempt to free a socket.  This should really be sotryfree().
556  *
557  * sofree() will succeed if:
558  *
559  * - There are no outstanding file descriptor references or related consumers
560  *   (so_count == 0).
561  *
562  * - The socket has been closed by user space, if ever open (SS_NOFDREF).
563  *
564  * - The protocol does not have an outstanding strong reference on the socket
565  *   (SS_PROTOREF).
566  *
567  * - The socket is not in a completed connection queue, so a process has been
568  *   notified that it is present.  If it is removed, the user process may
569  *   block in accept() despite select() saying the socket was ready.
570  *
571  * Otherwise, it will quietly abort so that a future call to sofree(), when
572  * conditions are right, can succeed.
573  */
574 void
575 sofree(struct socket *so)
576 {
577         struct protosw *pr = so->so_proto;
578         struct socket *head;
579
580         ACCEPT_LOCK_ASSERT();
581         SOCK_LOCK_ASSERT(so);
582
583         if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
584             (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
585                 SOCK_UNLOCK(so);
586                 ACCEPT_UNLOCK();
587                 return;
588         }
589
590         head = so->so_head;
591         if (head != NULL) {
592                 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
593                     (so->so_qstate & SQ_INCOMP) != 0,
594                     ("sofree: so_head != NULL, but neither SQ_COMP nor "
595                     "SQ_INCOMP"));
596                 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
597                     (so->so_qstate & SQ_INCOMP) == 0,
598                     ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
599                 TAILQ_REMOVE(&head->so_incomp, so, so_list);
600                 head->so_incqlen--;
601                 so->so_qstate &= ~SQ_INCOMP;
602                 so->so_head = NULL;
603         }
604         KASSERT((so->so_qstate & SQ_COMP) == 0 &&
605             (so->so_qstate & SQ_INCOMP) == 0,
606             ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
607             so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
608         if (so->so_options & SO_ACCEPTCONN) {
609                 KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
610                 KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_comp populated"));
611         }
612         SOCK_UNLOCK(so);
613         ACCEPT_UNLOCK();
614
615         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
616                 (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
617         if (pr->pr_usrreqs->pru_detach != NULL)
618                 (*pr->pr_usrreqs->pru_detach)(so);
619
620         /*
621          * From this point on, we assume that no other references to this
622          * socket exist anywhere else in the stack.  Therefore, no locks need
623          * to be acquired or held.
624          *
625          * We used to do a lot of socket buffer and socket locking here, as
626          * well as invoke sorflush() and perform wakeups.  The direct call to
627          * dom_dispose() and sbrelease_internal() are an inlining of what was
628          * necessary from sorflush().
629          *
630          * Notice that the socket buffer and kqueue state are torn down
631          * before calling pru_detach.  This means that protocols shold not
632          * assume they can perform socket wakeups, etc, in their detach code.
633          */
634         sbdestroy(&so->so_snd, so);
635         sbdestroy(&so->so_rcv, so);
636         knlist_destroy(&so->so_rcv.sb_sel.si_note);
637         knlist_destroy(&so->so_snd.sb_sel.si_note);
638         sodealloc(so);
639 }
640
641 /*
642  * Close a socket on last file table reference removal.  Initiate disconnect
643  * if connected.  Free socket when disconnect complete.
644  *
645  * This function will sorele() the socket.  Note that soclose() may be called
646  * prior to the ref count reaching zero.  The actual socket structure will
647  * not be freed until the ref count reaches zero.
648  */
649 int
650 soclose(struct socket *so)
651 {
652         int error = 0;
653
654         KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
655
656         CURVNET_SET(so->so_vnet);
657         funsetown(&so->so_sigio);
658         if (so->so_state & SS_ISCONNECTED) {
659                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
660                         error = sodisconnect(so);
661                         if (error)
662                                 goto drop;
663                 }
664                 if (so->so_options & SO_LINGER) {
665                         if ((so->so_state & SS_ISDISCONNECTING) &&
666                             (so->so_state & SS_NBIO))
667                                 goto drop;
668                         while (so->so_state & SS_ISCONNECTED) {
669                                 error = tsleep(&so->so_timeo,
670                                     PSOCK | PCATCH, "soclos", so->so_linger * hz);
671                                 if (error)
672                                         break;
673                         }
674                 }
675         }
676
677 drop:
678         if (so->so_proto->pr_usrreqs->pru_close != NULL)
679                 (*so->so_proto->pr_usrreqs->pru_close)(so);
680         if (so->so_options & SO_ACCEPTCONN) {
681                 struct socket *sp;
682                 ACCEPT_LOCK();
683                 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
684                         TAILQ_REMOVE(&so->so_incomp, sp, so_list);
685                         so->so_incqlen--;
686                         sp->so_qstate &= ~SQ_INCOMP;
687                         sp->so_head = NULL;
688                         ACCEPT_UNLOCK();
689                         soabort(sp);
690                         ACCEPT_LOCK();
691                 }
692                 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
693                         TAILQ_REMOVE(&so->so_comp, sp, so_list);
694                         so->so_qlen--;
695                         sp->so_qstate &= ~SQ_COMP;
696                         sp->so_head = NULL;
697                         ACCEPT_UNLOCK();
698                         soabort(sp);
699                         ACCEPT_LOCK();
700                 }
701                 ACCEPT_UNLOCK();
702         }
703         ACCEPT_LOCK();
704         SOCK_LOCK(so);
705         KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
706         so->so_state |= SS_NOFDREF;
707         sorele(so);
708         CURVNET_RESTORE();
709         return (error);
710 }
711
712 /*
713  * soabort() is used to abruptly tear down a connection, such as when a
714  * resource limit is reached (listen queue depth exceeded), or if a listen
715  * socket is closed while there are sockets waiting to be accepted.
716  *
717  * This interface is tricky, because it is called on an unreferenced socket,
718  * and must be called only by a thread that has actually removed the socket
719  * from the listen queue it was on, or races with other threads are risked.
720  *
721  * This interface will call into the protocol code, so must not be called
722  * with any socket locks held.  Protocols do call it while holding their own
723  * recursible protocol mutexes, but this is something that should be subject
724  * to review in the future.
725  */
726 void
727 soabort(struct socket *so)
728 {
729
730         /*
731          * In as much as is possible, assert that no references to this
732          * socket are held.  This is not quite the same as asserting that the
733          * current thread is responsible for arranging for no references, but
734          * is as close as we can get for now.
735          */
736         KASSERT(so->so_count == 0, ("soabort: so_count"));
737         KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
738         KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
739         KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
740         KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
741
742         if (so->so_proto->pr_usrreqs->pru_abort != NULL)
743                 (*so->so_proto->pr_usrreqs->pru_abort)(so);
744         ACCEPT_LOCK();
745         SOCK_LOCK(so);
746         sofree(so);
747 }
748
749 int
750 soaccept(struct socket *so, struct sockaddr **nam)
751 {
752         int error;
753
754         SOCK_LOCK(so);
755         KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
756         so->so_state &= ~SS_NOFDREF;
757         SOCK_UNLOCK(so);
758         error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
759         return (error);
760 }
761
762 int
763 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
764 {
765         int error;
766
767         if (so->so_options & SO_ACCEPTCONN)
768                 return (EOPNOTSUPP);
769         /*
770          * If protocol is connection-based, can only connect once.
771          * Otherwise, if connected, try to disconnect first.  This allows
772          * user to disconnect by connecting to, e.g., a null address.
773          */
774         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
775             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
776             (error = sodisconnect(so)))) {
777                 error = EISCONN;
778         } else {
779                 /*
780                  * Prevent accumulated error from previous connection from
781                  * biting us.
782                  */
783                 so->so_error = 0;
784                 CURVNET_SET(so->so_vnet);
785                 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
786                 CURVNET_RESTORE();
787         }
788
789         return (error);
790 }
791
792 int
793 soconnect2(struct socket *so1, struct socket *so2)
794 {
795
796         return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
797 }
798
799 int
800 sodisconnect(struct socket *so)
801 {
802         int error;
803
804         if ((so->so_state & SS_ISCONNECTED) == 0)
805                 return (ENOTCONN);
806         if (so->so_state & SS_ISDISCONNECTING)
807                 return (EALREADY);
808         error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
809         return (error);
810 }
811
812 #ifdef ZERO_COPY_SOCKETS
813 struct so_zerocopy_stats{
814         int size_ok;
815         int align_ok;
816         int found_ifp;
817 };
818 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
819 #include <netinet/in.h>
820 #include <net/route.h>
821 #include <netinet/in_pcb.h>
822 #include <vm/vm.h>
823 #include <vm/vm_page.h>
824 #include <vm/vm_object.h>
825
826 /*
827  * sosend_copyin() is only used if zero copy sockets are enabled.  Otherwise
828  * sosend_dgram() and sosend_generic() use m_uiotombuf().
829  * 
830  * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
831  * all of the data referenced by the uio.  If desired, it uses zero-copy.
832  * *space will be updated to reflect data copied in.
833  *
834  * NB: If atomic I/O is requested, the caller must already have checked that
835  * space can hold resid bytes.
836  *
837  * NB: In the event of an error, the caller may need to free the partial
838  * chain pointed to by *mpp.  The contents of both *uio and *space may be
839  * modified even in the case of an error.
840  */
841 static int
842 sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
843     int flags)
844 {
845         struct mbuf *m, **mp, *top;
846         long len, resid;
847         int error;
848 #ifdef ZERO_COPY_SOCKETS
849         int cow_send;
850 #endif
851
852         *retmp = top = NULL;
853         mp = &top;
854         len = 0;
855         resid = uio->uio_resid;
856         error = 0;
857         do {
858 #ifdef ZERO_COPY_SOCKETS
859                 cow_send = 0;
860 #endif /* ZERO_COPY_SOCKETS */
861                 if (resid >= MINCLSIZE) {
862 #ifdef ZERO_COPY_SOCKETS
863                         if (top == NULL) {
864                                 m = m_gethdr(M_WAITOK, MT_DATA);
865                                 m->m_pkthdr.len = 0;
866                                 m->m_pkthdr.rcvif = NULL;
867                         } else
868                                 m = m_get(M_WAITOK, MT_DATA);
869                         if (so_zero_copy_send &&
870                             resid>=PAGE_SIZE &&
871                             *space>=PAGE_SIZE &&
872                             uio->uio_iov->iov_len>=PAGE_SIZE) {
873                                 so_zerocp_stats.size_ok++;
874                                 so_zerocp_stats.align_ok++;
875                                 cow_send = socow_setup(m, uio);
876                                 len = cow_send;
877                         }
878                         if (!cow_send) {
879                                 m_clget(m, M_WAITOK);
880                                 len = min(min(MCLBYTES, resid), *space);
881                         }
882 #else /* ZERO_COPY_SOCKETS */
883                         if (top == NULL) {
884                                 m = m_getcl(M_WAIT, MT_DATA, M_PKTHDR);
885                                 m->m_pkthdr.len = 0;
886                                 m->m_pkthdr.rcvif = NULL;
887                         } else
888                                 m = m_getcl(M_WAIT, MT_DATA, 0);
889                         len = min(min(MCLBYTES, resid), *space);
890 #endif /* ZERO_COPY_SOCKETS */
891                 } else {
892                         if (top == NULL) {
893                                 m = m_gethdr(M_WAIT, MT_DATA);
894                                 m->m_pkthdr.len = 0;
895                                 m->m_pkthdr.rcvif = NULL;
896
897                                 len = min(min(MHLEN, resid), *space);
898                                 /*
899                                  * For datagram protocols, leave room
900                                  * for protocol headers in first mbuf.
901                                  */
902                                 if (atomic && m && len < MHLEN)
903                                         MH_ALIGN(m, len);
904                         } else {
905                                 m = m_get(M_WAIT, MT_DATA);
906                                 len = min(min(MLEN, resid), *space);
907                         }
908                 }
909                 if (m == NULL) {
910                         error = ENOBUFS;
911                         goto out;
912                 }
913
914                 *space -= len;
915 #ifdef ZERO_COPY_SOCKETS
916                 if (cow_send)
917                         error = 0;
918                 else
919 #endif /* ZERO_COPY_SOCKETS */
920                 error = uiomove(mtod(m, void *), (int)len, uio);
921                 resid = uio->uio_resid;
922                 m->m_len = len;
923                 *mp = m;
924                 top->m_pkthdr.len += len;
925                 if (error)
926                         goto out;
927                 mp = &m->m_next;
928                 if (resid <= 0) {
929                         if (flags & MSG_EOR)
930                                 top->m_flags |= M_EOR;
931                         break;
932                 }
933         } while (*space > 0 && atomic);
934 out:
935         *retmp = top;
936         return (error);
937 }
938 #endif /*ZERO_COPY_SOCKETS*/
939
940 #define SBLOCKWAIT(f)   (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
941
942 int
943 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
944     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
945 {
946         long space, resid;
947         int clen = 0, error, dontroute;
948 #ifdef ZERO_COPY_SOCKETS
949         int atomic = sosendallatonce(so) || top;
950 #endif
951
952         KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
953         KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
954             ("sodgram_send: !PR_ATOMIC"));
955
956         if (uio != NULL)
957                 resid = uio->uio_resid;
958         else
959                 resid = top->m_pkthdr.len;
960         /*
961          * In theory resid should be unsigned.  However, space must be
962          * signed, as it might be less than 0 if we over-committed, and we
963          * must use a signed comparison of space and resid.  On the other
964          * hand, a negative resid causes us to loop sending 0-length
965          * segments to the protocol.
966          *
967          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
968          * type sockets since that's an error.
969          */
970         if (resid < 0) {
971                 error = EINVAL;
972                 goto out;
973         }
974
975         dontroute =
976             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
977         if (td != NULL)
978                 td->td_ru.ru_msgsnd++;
979         if (control != NULL)
980                 clen = control->m_len;
981
982         SOCKBUF_LOCK(&so->so_snd);
983         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
984                 SOCKBUF_UNLOCK(&so->so_snd);
985                 error = EPIPE;
986                 goto out;
987         }
988         if (so->so_error) {
989                 error = so->so_error;
990                 so->so_error = 0;
991                 SOCKBUF_UNLOCK(&so->so_snd);
992                 goto out;
993         }
994         if ((so->so_state & SS_ISCONNECTED) == 0) {
995                 /*
996                  * `sendto' and `sendmsg' is allowed on a connection-based
997                  * socket if it supports implied connect.  Return ENOTCONN if
998                  * not connected and no address is supplied.
999                  */
1000                 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1001                     (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1002                         if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1003                             !(resid == 0 && clen != 0)) {
1004                                 SOCKBUF_UNLOCK(&so->so_snd);
1005                                 error = ENOTCONN;
1006                                 goto out;
1007                         }
1008                 } else if (addr == NULL) {
1009                         if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1010                                 error = ENOTCONN;
1011                         else
1012                                 error = EDESTADDRREQ;
1013                         SOCKBUF_UNLOCK(&so->so_snd);
1014                         goto out;
1015                 }
1016         }
1017
1018         /*
1019          * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
1020          * problem and need fixing.
1021          */
1022         space = sbspace(&so->so_snd);
1023         if (flags & MSG_OOB)
1024                 space += 1024;
1025         space -= clen;
1026         SOCKBUF_UNLOCK(&so->so_snd);
1027         if (resid > space) {
1028                 error = EMSGSIZE;
1029                 goto out;
1030         }
1031         if (uio == NULL) {
1032                 resid = 0;
1033                 if (flags & MSG_EOR)
1034                         top->m_flags |= M_EOR;
1035         } else {
1036 #ifdef ZERO_COPY_SOCKETS
1037                 error = sosend_copyin(uio, &top, atomic, &space, flags);
1038                 if (error)
1039                         goto out;
1040 #else
1041                 /*
1042                  * Copy the data from userland into a mbuf chain.
1043                  * If no data is to be copied in, a single empty mbuf
1044                  * is returned.
1045                  */
1046                 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1047                     (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1048                 if (top == NULL) {
1049                         error = EFAULT; /* only possible error */
1050                         goto out;
1051                 }
1052                 space -= resid - uio->uio_resid;
1053 #endif
1054                 resid = uio->uio_resid;
1055         }
1056         KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1057         /*
1058          * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1059          * than with.
1060          */
1061         if (dontroute) {
1062                 SOCK_LOCK(so);
1063                 so->so_options |= SO_DONTROUTE;
1064                 SOCK_UNLOCK(so);
1065         }
1066         /*
1067          * XXX all the SBS_CANTSENDMORE checks previously done could be out
1068          * of date.  We could have recieved a reset packet in an interrupt or
1069          * maybe we slept while doing page faults in uiomove() etc.  We could
1070          * probably recheck again inside the locking protection here, but
1071          * there are probably other places that this also happens.  We must
1072          * rethink this.
1073          */
1074         error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1075             (flags & MSG_OOB) ? PRUS_OOB :
1076         /*
1077          * If the user set MSG_EOF, the protocol understands this flag and
1078          * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1079          */
1080             ((flags & MSG_EOF) &&
1081              (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1082              (resid <= 0)) ?
1083                 PRUS_EOF :
1084                 /* If there is more to send set PRUS_MORETOCOME */
1085                 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1086                 top, addr, control, td);
1087         if (dontroute) {
1088                 SOCK_LOCK(so);
1089                 so->so_options &= ~SO_DONTROUTE;
1090                 SOCK_UNLOCK(so);
1091         }
1092         clen = 0;
1093         control = NULL;
1094         top = NULL;
1095 out:
1096         if (top != NULL)
1097                 m_freem(top);
1098         if (control != NULL)
1099                 m_freem(control);
1100         return (error);
1101 }
1102
1103 /*
1104  * Send on a socket.  If send must go all at once and message is larger than
1105  * send buffering, then hard error.  Lock against other senders.  If must go
1106  * all at once and not enough room now, then inform user that this would
1107  * block and do nothing.  Otherwise, if nonblocking, send as much as
1108  * possible.  The data to be sent is described by "uio" if nonzero, otherwise
1109  * by the mbuf chain "top" (which must be null if uio is not).  Data provided
1110  * in mbuf chain must be small enough to send all at once.
1111  *
1112  * Returns nonzero on error, timeout or signal; callers must check for short
1113  * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
1114  * on return.
1115  */
1116 int
1117 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1118     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1119 {
1120         long space, resid;
1121         int clen = 0, error, dontroute;
1122         int atomic = sosendallatonce(so) || top;
1123
1124         if (uio != NULL)
1125                 resid = uio->uio_resid;
1126         else
1127                 resid = top->m_pkthdr.len;
1128         /*
1129          * In theory resid should be unsigned.  However, space must be
1130          * signed, as it might be less than 0 if we over-committed, and we
1131          * must use a signed comparison of space and resid.  On the other
1132          * hand, a negative resid causes us to loop sending 0-length
1133          * segments to the protocol.
1134          *
1135          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1136          * type sockets since that's an error.
1137          */
1138         if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1139                 error = EINVAL;
1140                 goto out;
1141         }
1142
1143         dontroute =
1144             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1145             (so->so_proto->pr_flags & PR_ATOMIC);
1146         if (td != NULL)
1147                 td->td_ru.ru_msgsnd++;
1148         if (control != NULL)
1149                 clen = control->m_len;
1150
1151         error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1152         if (error)
1153                 goto out;
1154
1155 restart:
1156         do {
1157                 SOCKBUF_LOCK(&so->so_snd);
1158                 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1159                         SOCKBUF_UNLOCK(&so->so_snd);
1160                         error = EPIPE;
1161                         goto release;
1162                 }
1163                 if (so->so_error) {
1164                         error = so->so_error;
1165                         so->so_error = 0;
1166                         SOCKBUF_UNLOCK(&so->so_snd);
1167                         goto release;
1168                 }
1169                 if ((so->so_state & SS_ISCONNECTED) == 0) {
1170                         /*
1171                          * `sendto' and `sendmsg' is allowed on a connection-
1172                          * based socket if it supports implied connect.
1173                          * Return ENOTCONN if not connected and no address is
1174                          * supplied.
1175                          */
1176                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1177                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1178                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1179                                     !(resid == 0 && clen != 0)) {
1180                                         SOCKBUF_UNLOCK(&so->so_snd);
1181                                         error = ENOTCONN;
1182                                         goto release;
1183                                 }
1184                         } else if (addr == NULL) {
1185                                 SOCKBUF_UNLOCK(&so->so_snd);
1186                                 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1187                                         error = ENOTCONN;
1188                                 else
1189                                         error = EDESTADDRREQ;
1190                                 goto release;
1191                         }
1192                 }
1193                 space = sbspace(&so->so_snd);
1194                 if (flags & MSG_OOB)
1195                         space += 1024;
1196                 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1197                     clen > so->so_snd.sb_hiwat) {
1198                         SOCKBUF_UNLOCK(&so->so_snd);
1199                         error = EMSGSIZE;
1200                         goto release;
1201                 }
1202                 if (space < resid + clen &&
1203                     (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1204                         if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1205                                 SOCKBUF_UNLOCK(&so->so_snd);
1206                                 error = EWOULDBLOCK;
1207                                 goto release;
1208                         }
1209                         error = sbwait(&so->so_snd);
1210                         SOCKBUF_UNLOCK(&so->so_snd);
1211                         if (error)
1212                                 goto release;
1213                         goto restart;
1214                 }
1215                 SOCKBUF_UNLOCK(&so->so_snd);
1216                 space -= clen;
1217                 do {
1218                         if (uio == NULL) {
1219                                 resid = 0;
1220                                 if (flags & MSG_EOR)
1221                                         top->m_flags |= M_EOR;
1222                         } else {
1223 #ifdef ZERO_COPY_SOCKETS
1224                                 error = sosend_copyin(uio, &top, atomic,
1225                                     &space, flags);
1226                                 if (error != 0)
1227                                         goto release;
1228 #else
1229                                 /*
1230                                  * Copy the data from userland into a mbuf
1231                                  * chain.  If no data is to be copied in,
1232                                  * a single empty mbuf is returned.
1233                                  */
1234                                 top = m_uiotombuf(uio, M_WAITOK, space,
1235                                     (atomic ? max_hdr : 0),
1236                                     (atomic ? M_PKTHDR : 0) |
1237                                     ((flags & MSG_EOR) ? M_EOR : 0));
1238                                 if (top == NULL) {
1239                                         error = EFAULT; /* only possible error */
1240                                         goto release;
1241                                 }
1242                                 space -= resid - uio->uio_resid;
1243 #endif
1244                                 resid = uio->uio_resid;
1245                         }
1246                         if (dontroute) {
1247                                 SOCK_LOCK(so);
1248                                 so->so_options |= SO_DONTROUTE;
1249                                 SOCK_UNLOCK(so);
1250                         }
1251                         /*
1252                          * XXX all the SBS_CANTSENDMORE checks previously
1253                          * done could be out of date.  We could have recieved
1254                          * a reset packet in an interrupt or maybe we slept
1255                          * while doing page faults in uiomove() etc.  We
1256                          * could probably recheck again inside the locking
1257                          * protection here, but there are probably other
1258                          * places that this also happens.  We must rethink
1259                          * this.
1260                          */
1261                         error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1262                             (flags & MSG_OOB) ? PRUS_OOB :
1263                         /*
1264                          * If the user set MSG_EOF, the protocol understands
1265                          * this flag and nothing left to send then use
1266                          * PRU_SEND_EOF instead of PRU_SEND.
1267                          */
1268                             ((flags & MSG_EOF) &&
1269                              (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1270                              (resid <= 0)) ?
1271                                 PRUS_EOF :
1272                         /* If there is more to send set PRUS_MORETOCOME. */
1273                             (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1274                             top, addr, control, td);
1275                         if (dontroute) {
1276                                 SOCK_LOCK(so);
1277                                 so->so_options &= ~SO_DONTROUTE;
1278                                 SOCK_UNLOCK(so);
1279                         }
1280                         clen = 0;
1281                         control = NULL;
1282                         top = NULL;
1283                         if (error)
1284                                 goto release;
1285                 } while (resid && space > 0);
1286         } while (resid);
1287
1288 release:
1289         sbunlock(&so->so_snd);
1290 out:
1291         if (top != NULL)
1292                 m_freem(top);
1293         if (control != NULL)
1294                 m_freem(control);
1295         return (error);
1296 }
1297
1298 int
1299 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1300     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1301 {
1302         int error;
1303
1304         CURVNET_SET(so->so_vnet);
1305         error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1306             control, flags, td);
1307         CURVNET_RESTORE();
1308         return (error);
1309 }
1310
1311 /*
1312  * The part of soreceive() that implements reading non-inline out-of-band
1313  * data from a socket.  For more complete comments, see soreceive(), from
1314  * which this code originated.
1315  *
1316  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1317  * unable to return an mbuf chain to the caller.
1318  */
1319 static int
1320 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1321 {
1322         struct protosw *pr = so->so_proto;
1323         struct mbuf *m;
1324         int error;
1325
1326         KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1327
1328         m = m_get(M_WAIT, MT_DATA);
1329         error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1330         if (error)
1331                 goto bad;
1332         do {
1333 #ifdef ZERO_COPY_SOCKETS
1334                 if (so_zero_copy_receive) {
1335                         int disposable;
1336
1337                         if ((m->m_flags & M_EXT)
1338                          && (m->m_ext.ext_type == EXT_DISPOSABLE))
1339                                 disposable = 1;
1340                         else
1341                                 disposable = 0;
1342
1343                         error = uiomoveco(mtod(m, void *),
1344                                           min(uio->uio_resid, m->m_len),
1345                                           uio, disposable);
1346                 } else
1347 #endif /* ZERO_COPY_SOCKETS */
1348                 error = uiomove(mtod(m, void *),
1349                     (int) min(uio->uio_resid, m->m_len), uio);
1350                 m = m_free(m);
1351         } while (uio->uio_resid && error == 0 && m);
1352 bad:
1353         if (m != NULL)
1354                 m_freem(m);
1355         return (error);
1356 }
1357
1358 /*
1359  * Following replacement or removal of the first mbuf on the first mbuf chain
1360  * of a socket buffer, push necessary state changes back into the socket
1361  * buffer so that other consumers see the values consistently.  'nextrecord'
1362  * is the callers locally stored value of the original value of
1363  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1364  * NOTE: 'nextrecord' may be NULL.
1365  */
1366 static __inline void
1367 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1368 {
1369
1370         SOCKBUF_LOCK_ASSERT(sb);
1371         /*
1372          * First, update for the new value of nextrecord.  If necessary, make
1373          * it the first record.
1374          */
1375         if (sb->sb_mb != NULL)
1376                 sb->sb_mb->m_nextpkt = nextrecord;
1377         else
1378                 sb->sb_mb = nextrecord;
1379
1380         /*
1381          * Now update any dependent socket buffer fields to reflect the new
1382          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
1383          * addition of a second clause that takes care of the case where
1384          * sb_mb has been updated, but remains the last record.
1385          */
1386         if (sb->sb_mb == NULL) {
1387                 sb->sb_mbtail = NULL;
1388                 sb->sb_lastrecord = NULL;
1389         } else if (sb->sb_mb->m_nextpkt == NULL)
1390                 sb->sb_lastrecord = sb->sb_mb;
1391 }
1392
1393
1394 /*
1395  * Implement receive operations on a socket.  We depend on the way that
1396  * records are added to the sockbuf by sbappend.  In particular, each record
1397  * (mbufs linked through m_next) must begin with an address if the protocol
1398  * so specifies, followed by an optional mbuf or mbufs containing ancillary
1399  * data, and then zero or more mbufs of data.  In order to allow parallelism
1400  * between network receive and copying to user space, as well as avoid
1401  * sleeping with a mutex held, we release the socket buffer mutex during the
1402  * user space copy.  Although the sockbuf is locked, new data may still be
1403  * appended, and thus we must maintain consistency of the sockbuf during that
1404  * time.
1405  *
1406  * The caller may receive the data as a single mbuf chain by supplying an
1407  * mbuf **mp0 for use in returning the chain.  The uio is then used only for
1408  * the count in uio_resid.
1409  */
1410 int
1411 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1412     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1413 {
1414         struct mbuf *m, **mp;
1415         int flags, len, error, offset;
1416         struct protosw *pr = so->so_proto;
1417         struct mbuf *nextrecord;
1418         int moff, type = 0;
1419         int orig_resid = uio->uio_resid;
1420
1421         mp = mp0;
1422         if (psa != NULL)
1423                 *psa = NULL;
1424         if (controlp != NULL)
1425                 *controlp = NULL;
1426         if (flagsp != NULL)
1427                 flags = *flagsp &~ MSG_EOR;
1428         else
1429                 flags = 0;
1430         if (flags & MSG_OOB)
1431                 return (soreceive_rcvoob(so, uio, flags));
1432         if (mp != NULL)
1433                 *mp = NULL;
1434         if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1435             && uio->uio_resid)
1436                 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1437
1438         error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1439         if (error)
1440                 return (error);
1441
1442 restart:
1443         SOCKBUF_LOCK(&so->so_rcv);
1444         m = so->so_rcv.sb_mb;
1445         /*
1446          * If we have less data than requested, block awaiting more (subject
1447          * to any timeout) if:
1448          *   1. the current count is less than the low water mark, or
1449          *   2. MSG_WAITALL is set, and it is possible to do the entire
1450          *      receive operation at once if we block (resid <= hiwat).
1451          *   3. MSG_DONTWAIT is not set
1452          * If MSG_WAITALL is set but resid is larger than the receive buffer,
1453          * we have to do the receive in sections, and thus risk returning a
1454          * short count if a timeout or signal occurs after we start.
1455          */
1456         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1457             so->so_rcv.sb_cc < uio->uio_resid) &&
1458             (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1459             ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1460             m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1461                 KASSERT(m != NULL || !so->so_rcv.sb_cc,
1462                     ("receive: m == %p so->so_rcv.sb_cc == %u",
1463                     m, so->so_rcv.sb_cc));
1464                 if (so->so_error) {
1465                         if (m != NULL)
1466                                 goto dontblock;
1467                         error = so->so_error;
1468                         if ((flags & MSG_PEEK) == 0)
1469                                 so->so_error = 0;
1470                         SOCKBUF_UNLOCK(&so->so_rcv);
1471                         goto release;
1472                 }
1473                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1474                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1475                         if (m == NULL) {
1476                                 SOCKBUF_UNLOCK(&so->so_rcv);
1477                                 goto release;
1478                         } else
1479                                 goto dontblock;
1480                 }
1481                 for (; m != NULL; m = m->m_next)
1482                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1483                                 m = so->so_rcv.sb_mb;
1484                                 goto dontblock;
1485                         }
1486                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1487                     (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1488                         SOCKBUF_UNLOCK(&so->so_rcv);
1489                         error = ENOTCONN;
1490                         goto release;
1491                 }
1492                 if (uio->uio_resid == 0) {
1493                         SOCKBUF_UNLOCK(&so->so_rcv);
1494                         goto release;
1495                 }
1496                 if ((so->so_state & SS_NBIO) ||
1497                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1498                         SOCKBUF_UNLOCK(&so->so_rcv);
1499                         error = EWOULDBLOCK;
1500                         goto release;
1501                 }
1502                 SBLASTRECORDCHK(&so->so_rcv);
1503                 SBLASTMBUFCHK(&so->so_rcv);
1504                 error = sbwait(&so->so_rcv);
1505                 SOCKBUF_UNLOCK(&so->so_rcv);
1506                 if (error)
1507                         goto release;
1508                 goto restart;
1509         }
1510 dontblock:
1511         /*
1512          * From this point onward, we maintain 'nextrecord' as a cache of the
1513          * pointer to the next record in the socket buffer.  We must keep the
1514          * various socket buffer pointers and local stack versions of the
1515          * pointers in sync, pushing out modifications before dropping the
1516          * socket buffer mutex, and re-reading them when picking it up.
1517          *
1518          * Otherwise, we will race with the network stack appending new data
1519          * or records onto the socket buffer by using inconsistent/stale
1520          * versions of the field, possibly resulting in socket buffer
1521          * corruption.
1522          *
1523          * By holding the high-level sblock(), we prevent simultaneous
1524          * readers from pulling off the front of the socket buffer.
1525          */
1526         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1527         if (uio->uio_td)
1528                 uio->uio_td->td_ru.ru_msgrcv++;
1529         KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1530         SBLASTRECORDCHK(&so->so_rcv);
1531         SBLASTMBUFCHK(&so->so_rcv);
1532         nextrecord = m->m_nextpkt;
1533         if (pr->pr_flags & PR_ADDR) {
1534                 KASSERT(m->m_type == MT_SONAME,
1535                     ("m->m_type == %d", m->m_type));
1536                 orig_resid = 0;
1537                 if (psa != NULL)
1538                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1539                             M_NOWAIT);
1540                 if (flags & MSG_PEEK) {
1541                         m = m->m_next;
1542                 } else {
1543                         sbfree(&so->so_rcv, m);
1544                         so->so_rcv.sb_mb = m_free(m);
1545                         m = so->so_rcv.sb_mb;
1546                         sockbuf_pushsync(&so->so_rcv, nextrecord);
1547                 }
1548         }
1549
1550         /*
1551          * Process one or more MT_CONTROL mbufs present before any data mbufs
1552          * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1553          * just copy the data; if !MSG_PEEK, we call into the protocol to
1554          * perform externalization (or freeing if controlp == NULL).
1555          */
1556         if (m != NULL && m->m_type == MT_CONTROL) {
1557                 struct mbuf *cm = NULL, *cmn;
1558                 struct mbuf **cme = &cm;
1559
1560                 do {
1561                         if (flags & MSG_PEEK) {
1562                                 if (controlp != NULL) {
1563                                         *controlp = m_copy(m, 0, m->m_len);
1564                                         controlp = &(*controlp)->m_next;
1565                                 }
1566                                 m = m->m_next;
1567                         } else {
1568                                 sbfree(&so->so_rcv, m);
1569                                 so->so_rcv.sb_mb = m->m_next;
1570                                 m->m_next = NULL;
1571                                 *cme = m;
1572                                 cme = &(*cme)->m_next;
1573                                 m = so->so_rcv.sb_mb;
1574                         }
1575                 } while (m != NULL && m->m_type == MT_CONTROL);
1576                 if ((flags & MSG_PEEK) == 0)
1577                         sockbuf_pushsync(&so->so_rcv, nextrecord);
1578                 while (cm != NULL) {
1579                         cmn = cm->m_next;
1580                         cm->m_next = NULL;
1581                         if (pr->pr_domain->dom_externalize != NULL) {
1582                                 SOCKBUF_UNLOCK(&so->so_rcv);
1583                                 error = (*pr->pr_domain->dom_externalize)
1584                                     (cm, controlp);
1585                                 SOCKBUF_LOCK(&so->so_rcv);
1586                         } else if (controlp != NULL)
1587                                 *controlp = cm;
1588                         else
1589                                 m_freem(cm);
1590                         if (controlp != NULL) {
1591                                 orig_resid = 0;
1592                                 while (*controlp != NULL)
1593                                         controlp = &(*controlp)->m_next;
1594                         }
1595                         cm = cmn;
1596                 }
1597                 if (m != NULL)
1598                         nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1599                 else
1600                         nextrecord = so->so_rcv.sb_mb;
1601                 orig_resid = 0;
1602         }
1603         if (m != NULL) {
1604                 if ((flags & MSG_PEEK) == 0) {
1605                         KASSERT(m->m_nextpkt == nextrecord,
1606                             ("soreceive: post-control, nextrecord !sync"));
1607                         if (nextrecord == NULL) {
1608                                 KASSERT(so->so_rcv.sb_mb == m,
1609                                     ("soreceive: post-control, sb_mb!=m"));
1610                                 KASSERT(so->so_rcv.sb_lastrecord == m,
1611                                     ("soreceive: post-control, lastrecord!=m"));
1612                         }
1613                 }
1614                 type = m->m_type;
1615                 if (type == MT_OOBDATA)
1616                         flags |= MSG_OOB;
1617         } else {
1618                 if ((flags & MSG_PEEK) == 0) {
1619                         KASSERT(so->so_rcv.sb_mb == nextrecord,
1620                             ("soreceive: sb_mb != nextrecord"));
1621                         if (so->so_rcv.sb_mb == NULL) {
1622                                 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1623                                     ("soreceive: sb_lastercord != NULL"));
1624                         }
1625                 }
1626         }
1627         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1628         SBLASTRECORDCHK(&so->so_rcv);
1629         SBLASTMBUFCHK(&so->so_rcv);
1630
1631         /*
1632          * Now continue to read any data mbufs off of the head of the socket
1633          * buffer until the read request is satisfied.  Note that 'type' is
1634          * used to store the type of any mbuf reads that have happened so far
1635          * such that soreceive() can stop reading if the type changes, which
1636          * causes soreceive() to return only one of regular data and inline
1637          * out-of-band data in a single socket receive operation.
1638          */
1639         moff = 0;
1640         offset = 0;
1641         while (m != NULL && uio->uio_resid > 0 && error == 0) {
1642                 /*
1643                  * If the type of mbuf has changed since the last mbuf
1644                  * examined ('type'), end the receive operation.
1645                  */
1646                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1647                 if (m->m_type == MT_OOBDATA) {
1648                         if (type != MT_OOBDATA)
1649                                 break;
1650                 } else if (type == MT_OOBDATA)
1651                         break;
1652                 else
1653                     KASSERT(m->m_type == MT_DATA,
1654                         ("m->m_type == %d", m->m_type));
1655                 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1656                 len = uio->uio_resid;
1657                 if (so->so_oobmark && len > so->so_oobmark - offset)
1658                         len = so->so_oobmark - offset;
1659                 if (len > m->m_len - moff)
1660                         len = m->m_len - moff;
1661                 /*
1662                  * If mp is set, just pass back the mbufs.  Otherwise copy
1663                  * them out via the uio, then free.  Sockbuf must be
1664                  * consistent here (points to current mbuf, it points to next
1665                  * record) when we drop priority; we must note any additions
1666                  * to the sockbuf when we block interrupts again.
1667                  */
1668                 if (mp == NULL) {
1669                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1670                         SBLASTRECORDCHK(&so->so_rcv);
1671                         SBLASTMBUFCHK(&so->so_rcv);
1672                         SOCKBUF_UNLOCK(&so->so_rcv);
1673 #ifdef ZERO_COPY_SOCKETS
1674                         if (so_zero_copy_receive) {
1675                                 int disposable;
1676
1677                                 if ((m->m_flags & M_EXT)
1678                                  && (m->m_ext.ext_type == EXT_DISPOSABLE))
1679                                         disposable = 1;
1680                                 else
1681                                         disposable = 0;
1682
1683                                 error = uiomoveco(mtod(m, char *) + moff,
1684                                                   (int)len, uio,
1685                                                   disposable);
1686                         } else
1687 #endif /* ZERO_COPY_SOCKETS */
1688                         error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1689                         SOCKBUF_LOCK(&so->so_rcv);
1690                         if (error) {
1691                                 /*
1692                                  * The MT_SONAME mbuf has already been removed
1693                                  * from the record, so it is necessary to
1694                                  * remove the data mbufs, if any, to preserve
1695                                  * the invariant in the case of PR_ADDR that
1696                                  * requires MT_SONAME mbufs at the head of
1697                                  * each record.
1698                                  */
1699                                 if (m && pr->pr_flags & PR_ATOMIC &&
1700                                     ((flags & MSG_PEEK) == 0))
1701                                         (void)sbdroprecord_locked(&so->so_rcv);
1702                                 SOCKBUF_UNLOCK(&so->so_rcv);
1703                                 goto release;
1704                         }
1705                 } else
1706                         uio->uio_resid -= len;
1707                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1708                 if (len == m->m_len - moff) {
1709                         if (m->m_flags & M_EOR)
1710                                 flags |= MSG_EOR;
1711                         if (flags & MSG_PEEK) {
1712                                 m = m->m_next;
1713                                 moff = 0;
1714                         } else {
1715                                 nextrecord = m->m_nextpkt;
1716                                 sbfree(&so->so_rcv, m);
1717                                 if (mp != NULL) {
1718                                         *mp = m;
1719                                         mp = &m->m_next;
1720                                         so->so_rcv.sb_mb = m = m->m_next;
1721                                         *mp = NULL;
1722                                 } else {
1723                                         so->so_rcv.sb_mb = m_free(m);
1724                                         m = so->so_rcv.sb_mb;
1725                                 }
1726                                 sockbuf_pushsync(&so->so_rcv, nextrecord);
1727                                 SBLASTRECORDCHK(&so->so_rcv);
1728                                 SBLASTMBUFCHK(&so->so_rcv);
1729                         }
1730                 } else {
1731                         if (flags & MSG_PEEK)
1732                                 moff += len;
1733                         else {
1734                                 if (mp != NULL) {
1735                                         int copy_flag;
1736
1737                                         if (flags & MSG_DONTWAIT)
1738                                                 copy_flag = M_DONTWAIT;
1739                                         else
1740                                                 copy_flag = M_WAIT;
1741                                         if (copy_flag == M_WAIT)
1742                                                 SOCKBUF_UNLOCK(&so->so_rcv);
1743                                         *mp = m_copym(m, 0, len, copy_flag);
1744                                         if (copy_flag == M_WAIT)
1745                                                 SOCKBUF_LOCK(&so->so_rcv);
1746                                         if (*mp == NULL) {
1747                                                 /*
1748                                                  * m_copym() couldn't
1749                                                  * allocate an mbuf.  Adjust
1750                                                  * uio_resid back (it was
1751                                                  * adjusted down by len
1752                                                  * bytes, which we didn't end
1753                                                  * up "copying" over).
1754                                                  */
1755                                                 uio->uio_resid += len;
1756                                                 break;
1757                                         }
1758                                 }
1759                                 m->m_data += len;
1760                                 m->m_len -= len;
1761                                 so->so_rcv.sb_cc -= len;
1762                         }
1763                 }
1764                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1765                 if (so->so_oobmark) {
1766                         if ((flags & MSG_PEEK) == 0) {
1767                                 so->so_oobmark -= len;
1768                                 if (so->so_oobmark == 0) {
1769                                         so->so_rcv.sb_state |= SBS_RCVATMARK;
1770                                         break;
1771                                 }
1772                         } else {
1773                                 offset += len;
1774                                 if (offset == so->so_oobmark)
1775                                         break;
1776                         }
1777                 }
1778                 if (flags & MSG_EOR)
1779                         break;
1780                 /*
1781                  * If the MSG_WAITALL flag is set (for non-atomic socket), we
1782                  * must not quit until "uio->uio_resid == 0" or an error
1783                  * termination.  If a signal/timeout occurs, return with a
1784                  * short count but without error.  Keep sockbuf locked
1785                  * against other readers.
1786                  */
1787                 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1788                     !sosendallatonce(so) && nextrecord == NULL) {
1789                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1790                         if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1791                                 break;
1792                         /*
1793                          * Notify the protocol that some data has been
1794                          * drained before blocking.
1795                          */
1796                         if (pr->pr_flags & PR_WANTRCVD) {
1797                                 SOCKBUF_UNLOCK(&so->so_rcv);
1798                                 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1799                                 SOCKBUF_LOCK(&so->so_rcv);
1800                         }
1801                         SBLASTRECORDCHK(&so->so_rcv);
1802                         SBLASTMBUFCHK(&so->so_rcv);
1803                         error = sbwait(&so->so_rcv);
1804                         if (error) {
1805                                 SOCKBUF_UNLOCK(&so->so_rcv);
1806                                 goto release;
1807                         }
1808                         m = so->so_rcv.sb_mb;
1809                         if (m != NULL)
1810                                 nextrecord = m->m_nextpkt;
1811                 }
1812         }
1813
1814         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1815         if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1816                 flags |= MSG_TRUNC;
1817                 if ((flags & MSG_PEEK) == 0)
1818                         (void) sbdroprecord_locked(&so->so_rcv);
1819         }
1820         if ((flags & MSG_PEEK) == 0) {
1821                 if (m == NULL) {
1822                         /*
1823                          * First part is an inline SB_EMPTY_FIXUP().  Second
1824                          * part makes sure sb_lastrecord is up-to-date if
1825                          * there is still data in the socket buffer.
1826                          */
1827                         so->so_rcv.sb_mb = nextrecord;
1828                         if (so->so_rcv.sb_mb == NULL) {
1829                                 so->so_rcv.sb_mbtail = NULL;
1830                                 so->so_rcv.sb_lastrecord = NULL;
1831                         } else if (nextrecord->m_nextpkt == NULL)
1832                                 so->so_rcv.sb_lastrecord = nextrecord;
1833                 }
1834                 SBLASTRECORDCHK(&so->so_rcv);
1835                 SBLASTMBUFCHK(&so->so_rcv);
1836                 /*
1837                  * If soreceive() is being done from the socket callback,
1838                  * then don't need to generate ACK to peer to update window,
1839                  * since ACK will be generated on return to TCP.
1840                  */
1841                 if (!(flags & MSG_SOCALLBCK) &&
1842                     (pr->pr_flags & PR_WANTRCVD)) {
1843                         SOCKBUF_UNLOCK(&so->so_rcv);
1844                         (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1845                         SOCKBUF_LOCK(&so->so_rcv);
1846                 }
1847         }
1848         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1849         if (orig_resid == uio->uio_resid && orig_resid &&
1850             (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1851                 SOCKBUF_UNLOCK(&so->so_rcv);
1852                 goto restart;
1853         }
1854         SOCKBUF_UNLOCK(&so->so_rcv);
1855
1856         if (flagsp != NULL)
1857                 *flagsp |= flags;
1858 release:
1859         sbunlock(&so->so_rcv);
1860         return (error);
1861 }
1862
1863 /*
1864  * Optimized version of soreceive() for simple datagram cases from userspace.
1865  * Unlike in the stream case, we're able to drop a datagram if copyout()
1866  * fails, and because we handle datagrams atomically, we don't need to use a
1867  * sleep lock to prevent I/O interlacing.
1868  */
1869 int
1870 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1871     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1872 {
1873         struct mbuf *m, *m2;
1874         int flags, len, error;
1875         struct protosw *pr = so->so_proto;
1876         struct mbuf *nextrecord;
1877
1878         if (psa != NULL)
1879                 *psa = NULL;
1880         if (controlp != NULL)
1881                 *controlp = NULL;
1882         if (flagsp != NULL)
1883                 flags = *flagsp &~ MSG_EOR;
1884         else
1885                 flags = 0;
1886
1887         /*
1888          * For any complicated cases, fall back to the full
1889          * soreceive_generic().
1890          */
1891         if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
1892                 return (soreceive_generic(so, psa, uio, mp0, controlp,
1893                     flagsp));
1894
1895         /*
1896          * Enforce restrictions on use.
1897          */
1898         KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
1899             ("soreceive_dgram: wantrcvd"));
1900         KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
1901         KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
1902             ("soreceive_dgram: SBS_RCVATMARK"));
1903         KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
1904             ("soreceive_dgram: P_CONNREQUIRED"));
1905
1906         /*
1907          * Loop blocking while waiting for a datagram.
1908          */
1909         SOCKBUF_LOCK(&so->so_rcv);
1910         while ((m = so->so_rcv.sb_mb) == NULL) {
1911                 KASSERT(so->so_rcv.sb_cc == 0,
1912                     ("soreceive_dgram: sb_mb NULL but sb_cc %u",
1913                     so->so_rcv.sb_cc));
1914                 if (so->so_error) {
1915                         error = so->so_error;
1916                         so->so_error = 0;
1917                         SOCKBUF_UNLOCK(&so->so_rcv);
1918                         return (error);
1919                 }
1920                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1921                     uio->uio_resid == 0) {
1922                         SOCKBUF_UNLOCK(&so->so_rcv);
1923                         return (0);
1924                 }
1925                 if ((so->so_state & SS_NBIO) ||
1926                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1927                         SOCKBUF_UNLOCK(&so->so_rcv);
1928                         return (EWOULDBLOCK);
1929                 }
1930                 SBLASTRECORDCHK(&so->so_rcv);
1931                 SBLASTMBUFCHK(&so->so_rcv);
1932                 error = sbwait(&so->so_rcv);
1933                 if (error) {
1934                         SOCKBUF_UNLOCK(&so->so_rcv);
1935                         return (error);
1936                 }
1937         }
1938         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1939
1940         if (uio->uio_td)
1941                 uio->uio_td->td_ru.ru_msgrcv++;
1942         SBLASTRECORDCHK(&so->so_rcv);
1943         SBLASTMBUFCHK(&so->so_rcv);
1944         nextrecord = m->m_nextpkt;
1945         if (nextrecord == NULL) {
1946                 KASSERT(so->so_rcv.sb_lastrecord == m,
1947                     ("soreceive_dgram: lastrecord != m"));
1948         }
1949
1950         KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
1951             ("soreceive_dgram: m_nextpkt != nextrecord"));
1952
1953         /*
1954          * Pull 'm' and its chain off the front of the packet queue.
1955          */
1956         so->so_rcv.sb_mb = NULL;
1957         sockbuf_pushsync(&so->so_rcv, nextrecord);
1958
1959         /*
1960          * Walk 'm's chain and free that many bytes from the socket buffer.
1961          */
1962         for (m2 = m; m2 != NULL; m2 = m2->m_next)
1963                 sbfree(&so->so_rcv, m2);
1964
1965         /*
1966          * Do a few last checks before we let go of the lock.
1967          */
1968         SBLASTRECORDCHK(&so->so_rcv);
1969         SBLASTMBUFCHK(&so->so_rcv);
1970         SOCKBUF_UNLOCK(&so->so_rcv);
1971
1972         if (pr->pr_flags & PR_ADDR) {
1973                 KASSERT(m->m_type == MT_SONAME,
1974                     ("m->m_type == %d", m->m_type));
1975                 if (psa != NULL)
1976                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1977                             M_NOWAIT);
1978                 m = m_free(m);
1979         }
1980         if (m == NULL) {
1981                 /* XXXRW: Can this happen? */
1982                 return (0);
1983         }
1984
1985         /*
1986          * Packet to copyout() is now in 'm' and it is disconnected from the
1987          * queue.
1988          *
1989          * Process one or more MT_CONTROL mbufs present before any data mbufs
1990          * in the first mbuf chain on the socket buffer.  We call into the
1991          * protocol to perform externalization (or freeing if controlp ==
1992          * NULL).
1993          */
1994         if (m->m_type == MT_CONTROL) {
1995                 struct mbuf *cm = NULL, *cmn;
1996                 struct mbuf **cme = &cm;
1997
1998                 do {
1999                         m2 = m->m_next;
2000                         m->m_next = NULL;
2001                         *cme = m;
2002                         cme = &(*cme)->m_next;
2003                         m = m2;
2004                 } while (m != NULL && m->m_type == MT_CONTROL);
2005                 while (cm != NULL) {
2006                         cmn = cm->m_next;
2007                         cm->m_next = NULL;
2008                         if (pr->pr_domain->dom_externalize != NULL) {
2009                                 error = (*pr->pr_domain->dom_externalize)
2010                                     (cm, controlp);
2011                         } else if (controlp != NULL)
2012                                 *controlp = cm;
2013                         else
2014                                 m_freem(cm);
2015                         if (controlp != NULL) {
2016                                 while (*controlp != NULL)
2017                                         controlp = &(*controlp)->m_next;
2018                         }
2019                         cm = cmn;
2020                 }
2021         }
2022         KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
2023
2024         while (m != NULL && uio->uio_resid > 0) {
2025                 len = uio->uio_resid;
2026                 if (len > m->m_len)
2027                         len = m->m_len;
2028                 error = uiomove(mtod(m, char *), (int)len, uio);
2029                 if (error) {
2030                         m_freem(m);
2031                         return (error);
2032                 }
2033                 m = m_free(m);
2034         }
2035         if (m != NULL)
2036                 flags |= MSG_TRUNC;
2037         m_freem(m);
2038         if (flagsp != NULL)
2039                 *flagsp |= flags;
2040         return (0);
2041 }
2042
2043 int
2044 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2045     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2046 {
2047
2048         return (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2049             controlp, flagsp));
2050 }
2051
2052 int
2053 soshutdown(struct socket *so, int how)
2054 {
2055         struct protosw *pr = so->so_proto;
2056         int error;
2057
2058         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2059                 return (EINVAL);
2060         if (pr->pr_usrreqs->pru_flush != NULL) {
2061                 (*pr->pr_usrreqs->pru_flush)(so, how);
2062         }
2063         if (how != SHUT_WR)
2064                 sorflush(so);
2065         if (how != SHUT_RD) {
2066                 CURVNET_SET(so->so_vnet);
2067                 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2068                 CURVNET_RESTORE();
2069                 return (error);
2070         }
2071         return (0);
2072 }
2073
2074 void
2075 sorflush(struct socket *so)
2076 {
2077         struct sockbuf *sb = &so->so_rcv;
2078         struct protosw *pr = so->so_proto;
2079         struct sockbuf asb;
2080
2081         /*
2082          * In order to avoid calling dom_dispose with the socket buffer mutex
2083          * held, and in order to generally avoid holding the lock for a long
2084          * time, we make a copy of the socket buffer and clear the original
2085          * (except locks, state).  The new socket buffer copy won't have
2086          * initialized locks so we can only call routines that won't use or
2087          * assert those locks.
2088          *
2089          * Dislodge threads currently blocked in receive and wait to acquire
2090          * a lock against other simultaneous readers before clearing the
2091          * socket buffer.  Don't let our acquire be interrupted by a signal
2092          * despite any existing socket disposition on interruptable waiting.
2093          */
2094         CURVNET_SET(so->so_vnet);
2095         socantrcvmore(so);
2096         (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2097
2098         /*
2099          * Invalidate/clear most of the sockbuf structure, but leave selinfo
2100          * and mutex data unchanged.
2101          */
2102         SOCKBUF_LOCK(sb);
2103         bzero(&asb, offsetof(struct sockbuf, sb_startzero));
2104         bcopy(&sb->sb_startzero, &asb.sb_startzero,
2105             sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2106         bzero(&sb->sb_startzero,
2107             sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2108         SOCKBUF_UNLOCK(sb);
2109         sbunlock(sb);
2110
2111         /*
2112          * Dispose of special rights and flush the socket buffer.  Don't call
2113          * any unsafe routines (that rely on locks being initialized) on asb.
2114          */
2115         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2116                 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
2117         sbrelease_internal(&asb, so);
2118         CURVNET_RESTORE();
2119 }
2120
2121 /*
2122  * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2123  * additional variant to handle the case where the option value needs to be
2124  * some kind of integer, but not a specific size.  In addition to their use
2125  * here, these functions are also called by the protocol-level pr_ctloutput()
2126  * routines.
2127  */
2128 int
2129 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2130 {
2131         size_t  valsize;
2132
2133         /*
2134          * If the user gives us more than we wanted, we ignore it, but if we
2135          * don't get the minimum length the caller wants, we return EINVAL.
2136          * On success, sopt->sopt_valsize is set to however much we actually
2137          * retrieved.
2138          */
2139         if ((valsize = sopt->sopt_valsize) < minlen)
2140                 return EINVAL;
2141         if (valsize > len)
2142                 sopt->sopt_valsize = valsize = len;
2143
2144         if (sopt->sopt_td != NULL)
2145                 return (copyin(sopt->sopt_val, buf, valsize));
2146
2147         bcopy(sopt->sopt_val, buf, valsize);
2148         return (0);
2149 }
2150
2151 /*
2152  * Kernel version of setsockopt(2).
2153  *
2154  * XXX: optlen is size_t, not socklen_t
2155  */
2156 int
2157 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2158     size_t optlen)
2159 {
2160         struct sockopt sopt;
2161
2162         sopt.sopt_level = level;
2163         sopt.sopt_name = optname;
2164         sopt.sopt_dir = SOPT_SET;
2165         sopt.sopt_val = optval;
2166         sopt.sopt_valsize = optlen;
2167         sopt.sopt_td = NULL;
2168         return (sosetopt(so, &sopt));
2169 }
2170
2171 int
2172 sosetopt(struct socket *so, struct sockopt *sopt)
2173 {
2174         int     error, optval;
2175         struct  linger l;
2176         struct  timeval tv;
2177         u_long  val;
2178 #ifdef MAC
2179         struct mac extmac;
2180 #endif
2181
2182         error = 0;
2183         if (sopt->sopt_level != SOL_SOCKET) {
2184                 if (so->so_proto && so->so_proto->pr_ctloutput)
2185                         return ((*so->so_proto->pr_ctloutput)
2186                                   (so, sopt));
2187                 error = ENOPROTOOPT;
2188         } else {
2189                 switch (sopt->sopt_name) {
2190 #ifdef INET
2191                 case SO_ACCEPTFILTER:
2192                         error = do_setopt_accept_filter(so, sopt);
2193                         if (error)
2194                                 goto bad;
2195                         break;
2196 #endif
2197                 case SO_LINGER:
2198                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2199                         if (error)
2200                                 goto bad;
2201
2202                         SOCK_LOCK(so);
2203                         so->so_linger = l.l_linger;
2204                         if (l.l_onoff)
2205                                 so->so_options |= SO_LINGER;
2206                         else
2207                                 so->so_options &= ~SO_LINGER;
2208                         SOCK_UNLOCK(so);
2209                         break;
2210
2211                 case SO_DEBUG:
2212                 case SO_KEEPALIVE:
2213                 case SO_DONTROUTE:
2214                 case SO_USELOOPBACK:
2215                 case SO_BROADCAST:
2216                 case SO_REUSEADDR:
2217                 case SO_REUSEPORT:
2218                 case SO_OOBINLINE:
2219                 case SO_TIMESTAMP:
2220                 case SO_BINTIME:
2221                 case SO_NOSIGPIPE:
2222                 case SO_NO_DDP:
2223                 case SO_NO_OFFLOAD:
2224                         error = sooptcopyin(sopt, &optval, sizeof optval,
2225                                             sizeof optval);
2226                         if (error)
2227                                 goto bad;
2228                         SOCK_LOCK(so);
2229                         if (optval)
2230                                 so->so_options |= sopt->sopt_name;
2231                         else
2232                                 so->so_options &= ~sopt->sopt_name;
2233                         SOCK_UNLOCK(so);
2234                         break;
2235
2236                 case SO_SETFIB:
2237                         error = sooptcopyin(sopt, &optval, sizeof optval,
2238                                             sizeof optval);
2239                         if (optval < 1 || optval > rt_numfibs) {
2240                                 error = EINVAL;
2241                                 goto bad;
2242                         }
2243                         if ((so->so_proto->pr_domain->dom_family == PF_INET) ||
2244                             (so->so_proto->pr_domain->dom_family == PF_ROUTE)) {
2245                                 so->so_fibnum = optval;
2246                                 /* Note: ignore error */
2247                                 if (so->so_proto && so->so_proto->pr_ctloutput)
2248                                         (*so->so_proto->pr_ctloutput)(so, sopt);
2249                         } else {
2250                                 so->so_fibnum = 0;
2251                         }
2252                         break;
2253                 case SO_SNDBUF:
2254                 case SO_RCVBUF:
2255                 case SO_SNDLOWAT:
2256                 case SO_RCVLOWAT:
2257                         error = sooptcopyin(sopt, &optval, sizeof optval,
2258                                             sizeof optval);
2259                         if (error)
2260                                 goto bad;
2261
2262                         /*
2263                          * Values < 1 make no sense for any of these options,
2264                          * so disallow them.
2265                          */
2266                         if (optval < 1) {
2267                                 error = EINVAL;
2268                                 goto bad;
2269                         }
2270
2271                         switch (sopt->sopt_name) {
2272                         case SO_SNDBUF:
2273                         case SO_RCVBUF:
2274                                 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2275                                     &so->so_snd : &so->so_rcv, (u_long)optval,
2276                                     so, curthread) == 0) {
2277                                         error = ENOBUFS;
2278                                         goto bad;
2279                                 }
2280                                 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2281                                     &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2282                                 break;
2283
2284                         /*
2285                          * Make sure the low-water is never greater than the
2286                          * high-water.
2287                          */
2288                         case SO_SNDLOWAT:
2289                                 SOCKBUF_LOCK(&so->so_snd);
2290                                 so->so_snd.sb_lowat =
2291                                     (optval > so->so_snd.sb_hiwat) ?
2292                                     so->so_snd.sb_hiwat : optval;
2293                                 SOCKBUF_UNLOCK(&so->so_snd);
2294                                 break;
2295                         case SO_RCVLOWAT:
2296                                 SOCKBUF_LOCK(&so->so_rcv);
2297                                 so->so_rcv.sb_lowat =
2298                                     (optval > so->so_rcv.sb_hiwat) ?
2299                                     so->so_rcv.sb_hiwat : optval;
2300                                 SOCKBUF_UNLOCK(&so->so_rcv);
2301                                 break;
2302                         }
2303                         break;
2304
2305                 case SO_SNDTIMEO:
2306                 case SO_RCVTIMEO:
2307 #ifdef COMPAT_IA32
2308                         if (SV_CURPROC_FLAG(SV_ILP32)) {
2309                                 struct timeval32 tv32;
2310
2311                                 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2312                                     sizeof tv32);
2313                                 CP(tv32, tv, tv_sec);
2314                                 CP(tv32, tv, tv_usec);
2315                         } else
2316 #endif
2317                                 error = sooptcopyin(sopt, &tv, sizeof tv,
2318                                     sizeof tv);
2319                         if (error)
2320                                 goto bad;
2321
2322                         /* assert(hz > 0); */
2323                         if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2324                             tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2325                                 error = EDOM;
2326                                 goto bad;
2327                         }
2328                         /* assert(tick > 0); */
2329                         /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2330                         val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
2331                         if (val > INT_MAX) {
2332                                 error = EDOM;
2333                                 goto bad;
2334                         }
2335                         if (val == 0 && tv.tv_usec != 0)
2336                                 val = 1;
2337
2338                         switch (sopt->sopt_name) {
2339                         case SO_SNDTIMEO:
2340                                 so->so_snd.sb_timeo = val;
2341                                 break;
2342                         case SO_RCVTIMEO:
2343                                 so->so_rcv.sb_timeo = val;
2344                                 break;
2345                         }
2346                         break;
2347
2348                 case SO_LABEL:
2349 #ifdef MAC
2350                         error = sooptcopyin(sopt, &extmac, sizeof extmac,
2351                             sizeof extmac);
2352                         if (error)
2353                                 goto bad;
2354                         error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2355                             so, &extmac);
2356 #else
2357                         error = EOPNOTSUPP;
2358 #endif
2359                         break;
2360
2361                 default:
2362                         error = ENOPROTOOPT;
2363                         break;
2364                 }
2365                 if (error == 0 && so->so_proto != NULL &&
2366                     so->so_proto->pr_ctloutput != NULL) {
2367                         (void) ((*so->so_proto->pr_ctloutput)
2368                                   (so, sopt));
2369                 }
2370         }
2371 bad:
2372         return (error);
2373 }
2374
2375 /*
2376  * Helper routine for getsockopt.
2377  */
2378 int
2379 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2380 {
2381         int     error;
2382         size_t  valsize;
2383
2384         error = 0;
2385
2386         /*
2387          * Documented get behavior is that we always return a value, possibly
2388          * truncated to fit in the user's buffer.  Traditional behavior is
2389          * that we always tell the user precisely how much we copied, rather
2390          * than something useful like the total amount we had available for
2391          * her.  Note that this interface is not idempotent; the entire
2392          * answer must generated ahead of time.
2393          */
2394         valsize = min(len, sopt->sopt_valsize);
2395         sopt->sopt_valsize = valsize;
2396         if (sopt->sopt_val != NULL) {
2397                 if (sopt->sopt_td != NULL)
2398                         error = copyout(buf, sopt->sopt_val, valsize);
2399                 else
2400                         bcopy(buf, sopt->sopt_val, valsize);
2401         }
2402         return (error);
2403 }
2404
2405 int
2406 sogetopt(struct socket *so, struct sockopt *sopt)
2407 {
2408         int     error, optval;
2409         struct  linger l;
2410         struct  timeval tv;
2411 #ifdef MAC
2412         struct mac extmac;
2413 #endif
2414
2415         error = 0;
2416         if (sopt->sopt_level != SOL_SOCKET) {
2417                 if (so->so_proto && so->so_proto->pr_ctloutput) {
2418                         return ((*so->so_proto->pr_ctloutput)
2419                                   (so, sopt));
2420                 } else
2421                         return (ENOPROTOOPT);
2422         } else {
2423                 switch (sopt->sopt_name) {
2424 #ifdef INET
2425                 case SO_ACCEPTFILTER:
2426                         error = do_getopt_accept_filter(so, sopt);
2427                         break;
2428 #endif
2429                 case SO_LINGER:
2430                         SOCK_LOCK(so);
2431                         l.l_onoff = so->so_options & SO_LINGER;
2432                         l.l_linger = so->so_linger;
2433                         SOCK_UNLOCK(so);
2434                         error = sooptcopyout(sopt, &l, sizeof l);
2435                         break;
2436
2437                 case SO_USELOOPBACK:
2438                 case SO_DONTROUTE:
2439                 case SO_DEBUG:
2440                 case SO_KEEPALIVE:
2441                 case SO_REUSEADDR:
2442                 case SO_REUSEPORT:
2443                 case SO_BROADCAST:
2444                 case SO_OOBINLINE:
2445                 case SO_ACCEPTCONN:
2446                 case SO_TIMESTAMP:
2447                 case SO_BINTIME:
2448                 case SO_NOSIGPIPE:
2449                         optval = so->so_options & sopt->sopt_name;
2450 integer:
2451                         error = sooptcopyout(sopt, &optval, sizeof optval);
2452                         break;
2453
2454                 case SO_TYPE:
2455                         optval = so->so_type;
2456                         goto integer;
2457
2458                 case SO_ERROR:
2459                         SOCK_LOCK(so);
2460                         optval = so->so_error;
2461                         so->so_error = 0;
2462                         SOCK_UNLOCK(so);
2463                         goto integer;
2464
2465                 case SO_SNDBUF:
2466                         optval = so->so_snd.sb_hiwat;
2467                         goto integer;
2468
2469                 case SO_RCVBUF:
2470                         optval = so->so_rcv.sb_hiwat;
2471                         goto integer;
2472
2473                 case SO_SNDLOWAT:
2474                         optval = so->so_snd.sb_lowat;
2475                         goto integer;
2476
2477                 case SO_RCVLOWAT:
2478                         optval = so->so_rcv.sb_lowat;
2479                         goto integer;
2480
2481                 case SO_SNDTIMEO:
2482                 case SO_RCVTIMEO:
2483                         optval = (sopt->sopt_name == SO_SNDTIMEO ?
2484                                   so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2485
2486                         tv.tv_sec = optval / hz;
2487                         tv.tv_usec = (optval % hz) * tick;
2488 #ifdef COMPAT_IA32
2489                         if (SV_CURPROC_FLAG(SV_ILP32)) {
2490                                 struct timeval32 tv32;
2491
2492                                 CP(tv, tv32, tv_sec);
2493                                 CP(tv, tv32, tv_usec);
2494                                 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2495                         } else
2496 #endif
2497                                 error = sooptcopyout(sopt, &tv, sizeof tv);
2498                         break;
2499
2500                 case SO_LABEL:
2501 #ifdef MAC
2502                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2503                             sizeof(extmac));
2504                         if (error)
2505                                 return (error);
2506                         error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2507                             so, &extmac);
2508                         if (error)
2509                                 return (error);
2510                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
2511 #else
2512                         error = EOPNOTSUPP;
2513 #endif
2514                         break;
2515
2516                 case SO_PEERLABEL:
2517 #ifdef MAC
2518                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2519                             sizeof(extmac));
2520                         if (error)
2521                                 return (error);
2522                         error = mac_getsockopt_peerlabel(
2523                             sopt->sopt_td->td_ucred, so, &extmac);
2524                         if (error)
2525                                 return (error);
2526                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
2527 #else
2528                         error = EOPNOTSUPP;
2529 #endif
2530                         break;
2531
2532                 case SO_LISTENQLIMIT:
2533                         optval = so->so_qlimit;
2534                         goto integer;
2535
2536                 case SO_LISTENQLEN:
2537                         optval = so->so_qlen;
2538                         goto integer;
2539
2540                 case SO_LISTENINCQLEN:
2541                         optval = so->so_incqlen;
2542                         goto integer;
2543
2544                 default:
2545                         error = ENOPROTOOPT;
2546                         break;
2547                 }
2548                 return (error);
2549         }
2550 }
2551
2552 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2553 int
2554 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2555 {
2556         struct mbuf *m, *m_prev;
2557         int sopt_size = sopt->sopt_valsize;
2558
2559         MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
2560         if (m == NULL)
2561                 return ENOBUFS;
2562         if (sopt_size > MLEN) {
2563                 MCLGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT);
2564                 if ((m->m_flags & M_EXT) == 0) {
2565                         m_free(m);
2566                         return ENOBUFS;
2567                 }
2568                 m->m_len = min(MCLBYTES, sopt_size);
2569         } else {
2570                 m->m_len = min(MLEN, sopt_size);
2571         }
2572         sopt_size -= m->m_len;
2573         *mp = m;
2574         m_prev = m;
2575
2576         while (sopt_size) {
2577                 MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
2578                 if (m == NULL) {
2579                         m_freem(*mp);
2580                         return ENOBUFS;
2581                 }
2582                 if (sopt_size > MLEN) {
2583                         MCLGET(m, sopt->sopt_td != NULL ? M_WAIT :
2584                             M_DONTWAIT);
2585                         if ((m->m_flags & M_EXT) == 0) {
2586                                 m_freem(m);
2587                                 m_freem(*mp);
2588                                 return ENOBUFS;
2589                         }
2590                         m->m_len = min(MCLBYTES, sopt_size);
2591                 } else {
2592                         m->m_len = min(MLEN, sopt_size);
2593                 }
2594                 sopt_size -= m->m_len;
2595                 m_prev->m_next = m;
2596                 m_prev = m;
2597         }
2598         return (0);
2599 }
2600
2601 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2602 int
2603 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2604 {
2605         struct mbuf *m0 = m;
2606
2607         if (sopt->sopt_val == NULL)
2608                 return (0);
2609         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2610                 if (sopt->sopt_td != NULL) {
2611                         int error;
2612
2613                         error = copyin(sopt->sopt_val, mtod(m, char *),
2614                                        m->m_len);
2615                         if (error != 0) {
2616                                 m_freem(m0);
2617                                 return(error);
2618                         }
2619                 } else
2620                         bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2621                 sopt->sopt_valsize -= m->m_len;
2622                 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2623                 m = m->m_next;
2624         }
2625         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2626                 panic("ip6_sooptmcopyin");
2627         return (0);
2628 }
2629
2630 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2631 int
2632 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2633 {
2634         struct mbuf *m0 = m;
2635         size_t valsize = 0;
2636
2637         if (sopt->sopt_val == NULL)
2638                 return (0);
2639         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2640                 if (sopt->sopt_td != NULL) {
2641                         int error;
2642
2643                         error = copyout(mtod(m, char *), sopt->sopt_val,
2644                                        m->m_len);
2645                         if (error != 0) {
2646                                 m_freem(m0);
2647                                 return(error);
2648                         }
2649                 } else
2650                         bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2651                sopt->sopt_valsize -= m->m_len;
2652                sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2653                valsize += m->m_len;
2654                m = m->m_next;
2655         }
2656         if (m != NULL) {
2657                 /* enough soopt buffer should be given from user-land */
2658                 m_freem(m0);
2659                 return(EINVAL);
2660         }
2661         sopt->sopt_valsize = valsize;
2662         return (0);
2663 }
2664
2665 /*
2666  * sohasoutofband(): protocol notifies socket layer of the arrival of new
2667  * out-of-band data, which will then notify socket consumers.
2668  */
2669 void
2670 sohasoutofband(struct socket *so)
2671 {
2672
2673         if (so->so_sigio != NULL)
2674                 pgsigio(&so->so_sigio, SIGURG, 0);
2675         selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2676 }
2677
2678 int
2679 sopoll(struct socket *so, int events, struct ucred *active_cred,
2680     struct thread *td)
2681 {
2682
2683         return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
2684             td));
2685 }
2686
2687 int
2688 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
2689     struct thread *td)
2690 {
2691         int revents = 0;
2692
2693         SOCKBUF_LOCK(&so->so_snd);
2694         SOCKBUF_LOCK(&so->so_rcv);
2695         if (events & (POLLIN | POLLRDNORM))
2696                 if (soreadable(so))
2697                         revents |= events & (POLLIN | POLLRDNORM);
2698
2699         if (events & POLLINIGNEOF)
2700                 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2701                     !TAILQ_EMPTY(&so->so_comp) || so->so_error)
2702                         revents |= POLLINIGNEOF;
2703
2704         if (events & (POLLOUT | POLLWRNORM))
2705                 if (sowriteable(so))
2706                         revents |= events & (POLLOUT | POLLWRNORM);
2707
2708         if (events & (POLLPRI | POLLRDBAND))
2709                 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2710                         revents |= events & (POLLPRI | POLLRDBAND);
2711
2712         if (revents == 0) {
2713                 if (events &
2714                     (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2715                      POLLRDBAND)) {
2716                         selrecord(td, &so->so_rcv.sb_sel);
2717                         so->so_rcv.sb_flags |= SB_SEL;
2718                 }
2719
2720                 if (events & (POLLOUT | POLLWRNORM)) {
2721                         selrecord(td, &so->so_snd.sb_sel);
2722                         so->so_snd.sb_flags |= SB_SEL;
2723                 }
2724         }
2725
2726         SOCKBUF_UNLOCK(&so->so_rcv);
2727         SOCKBUF_UNLOCK(&so->so_snd);
2728         return (revents);
2729 }
2730
2731 int
2732 soo_kqfilter(struct file *fp, struct knote *kn)
2733 {
2734         struct socket *so = kn->kn_fp->f_data;
2735         struct sockbuf *sb;
2736
2737         switch (kn->kn_filter) {
2738         case EVFILT_READ:
2739                 if (so->so_options & SO_ACCEPTCONN)
2740                         kn->kn_fop = &solisten_filtops;
2741                 else
2742                         kn->kn_fop = &soread_filtops;
2743                 sb = &so->so_rcv;
2744                 break;
2745         case EVFILT_WRITE:
2746                 kn->kn_fop = &sowrite_filtops;
2747                 sb = &so->so_snd;
2748                 break;
2749         default:
2750                 return (EINVAL);
2751         }
2752
2753         SOCKBUF_LOCK(sb);
2754         knlist_add(&sb->sb_sel.si_note, kn, 1);
2755         sb->sb_flags |= SB_KNOTE;
2756         SOCKBUF_UNLOCK(sb);
2757         return (0);
2758 }
2759
2760 /*
2761  * Some routines that return EOPNOTSUPP for entry points that are not
2762  * supported by a protocol.  Fill in as needed.
2763  */
2764 int
2765 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
2766 {
2767
2768         return EOPNOTSUPP;
2769 }
2770
2771 int
2772 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
2773 {
2774
2775         return EOPNOTSUPP;
2776 }
2777
2778 int
2779 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
2780 {
2781
2782         return EOPNOTSUPP;
2783 }
2784
2785 int
2786 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
2787 {
2788
2789         return EOPNOTSUPP;
2790 }
2791
2792 int
2793 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
2794 {
2795
2796         return EOPNOTSUPP;
2797 }
2798
2799 int
2800 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
2801     struct ifnet *ifp, struct thread *td)
2802 {
2803
2804         return EOPNOTSUPP;
2805 }
2806
2807 int
2808 pru_disconnect_notsupp(struct socket *so)
2809 {
2810
2811         return EOPNOTSUPP;
2812 }
2813
2814 int
2815 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
2816 {
2817
2818         return EOPNOTSUPP;
2819 }
2820
2821 int
2822 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
2823 {
2824
2825         return EOPNOTSUPP;
2826 }
2827
2828 int
2829 pru_rcvd_notsupp(struct socket *so, int flags)
2830 {
2831
2832         return EOPNOTSUPP;
2833 }
2834
2835 int
2836 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
2837 {
2838
2839         return EOPNOTSUPP;
2840 }
2841
2842 int
2843 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
2844     struct sockaddr *addr, struct mbuf *control, struct thread *td)
2845 {
2846
2847         return EOPNOTSUPP;
2848 }
2849
2850 /*
2851  * This isn't really a ``null'' operation, but it's the default one and
2852  * doesn't do anything destructive.
2853  */
2854 int
2855 pru_sense_null(struct socket *so, struct stat *sb)
2856 {
2857
2858         sb->st_blksize = so->so_snd.sb_hiwat;
2859         return 0;
2860 }
2861
2862 int
2863 pru_shutdown_notsupp(struct socket *so)
2864 {
2865
2866         return EOPNOTSUPP;
2867 }
2868
2869 int
2870 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
2871 {
2872
2873         return EOPNOTSUPP;
2874 }
2875
2876 int
2877 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
2878     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2879 {
2880
2881         return EOPNOTSUPP;
2882 }
2883
2884 int
2885 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
2886     struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2887 {
2888
2889         return EOPNOTSUPP;
2890 }
2891
2892 int
2893 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
2894     struct thread *td)
2895 {
2896
2897         return EOPNOTSUPP;
2898 }
2899
2900 static void
2901 filt_sordetach(struct knote *kn)
2902 {
2903         struct socket *so = kn->kn_fp->f_data;
2904
2905         SOCKBUF_LOCK(&so->so_rcv);
2906         knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2907         if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2908                 so->so_rcv.sb_flags &= ~SB_KNOTE;
2909         SOCKBUF_UNLOCK(&so->so_rcv);
2910 }
2911
2912 /*ARGSUSED*/
2913 static int
2914 filt_soread(struct knote *kn, long hint)
2915 {
2916         struct socket *so;
2917
2918         so = kn->kn_fp->f_data;
2919         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2920
2921         kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2922         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2923                 kn->kn_flags |= EV_EOF;
2924                 kn->kn_fflags = so->so_error;
2925                 return (1);
2926         } else if (so->so_error)        /* temporary udp error */
2927                 return (1);
2928         else if (kn->kn_sfflags & NOTE_LOWAT)
2929                 return (kn->kn_data >= kn->kn_sdata);
2930         else
2931                 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2932 }
2933
2934 static void
2935 filt_sowdetach(struct knote *kn)
2936 {
2937         struct socket *so = kn->kn_fp->f_data;
2938
2939         SOCKBUF_LOCK(&so->so_snd);
2940         knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2941         if (knlist_empty(&so->so_snd.sb_sel.si_note))
2942                 so->so_snd.sb_flags &= ~SB_KNOTE;
2943         SOCKBUF_UNLOCK(&so->so_snd);
2944 }
2945
2946 /*ARGSUSED*/
2947 static int
2948 filt_sowrite(struct knote *kn, long hint)
2949 {
2950         struct socket *so;
2951
2952         so = kn->kn_fp->f_data;
2953         SOCKBUF_LOCK_ASSERT(&so->so_snd);
2954         kn->kn_data = sbspace(&so->so_snd);
2955         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2956                 kn->kn_flags |= EV_EOF;
2957                 kn->kn_fflags = so->so_error;
2958                 return (1);
2959         } else if (so->so_error)        /* temporary udp error */
2960                 return (1);
2961         else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2962             (so->so_proto->pr_flags & PR_CONNREQUIRED))
2963                 return (0);
2964         else if (kn->kn_sfflags & NOTE_LOWAT)
2965                 return (kn->kn_data >= kn->kn_sdata);
2966         else
2967                 return (kn->kn_data >= so->so_snd.sb_lowat);
2968 }
2969
2970 /*ARGSUSED*/
2971 static int
2972 filt_solisten(struct knote *kn, long hint)
2973 {
2974         struct socket *so = kn->kn_fp->f_data;
2975
2976         kn->kn_data = so->so_qlen;
2977         return (! TAILQ_EMPTY(&so->so_comp));
2978 }
2979
2980 int
2981 socheckuid(struct socket *so, uid_t uid)
2982 {
2983
2984         if (so == NULL)
2985                 return (EPERM);
2986         if (so->so_cred->cr_uid != uid)
2987                 return (EPERM);
2988         return (0);
2989 }
2990
2991 static int
2992 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
2993 {
2994         int error;
2995         int val;
2996
2997         val = somaxconn;
2998         error = sysctl_handle_int(oidp, &val, 0, req);
2999         if (error || !req->newptr )
3000                 return (error);
3001
3002         if (val < 1 || val > USHRT_MAX)
3003                 return (EINVAL);
3004
3005         somaxconn = val;
3006         return (0);
3007 }
3008
3009 /*
3010  * These functions are used by protocols to notify the socket layer (and its
3011  * consumers) of state changes in the sockets driven by protocol-side events.
3012  */
3013
3014 /*
3015  * Procedures to manipulate state flags of socket and do appropriate wakeups.
3016  *
3017  * Normal sequence from the active (originating) side is that
3018  * soisconnecting() is called during processing of connect() call, resulting
3019  * in an eventual call to soisconnected() if/when the connection is
3020  * established.  When the connection is torn down soisdisconnecting() is
3021  * called during processing of disconnect() call, and soisdisconnected() is
3022  * called when the connection to the peer is totally severed.  The semantics
3023  * of these routines are such that connectionless protocols can call
3024  * soisconnected() and soisdisconnected() only, bypassing the in-progress
3025  * calls when setting up a ``connection'' takes no time.
3026  *
3027  * From the passive side, a socket is created with two queues of sockets:
3028  * so_incomp for connections in progress and so_comp for connections already
3029  * made and awaiting user acceptance.  As a protocol is preparing incoming
3030  * connections, it creates a socket structure queued on so_incomp by calling
3031  * sonewconn().  When the connection is established, soisconnected() is
3032  * called, and transfers the socket structure to so_comp, making it available
3033  * to accept().
3034  *
3035  * If a socket is closed with sockets on either so_incomp or so_comp, these
3036  * sockets are dropped.
3037  *
3038  * If higher-level protocols are implemented in the kernel, the wakeups done
3039  * here will sometimes cause software-interrupt process scheduling.
3040  */
3041 void
3042 soisconnecting(struct socket *so)
3043 {
3044
3045         SOCK_LOCK(so);
3046         so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3047         so->so_state |= SS_ISCONNECTING;
3048         SOCK_UNLOCK(so);
3049 }
3050
3051 void
3052 soisconnected(struct socket *so)
3053 {
3054         struct socket *head;    
3055         int ret;
3056
3057 restart:
3058         ACCEPT_LOCK();
3059         SOCK_LOCK(so);
3060         so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3061         so->so_state |= SS_ISCONNECTED;
3062         head = so->so_head;
3063         if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3064                 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3065                         SOCK_UNLOCK(so);
3066                         TAILQ_REMOVE(&head->so_incomp, so, so_list);
3067                         head->so_incqlen--;
3068                         so->so_qstate &= ~SQ_INCOMP;
3069                         TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3070                         head->so_qlen++;
3071                         so->so_qstate |= SQ_COMP;
3072                         ACCEPT_UNLOCK();
3073                         sorwakeup(head);
3074                         wakeup_one(&head->so_timeo);
3075                 } else {
3076                         ACCEPT_UNLOCK();
3077                         soupcall_set(so, SO_RCV,
3078                             head->so_accf->so_accept_filter->accf_callback,
3079                             head->so_accf->so_accept_filter_arg);
3080                         so->so_options &= ~SO_ACCEPTFILTER;
3081                         ret = head->so_accf->so_accept_filter->accf_callback(so,
3082                             head->so_accf->so_accept_filter_arg, M_DONTWAIT);
3083                         if (ret == SU_ISCONNECTED)
3084                                 soupcall_clear(so, SO_RCV);
3085                         SOCK_UNLOCK(so);
3086                         if (ret == SU_ISCONNECTED)
3087                                 goto restart;
3088                 }
3089                 return;
3090         }
3091         SOCK_UNLOCK(so);
3092         ACCEPT_UNLOCK();
3093         wakeup(&so->so_timeo);
3094         sorwakeup(so);
3095         sowwakeup(so);
3096 }
3097
3098 void
3099 soisdisconnecting(struct socket *so)
3100 {
3101
3102         /*
3103          * Note: This code assumes that SOCK_LOCK(so) and
3104          * SOCKBUF_LOCK(&so->so_rcv) are the same.
3105          */
3106         SOCKBUF_LOCK(&so->so_rcv);
3107         so->so_state &= ~SS_ISCONNECTING;
3108         so->so_state |= SS_ISDISCONNECTING;
3109         so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3110         sorwakeup_locked(so);
3111         SOCKBUF_LOCK(&so->so_snd);
3112         so->so_snd.sb_state |= SBS_CANTSENDMORE;
3113         sowwakeup_locked(so);
3114         wakeup(&so->so_timeo);
3115 }
3116
3117 void
3118 soisdisconnected(struct socket *so)
3119 {
3120
3121         /*
3122          * Note: This code assumes that SOCK_LOCK(so) and
3123          * SOCKBUF_LOCK(&so->so_rcv) are the same.
3124          */
3125         SOCKBUF_LOCK(&so->so_rcv);
3126         so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3127         so->so_state |= SS_ISDISCONNECTED;
3128         so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3129         sorwakeup_locked(so);
3130         SOCKBUF_LOCK(&so->so_snd);
3131         so->so_snd.sb_state |= SBS_CANTSENDMORE;
3132         sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
3133         sowwakeup_locked(so);
3134         wakeup(&so->so_timeo);
3135 }
3136
3137 /*
3138  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3139  */
3140 struct sockaddr *
3141 sodupsockaddr(const struct sockaddr *sa, int mflags)
3142 {
3143         struct sockaddr *sa2;
3144
3145         sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3146         if (sa2)
3147                 bcopy(sa, sa2, sa->sa_len);
3148         return sa2;
3149 }
3150
3151 /*
3152  * Register per-socket buffer upcalls.
3153  */
3154 void
3155 soupcall_set(struct socket *so, int which,
3156     int (*func)(struct socket *, void *, int), void *arg)
3157 {
3158         struct sockbuf *sb;
3159         
3160         switch (which) {
3161         case SO_RCV:
3162                 sb = &so->so_rcv;
3163                 break;
3164         case SO_SND:
3165                 sb = &so->so_snd;
3166                 break;
3167         default:
3168                 panic("soupcall_set: bad which");
3169         }
3170         SOCKBUF_LOCK_ASSERT(sb);
3171 #if 0
3172         /* XXX: accf_http actually wants to do this on purpose. */
3173         KASSERT(sb->sb_upcall == NULL, ("soupcall_set: overwriting upcall"));
3174 #endif
3175         sb->sb_upcall = func;
3176         sb->sb_upcallarg = arg;
3177         sb->sb_flags |= SB_UPCALL;
3178 }
3179
3180 void
3181 soupcall_clear(struct socket *so, int which)
3182 {
3183         struct sockbuf *sb;
3184
3185         switch (which) {
3186         case SO_RCV:
3187                 sb = &so->so_rcv;
3188                 break;
3189         case SO_SND:
3190                 sb = &so->so_snd;
3191                 break;
3192         default:
3193                 panic("soupcall_clear: bad which");
3194         }
3195         SOCKBUF_LOCK_ASSERT(sb);
3196         KASSERT(sb->sb_upcall != NULL, ("soupcall_clear: no upcall to clear"));
3197         sb->sb_upcall = NULL;
3198         sb->sb_upcallarg = NULL;
3199         sb->sb_flags &= ~SB_UPCALL;
3200 }
3201
3202 /*
3203  * Create an external-format (``xsocket'') structure using the information in
3204  * the kernel-format socket structure pointed to by so.  This is done to
3205  * reduce the spew of irrelevant information over this interface, to isolate
3206  * user code from changes in the kernel structure, and potentially to provide
3207  * information-hiding if we decide that some of this information should be
3208  * hidden from users.
3209  */
3210 void
3211 sotoxsocket(struct socket *so, struct xsocket *xso)
3212 {
3213
3214         xso->xso_len = sizeof *xso;
3215         xso->xso_so = so;
3216         xso->so_type = so->so_type;
3217         xso->so_options = so->so_options;
3218         xso->so_linger = so->so_linger;
3219         xso->so_state = so->so_state;
3220         xso->so_pcb = so->so_pcb;
3221         xso->xso_protocol = so->so_proto->pr_protocol;
3222         xso->xso_family = so->so_proto->pr_domain->dom_family;
3223         xso->so_qlen = so->so_qlen;
3224         xso->so_incqlen = so->so_incqlen;
3225         xso->so_qlimit = so->so_qlimit;
3226         xso->so_timeo = so->so_timeo;
3227         xso->so_error = so->so_error;
3228         xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3229         xso->so_oobmark = so->so_oobmark;
3230         sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3231         sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3232         xso->so_uid = so->so_cred->cr_uid;
3233 }
3234
3235
3236 /*
3237  * Socket accessor functions to provide external consumers with
3238  * a safe interface to socket state
3239  *
3240  */
3241
3242 void
3243 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *), void *arg)
3244 {
3245         
3246         TAILQ_FOREACH(so, &so->so_comp, so_list)
3247                 func(so, arg);
3248 }
3249
3250 struct sockbuf *
3251 so_sockbuf_rcv(struct socket *so)
3252 {
3253
3254         return (&so->so_rcv);
3255 }
3256
3257 struct sockbuf *
3258 so_sockbuf_snd(struct socket *so)
3259 {
3260
3261         return (&so->so_snd);
3262 }
3263
3264 int
3265 so_state_get(const struct socket *so)
3266 {
3267
3268         return (so->so_state);
3269 }
3270
3271 void
3272 so_state_set(struct socket *so, int val)
3273 {
3274
3275         so->so_state = val;
3276 }
3277
3278 int
3279 so_options_get(const struct socket *so)
3280 {
3281
3282         return (so->so_options);
3283 }
3284
3285 void
3286 so_options_set(struct socket *so, int val)
3287 {
3288
3289         so->so_options = val;
3290 }
3291
3292 int
3293 so_error_get(const struct socket *so)
3294 {
3295
3296         return (so->so_error);
3297 }
3298
3299 void
3300 so_error_set(struct socket *so, int val)
3301 {
3302
3303         so->so_error = val;
3304 }
3305
3306 int
3307 so_linger_get(const struct socket *so)
3308 {
3309
3310         return (so->so_linger);
3311 }
3312
3313 void
3314 so_linger_set(struct socket *so, int val)
3315 {
3316
3317         so->so_linger = val;
3318 }
3319
3320 struct protosw *
3321 so_protosw_get(const struct socket *so)
3322 {
3323
3324         return (so->so_proto);
3325 }
3326
3327 void
3328 so_protosw_set(struct socket *so, struct protosw *val)
3329 {
3330
3331         so->so_proto = val;
3332 }
3333
3334 void
3335 so_sorwakeup(struct socket *so)
3336 {
3337
3338         sorwakeup(so);
3339 }
3340
3341 void
3342 so_sowwakeup(struct socket *so)
3343 {
3344
3345         sowwakeup(so);
3346 }
3347
3348 void
3349 so_sorwakeup_locked(struct socket *so)
3350 {
3351
3352         sorwakeup_locked(so);
3353 }
3354
3355 void
3356 so_sowwakeup_locked(struct socket *so)
3357 {
3358
3359         sowwakeup_locked(so);
3360 }
3361
3362 void
3363 so_lock(struct socket *so)
3364 {
3365         SOCK_LOCK(so);
3366 }
3367
3368 void
3369 so_unlock(struct socket *so)
3370 {
3371         SOCK_UNLOCK(so);
3372 }