Fix a critical bug in the IPI messaging code, effecting SMP systems. In
[dragonfly.git] / sys / kern / uipc_socket2.c
CommitLineData
984263bc 1/*
df80f2ea 2 * Copyright (c) 2005 Jeffrey M. Hsu. All rights reserved.
984263bc
MD
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 $
7b6f875f 36 * $DragonFly: src/sys/kern/uipc_socket2.c,v 1.21 2005/06/07 19:08:55 hsu Exp $
984263bc
MD
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/signalvar.h>
54#include <sys/sysctl.h>
55#include <sys/aio.h> /* for aio_swake proto */
56#include <sys/event.h>
57
c1d0003c
JH
58#include <sys/thread2.h>
59#include <sys/msgport2.h>
60
984263bc
MD
61int maxsockets;
62
63/*
64 * Primitive routines for operating on sockets and socket buffers
65 */
66
67u_long sb_max = SB_MAX;
68u_long sb_max_adj =
69 SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
70
71static u_long sb_efficiency = 8; /* parameter for sbreserve() */
72
73/*
74 * Procedures to manipulate state flags of socket
75 * and do appropriate wakeups. Normal sequence from the
76 * active (originating) side is that soisconnecting() is
77 * called during processing of connect() call,
78 * resulting in an eventual call to soisconnected() if/when the
79 * connection is established. When the connection is torn down
80 * soisdisconnecting() is called during processing of disconnect() call,
81 * and soisdisconnected() is called when the connection to the peer
82 * is totally severed. The semantics of these routines are such that
83 * connectionless protocols can call soisconnected() and soisdisconnected()
84 * only, bypassing the in-progress calls when setting up a ``connection''
85 * takes no time.
86 *
87 * From the passive side, a socket is created with
88 * two queues of sockets: so_incomp for connections in progress
89 * and so_comp for connections already made and awaiting user acceptance.
90 * As a protocol is preparing incoming connections, it creates a socket
91 * structure queued on so_incomp by calling sonewconn(). When the connection
92 * is established, soisconnected() is called, and transfers the
93 * socket structure to so_comp, making it available to accept().
94 *
95 * If a socket is closed with sockets on either
96 * so_incomp or so_comp, these sockets are dropped.
97 *
98 * If higher level protocols are implemented in
99 * the kernel, the wakeups done here will sometimes
100 * cause software-interrupt process scheduling.
101 */
102
103void
104soisconnecting(so)
1fd87d54 105 struct socket *so;
984263bc
MD
106{
107
108 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
109 so->so_state |= SS_ISCONNECTING;
110}
111
112void
113soisconnected(so)
114 struct socket *so;
115{
116 struct socket *head = so->so_head;
117
118 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
119 so->so_state |= SS_ISCONNECTED;
120 if (head && (so->so_state & SS_INCOMP)) {
121 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
122 so->so_upcall = head->so_accf->so_accept_filter->accf_callback;
123 so->so_upcallarg = head->so_accf->so_accept_filter_arg;
124 so->so_rcv.sb_flags |= SB_UPCALL;
125 so->so_options &= ~SO_ACCEPTFILTER;
126 so->so_upcall(so, so->so_upcallarg, 0);
127 return;
128 }
129 TAILQ_REMOVE(&head->so_incomp, so, so_list);
130 head->so_incqlen--;
131 so->so_state &= ~SS_INCOMP;
132 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
133 head->so_qlen++;
134 so->so_state |= SS_COMP;
135 sorwakeup(head);
136 wakeup_one(&head->so_timeo);
137 } else {
138 wakeup(&so->so_timeo);
139 sorwakeup(so);
140 sowwakeup(so);
141 }
142}
143
144void
145soisdisconnecting(so)
1fd87d54 146 struct socket *so;
984263bc
MD
147{
148
149 so->so_state &= ~SS_ISCONNECTING;
150 so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
151 wakeup((caddr_t)&so->so_timeo);
152 sowwakeup(so);
153 sorwakeup(so);
154}
155
156void
157soisdisconnected(so)
1fd87d54 158 struct socket *so;
984263bc
MD
159{
160
161 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
162 so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
163 wakeup((caddr_t)&so->so_timeo);
164 sbdrop(&so->so_snd, so->so_snd.sb_cc);
165 sowwakeup(so);
166 sorwakeup(so);
167}
168
169/*
170 * When an attempt at a new connection is noted on a socket
171 * which accepts connections, sonewconn is called. If the
172 * connection is possible (subject to space constraints, etc.)
173 * then we allocate a new structure, propoerly linked into the
174 * data structure of the original socket, and return this.
175 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
176 */
177struct socket *
dadab5e9 178sonewconn(struct socket *head, int connstatus)
984263bc 179{
1fd87d54 180 struct socket *so;
e4700d00 181 struct pru_attach_info ai;
984263bc
MD
182
183 if (head->so_qlen > 3 * head->so_qlimit / 2)
184 return ((struct socket *)0);
185 so = soalloc(0);
186 if (so == NULL)
187 return ((struct socket *)0);
188 if ((head->so_options & SO_ACCEPTFILTER) != 0)
189 connstatus = 0;
190 so->so_head = head;
191 so->so_type = head->so_type;
192 so->so_options = head->so_options &~ SO_ACCEPTCONN;
193 so->so_linger = head->so_linger;
194 so->so_state = head->so_state | SS_NOFDREF;
195 so->so_proto = head->so_proto;
196 so->so_timeo = head->so_timeo;
dadab5e9 197 so->so_cred = crhold(head->so_cred);
e4700d00
JH
198 ai.sb_rlimit = NULL;
199 ai.p_ucred = NULL;
200 ai.fd_rdir = NULL; /* jail code cruft XXX JH */
201 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat, NULL) ||
9eeaa8a9 202 /* Directly call function since we're already at protocol level. */
e4700d00 203 (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, &ai)) {
984263bc
MD
204 sodealloc(so);
205 return ((struct socket *)0);
206 }
207
208 if (connstatus) {
209 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
210 so->so_state |= SS_COMP;
211 head->so_qlen++;
212 } else {
213 if (head->so_incqlen > head->so_qlimit) {
214 struct socket *sp;
215 sp = TAILQ_FIRST(&head->so_incomp);
216 (void) soabort(sp);
217 }
218 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
219 so->so_state |= SS_INCOMP;
220 head->so_incqlen++;
221 }
222 if (connstatus) {
223 sorwakeup(head);
224 wakeup((caddr_t)&head->so_timeo);
225 so->so_state |= connstatus;
226 }
227 return (so);
228}
229
230/*
231 * Socantsendmore indicates that no more data will be sent on the
232 * socket; it would normally be applied to a socket when the user
233 * informs the system that no more data is to be sent, by the protocol
234 * code (in case PRU_SHUTDOWN). Socantrcvmore indicates that no more data
235 * will be received, and will normally be applied to the socket by a
236 * protocol when it detects that the peer will send no more data.
237 * Data queued for reading in the socket may yet be read.
238 */
239
240void
241socantsendmore(so)
242 struct socket *so;
243{
244
245 so->so_state |= SS_CANTSENDMORE;
246 sowwakeup(so);
247}
248
249void
250socantrcvmore(so)
251 struct socket *so;
252{
253
254 so->so_state |= SS_CANTRCVMORE;
255 sorwakeup(so);
256}
257
258/*
259 * Wait for data to arrive at/drain from a socket buffer.
260 */
261int
262sbwait(sb)
263 struct sockbuf *sb;
264{
265
266 sb->sb_flags |= SB_WAIT;
267 return (tsleep((caddr_t)&sb->sb_cc,
377d4740
MD
268 ((sb->sb_flags & SB_NOINTR) ? 0 : PCATCH),
269 "sbwait",
270 sb->sb_timeo));
984263bc
MD
271}
272
273/*
274 * Lock a sockbuf already known to be locked;
275 * return any error returned from sleep (EINTR).
276 */
277int
278sb_lock(sb)
1fd87d54 279 struct sockbuf *sb;
984263bc
MD
280{
281 int error;
282
283 while (sb->sb_flags & SB_LOCK) {
284 sb->sb_flags |= SB_WANT;
285 error = tsleep((caddr_t)&sb->sb_flags,
377d4740
MD
286 ((sb->sb_flags & SB_NOINTR) ? 0 : PCATCH),
287 "sblock", 0);
984263bc
MD
288 if (error)
289 return (error);
290 }
291 sb->sb_flags |= SB_LOCK;
292 return (0);
293}
294
295/*
b44419cb
MD
296 * Wakeup processes waiting on a socket buffer. Do asynchronous notification
297 * via SIGIO if the socket has the SS_ASYNC flag set.
984263bc
MD
298 */
299void
300sowakeup(so, sb)
1fd87d54
RG
301 struct socket *so;
302 struct sockbuf *sb;
984263bc 303{
c1d0003c
JH
304 struct selinfo *selinfo = &sb->sb_sel;
305
306 selwakeup(selinfo);
984263bc
MD
307 sb->sb_flags &= ~SB_SEL;
308 if (sb->sb_flags & SB_WAIT) {
309 sb->sb_flags &= ~SB_WAIT;
310 wakeup((caddr_t)&sb->sb_cc);
311 }
312 if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
313 pgsigio(so->so_sigio, SIGIO, 0);
314 if (sb->sb_flags & SB_UPCALL)
74f1caca 315 (*so->so_upcall)(so, so->so_upcallarg, MB_DONTWAIT);
984263bc
MD
316 if (sb->sb_flags & SB_AIO)
317 aio_swake(so, sb);
c1d0003c
JH
318 KNOTE(&selinfo->si_note, 0);
319 if (sb->sb_flags & SB_MEVENT) {
320 struct netmsg_so_notify *msg, *nmsg;
321
322 TAILQ_FOREACH_MUTABLE(msg, &selinfo->si_mlist, nm_list, nmsg) {
323 if (msg->nm_predicate((struct netmsg *)msg)) {
c1d0003c 324 TAILQ_REMOVE(&selinfo->si_mlist, msg, nm_list);
b44419cb
MD
325 lwkt_replymsg(&msg->nm_lmsg,
326 msg->nm_lmsg.ms_error);
c1d0003c
JH
327 }
328 }
c1d0003c
JH
329 if (TAILQ_EMPTY(&sb->sb_sel.si_mlist))
330 sb->sb_flags &= ~SB_MEVENT;
331 }
984263bc
MD
332}
333
334/*
335 * Socket buffer (struct sockbuf) utility routines.
336 *
337 * Each socket contains two socket buffers: one for sending data and
338 * one for receiving data. Each buffer contains a queue of mbufs,
339 * information about the number of mbufs and amount of data in the
340 * queue, and other fields allowing select() statements and notification
341 * on data availability to be implemented.
342 *
343 * Data stored in a socket buffer is maintained as a list of records.
344 * Each record is a list of mbufs chained together with the m_next
345 * field. Records are chained together with the m_nextpkt field. The upper
346 * level routine soreceive() expects the following conventions to be
347 * observed when placing information in the receive buffer:
348 *
349 * 1. If the protocol requires each message be preceded by the sender's
350 * name, then a record containing that name must be present before
351 * any associated data (mbuf's must be of type MT_SONAME).
352 * 2. If the protocol supports the exchange of ``access rights'' (really
353 * just additional data associated with the message), and there are
354 * ``rights'' to be received, then a record containing this data
355 * should be present (mbuf's must be of type MT_RIGHTS).
356 * 3. If a name or rights record exists, then it must be followed by
357 * a data record, perhaps of zero length.
358 *
359 * Before using a new socket structure it is first necessary to reserve
360 * buffer space to the socket, by calling sbreserve(). This should commit
361 * some of the available buffer space in the system buffer pool for the
362 * socket (currently, it does nothing but enforce limits). The space
363 * should be released by calling sbrelease() when the socket is destroyed.
364 */
365
366int
e4700d00 367soreserve(struct socket *so, u_long sndcc, u_long rcvcc, struct rlimit *rl)
984263bc 368{
e4700d00 369 if (sbreserve(&so->so_snd, sndcc, so, rl) == 0)
984263bc 370 goto bad;
e4700d00 371 if (sbreserve(&so->so_rcv, rcvcc, so, rl) == 0)
984263bc
MD
372 goto bad2;
373 if (so->so_rcv.sb_lowat == 0)
374 so->so_rcv.sb_lowat = 1;
375 if (so->so_snd.sb_lowat == 0)
376 so->so_snd.sb_lowat = MCLBYTES;
377 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
378 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
379 return (0);
380bad2:
381 sbrelease(&so->so_snd, so);
382bad:
383 return (ENOBUFS);
384}
385
386static int
387sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
388{
389 int error = 0;
390 u_long old_sb_max = sb_max;
391
392 error = SYSCTL_OUT(req, arg1, sizeof(int));
393 if (error || !req->newptr)
394 return (error);
395 error = SYSCTL_IN(req, arg1, sizeof(int));
396 if (error)
397 return (error);
398 if (sb_max < MSIZE + MCLBYTES) {
399 sb_max = old_sb_max;
400 return (EINVAL);
401 }
402 sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
403 return (0);
404}
405
406/*
407 * Allot mbufs to a sockbuf.
408 * Attempt to scale mbmax so that mbcnt doesn't become limiting
409 * if buffering efficiency is near the normal case.
410 */
411int
e4700d00 412sbreserve(struct sockbuf *sb, u_long cc, struct socket *so, struct rlimit *rl)
984263bc
MD
413{
414
415 /*
e4700d00
JH
416 * rl will only be NULL when we're in an interrupt (eg, in tcp_input)
417 * or when called from netgraph (ie, ngd_attach)
984263bc
MD
418 */
419 if (cc > sb_max_adj)
420 return (0);
421 if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
e4700d00 422 rl ? rl->rlim_cur : RLIM_INFINITY)) {
984263bc
MD
423 return (0);
424 }
425 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
426 if (sb->sb_lowat > sb->sb_hiwat)
427 sb->sb_lowat = sb->sb_hiwat;
428 return (1);
429}
430
431/*
432 * Free mbufs held by a socket, and reserved mbuf space.
433 */
434void
435sbrelease(sb, so)
436 struct sockbuf *sb;
437 struct socket *so;
438{
439
440 sbflush(sb);
441 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
442 RLIM_INFINITY);
443 sb->sb_mbmax = 0;
444}
445
446/*
447 * Routines to add and remove
448 * data from an mbuf queue.
449 *
450 * The routines sbappend() or sbappendrecord() are normally called to
451 * append new mbufs to a socket buffer, after checking that adequate
452 * space is available, comparing the function sbspace() with the amount
453 * of data to be added. sbappendrecord() differs from sbappend() in
454 * that data supplied is treated as the beginning of a new record.
455 * To place a sender's address, optional access rights, and data in a
456 * socket receive buffer, sbappendaddr() should be used. To place
457 * access rights and data in a socket receive buffer, sbappendrights()
458 * should be used. In either case, the new data begins a new record.
459 * Note that unlike sbappend() and sbappendrecord(), these routines check
460 * for the caller that there will be enough space to store the data.
461 * Each fails if there is not enough space, or if it cannot find mbufs
462 * to store additional information in.
463 *
464 * Reliable protocols may use the socket send buffer to hold data
465 * awaiting acknowledgement. Data is normally copied from a socket
466 * send buffer in a protocol with m_copy for output to a peer,
467 * and then removing the data from the socket buffer with sbdrop()
468 * or sbdroprecord() when the data is acknowledged by the peer.
469 */
470
471/*
472 * Append mbuf chain m to the last record in the
473 * socket buffer sb. The additional space associated
474 * the mbuf chain is recorded in sb. Empty mbufs are
475 * discarded and mbufs are compacted where possible.
476 */
477void
df80f2ea 478sbappend(struct sockbuf *sb, struct mbuf *m)
984263bc 479{
1fd87d54 480 struct mbuf *n;
984263bc 481
df80f2ea 482 if (m == NULL)
984263bc
MD
483 return;
484 n = sb->sb_mb;
485 if (n) {
2e17bcfa
JH
486 while (n->m_nextpkt)
487 n = n->m_nextpkt;
984263bc
MD
488 do {
489 if (n->m_flags & M_EOR) {
490 sbappendrecord(sb, m); /* XXXXXX!!!! */
491 return;
492 }
493 } while (n->m_next && (n = n->m_next));
494 }
495 sbcompress(sb, m, n);
df80f2ea 496 if (n == NULL)
bf8a9a6f 497 sb->sb_lastrecord = sb->sb_mb;
984263bc
MD
498}
499
507106e0
JH
500/*
501 * sbappendstream() is an optimized form of sbappend() for protocols
502 * such as TCP that only have one record in the socket buffer, are
bf8a9a6f
JH
503 * not PR_ATOMIC, nor allow MT_CONTROL data. A protocol that uses
504 * sbappendstream() must use sbappendstream() exclusively.
507106e0
JH
505 */
506void
507sbappendstream(struct sockbuf *sb, struct mbuf *m)
508{
509 KKASSERT(m->m_nextpkt == NULL);
510 sbcompress(sb, m, sb->sb_lastmbuf);
511}
512
984263bc
MD
513#ifdef SOCKBUF_DEBUG
514void
515sbcheck(sb)
1fd87d54 516 struct sockbuf *sb;
984263bc 517{
1fd87d54
RG
518 struct mbuf *m;
519 struct mbuf *n = 0;
520 u_long len = 0, mbcnt = 0;
984263bc
MD
521
522 for (m = sb->sb_mb; m; m = n) {
523 n = m->m_nextpkt;
524 for (; m; m = m->m_next) {
525 len += m->m_len;
526 mbcnt += MSIZE;
527 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
528 mbcnt += m->m_ext.ext_size;
529 }
530 }
531 if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
532 printf("cc %ld != %ld || mbcnt %ld != %ld\n", len, sb->sb_cc,
533 mbcnt, sb->sb_mbcnt);
534 panic("sbcheck");
535 }
536}
537#endif
538
539/*
df80f2ea 540 * Same as sbappend(), except the mbuf chain begins a new record.
984263bc
MD
541 */
542void
df80f2ea 543sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
984263bc 544{
df80f2ea
JH
545 struct mbuf *firstmbuf;
546 struct mbuf *secondmbuf;
984263bc 547
df80f2ea 548 if (m0 == NULL)
984263bc 549 return;
bf8a9a6f 550
984263bc 551 /*
df80f2ea 552 * Break the first mbuf off from the rest of the mbuf chain.
984263bc 553 */
df80f2ea
JH
554 firstmbuf = m0;
555 secondmbuf = m0->m_next;
556 m0->m_next = NULL;
557
558 /*
559 * Insert the first mbuf of the m0 mbuf chain as the last record of
560 * the sockbuf. Note this permits zero length records!
561 */
562 if (sb->sb_mb == NULL)
563 sb->sb_mb = firstmbuf;
984263bc 564 else
df80f2ea
JH
565 sb->sb_lastrecord->m_nextpkt = firstmbuf;
566 sb->sb_lastrecord = firstmbuf; /* update hint for new last record */
bf8a9a6f 567
df80f2ea
JH
568 if ((firstmbuf->m_flags & M_EOR) && (secondmbuf != NULL)) {
569 /* propagate the EOR flag */
570 firstmbuf->m_flags &= ~M_EOR;
571 secondmbuf->m_flags |= M_EOR;
984263bc 572 }
df80f2ea
JH
573
574 /*
575 * The succeeding call to sbcompress() omits accounting for
576 * the first mbuf, so do it here.
577 */
578 sballoc(sb, firstmbuf);
579
580 /* Compact the rest of the mbuf chain in after the first mbuf. */
581 sbcompress(sb, secondmbuf, firstmbuf);
984263bc
MD
582}
583
584/*
df80f2ea 585 * As above except that OOB data is inserted at the beginning of the sockbuf,
984263bc
MD
586 * but after any other OOB data.
587 */
588void
df80f2ea 589sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
984263bc 590{
1fd87d54
RG
591 struct mbuf *m;
592 struct mbuf **mp;
984263bc
MD
593
594 if (m0 == 0)
595 return;
596 for (mp = &sb->sb_mb; *mp ; mp = &((*mp)->m_nextpkt)) {
597 m = *mp;
598 again:
599 switch (m->m_type) {
600
601 case MT_OOBDATA:
602 continue; /* WANT next train */
603
604 case MT_CONTROL:
605 m = m->m_next;
606 if (m)
607 goto again; /* inspect THIS train further */
608 }
609 break;
610 }
611 /*
612 * Put the first mbuf on the queue.
613 * Note this permits zero length records.
614 */
615 sballoc(sb, m0);
616 m0->m_nextpkt = *mp;
617 *mp = m0;
bf8a9a6f
JH
618 if (m0->m_nextpkt == NULL)
619 sb->sb_lastrecord = m0;
620
984263bc
MD
621 m = m0->m_next;
622 m0->m_next = 0;
623 if (m && (m0->m_flags & M_EOR)) {
624 m0->m_flags &= ~M_EOR;
625 m->m_flags |= M_EOR;
626 }
627 sbcompress(sb, m, m0);
628}
629
630/*
631 * Append address and data, and optionally, control (ancillary) data
632 * to the receive queue of a socket. If present,
633 * m0 must include a packet header with total length.
634 * Returns 0 if no space in sockbuf or insufficient mbufs.
635 */
636int
637sbappendaddr(sb, asa, m0, control)
1fd87d54 638 struct sockbuf *sb;
590b8cd4 639 const struct sockaddr *asa;
984263bc
MD
640 struct mbuf *m0, *control;
641{
1fd87d54 642 struct mbuf *m, *n;
984263bc
MD
643 int space = asa->sa_len;
644
a8a35116
HP
645 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
646 panic("sbappendaddr");
647
984263bc
MD
648 if (m0)
649 space += m0->m_pkthdr.len;
650 for (n = control; n; n = n->m_next) {
651 space += n->m_len;
652 if (n->m_next == 0) /* keep pointer to last control buf */
653 break;
654 }
655 if (space > sbspace(sb))
656 return (0);
657 if (asa->sa_len > MLEN)
658 return (0);
74f1caca 659 MGET(m, MB_DONTWAIT, MT_SONAME);
984263bc
MD
660 if (m == 0)
661 return (0);
662 m->m_len = asa->sa_len;
590b8cd4 663 bcopy(asa, mtod(m, caddr_t), asa->sa_len);
984263bc
MD
664 if (n)
665 n->m_next = m0; /* concatenate data to control */
666 else
667 control = m0;
668 m->m_next = control;
669 for (n = m; n; n = n->m_next)
670 sballoc(sb, n);
bf8a9a6f 671
df80f2ea 672 if (sb->sb_mb == NULL)
984263bc 673 sb->sb_mb = m;
df80f2ea
JH
674 else
675 sb->sb_lastrecord->m_nextpkt = m;
bf8a9a6f
JH
676 sb->sb_lastrecord = m;
677
984263bc
MD
678 return (1);
679}
680
df80f2ea
JH
681/*
682 * Append control information followed by data.
683 * control must be non-null.
684 */
984263bc 685int
df80f2ea 686sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
984263bc 687{
df80f2ea
JH
688 struct mbuf *n;
689 u_int length, cmbcnt, m0mbcnt;
984263bc 690
df80f2ea
JH
691 KASSERT(control != NULL, ("sbappendcontrol"));
692
693 length = m_countm(control, &n, &cmbcnt) + m_countm(m0, NULL, &m0mbcnt);
694 if (length > sbspace(sb))
984263bc 695 return (0);
df80f2ea 696
984263bc 697 n->m_next = m0; /* concatenate data to control */
bf8a9a6f 698
df80f2ea 699 if (sb->sb_mb == NULL)
984263bc 700 sb->sb_mb = control;
df80f2ea
JH
701 else
702 sb->sb_lastrecord->m_nextpkt = control;
bf8a9a6f
JH
703 sb->sb_lastrecord = control;
704
df80f2ea
JH
705 sb->sb_cc += length;
706 sb->sb_mbcnt += cmbcnt + m0mbcnt;
707
984263bc
MD
708 return (1);
709}
710
711/*
df80f2ea
JH
712 * Compress mbuf chain m into the socket buffer sb following mbuf tailm.
713 * If tailm is null, the buffer is presumed empty. Also, as a side-effect,
714 * increment the sockbuf counts for each mbuf in the chain.
984263bc
MD
715 */
716void
df80f2ea 717sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *tailm)
984263bc 718{
1fd87d54 719 int eor = 0;
984263bc
MD
720
721 while (m) {
df80f2ea
JH
722 struct mbuf *o;
723
984263bc 724 eor |= m->m_flags & M_EOR;
df80f2ea
JH
725 /*
726 * Disregard empty mbufs as long as we don't encounter
727 * an end-of-record or there is a trailing mbuf of
728 * the same type to propagate the EOR flag to.
729 */
984263bc
MD
730 if (m->m_len == 0 &&
731 (eor == 0 ||
df80f2ea 732 (((o = m->m_next) || (o = tailm)) &&
984263bc
MD
733 o->m_type == m->m_type))) {
734 m = m_free(m);
735 continue;
736 }
df80f2ea
JH
737
738 /* See if we can coalesce with preceding mbuf. */
739 if (tailm && !(tailm->m_flags & M_EOR) && M_WRITABLE(tailm) &&
984263bc 740 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
df80f2ea
JH
741 m->m_len <= M_TRAILINGSPACE(tailm) &&
742 tailm->m_type == m->m_type) {
743 bcopy(mtod(m, caddr_t),
744 mtod(tailm, caddr_t) + tailm->m_len,
745 (unsigned)m->m_len);
746 tailm->m_len += m->m_len;
747 sb->sb_cc += m->m_len; /* update sb counter */
984263bc
MD
748 m = m_free(m);
749 continue;
750 }
df80f2ea
JH
751
752 /* Insert whole mbuf. */
753 if (tailm == NULL) {
754 KASSERT(sb->sb_mb == NULL,
755 ("sbcompress: sb_mb not NULL"));
756 sb->sb_mb = m; /* put at front of sockbuf */
757 } else {
758 tailm->m_next = m; /* tack m on following tailm */
759 }
760 sb->sb_lastmbuf = m; /* update last mbuf hint */
761
762 tailm = m; /* just inserted mbuf becomes the new tail */
763 m = m->m_next; /* advance to next mbuf */
764 tailm->m_next = NULL; /* split inserted mbuf off from chain */
765
766 /* update sb counters for just added mbuf */
767 sballoc(sb, tailm);
768
769 /* clear EOR on intermediate mbufs */
770 tailm->m_flags &= ~M_EOR;
984263bc 771 }
df80f2ea 772
984263bc 773 if (eor) {
df80f2ea
JH
774 if (tailm)
775 tailm->m_flags |= eor; /* propagate EOR to last mbuf */
984263bc 776 else
fc92d4aa 777 printf("semi-panic: sbcompress");
984263bc
MD
778 }
779}
780
781/*
782 * Free all mbufs in a sockbuf.
783 * Check that all resources are reclaimed.
784 */
785void
786sbflush(sb)
1fd87d54 787 struct sockbuf *sb;
984263bc
MD
788{
789
790 if (sb->sb_flags & SB_LOCK)
791 panic("sbflush: locked");
792 while (sb->sb_mbcnt) {
793 /*
794 * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
795 * we would loop forever. Panic instead.
796 */
797 if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
798 break;
799 sbdrop(sb, (int)sb->sb_cc);
800 }
507106e0 801 KASSERT(!(sb->sb_cc || sb->sb_mb || sb->sb_mbcnt || sb->sb_lastmbuf),
bf8a9a6f 802 ("sbflush: cc %ld || mb %p || mbcnt %ld || lastmbuf %p",
507106e0 803 sb->sb_cc, sb->sb_mb, sb->sb_mbcnt, sb->sb_lastmbuf));
984263bc
MD
804}
805
806/*
807 * Drop data from (the front of) a sockbuf.
808 */
809void
810sbdrop(sb, len)
1fd87d54
RG
811 struct sockbuf *sb;
812 int len;
984263bc 813{
1fd87d54 814 struct mbuf *m;
6c6ee982 815 struct mbuf *nextpkt;
984263bc 816
6c6ee982
JH
817 m = sb->sb_mb;
818 nextpkt = (m != NULL) ? m->m_nextpkt : NULL;
984263bc 819 while (len > 0) {
6c6ee982
JH
820 if (m == NULL) {
821 if (nextpkt == NULL)
984263bc 822 panic("sbdrop");
6c6ee982
JH
823 m = nextpkt;
824 nextpkt = m->m_nextpkt;
825 m->m_nextpkt = NULL;
984263bc
MD
826 continue;
827 }
828 if (m->m_len > len) {
829 m->m_len -= len;
830 m->m_data += len;
831 sb->sb_cc -= len;
832 break;
833 }
834 len -= m->m_len;
835 sbfree(sb, m);
836 m = m_free(m);
837 }
838 while (m && m->m_len == 0) {
839 sbfree(sb, m);
840 m = m_free(m);
841 }
6c6ee982 842 if (m != NULL) {
984263bc 843 sb->sb_mb = m;
6c6ee982 844 m->m_nextpkt = nextpkt;
507106e0 845 } else {
6c6ee982
JH
846 sb->sb_mb = nextpkt;
847 sb->sb_lastmbuf = NULL; /* invalidate hint */
507106e0 848 }
984263bc
MD
849}
850
851/*
852 * Drop a record off the front of a sockbuf
853 * and move the next record to the front.
854 */
855void
856sbdroprecord(sb)
1fd87d54 857 struct sockbuf *sb;
984263bc 858{
1fd87d54 859 struct mbuf *m;
984263bc
MD
860
861 m = sb->sb_mb;
862 if (m) {
863 sb->sb_mb = m->m_nextpkt;
7b6f875f 864 m->m_nextpkt = NULL;
984263bc
MD
865 do {
866 sbfree(sb, m);
867 m = m_free(m);
868 } while (m);
869 }
870}
871
872/*
873 * Create a "control" mbuf containing the specified data
874 * with the specified type for presentation on a socket buffer.
875 */
876struct mbuf *
877sbcreatecontrol(p, size, type, level)
878 caddr_t p;
1fd87d54 879 int size;
984263bc
MD
880 int type, level;
881{
1fd87d54 882 struct cmsghdr *cp;
984263bc
MD
883 struct mbuf *m;
884
885 if (CMSG_SPACE((u_int)size) > MCLBYTES)
50503f0f
JH
886 return (NULL);
887 m = m_getl(CMSG_SPACE((u_int)size), MB_DONTWAIT, MT_CONTROL, 0, NULL);
888 if (m == NULL)
889 return (NULL);
890 m->m_len = CMSG_SPACE(size);
984263bc 891 cp = mtod(m, struct cmsghdr *);
984263bc 892 if (p != NULL)
50503f0f 893 memcpy(CMSG_DATA(cp), p, size);
984263bc
MD
894 cp->cmsg_len = CMSG_LEN(size);
895 cp->cmsg_level = level;
896 cp->cmsg_type = type;
897 return (m);
898}
899
900/*
901 * Some routines that return EOPNOTSUPP for entry points that are not
902 * supported by a protocol. Fill in as needed.
903 */
904int
905pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
906{
907 return EOPNOTSUPP;
908}
909
910int
dadab5e9 911pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
984263bc
MD
912{
913 return EOPNOTSUPP;
914}
915
916int
917pru_connect2_notsupp(struct socket *so1, struct socket *so2)
918{
919 return EOPNOTSUPP;
920}
921
922int
923pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
dadab5e9 924 struct ifnet *ifp, struct thread *td)
984263bc
MD
925{
926 return EOPNOTSUPP;
927}
928
929int
dadab5e9 930pru_listen_notsupp(struct socket *so, struct thread *td)
984263bc
MD
931{
932 return EOPNOTSUPP;
933}
934
935int
936pru_rcvd_notsupp(struct socket *so, int flags)
937{
938 return EOPNOTSUPP;
939}
940
941int
942pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
943{
944 return EOPNOTSUPP;
945}
946
947/*
948 * This isn't really a ``null'' operation, but it's the default one
949 * and doesn't do anything destructive.
950 */
951int
952pru_sense_null(struct socket *so, struct stat *sb)
953{
954 sb->st_blksize = so->so_snd.sb_hiwat;
955 return 0;
956}
957
958/*
cfa2ba21
MD
959 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME. Callers
960 * of this routine assume that it always succeeds, so we have to use a
961 * blockable allocation even though we might be called from a critical thread.
984263bc
MD
962 */
963struct sockaddr *
590b8cd4 964dup_sockaddr(const struct sockaddr *sa)
984263bc
MD
965{
966 struct sockaddr *sa2;
967
cfa2ba21
MD
968 sa2 = malloc(sa->sa_len, M_SONAME, M_INTWAIT);
969 bcopy(sa, sa2, sa->sa_len);
970 return (sa2);
984263bc
MD
971}
972
973/*
974 * Create an external-format (``xsocket'') structure using the information
975 * in the kernel-format socket structure pointed to by so. This is done
976 * to reduce the spew of irrelevant information over this interface,
977 * to isolate user code from changes in the kernel structure, and
978 * potentially to provide information-hiding if we decide that
979 * some of this information should be hidden from users.
980 */
981void
982sotoxsocket(struct socket *so, struct xsocket *xso)
983{
984 xso->xso_len = sizeof *xso;
985 xso->xso_so = so;
986 xso->so_type = so->so_type;
987 xso->so_options = so->so_options;
988 xso->so_linger = so->so_linger;
989 xso->so_state = so->so_state;
990 xso->so_pcb = so->so_pcb;
991 xso->xso_protocol = so->so_proto->pr_protocol;
992 xso->xso_family = so->so_proto->pr_domain->dom_family;
993 xso->so_qlen = so->so_qlen;
994 xso->so_incqlen = so->so_incqlen;
995 xso->so_qlimit = so->so_qlimit;
996 xso->so_timeo = so->so_timeo;
997 xso->so_error = so->so_error;
998 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
999 xso->so_oobmark = so->so_oobmark;
1000 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
1001 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
1002 xso->so_uid = so->so_cred->cr_uid;
1003}
1004
1005/*
1006 * This does the same for sockbufs. Note that the xsockbuf structure,
1007 * since it is always embedded in a socket, does not include a self
1008 * pointer nor a length. We make this entry point public in case
1009 * some other mechanism needs it.
1010 */
1011void
1012sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1013{
1014 xsb->sb_cc = sb->sb_cc;
1015 xsb->sb_hiwat = sb->sb_hiwat;
1016 xsb->sb_mbcnt = sb->sb_mbcnt;
1017 xsb->sb_mbmax = sb->sb_mbmax;
1018 xsb->sb_lowat = sb->sb_lowat;
1019 xsb->sb_flags = sb->sb_flags;
1020 xsb->sb_timeo = sb->sb_timeo;
1021}
1022
1023/*
1024 * Here is the definition of some of the basic objects in the kern.ipc
1025 * branch of the MIB.
1026 */
1027SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
1028
1029/* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1030static int dummy;
1031SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
1032SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_INT|CTLFLAG_RW,
1033 &sb_max, 0, sysctl_handle_sb_max, "I", "Maximum socket buffer size");
1034SYSCTL_INT(_kern_ipc, OID_AUTO, maxsockets, CTLFLAG_RD,
1035 &maxsockets, 0, "Maximum number of sockets avaliable");
1036SYSCTL_INT(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1037 &sb_efficiency, 0, "");
1038
1039/*
1040 * Initialise maxsockets
1041 */
1042static void init_maxsockets(void *ignored)
1043{
1044 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
1045 maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
1046}
1047SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);