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