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