1 //==========================================================================
3 // src/sys/kern/uipc_socket2.c
5 //==========================================================================
6 //####BSDCOPYRIGHTBEGIN####
8 // -------------------------------------------
10 // Portions of this software may have been derived from OpenBSD,
11 // FreeBSD or other sources, and are covered by the appropriate
12 // copyright disclaimers included herein.
14 // Portions created by Red Hat are
15 // Copyright (C) 2002 Red Hat, Inc. All Rights Reserved.
17 // -------------------------------------------
19 //####BSDCOPYRIGHTEND####
20 //==========================================================================
23 * Copyright (c) 1982, 1986, 1988, 1990, 1993
24 * The Regents of the University of California. All rights reserved.
26 * Redistribution and use in source and binary forms, with or without
27 * modification, are permitted provided that the following conditions
29 * 1. Redistributions of source code must retain the above copyright
30 * notice, this list of conditions and the following disclaimer.
31 * 2. Redistributions in binary form must reproduce the above copyright
32 * notice, this list of conditions and the following disclaimer in the
33 * documentation and/or other materials provided with the distribution.
34 * 3. All advertising materials mentioning features or use of this software
35 * must display the following acknowledgement:
36 * This product includes software developed by the University of
37 * California, Berkeley and its contributors.
38 * 4. Neither the name of the University nor the names of its contributors
39 * may be used to endorse or promote products derived from this software
40 * without specific prior written permission.
42 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * @(#)uipc_socket2.c 8.1 (Berkeley) 6/10/93
55 * $FreeBSD: src/sys/kern/uipc_socket2.c,v 1.55.2.9 2001/07/26 18:53:02 peter Exp $
58 #include <sys/param.h>
59 #include <sys/domain.h>
60 #include <sys/malloc.h>
62 #include <sys/protosw.h>
63 #include <sys/socket.h>
64 #include <sys/socketvar.h>
66 #include <cyg/io/file.h>
69 int maxsockets = CYGPKG_NET_MAXSOCKETS;
72 * Primitive routines for operating on sockets and socket buffers
75 u_long sb_max = SB_MAX; /* XXX should be static */
77 static u_long sb_efficiency = 8; /* parameter for sbreserve() */
80 * Procedures to manipulate state flags of socket
81 * and do appropriate wakeups. Normal sequence from the
82 * active (originating) side is that soisconnecting() is
83 * called during processing of connect() call,
84 * resulting in an eventual call to soisconnected() if/when the
85 * connection is established. When the connection is torn down
86 * soisdisconnecting() is called during processing of disconnect() call,
87 * and soisdisconnected() is called when the connection to the peer
88 * is totally severed. The semantics of these routines are such that
89 * connectionless protocols can call soisconnected() and soisdisconnected()
90 * only, bypassing the in-progress calls when setting up a ``connection''
93 * From the passive side, a socket is created with
94 * two queues of sockets: so_incomp for connections in progress
95 * and so_comp for connections already made and awaiting user acceptance.
96 * As a protocol is preparing incoming connections, it creates a socket
97 * structure queued on so_incomp by calling sonewconn(). When the connection
98 * is established, soisconnected() is called, and transfers the
99 * socket structure to so_comp, making it available to accept().
101 * If a socket is closed with sockets on either
102 * so_incomp or so_comp, these sockets are dropped.
104 * If higher level protocols are implemented in
105 * the kernel, the wakeups done here will sometimes
106 * cause software-interrupt process scheduling.
111 register struct socket *so;
114 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
115 so->so_state |= SS_ISCONNECTING;
122 struct socket *head = so->so_head;
124 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
125 so->so_state |= SS_ISCONNECTED;
126 if (head && (so->so_state & SS_INCOMP)) {
127 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
128 so->so_upcall = head->so_accf->so_accept_filter->accf_callback;
129 so->so_upcallarg = head->so_accf->so_accept_filter_arg;
130 so->so_rcv.sb_flags |= SB_UPCALL;
131 so->so_options &= ~SO_ACCEPTFILTER;
132 so->so_upcall(so, so->so_upcallarg, 0);
135 TAILQ_REMOVE(&head->so_incomp, so, so_list);
137 so->so_state &= ~SS_INCOMP;
138 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
139 so->so_state |= SS_COMP;
141 wakeup_one(&head->so_timeo);
143 wakeup(&so->so_timeo);
150 soisdisconnecting(so)
151 register struct socket *so;
154 so->so_state &= ~SS_ISCONNECTING;
155 so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
156 wakeup((caddr_t)&so->so_timeo);
163 register struct socket *so;
166 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
167 so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
168 wakeup((caddr_t)&so->so_timeo);
174 * Return a random connection that hasn't been serviced yet and
175 * is eligible for discard. There is a one in qlen chance that
176 * we will return a null, saying that there are no dropable
177 * requests. In this case, the protocol specific code should drop
178 * the new request. This insures fairness.
180 * This may be used in conjunction with protocol specific queue
181 * congestion routines.
185 register struct socket *head;
187 register struct socket *so;
188 unsigned int i, j, qlen;
190 static struct timeval old_runtime;
191 static unsigned int cur_cnt, old_cnt;
195 if ((i = (tv.tv_sec - old_runtime.tv_sec)) != 0) {
197 old_cnt = cur_cnt / i;
201 so = TAILQ_FIRST(&head->so_incomp);
205 qlen = head->so_incqlen;
206 if (++cur_cnt > qlen || old_cnt > qlen) {
207 rnd = (314159 * rnd + 66329) & 0xffff;
208 j = ((qlen + 1) * rnd) >> 16;
211 so = TAILQ_NEXT(so, so_list);
218 * When an attempt at a new connection is noted on a socket
219 * which accepts connections, sonewconn is called. If the
220 * connection is possible (subject to space constraints, etc.)
221 * then we allocate a new structure, propoerly linked into the
222 * data structure of the original socket, and return this.
223 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
226 sonewconn(head, connstatus)
227 register struct socket *head;
231 return (sonewconn3(head, connstatus, NULL));
235 sonewconn3(head, connstatus, p)
236 register struct socket *head;
240 register struct socket *so;
242 if (head->so_qlen > 3 * head->so_qlimit / 2)
243 return ((struct socket *)0);
246 return ((struct socket *)0);
248 so->so_type = head->so_type;
249 so->so_options = head->so_options &~ SO_ACCEPTCONN;
250 so->so_linger = head->so_linger;
251 so->so_state = head->so_state | SS_NOFDREF;
252 so->so_proto = head->so_proto;
253 so->so_timeo = head->so_timeo;
254 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
255 (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
257 return ((struct socket *)0);
261 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
262 so->so_state |= SS_COMP;
264 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
265 so->so_state |= SS_INCOMP;
271 wakeup((caddr_t)&head->so_timeo);
272 so->so_state |= connstatus;
278 * Socantsendmore indicates that no more data will be sent on the
279 * socket; it would normally be applied to a socket when the user
280 * informs the system that no more data is to be sent, by the protocol
281 * code (in case PRU_SHUTDOWN). Socantrcvmore indicates that no more data
282 * will be received, and will normally be applied to the socket by a
283 * protocol when it detects that the peer will send no more data.
284 * Data queued for reading in the socket may yet be read.
292 so->so_state |= SS_CANTSENDMORE;
301 so->so_state |= SS_CANTRCVMORE;
306 * Wait for data to arrive at/drain from a socket buffer.
313 sb->sb_flags |= SB_WAIT;
314 return (tsleep((caddr_t)&sb->sb_cc,
315 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
320 * Lock a sockbuf already known to be locked;
321 * return any error returned from sleep (EINTR).
325 register struct sockbuf *sb;
329 while (sb->sb_flags & SB_LOCK) {
330 sb->sb_flags |= SB_WANT;
331 error = tsleep((caddr_t)&sb->sb_flags,
332 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK|PCATCH,
337 sb->sb_flags |= SB_LOCK;
342 * Wakeup processes waiting on a socket buffer.
343 * Do asynchronous notification via SIGIO
344 * if the socket has the SS_ASYNC flag set.
348 register struct socket *so;
349 register struct sockbuf *sb;
351 selwakeup(&sb->sb_sel);
352 sb->sb_flags &= ~SB_SEL;
353 if (sb->sb_flags & SB_WAIT) {
354 sb->sb_flags &= ~SB_WAIT;
355 wakeup((caddr_t)&sb->sb_cc);
357 if (sb->sb_flags & SB_UPCALL)
358 (*so->so_upcall)(so, so->so_upcallarg, M_DONTWAIT);
362 * Socket buffer (struct sockbuf) utility routines.
364 * Each socket contains two socket buffers: one for sending data and
365 * one for receiving data. Each buffer contains a queue of mbufs,
366 * information about the number of mbufs and amount of data in the
367 * queue, and other fields allowing select() statements and notification
368 * on data availability to be implemented.
370 * Data stored in a socket buffer is maintained as a list of records.
371 * Each record is a list of mbufs chained together with the m_next
372 * field. Records are chained together with the m_nextpkt field. The upper
373 * level routine soreceive() expects the following conventions to be
374 * observed when placing information in the receive buffer:
376 * 1. If the protocol requires each message be preceded by the sender's
377 * name, then a record containing that name must be present before
378 * any associated data (mbuf's must be of type MT_SONAME).
379 * 2. If the protocol supports the exchange of ``access rights'' (really
380 * just additional data associated with the message), and there are
381 * ``rights'' to be received, then a record containing this data
382 * should be present (mbuf's must be of type MT_RIGHTS).
383 * 3. If a name or rights record exists, then it must be followed by
384 * a data record, perhaps of zero length.
386 * Before using a new socket structure it is first necessary to reserve
387 * buffer space to the socket, by calling sbreserve(). This should commit
388 * some of the available buffer space in the system buffer pool for the
389 * socket (currently, it does nothing but enforce limits). The space
390 * should be released by calling sbrelease() when the socket is destroyed.
394 soreserve(so, sndcc, rcvcc)
395 register struct socket *so;
398 struct proc *p = curproc;
400 if (sbreserve(&so->so_snd, sndcc, so, p) == 0)
402 if (sbreserve(&so->so_rcv, rcvcc, so, p) == 0)
404 if (so->so_rcv.sb_lowat == 0)
405 so->so_rcv.sb_lowat = 1;
406 if (so->so_snd.sb_lowat == 0)
407 so->so_snd.sb_lowat = MCLBYTES;
408 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
409 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
412 sbrelease(&so->so_snd, so);
418 * Allot mbufs to a sockbuf.
419 * Attempt to scale mbmax so that mbcnt doesn't become limiting
420 * if buffering efficiency is near the normal case.
423 sbreserve(sb, cc, so, p)
431 * p will only be NULL when we're in an interrupt
432 * (e.g. in tcp_input())
434 if ((u_quad_t)cc > (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES))
437 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
438 if (sb->sb_lowat > sb->sb_hiwat)
439 sb->sb_lowat = sb->sb_hiwat;
444 * Free mbufs held by a socket, and reserved mbuf space.
457 * Routines to add and remove
458 * data from an mbuf queue.
460 * The routines sbappend() or sbappendrecord() are normally called to
461 * append new mbufs to a socket buffer, after checking that adequate
462 * space is available, comparing the function sbspace() with the amount
463 * of data to be added. sbappendrecord() differs from sbappend() in
464 * that data supplied is treated as the beginning of a new record.
465 * To place a sender's address, optional access rights, and data in a
466 * socket receive buffer, sbappendaddr() should be used. To place
467 * access rights and data in a socket receive buffer, sbappendrights()
468 * should be used. In either case, the new data begins a new record.
469 * Note that unlike sbappend() and sbappendrecord(), these routines check
470 * for the caller that there will be enough space to store the data.
471 * Each fails if there is not enough space, or if it cannot find mbufs
472 * to store additional information in.
474 * Reliable protocols may use the socket send buffer to hold data
475 * awaiting acknowledgement. Data is normally copied from a socket
476 * send buffer in a protocol with m_copy for output to a peer,
477 * and then removing the data from the socket buffer with sbdrop()
478 * or sbdroprecord() when the data is acknowledged by the peer.
482 * Append mbuf chain m to the last record in the
483 * socket buffer sb. The additional space associated
484 * the mbuf chain is recorded in sb. Empty mbufs are
485 * discarded and mbufs are compacted where possible.
492 register struct mbuf *n;
501 if (n->m_flags & M_EOR) {
502 sbappendrecord(sb, m); /* XXXXXX!!!! */
505 } while (n->m_next && (n = n->m_next));
507 sbcompress(sb, m, n);
513 register struct sockbuf *sb;
515 register struct mbuf *m;
516 register struct mbuf *n = 0;
517 register u_long len = 0, mbcnt = 0;
519 for (m = sb->sb_mb; m; m = n) {
521 for (; m; m = m->m_next) {
524 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
525 mbcnt += m->m_ext.ext_size;
528 if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
529 printf("cc %ld != %ld || mbcnt %ld != %ld\n", len, sb->sb_cc,
530 mbcnt, sb->sb_mbcnt);
537 * As above, except the mbuf chain
538 * begins a new record.
541 sbappendrecord(sb, m0)
542 register struct sockbuf *sb;
543 register struct mbuf *m0;
545 register struct mbuf *m;
554 * Put the first mbuf on the queue.
555 * Note this permits zero length records.
564 if (m && (m0->m_flags & M_EOR)) {
565 m0->m_flags &= ~M_EOR;
568 sbcompress(sb, m, m0);
572 * As above except that OOB data
573 * is inserted at the beginning of the sockbuf,
574 * but after any other OOB data.
578 register struct sockbuf *sb;
579 register struct mbuf *m0;
581 register struct mbuf *m;
582 register struct mbuf **mp;
586 for (mp = &sb->sb_mb; *mp ; mp = &((*mp)->m_nextpkt)) {
592 continue; /* WANT next train */
597 goto again; /* inspect THIS train further */
602 * Put the first mbuf on the queue.
603 * Note this permits zero length records.
610 if (m && (m0->m_flags & M_EOR)) {
611 m0->m_flags &= ~M_EOR;
614 sbcompress(sb, m, m0);
618 * Append address and data, and optionally, control (ancillary) data
619 * to the receive queue of a socket. If present,
620 * m0 must include a packet header with total length.
621 * Returns 0 if no space in sockbuf or insufficient mbufs.
624 sbappendaddr(sb, asa, m0, control)
625 register struct sockbuf *sb;
626 struct sockaddr *asa;
627 struct mbuf *m0, *control;
629 register struct mbuf *m, *n;
630 int space = asa->sa_len;
632 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
633 panic("sbappendaddr");
635 space += m0->m_pkthdr.len;
636 for (n = control; n; n = n->m_next) {
638 if (n->m_next == 0) /* keep pointer to last control buf */
641 if (space > sbspace(sb))
643 if (asa->sa_len > MLEN)
645 MGET(m, M_DONTWAIT, MT_SONAME);
648 m->m_len = asa->sa_len;
649 bcopy((caddr_t)asa, mtod(m, caddr_t), asa->sa_len);
651 n->m_next = m0; /* concatenate data to control */
655 for (n = m; n; n = n->m_next)
668 sbappendcontrol(sb, m0, control)
670 struct mbuf *control, *m0;
672 register struct mbuf *m, *n;
676 panic("sbappendcontrol");
677 for (m = control; ; m = m->m_next) {
682 n = m; /* save pointer to last control buffer */
683 for (m = m0; m; m = m->m_next)
685 if (space > sbspace(sb))
687 n->m_next = m0; /* concatenate data to control */
688 for (m = control; m; m = m->m_next)
694 n->m_nextpkt = control;
701 * Compress mbuf chain m into the socket
702 * buffer sb following mbuf n. If n
703 * is null, the buffer is presumed empty.
707 register struct sockbuf *sb;
708 register struct mbuf *m, *n;
710 register int eor = 0;
711 register struct mbuf *o;
714 eor |= m->m_flags & M_EOR;
717 (((o = m->m_next) || (o = n)) &&
718 o->m_type == m->m_type))) {
722 if (n && (n->m_flags & M_EOR) == 0 &&
724 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
725 m->m_len <= M_TRAILINGSPACE(n) &&
726 n->m_type == m->m_type) {
727 bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
729 n->m_len += m->m_len;
730 sb->sb_cc += m->m_len;
740 m->m_flags &= ~M_EOR;
748 printf("semi-panic: sbcompress\n");
753 * Free all mbufs in a sockbuf.
754 * Check that all resources are reclaimed.
758 register struct sockbuf *sb;
761 if (sb->sb_flags & SB_LOCK)
762 panic("sbflush: locked");
763 while (sb->sb_mbcnt) {
765 * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
766 * we would loop forever. Panic instead.
768 if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
770 sbdrop(sb, (int)sb->sb_cc);
772 if (sb->sb_cc || sb->sb_mb || sb->sb_mbcnt)
773 panic("sbflush: cc %ld || mb %p || mbcnt %ld", sb->sb_cc, (void *)sb->sb_mb, sb->sb_mbcnt);
777 * Drop data from (the front of) a sockbuf.
781 register struct sockbuf *sb;
784 register struct mbuf *m, *mn;
787 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
796 if (m->m_len > len) {
807 while (m && m->m_len == 0) {
820 * Drop a record off the front of a sockbuf
821 * and move the next record to the front.
825 register struct sockbuf *sb;
827 register struct mbuf *m, *mn;
831 sb->sb_mb = m->m_nextpkt;
841 * Create a "control" mbuf containing the specified data
842 * with the specified type for presentation on a socket buffer.
845 sbcreatecontrol(p, size, type, level)
850 register struct cmsghdr *cp;
853 if (CMSG_SPACE((u_int)size) > MLEN)
854 return ((struct mbuf *) NULL);
855 if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
856 return ((struct mbuf *) NULL);
857 cp = mtod(m, struct cmsghdr *);
858 /* XXX check size? */
859 (void)memcpy(CMSG_DATA(cp), p, size);
860 m->m_len = CMSG_SPACE(size);
861 cp->cmsg_len = CMSG_LEN(size);
862 cp->cmsg_level = level;
863 cp->cmsg_type = type;
868 * Some routines that return EOPNOTSUPP for entry points that are not
869 * supported by a protocol. Fill in as needed.
872 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
878 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct proc *p)
884 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
890 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
891 struct ifnet *ifp, struct proc *p)
897 pru_listen_notsupp(struct socket *so, struct proc *p)
903 pru_rcvd_notsupp(struct socket *so, int flags)
909 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
915 * This isn't really a ``null'' operation, but it's the default one
916 * and doesn't do anything destructive.
919 pru_sense_null(struct socket *so, struct stat *sb)
925 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
928 dup_sockaddr(sa, canwait)
932 struct sockaddr *sa2;
934 MALLOC(sa2, struct sockaddr *, sa->sa_len, M_SONAME,
935 canwait ? M_WAITOK : M_NOWAIT);
937 bcopy(sa, sa2, sa->sa_len);
942 * Create an external-format (``xsocket'') structure using the information
943 * in the kernel-format socket structure pointed to by so. This is done
944 * to reduce the spew of irrelevant information over this interface,
945 * to isolate user code from changes in the kernel structure, and
946 * potentially to provide information-hiding if we decide that
947 * some of this information should be hidden from users.
950 sotoxsocket(struct socket *so, struct xsocket *xso)
952 xso->xso_len = sizeof *xso;
954 xso->so_type = so->so_type;
955 xso->so_options = so->so_options;
956 xso->so_linger = so->so_linger;
957 xso->so_state = so->so_state;
958 xso->so_pcb = so->so_pcb;
959 xso->xso_protocol = so->so_proto->pr_protocol;
960 xso->xso_family = so->so_proto->pr_domain->dom_family;
961 xso->so_qlen = so->so_qlen;
962 xso->so_incqlen = so->so_incqlen;
963 xso->so_qlimit = so->so_qlimit;
964 xso->so_timeo = so->so_timeo;
965 xso->so_error = so->so_error;
966 xso->so_oobmark = so->so_oobmark;
967 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
968 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
972 * This does the same for sockbufs. Note that the xsockbuf structure,
973 * since it is always embedded in a socket, does not include a self
974 * pointer nor a length. We make this entry point public in case
975 * some other mechanism needs it.
978 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
980 xsb->sb_cc = sb->sb_cc;
981 xsb->sb_hiwat = sb->sb_hiwat;
982 xsb->sb_mbcnt = sb->sb_mbcnt;
983 xsb->sb_mbmax = sb->sb_mbmax;
984 xsb->sb_lowat = sb->sb_lowat;
985 xsb->sb_flags = sb->sb_flags;
986 xsb->sb_timeo = sb->sb_timeo;