xref: /dragonfly/sys/kern/uipc_socket2.c (revision 3851e4b8)
1 /*
2  * Copyright (c) 2005 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 1982, 1986, 1988, 1990, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *	@(#)uipc_socket2.c	8.1 (Berkeley) 6/10/93
31  * $FreeBSD: src/sys/kern/uipc_socket2.c,v 1.55.2.17 2002/08/31 19:04:55 dwmalone Exp $
32  */
33 
34 #include "opt_param.h"
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/domain.h>
38 #include <sys/file.h>	/* for maxfiles */
39 #include <sys/kernel.h>
40 #include <sys/ktr.h>
41 #include <sys/proc.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/protosw.h>
45 #include <sys/resourcevar.h>
46 #include <sys/stat.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/socketops.h>
50 #include <sys/signalvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/event.h>
53 
54 #include <sys/msgport2.h>
55 #include <sys/socketvar2.h>
56 
57 #include <net/netisr2.h>
58 
59 #ifndef KTR_SOWAKEUP
60 #define KTR_SOWAKEUP	KTR_ALL
61 #endif
62 KTR_INFO_MASTER(sowakeup);
63 KTR_INFO(KTR_SOWAKEUP, sowakeup, nconn_start, 0, "newconn sorwakeup start");
64 KTR_INFO(KTR_SOWAKEUP, sowakeup, nconn_end, 1, "newconn sorwakeup end");
65 KTR_INFO(KTR_SOWAKEUP, sowakeup, nconn_wakeupstart, 2, "newconn wakeup start");
66 KTR_INFO(KTR_SOWAKEUP, sowakeup, nconn_wakeupend, 3, "newconn wakeup end");
67 #define logsowakeup(name)	KTR_LOG(sowakeup_ ## name)
68 
69 int	maxsockets;
70 
71 /*
72  * Primitive routines for operating on sockets and socket buffers
73  */
74 
75 u_long	sb_max = SB_MAX;
76 u_long	sb_max_adj =
77     SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
78 
79 static	u_long sb_efficiency = 8;	/* parameter for sbreserve() */
80 
81 /************************************************************************
82  * signalsockbuf procedures						*
83  ************************************************************************/
84 
85 /*
86  * Wait for data to arrive at/drain from a socket buffer.
87  *
88  * NOTE: Caller must generally hold the ssb_lock (client side lock) since
89  *	 WAIT/WAKEUP only works for one client at a time.
90  *
91  * NOTE: Caller always retries whatever operation it was waiting on.
92  */
93 int
94 ssb_wait(struct signalsockbuf *ssb)
95 {
96 	uint32_t flags;
97 	int pflags;
98 	int error;
99 
100 	pflags = (ssb->ssb_flags & SSB_NOINTR) ? 0 : PCATCH;
101 
102 	for (;;) {
103 		flags = ssb->ssb_flags;
104 		cpu_ccfence();
105 
106 		/*
107 		 * WAKEUP and WAIT interlock each other.  We can catch the
108 		 * race by checking to see if WAKEUP has already been set,
109 		 * and only setting WAIT if WAKEUP is clear.
110 		 */
111 		if (flags & SSB_WAKEUP) {
112 			if (atomic_cmpset_int(&ssb->ssb_flags, flags,
113 					      flags & ~SSB_WAKEUP)) {
114 				error = 0;
115 				break;
116 			}
117 			continue;
118 		}
119 
120 		/*
121 		 * Only set WAIT if WAKEUP is clear.
122 		 */
123 		tsleep_interlock(&ssb->ssb_cc, pflags);
124 		if (atomic_cmpset_int(&ssb->ssb_flags, flags,
125 				      flags | SSB_WAIT)) {
126 			error = tsleep(&ssb->ssb_cc, pflags | PINTERLOCKED,
127 				       "sbwait", ssb->ssb_timeo);
128 			break;
129 		}
130 	}
131 	return (error);
132 }
133 
134 /*
135  * Lock a sockbuf already known to be locked;
136  * return any error returned from sleep (EINTR).
137  */
138 int
139 _ssb_lock(struct signalsockbuf *ssb)
140 {
141 	uint32_t flags;
142 	int pflags;
143 	int error;
144 
145 	pflags = (ssb->ssb_flags & SSB_NOINTR) ? 0 : PCATCH;
146 
147 	for (;;) {
148 		flags = ssb->ssb_flags;
149 		cpu_ccfence();
150 		if (flags & SSB_LOCK) {
151 			tsleep_interlock(&ssb->ssb_flags, pflags);
152 			if (atomic_cmpset_int(&ssb->ssb_flags, flags,
153 					      flags | SSB_WANT)) {
154 				error = tsleep(&ssb->ssb_flags,
155 					       pflags | PINTERLOCKED,
156 					       "sblock", 0);
157 				if (error)
158 					break;
159 			}
160 		} else {
161 			if (atomic_cmpset_int(&ssb->ssb_flags, flags,
162 					      flags | SSB_LOCK)) {
163 				lwkt_gettoken(&ssb->ssb_token);
164 				error = 0;
165 				break;
166 			}
167 		}
168 	}
169 	return (error);
170 }
171 
172 /*
173  * This does the same for sockbufs.  Note that the xsockbuf structure,
174  * since it is always embedded in a socket, does not include a self
175  * pointer nor a length.  We make this entry point public in case
176  * some other mechanism needs it.
177  */
178 void
179 ssbtoxsockbuf(struct signalsockbuf *ssb, struct xsockbuf *xsb)
180 {
181 	xsb->sb_cc = ssb->ssb_cc;
182 	xsb->sb_hiwat = ssb->ssb_hiwat;
183 	xsb->sb_mbcnt = ssb->ssb_mbcnt;
184 	xsb->sb_mbmax = ssb->ssb_mbmax;
185 	xsb->sb_lowat = ssb->ssb_lowat;
186 	xsb->sb_flags = ssb->ssb_flags;
187 	xsb->sb_timeo = ssb->ssb_timeo;
188 }
189 
190 
191 /************************************************************************
192  * Procedures which manipulate socket state flags, wakeups, etc.	*
193  ************************************************************************
194  *
195  * Normal sequence from the active (originating) side is that
196  * soisconnecting() is called during processing of connect() call, resulting
197  * in an eventual call to soisconnected() if/when the connection is
198  * established.  When the connection is torn down soisdisconnecting() is
199  * called during processing of disconnect() call, and soisdisconnected() is
200  * called when the connection to the peer is totally severed.
201  *
202  * The semantics of these routines are such that connectionless protocols
203  * can call soisconnected() and soisdisconnected() only, bypassing the
204  * in-progress calls when setting up a ``connection'' takes no time.
205  *
206  * From the passive side, a socket is created with two queues of sockets:
207  * so_incomp for connections in progress and so_comp for connections
208  * already made and awaiting user acceptance.  As a protocol is preparing
209  * incoming connections, it creates a socket structure queued on so_incomp
210  * by calling sonewconn().  When the connection is established,
211  * soisconnected() is called, and transfers the socket structure to so_comp,
212  * making it available to accept().
213  *
214  * If a socket is closed with sockets on either so_incomp or so_comp, these
215  * sockets are dropped.
216  *
217  * If higher level protocols are implemented in the kernel, the wakeups
218  * done here will sometimes cause software-interrupt process scheduling.
219  */
220 
221 void
222 soisconnecting(struct socket *so)
223 {
224 	soclrstate(so, SS_ISCONNECTED | SS_ISDISCONNECTING);
225 	sosetstate(so, SS_ISCONNECTING);
226 }
227 
228 void
229 soisconnected(struct socket *so)
230 {
231 	struct socket *head;
232 
233 	while ((head = so->so_head) != NULL) {
234 		lwkt_getpooltoken(head);
235 		if (so->so_head == head)
236 			break;
237 		lwkt_relpooltoken(head);
238 	}
239 
240 	soclrstate(so, SS_ISCONNECTING | SS_ISDISCONNECTING | SS_ISCONFIRMING);
241 	sosetstate(so, SS_ISCONNECTED);
242 	if (head && (so->so_state & SS_INCOMP)) {
243 		if ((so->so_options & SO_ACCEPTFILTER) != 0) {
244 			so->so_upcall = head->so_accf->so_accept_filter->accf_callback;
245 			so->so_upcallarg = head->so_accf->so_accept_filter_arg;
246 			atomic_set_int(&so->so_rcv.ssb_flags, SSB_UPCALL);
247 			so->so_options &= ~SO_ACCEPTFILTER;
248 			so->so_upcall(so, so->so_upcallarg, 0);
249 			lwkt_relpooltoken(head);
250 			return;
251 		}
252 
253 		/*
254 		 * Listen socket are not per-cpu.
255 		 */
256 		KKASSERT((so->so_state & (SS_COMP | SS_INCOMP)) == SS_INCOMP);
257 		TAILQ_REMOVE(&head->so_incomp, so, so_list);
258 		head->so_incqlen--;
259 		TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
260 		head->so_qlen++;
261 		sosetstate(so, SS_COMP);
262 		soclrstate(so, SS_INCOMP);
263 
264 		/*
265 		 * XXX head may be on a different protocol thread.
266 		 *     sorwakeup()->sowakeup() is hacked atm.
267 		 */
268 		sorwakeup(head);
269 		wakeup_one(&head->so_timeo);
270 	} else {
271 		wakeup(&so->so_timeo);
272 		sorwakeup(so);
273 		sowwakeup(so);
274 	}
275 	if (head)
276 		lwkt_relpooltoken(head);
277 }
278 
279 void
280 soisdisconnecting(struct socket *so)
281 {
282 	soclrstate(so, SS_ISCONNECTING);
283 	sosetstate(so, SS_ISDISCONNECTING | SS_CANTRCVMORE | SS_CANTSENDMORE);
284 	wakeup((caddr_t)&so->so_timeo);
285 	sowwakeup(so);
286 	sorwakeup(so);
287 }
288 
289 void
290 soisdisconnected(struct socket *so)
291 {
292 	soclrstate(so, SS_ISCONNECTING | SS_ISCONNECTED | SS_ISDISCONNECTING);
293 	sosetstate(so, SS_CANTRCVMORE | SS_CANTSENDMORE | SS_ISDISCONNECTED);
294 	wakeup((caddr_t)&so->so_timeo);
295 	sbdrop(&so->so_snd.sb, so->so_snd.ssb_cc);
296 	sowwakeup(so);
297 	sorwakeup(so);
298 }
299 
300 void
301 soisreconnecting(struct socket *so)
302 {
303         soclrstate(so, SS_ISDISCONNECTING | SS_ISDISCONNECTED |
304 		       SS_CANTRCVMORE | SS_CANTSENDMORE);
305 	sosetstate(so, SS_ISCONNECTING);
306 }
307 
308 void
309 soisreconnected(struct socket *so)
310 {
311 	soclrstate(so, SS_ISDISCONNECTED | SS_CANTRCVMORE | SS_CANTSENDMORE);
312 	soisconnected(so);
313 }
314 
315 /*
316  * Set or change the message port a socket receives commands on.
317  *
318  * XXX
319  */
320 void
321 sosetport(struct socket *so, lwkt_port_t port)
322 {
323 	so->so_port = port;
324 }
325 
326 /*
327  * When an attempt at a new connection is noted on a socket
328  * which accepts connections, sonewconn is called.  If the
329  * connection is possible (subject to space constraints, etc.)
330  * then we allocate a new structure, propoerly linked into the
331  * data structure of the original socket, and return this.
332  * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
333  *
334  * The new socket is returned with one ref and so_pcb assigned.
335  * The reference is implied by so_pcb.
336  */
337 struct socket *
338 sonewconn_faddr(struct socket *head, int connstatus,
339     const struct sockaddr *faddr, boolean_t keep_ref)
340 {
341 	struct socket *so;
342 	struct socket *sp;
343 	struct pru_attach_info ai;
344 
345 	if (head->so_qlen > 3 * head->so_qlimit / 2)
346 		return (NULL);
347 	so = soalloc(1, head->so_proto);
348 	if (so == NULL)
349 		return (NULL);
350 
351 	/*
352 	 * Set the port prior to attaching the inpcb to the current
353 	 * cpu's protocol thread (which should be the current thread
354 	 * but might not be in all cases).  This serializes any pcb ops
355 	 * which occur to our cpu allowing us to complete the attachment
356 	 * without racing anything.
357 	 */
358 	if (head->so_proto->pr_flags & PR_SYNC_PORT)
359 		sosetport(so, &netisr_sync_port);
360 	else
361 		sosetport(so, netisr_cpuport(mycpuid));
362 	if ((head->so_options & SO_ACCEPTFILTER) != 0)
363 		connstatus = 0;
364 	so->so_head = head;
365 	so->so_type = head->so_type;
366 	so->so_options = head->so_options &~ SO_ACCEPTCONN;
367 	so->so_linger = head->so_linger;
368 
369 	/*
370 	 * NOTE: Clearing NOFDREF implies referencing the so with
371 	 *	 soreference().
372 	 */
373 	so->so_state = head->so_state | SS_NOFDREF | SS_ASSERTINPROG;
374 	so->so_cred = crhold(head->so_cred);
375 	ai.sb_rlimit = NULL;
376 	ai.p_ucred = NULL;
377 	ai.fd_rdir = NULL;		/* jail code cruft XXX JH */
378 
379 	/*
380 	 * Reserve space and call pru_attach.  We can direct-call the
381 	 * function since we're already in the protocol thread.
382 	 */
383 	if (soreserve(so, head->so_snd.ssb_hiwat,
384 		      head->so_rcv.ssb_hiwat, NULL) ||
385 	    so_pru_attach_direct(so, 0, &ai)) {
386 		so->so_head = NULL;
387 		soclrstate(so, SS_ASSERTINPROG);
388 		sofree(so);		/* remove implied pcb ref */
389 		return (NULL);
390 	}
391 	KKASSERT(((so->so_proto->pr_flags & PR_ASYNC_RCVD) == 0 &&
392 	    so->so_refs == 2) ||	/* attach + our base ref */
393 	   ((so->so_proto->pr_flags & PR_ASYNC_RCVD) &&
394 	    so->so_refs == 3));		/* + async rcvd ref */
395 	if (keep_ref) {
396 		/*
397 		 * Keep the reference; caller will free it.
398 		 */
399 	} else {
400 		sofree(so);
401 	}
402 	KKASSERT(so->so_port != NULL);
403 	so->so_rcv.ssb_lowat = head->so_rcv.ssb_lowat;
404 	so->so_snd.ssb_lowat = head->so_snd.ssb_lowat;
405 	so->so_rcv.ssb_timeo = head->so_rcv.ssb_timeo;
406 	so->so_snd.ssb_timeo = head->so_snd.ssb_timeo;
407 
408 	if (head->so_rcv.ssb_flags & SSB_AUTOLOWAT)
409 		so->so_rcv.ssb_flags |= SSB_AUTOLOWAT;
410 	else
411 		so->so_rcv.ssb_flags &= ~SSB_AUTOLOWAT;
412 
413 	if (head->so_snd.ssb_flags & SSB_AUTOLOWAT)
414 		so->so_snd.ssb_flags |= SSB_AUTOLOWAT;
415 	else
416 		so->so_snd.ssb_flags &= ~SSB_AUTOLOWAT;
417 
418 	if (head->so_rcv.ssb_flags & SSB_AUTOSIZE)
419 		so->so_rcv.ssb_flags |= SSB_AUTOSIZE;
420 	else
421 		so->so_rcv.ssb_flags &= ~SSB_AUTOSIZE;
422 
423 	if (head->so_snd.ssb_flags & SSB_AUTOSIZE)
424 		so->so_snd.ssb_flags |= SSB_AUTOSIZE;
425 	else
426 		so->so_snd.ssb_flags &= ~SSB_AUTOSIZE;
427 
428 	/*
429 	 * Save the faddr, if the information is provided and
430 	 * the protocol can perform the saving opertation.
431 	 */
432 	if (faddr != NULL && so->so_proto->pr_usrreqs->pru_savefaddr != NULL)
433 		so->so_proto->pr_usrreqs->pru_savefaddr(so, faddr);
434 
435 	lwkt_getpooltoken(head);
436 	if (connstatus) {
437 		KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) == 0);
438 		TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
439 		head->so_qlen++;
440 		/*
441 		 * Set connstatus within head token, so that the accepted
442 		 * socket will have connstatus (SS_ISCONNECTED) set.
443 		 */
444 		sosetstate(so, SS_COMP | connstatus);
445 	} else {
446 		if (head->so_incqlen > head->so_qlimit) {
447 			sp = TAILQ_FIRST(&head->so_incomp);
448 			KKASSERT((sp->so_state & (SS_INCOMP | SS_COMP)) ==
449 			    SS_INCOMP);
450 			TAILQ_REMOVE(&head->so_incomp, sp, so_list);
451 			head->so_incqlen--;
452 			soclrstate(sp, SS_INCOMP);
453 			soabort_async(sp, TRUE);
454 		}
455 		KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) == 0);
456 		TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
457 		head->so_incqlen++;
458 		sosetstate(so, SS_INCOMP);
459 	}
460 	/*
461 	 * Clear SS_ASSERTINPROG within head token, so that it will not
462 	 * race against accept-close or abort for "synchronous" sockets,
463 	 * e.g. unix socket, on other CPUs.
464 	 */
465 	soclrstate(so, SS_ASSERTINPROG);
466 	lwkt_relpooltoken(head);
467 
468 	if (connstatus) {
469 		/*
470 		 * XXX head may be on a different protocol thread.
471 		 *     sorwakeup()->sowakeup() is hacked atm.
472 		 */
473 		logsowakeup(nconn_start);
474 		sorwakeup(head);
475 		logsowakeup(nconn_end);
476 
477 		logsowakeup(nconn_wakeupstart);
478 		wakeup((caddr_t)&head->so_timeo);
479 		logsowakeup(nconn_wakeupend);
480 	}
481 	return (so);
482 }
483 
484 struct socket *
485 sonewconn(struct socket *head, int connstatus)
486 {
487 	return sonewconn_faddr(head, connstatus, NULL, FALSE /* don't ref */);
488 }
489 
490 /*
491  * Socantsendmore indicates that no more data will be sent on the
492  * socket; it would normally be applied to a socket when the user
493  * informs the system that no more data is to be sent, by the protocol
494  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
495  * will be received, and will normally be applied to the socket by a
496  * protocol when it detects that the peer will send no more data.
497  * Data queued for reading in the socket may yet be read.
498  */
499 void
500 socantsendmore(struct socket *so)
501 {
502 	sosetstate(so, SS_CANTSENDMORE);
503 	sowwakeup(so);
504 }
505 
506 void
507 socantrcvmore(struct socket *so)
508 {
509 	sosetstate(so, SS_CANTRCVMORE);
510 	sorwakeup(so);
511 }
512 
513 /*
514  * Wakeup processes waiting on a socket buffer.  Do asynchronous notification
515  * via SIGIO if the socket has the SS_ASYNC flag set.
516  *
517  * For users waiting on send/recv try to avoid unnecessary context switch
518  * thrashing.  Particularly for senders of large buffers (needs to be
519  * extended to sel and aio? XXX)
520  *
521  * WARNING!  Can be called on a foreign socket from the wrong protocol
522  *	     thread.  aka is called on the 'head' listen socket when
523  *	     a new connection comes in.
524  */
525 
526 void
527 sowakeup(struct socket *so, struct signalsockbuf *ssb)
528 {
529 	uint32_t flags;
530 
531 	/*
532 	 * Atomically check the flags.  When no special features are being
533 	 * used, WAIT is clear, and WAKEUP is already set, we can simply
534 	 * return.  The upcoming synchronous waiter will not block.
535 	 */
536 	flags = atomic_fetchadd_int(&ssb->ssb_flags, 0);
537 	if ((flags & SSB_NOTIFY_MASK) == 0) {
538 		if (flags & SSB_WAKEUP)
539 			return;
540 	}
541 
542 	/*
543 	 * Check conditions, set the WAKEUP flag, and clear and signal if
544 	 * the WAIT flag is found to be set.  This interlocks against the
545 	 * client side.
546 	 */
547 	for (;;) {
548 		long space;
549 
550 		flags = ssb->ssb_flags;
551 		cpu_ccfence();
552 		if (ssb->ssb_flags & SSB_PREALLOC)
553 			space = ssb_space_prealloc(ssb);
554 		else
555 			space = ssb_space(ssb);
556 
557 		if ((ssb == &so->so_snd && space >= ssb->ssb_lowat) ||
558 		    (ssb == &so->so_rcv && ssb->ssb_cc >= ssb->ssb_lowat) ||
559 		    (ssb == &so->so_snd && (so->so_state & SS_CANTSENDMORE)) ||
560 		    (ssb == &so->so_rcv && (so->so_state & SS_CANTRCVMORE))
561 		) {
562 			if (atomic_cmpset_int(&ssb->ssb_flags, flags,
563 					  (flags | SSB_WAKEUP) & ~SSB_WAIT)) {
564 				if (flags & SSB_WAIT)
565 					wakeup(&ssb->ssb_cc);
566 				break;
567 			}
568 		} else {
569 			break;
570 		}
571 	}
572 
573 	/*
574 	 * Misc other events
575 	 */
576 	if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
577 		pgsigio(so->so_sigio, SIGIO, 0);
578 	if (ssb->ssb_flags & SSB_UPCALL)
579 		(*so->so_upcall)(so, so->so_upcallarg, M_NOWAIT);
580 	KNOTE(&ssb->ssb_kq.ki_note, 0);
581 
582 	/*
583 	 * This is a bit of a hack.  Multiple threads can wind up scanning
584 	 * ssb_mlist concurrently due to the fact that this function can be
585 	 * called on a foreign socket, so we can't afford to block here.
586 	 *
587 	 * We need the pool token for (so) (likely the listne socket if
588 	 * SSB_MEVENT is set) because the predicate function may have
589 	 * to access the accept queue.
590 	 */
591 	if (ssb->ssb_flags & SSB_MEVENT) {
592 		struct netmsg_so_notify *msg, *nmsg;
593 
594 		lwkt_getpooltoken(so);
595 		TAILQ_FOREACH_MUTABLE(msg, &ssb->ssb_mlist, nm_list, nmsg) {
596 			if (msg->nm_predicate(msg)) {
597 				TAILQ_REMOVE(&ssb->ssb_mlist, msg, nm_list);
598 				lwkt_replymsg(&msg->base.lmsg,
599 					      msg->base.lmsg.ms_error);
600 			}
601 		}
602 		if (TAILQ_EMPTY(&ssb->ssb_mlist))
603 			atomic_clear_int(&ssb->ssb_flags, SSB_MEVENT);
604 		lwkt_relpooltoken(so);
605 	}
606 }
607 
608 /*
609  * Socket buffer (struct signalsockbuf) utility routines.
610  *
611  * Each socket contains two socket buffers: one for sending data and
612  * one for receiving data.  Each buffer contains a queue of mbufs,
613  * information about the number of mbufs and amount of data in the
614  * queue, and other fields allowing kevent()/select()/poll() statements
615  * and notification on data availability to be implemented.
616  *
617  * Data stored in a socket buffer is maintained as a list of records.
618  * Each record is a list of mbufs chained together with the m_next
619  * field.  Records are chained together with the m_nextpkt field. The upper
620  * level routine soreceive() expects the following conventions to be
621  * observed when placing information in the receive buffer:
622  *
623  * 1. If the protocol requires each message be preceded by the sender's
624  *    name, then a record containing that name must be present before
625  *    any associated data (mbuf's must be of type MT_SONAME).
626  * 2. If the protocol supports the exchange of ``access rights'' (really
627  *    just additional data associated with the message), and there are
628  *    ``rights'' to be received, then a record containing this data
629  *    should be present (mbuf's must be of type MT_RIGHTS).
630  * 3. If a name or rights record exists, then it must be followed by
631  *    a data record, perhaps of zero length.
632  *
633  * Before using a new socket structure it is first necessary to reserve
634  * buffer space to the socket, by calling sbreserve().  This should commit
635  * some of the available buffer space in the system buffer pool for the
636  * socket (currently, it does nothing but enforce limits).  The space
637  * should be released by calling ssb_release() when the socket is destroyed.
638  */
639 int
640 soreserve(struct socket *so, u_long sndcc, u_long rcvcc, struct rlimit *rl)
641 {
642 	if (so->so_snd.ssb_lowat == 0)
643 		atomic_set_int(&so->so_snd.ssb_flags, SSB_AUTOLOWAT);
644 	if (ssb_reserve(&so->so_snd, sndcc, so, rl) == 0)
645 		goto bad;
646 	if (ssb_reserve(&so->so_rcv, rcvcc, so, rl) == 0)
647 		goto bad2;
648 	if (so->so_rcv.ssb_lowat == 0)
649 		so->so_rcv.ssb_lowat = 1;
650 	if (so->so_snd.ssb_lowat == 0)
651 		so->so_snd.ssb_lowat = MCLBYTES;
652 	if (so->so_snd.ssb_lowat > so->so_snd.ssb_hiwat)
653 		so->so_snd.ssb_lowat = so->so_snd.ssb_hiwat;
654 	return (0);
655 bad2:
656 	ssb_release(&so->so_snd, so);
657 bad:
658 	return (ENOBUFS);
659 }
660 
661 static int
662 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
663 {
664 	int error = 0;
665 	u_long old_sb_max = sb_max;
666 
667 	error = SYSCTL_OUT(req, arg1, sizeof(int));
668 	if (error || !req->newptr)
669 		return (error);
670 	error = SYSCTL_IN(req, arg1, sizeof(int));
671 	if (error)
672 		return (error);
673 	if (sb_max < MSIZE + MCLBYTES) {
674 		sb_max = old_sb_max;
675 		return (EINVAL);
676 	}
677 	sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
678 	return (0);
679 }
680 
681 /*
682  * Allot mbufs to a signalsockbuf.
683  *
684  * Attempt to scale mbmax so that mbcnt doesn't become limiting
685  * if buffering efficiency is near the normal case.
686  *
687  * sb_max only applies to user-sockets (where rl != NULL).  It does
688  * not apply to kernel sockets or kernel-controlled sockets.  Note
689  * that NFS overrides the sockbuf limits created when nfsd creates
690  * a socket.
691  */
692 int
693 ssb_reserve(struct signalsockbuf *ssb, u_long cc, struct socket *so,
694 	    struct rlimit *rl)
695 {
696 	/*
697 	 * rl will only be NULL when we're in an interrupt (eg, in tcp_input)
698 	 * or when called from netgraph (ie, ngd_attach)
699 	 */
700 	if (rl && cc > sb_max_adj)
701 		cc = sb_max_adj;
702 	if (!chgsbsize(so->so_cred->cr_uidinfo, &ssb->ssb_hiwat, cc,
703 		       rl ? rl->rlim_cur : RLIM_INFINITY)) {
704 		return (0);
705 	}
706 	if (rl)
707 		ssb->ssb_mbmax = min(cc * sb_efficiency, sb_max);
708 	else
709 		ssb->ssb_mbmax = cc * sb_efficiency;
710 
711 	/*
712 	 * AUTOLOWAT is set on send buffers and prevents large writes
713 	 * from generating a huge number of context switches.
714 	 */
715 	if (ssb->ssb_flags & SSB_AUTOLOWAT) {
716 		ssb->ssb_lowat = ssb->ssb_hiwat / 4;
717 		if (ssb->ssb_lowat < MCLBYTES)
718 			ssb->ssb_lowat = MCLBYTES;
719 	}
720 	if (ssb->ssb_lowat > ssb->ssb_hiwat)
721 		ssb->ssb_lowat = ssb->ssb_hiwat;
722 	return (1);
723 }
724 
725 /*
726  * Free mbufs held by a socket, and reserved mbuf space.
727  */
728 void
729 ssb_release(struct signalsockbuf *ssb, struct socket *so)
730 {
731 	sbflush(&ssb->sb);
732 	(void)chgsbsize(so->so_cred->cr_uidinfo, &ssb->ssb_hiwat, 0,
733 	    RLIM_INFINITY);
734 	ssb->ssb_mbmax = 0;
735 }
736 
737 /*
738  * Some routines that return EOPNOTSUPP for entry points that are not
739  * supported by a protocol.  Fill in as needed.
740  */
741 void
742 pr_generic_notsupp(netmsg_t msg)
743 {
744 	lwkt_replymsg(&msg->lmsg, EOPNOTSUPP);
745 }
746 
747 int
748 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
749 	   struct mbuf *top, struct mbuf *control, int flags,
750 	   struct thread *td)
751 {
752 	if (top)
753 		m_freem(top);
754 	if (control)
755 		m_freem(control);
756 	return (EOPNOTSUPP);
757 }
758 
759 int
760 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
761 		      struct uio *uio, struct sockbuf *sio,
762 		      struct mbuf **controlp, int *flagsp)
763 {
764 	return (EOPNOTSUPP);
765 }
766 
767 /*
768  * This isn't really a ``null'' operation, but it's the default one
769  * and doesn't do anything destructive.
770  */
771 void
772 pru_sense_null(netmsg_t msg)
773 {
774 	msg->sense.nm_stat->st_blksize = msg->base.nm_so->so_snd.ssb_hiwat;
775 	lwkt_replymsg(&msg->lmsg, 0);
776 }
777 
778 /*
779  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.  Callers
780  * of this routine assume that it always succeeds, so we have to use a
781  * blockable allocation even though we might be called from a critical thread.
782  */
783 struct sockaddr *
784 dup_sockaddr(const struct sockaddr *sa)
785 {
786 	struct sockaddr *sa2;
787 
788 	sa2 = kmalloc(sa->sa_len, M_SONAME, M_INTWAIT);
789 	bcopy(sa, sa2, sa->sa_len);
790 	return (sa2);
791 }
792 
793 /*
794  * Create an external-format (``xsocket'') structure using the information
795  * in the kernel-format socket structure pointed to by so.  This is done
796  * to reduce the spew of irrelevant information over this interface,
797  * to isolate user code from changes in the kernel structure, and
798  * potentially to provide information-hiding if we decide that
799  * some of this information should be hidden from users.
800  */
801 void
802 sotoxsocket(struct socket *so, struct xsocket *xso)
803 {
804 	xso->xso_len = sizeof *xso;
805 	xso->xso_so = so;
806 	xso->so_type = so->so_type;
807 	xso->so_options = so->so_options;
808 	xso->so_linger = so->so_linger;
809 	xso->so_state = so->so_state;
810 	xso->so_pcb = so->so_pcb;
811 	xso->xso_protocol = so->so_proto->pr_protocol;
812 	xso->xso_family = so->so_proto->pr_domain->dom_family;
813 	xso->so_qlen = so->so_qlen;
814 	xso->so_incqlen = so->so_incqlen;
815 	xso->so_qlimit = so->so_qlimit;
816 	xso->so_timeo = so->so_timeo;
817 	xso->so_error = so->so_error;
818 	xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
819 	xso->so_oobmark = so->so_oobmark;
820 	ssbtoxsockbuf(&so->so_snd, &xso->so_snd);
821 	ssbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
822 	xso->so_uid = so->so_cred->cr_uid;
823 }
824 
825 /*
826  * Here is the definition of some of the basic objects in the kern.ipc
827  * branch of the MIB.
828  */
829 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
830 
831 /*
832  * This takes the place of kern.maxsockbuf, which moved to kern.ipc.
833  *
834  * NOTE! sb_max only applies to user-created socket buffers.
835  */
836 static int dummy;
837 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
838 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_INT|CTLFLAG_RW,
839     &sb_max, 0, sysctl_handle_sb_max, "I", "Maximum socket buffer size");
840 SYSCTL_INT(_kern_ipc, OID_AUTO, maxsockets, CTLFLAG_RD,
841     &maxsockets, 0, "Maximum number of sockets available");
842 SYSCTL_INT(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
843     &sb_efficiency, 0,
844     "Socket buffer limit scaler");
845 
846 /*
847  * Initialize maxsockets
848  */
849 static void
850 init_maxsockets(void *ignored)
851 {
852     TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
853     maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
854 }
855 SYSINIT(param, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
856 	init_maxsockets, NULL);
857 
858