]> git.saurik.com Git - apple/xnu.git/blobdiff - bsd/netinet/tcp_usrreq.c
xnu-1699.24.23.tar.gz
[apple/xnu.git] / bsd / netinet / tcp_usrreq.c
index cc9202e54ae23f368e4ffec5f2b6fe3c0c91306c..d4fddb517f371072233020fcce105ff492f20f32 100644 (file)
@@ -1,16 +1,19 @@
 /*
- * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
+ * Copyright (c) 2000-2011 Apple Inc. All rights reserved.
  *
- * @APPLE_LICENSE_HEADER_START@
- * 
- * Copyright (c) 1999-2003 Apple Computer, Inc.  All Rights Reserved.
+ * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
  * 
  * This file contains Original Code and/or Modifications of Original Code
  * as defined in and that are subject to the Apple Public Source License
  * Version 2.0 (the 'License'). You may not use this file except in
- * compliance with the License. Please obtain a copy of the License at
- * http://www.opensource.apple.com/apsl/ and read it before using this
- * file.
+ * compliance with the License. The rights granted to you under the License
+ * may not be used to create, or enable the creation or redistribution of,
+ * unlawful or unlicensed copies of an Apple operating system, or to
+ * circumvent, violate, or enable the circumvention or violation of, any
+ * terms of an Apple operating system software license agreement.
+ * 
+ * Please obtain a copy of the License at
+ * http://www.opensource.apple.com/apsl/ and read it before using this file.
  * 
  * The Original Code and all software distributed under the License are
  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
@@ -20,7 +23,7 @@
  * Please see the License for the specific language governing rights and
  * limitations under the License.
  * 
- * @APPLE_LICENSE_HEADER_END@
+ * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
  */
 /*
  * Copyright (c) 1982, 1986, 1988, 1993
@@ -73,6 +76,7 @@
 
 #include <net/if.h>
 #include <net/route.h>
+#include <net/ntstat.h>
 
 #include <netinet/in.h>
 #include <netinet/in_systm.h>
 #include <netinet6/ipsec.h>
 #endif /*IPSEC*/
 
+void   tcp_fill_info(struct tcpcb *, struct tcp_info *);
+errno_t tcp_fill_info_for_info_tuple(struct info_tuple *, struct tcp_info *);
+
+int tcp_sysctl_info(struct sysctl_oid *, void *, int , struct sysctl_req *);
+
 /*
  * TCP protocol interface to socket abstraction.
  */
 extern char *tcpstates[];      /* XXX ??? */
 
-static int     tcp_attach __P((struct socket *, struct proc *));
-static int     tcp_connect __P((struct tcpcb *, struct sockaddr *, 
-                                struct proc *));
+static int     tcp_attach(struct socket *, struct proc *);
+static int     tcp_connect(struct tcpcb *, struct sockaddr *, struct proc *);
 #if INET6
-static int     tcp6_connect __P((struct tcpcb *, struct sockaddr *,
-                                struct proc *));
+static int     tcp6_connect(struct tcpcb *, struct sockaddr *, struct proc *);
 #endif /* INET6 */
 static struct tcpcb *
-               tcp_disconnect __P((struct tcpcb *));
+               tcp_disconnect(struct tcpcb *);
 static struct tcpcb *
-               tcp_usrclosed __P((struct tcpcb *));
+               tcp_usrclosed(struct tcpcb *);
+
+__private_extern__ int tcp_win_scale = 3;
+SYSCTL_INT(_net_inet_tcp, OID_AUTO, win_scale_factor, CTLFLAG_RW | CTLFLAG_LOCKED,
+    &tcp_win_scale, 0, "Window scaling factor");
+
+static u_int32_t tcps_in_sw_cksum;
+SYSCTL_UINT(_net_inet_tcp, OID_AUTO, in_sw_cksum, CTLFLAG_RD | CTLFLAG_LOCKED,
+    &tcps_in_sw_cksum, 0,
+    "Number of received packets checksummed in software");
+
+static u_int64_t tcps_in_sw_cksum_bytes;
+SYSCTL_QUAD(_net_inet_tcp, OID_AUTO, in_sw_cksum_bytes, CTLFLAG_RD | CTLFLAG_LOCKED,
+    &tcps_in_sw_cksum_bytes,
+    "Amount of received data checksummed in software");
+
+static u_int32_t tcps_out_sw_cksum;
+SYSCTL_UINT(_net_inet_tcp, OID_AUTO, out_sw_cksum, CTLFLAG_RD | CTLFLAG_LOCKED,
+    &tcps_out_sw_cksum, 0,
+    "Number of transmitted packets checksummed in software");
+
+static u_int64_t tcps_out_sw_cksum_bytes;
+SYSCTL_QUAD(_net_inet_tcp, OID_AUTO, out_sw_cksum_bytes, CTLFLAG_RD | CTLFLAG_LOCKED,
+    &tcps_out_sw_cksum_bytes,
+    "Amount of transmitted data checksummed in software");
 
 #if TCPDEBUG
 #define        TCPDEBUG0       int ostate = 0
@@ -130,14 +161,31 @@ static struct tcpcb *
 #define        TCPDEBUG2(req)
 #endif
 
+#if CONFIG_USESOCKTHRESHOLD
+__private_extern__ unsigned int        tcp_sockthreshold = 64;
+#else
+__private_extern__ unsigned int        tcp_sockthreshold = 0;
+#endif
+SYSCTL_INT(_net_inet_tcp, OID_AUTO, sockthreshold, CTLFLAG_RW | CTLFLAG_LOCKED,
+    &tcp_sockthreshold , 0, "TCP Socket size increased if less than threshold");
+
+
+SYSCTL_PROC(_net_inet_tcp, OID_AUTO, info, CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_ANYBODY,
+    0 , 0, tcp_sysctl_info, "S", "TCP info per tuple");
+
 /*
  * TCP attaches to socket via pru_attach(), reserving space,
  * and an internet control block.
+ *
+ * Returns:    0                       Success
+ *             EISCONN
+ *     tcp_attach:ENOBUFS
+ *     tcp_attach:ENOMEM
+ *     tcp_attach:???                  [IPSEC specific]
  */
 static int
-tcp_usr_attach(struct socket *so, int proto, struct proc *p)
+tcp_usr_attach(struct socket *so, __unused int proto, struct proc *p)
 {
-       int s = splnet();
        int error;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp = 0;
@@ -148,7 +196,7 @@ tcp_usr_attach(struct socket *so, int proto, struct proc *p)
                error = EISCONN;
                goto out;
        }
-
+       
        error = tcp_attach(so, p);
        if (error)
                goto out;
@@ -158,7 +206,6 @@ tcp_usr_attach(struct socket *so, int proto, struct proc *p)
        tp = sototcpcb(so);
 out:
        TCPDEBUG2(PRU_ATTACH);
-       splx(s);
        return error;
 }
 
@@ -172,48 +219,59 @@ out:
 static int
 tcp_usr_detach(struct socket *so)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
        TCPDEBUG0;
 
-       if (inp == 0) {
-               splx(s);
+       if (inp == 0 || (inp->inp_state == INPCB_STATE_DEAD)) {
                return EINVAL;  /* XXX */
        }
+       lck_mtx_assert(&((struct inpcb *)so->so_pcb)->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
        tp = intotcpcb(inp);
        /* In case we got disconnected from the peer */
         if (tp == 0) 
            goto out;
        TCPDEBUG1();
+
+       calculate_tcp_clock();
+
        tp = tcp_disconnect(tp);
 out:
        TCPDEBUG2(PRU_DETACH);
-       splx(s);
        return error;
 }
 
 #define        COMMON_START()  TCPDEBUG0; \
                        do { \
-                                    if (inp == 0) { \
-                                            splx(s); \
+                                    if (inp == 0 || (inp->inp_state == INPCB_STATE_DEAD)) { \
                                             return EINVAL; \
                                     } \
                                     tp = intotcpcb(inp); \
                                     TCPDEBUG1(); \
+                                    calculate_tcp_clock(); \
                     } while(0)
                             
-#define COMMON_END(req)        out: TCPDEBUG2(req); splx(s); return error; goto out
+#define COMMON_END(req)        out: TCPDEBUG2(req); return error; goto out
 
 
 /*
  * Give the socket an address.
+ *
+ * Returns:    0                       Success
+ *             EINVAL                  Invalid argument [COMMON_START]
+ *             EAFNOSUPPORT            Address family not supported
+ *     in_pcbbind:EADDRNOTAVAIL        Address not available.
+ *     in_pcbbind:EINVAL               Invalid argument
+ *     in_pcbbind:EAFNOSUPPORT         Address family not supported [notdef]
+ *     in_pcbbind:EACCES               Permission denied
+ *     in_pcbbind:EADDRINUSE           Address in use
+ *     in_pcbbind:EAGAIN               Resource unavailable, try again
+ *     in_pcbbind:EPERM                Operation not permitted
  */
 static int
 tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -221,6 +279,11 @@ tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
 
        COMMON_START();
 
+       if (nam->sa_family != 0 && nam->sa_family != AF_INET) {
+               error = EAFNOSUPPORT;
+               goto out;
+       }
+
        /*
         * Must check for multicast addresses and disallow binding
         * to them.
@@ -242,7 +305,6 @@ tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
 static int
 tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -250,6 +312,11 @@ tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
 
        COMMON_START();
 
+       if (nam->sa_family != 0 && nam->sa_family != AF_INET6) {
+               error = EAFNOSUPPORT;
+               goto out;
+       }
+
        /*
         * Must check for multicast addresses and disallow binding
         * to them.
@@ -262,7 +329,7 @@ tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
        }
        inp->inp_vflag &= ~INP_IPV4;
        inp->inp_vflag |= INP_IPV6;
-       if (ip6_mapped_addr_on && (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
+       if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
                if (IN6_IS_ADDR_UNSPECIFIED(&sin6p->sin6_addr))
                        inp->inp_vflag |= INP_IPV4;
                else if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
@@ -284,11 +351,20 @@ tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
 
 /*
  * Prepare to accept connections.
+ *
+ * Returns:    0                       Success
+ *             EINVAL [COMMON_START]
+ *     in_pcbbind:EADDRNOTAVAIL        Address not available.
+ *     in_pcbbind:EINVAL               Invalid argument
+ *     in_pcbbind:EAFNOSUPPORT         Address family not supported [notdef]
+ *     in_pcbbind:EACCES               Permission denied
+ *     in_pcbbind:EADDRINUSE           Address in use
+ *     in_pcbbind:EAGAIN               Resource unavailable, try again
+ *     in_pcbbind:EPERM                Operation not permitted
  */
 static int
 tcp_usr_listen(struct socket *so, struct proc *p)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -305,7 +381,6 @@ tcp_usr_listen(struct socket *so, struct proc *p)
 static int
 tcp6_usr_listen(struct socket *so, struct proc *p)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -313,8 +388,7 @@ tcp6_usr_listen(struct socket *so, struct proc *p)
        COMMON_START();
        if (inp->inp_lport == 0) {
                inp->inp_vflag &= ~INP_IPV4;
-               if (ip6_mapped_addr_on &&
-                   (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
+               if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
                        inp->inp_vflag |= INP_IPV4;
                error = in6_pcbbind(inp, (struct sockaddr *)0, p);
        }
@@ -334,14 +408,31 @@ tcp6_usr_listen(struct socket *so, struct proc *p)
 static int
 tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
        struct sockaddr_in *sinp;
 
-       COMMON_START();
+       TCPDEBUG0;
+       if (inp == 0)
+               return EINVAL;
+       else if (inp->inp_state == INPCB_STATE_DEAD) {
+               if (so->so_error) {
+                       error = so->so_error;
+                       so->so_error = 0;
+                       return error;
+               } else
+                       return EINVAL;
+       }
+       tp = intotcpcb(inp);
+       TCPDEBUG1();
+
+       calculate_tcp_clock();
 
+       if (nam->sa_family != 0 && nam->sa_family != AF_INET) {
+               error = EAFNOSUPPORT;
+               goto out;
+       }
        /*
         * Must disallow TCP ``connections'' to multicast addresses.
         */
@@ -352,9 +443,6 @@ tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
                goto out;
        }
 
-#ifndef __APPLE__
-       prison_remote_ip(p, 0, &sinp->sin_addr.s_addr);
-#endif
 
        if ((error = tcp_connect(tp, nam, p)) != 0)
                goto out;
@@ -366,7 +454,6 @@ tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
 static int
 tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -374,6 +461,11 @@ tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
 
        COMMON_START();
 
+       if (nam->sa_family != 0 && nam->sa_family != AF_INET6) {
+               error = EAFNOSUPPORT;
+               goto out;
+       }
+
        /*
         * Must disallow TCP ``connections'' to multicast addresses.
         */
@@ -387,9 +479,8 @@ tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
        if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
                struct sockaddr_in sin;
 
-               if (!ip6_mapped_addr_on ||
-                   (inp->inp_flags & IN6P_IPV6_V6ONLY))
-                       return(EINVAL);
+               if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0)
+                       return (EINVAL);
 
                in6_sin6_2_sin(&sin, sin6p);
                inp->inp_vflag |= INP_IPV4;
@@ -424,11 +515,11 @@ tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
 static int
 tcp_usr_disconnect(struct socket *so)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
-
+       
+       lck_mtx_assert(&((struct inpcb *)so->so_pcb)->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
        COMMON_START();
         /* In case we got disconnected from the peer */
         if (tp == 0)
@@ -445,23 +536,25 @@ tcp_usr_disconnect(struct socket *so)
 static int
 tcp_usr_accept(struct socket *so, struct sockaddr **nam)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp = NULL;
        TCPDEBUG0;
 
+       in_setpeeraddr(so, nam);
+               
        if (so->so_state & SS_ISDISCONNECTED) {
                error = ECONNABORTED;
                goto out;
        }
-       if (inp == 0) {
-               splx(s);
+       if (inp == 0 || (inp->inp_state == INPCB_STATE_DEAD)) {
                return (EINVAL);
        }
        tp = intotcpcb(inp);
        TCPDEBUG1();
-       in_setpeeraddr(so, nam);
+
+       calculate_tcp_clock();
+
        COMMON_END(PRU_ACCEPT);
 }
 
@@ -469,7 +562,6 @@ tcp_usr_accept(struct socket *so, struct sockaddr **nam)
 static int
 tcp6_usr_accept(struct socket *so, struct sockaddr **nam)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp = NULL;
@@ -479,23 +571,39 @@ tcp6_usr_accept(struct socket *so, struct sockaddr **nam)
                error = ECONNABORTED;
                goto out;
        }
-       if (inp == 0) {
-               splx(s);
+       if (inp == 0 || (inp->inp_state == INPCB_STATE_DEAD)) {
                return (EINVAL);
        }
        tp = intotcpcb(inp);
        TCPDEBUG1();
+
+       calculate_tcp_clock();
+
        in6_mapped_peeraddr(so, nam);
        COMMON_END(PRU_ACCEPT);
 }
 #endif /* INET6 */
+
 /*
  * Mark the connection as being incapable of further output.
+ *
+ * Returns:    0                       Success
+ *             EINVAL [COMMON_START]
+ *     tcp_output:EADDRNOTAVAIL
+ *     tcp_output:ENOBUFS
+ *     tcp_output:EMSGSIZE
+ *     tcp_output:EHOSTUNREACH
+ *     tcp_output:ENETUNREACH
+ *     tcp_output:ENETDOWN
+ *     tcp_output:ENOMEM
+ *     tcp_output:EACCES
+ *     tcp_output:EMSGSIZE
+ *     tcp_output:ENOBUFS
+ *     tcp_output:???                  [ignorable: mostly IPSEC/firewall/DLIL]
  */
 static int
 tcp_usr_shutdown(struct socket *so)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -515,9 +623,8 @@ tcp_usr_shutdown(struct socket *so)
  * After a receive, possibly send window update to peer.
  */
 static int
-tcp_usr_rcvd(struct socket *so, int flags)
+tcp_usr_rcvd(struct socket *so, __unused int flags)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -536,12 +643,35 @@ tcp_usr_rcvd(struct socket *so, int flags)
  * pru_*() routines, the mbuf chains are our responsibility.  We
  * must either enqueue them or free them.  The other pru_* routines
  * generally are caller-frees.
+ *
+ * Returns:    0                       Success
+ *             ECONNRESET
+ *             EINVAL
+ *             ENOBUFS
+ *     tcp_connect:EADDRINUSE          Address in use
+ *     tcp_connect:EADDRNOTAVAIL       Address not available.
+ *     tcp_connect:EINVAL              Invalid argument
+ *     tcp_connect:EAFNOSUPPORT        Address family not supported [notdef]
+ *     tcp_connect:EACCES              Permission denied
+ *     tcp_connect:EAGAIN              Resource unavailable, try again
+ *     tcp_connect:EPERM               Operation not permitted
+ *     tcp_output:EADDRNOTAVAIL
+ *     tcp_output:ENOBUFS
+ *     tcp_output:EMSGSIZE
+ *     tcp_output:EHOSTUNREACH
+ *     tcp_output:ENETUNREACH
+ *     tcp_output:ENETDOWN
+ *     tcp_output:ENOMEM
+ *     tcp_output:EACCES
+ *     tcp_output:EMSGSIZE
+ *     tcp_output:ENOBUFS
+ *     tcp_output:???                  [ignorable: mostly IPSEC/firewall/DLIL]
+ *     tcp6_connect:???                [IPV6 only]
  */
 static int
 tcp_usr_send(struct socket *so, int flags, struct mbuf *m, 
             struct sockaddr *nam, struct mbuf *control, struct proc *p)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -550,7 +680,7 @@ tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
 #endif
        TCPDEBUG0;
 
-       if (inp == NULL) {
+       if (inp == NULL || inp->inp_state == INPCB_STATE_DEAD) {
                /*
                 * OOPS! we lost a race, the TCP session got reset after
                 * we checked SS_CANTSENDMORE, eg: while doing uiomove or a
@@ -570,6 +700,9 @@ tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
 #endif /* INET6 */
        tp = intotcpcb(inp);
        TCPDEBUG1();
+
+       calculate_tcp_clock();
+
        if (control) {
                /* TCP doesn't do control messages (rights, creds, etc) */
                if (control->m_len) {
@@ -582,7 +715,7 @@ tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
                m_freem(control);       /* empty control, just free it */
        }
        if(!(flags & PRUS_OOB)) {
-               sbappend(&so->so_snd, m);
+               sbappendstream(&so->so_snd, m);
                if (nam && tp->t_state < TCPS_SYN_SENT) {
                        /*
                         * Do implied connect if not yet connected,
@@ -599,7 +732,7 @@ tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
                        if (error)
                                goto out;
                        tp->snd_wnd = TTCP_CLIENT_SND_WND;
-                       tcp_mss(tp, -1);
+                       tcp_mss(tp, -1, IFSCOPE_NONE);
                }
 
                if (flags & PRUS_EOF) {
@@ -618,7 +751,9 @@ tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
                                tp->t_flags &= ~TF_MORETOCOME;
                }
        } else {
-               if (sbspace(&so->so_snd) < -512) {
+               if (sbspace(&so->so_snd) == 0) { 
+                       /* if no space is left in sockbuf, 
+                        * do not try to squeeze in OOB traffic */
                        m_freem(m);
                        error = ENOBUFS;
                        goto out;
@@ -631,7 +766,7 @@ tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
                 * of data past the urgent section.
                 * Otherwise, snd_up should be one lower.
                 */
-               sbappend(&so->so_snd, m);
+               sbappendstream(&so->so_snd, m);
                if (nam && tp->t_state < TCPS_SYN_SENT) {
                        /*
                         * Do implied connect if not yet connected,
@@ -648,7 +783,7 @@ tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
                        if (error)
                                goto out;
                        tp->snd_wnd = TTCP_CLIENT_SND_WND;
-                       tcp_mss(tp, -1);
+                       tcp_mss(tp, -1, IFSCOPE_NONE);
                }
                tp->snd_up = tp->snd_una + so->so_snd.sb_cc;
                tp->t_force = 1;
@@ -665,7 +800,6 @@ tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
 static int
 tcp_usr_abort(struct socket *so)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -675,16 +809,21 @@ tcp_usr_abort(struct socket *so)
         if (tp == 0)
             goto out;
        tp = tcp_drop(tp, ECONNABORTED);
+       so->so_usecount--;
        COMMON_END(PRU_ABORT);
 }
 
 /*
  * Receive out-of-band data.
+ *
+ * Returns:    0                       Success
+ *             EINVAL [COMMON_START]
+ *             EINVAL
+ *             EWOULDBLOCK
  */
 static int
 tcp_usr_rcvoob(struct socket *so, struct mbuf *m, int flags)
 {
-       int s = splnet();
        int error = 0;
        struct inpcb *inp = sotoinpcb(so);
        struct tcpcb *tp;
@@ -714,7 +853,7 @@ struct pr_usrreqs tcp_usrreqs = {
        tcp_usr_connect, pru_connect2_notsupp, in_control, tcp_usr_detach,
        tcp_usr_disconnect, tcp_usr_listen, in_setpeeraddr, tcp_usr_rcvd,
        tcp_usr_rcvoob, tcp_usr_send, pru_sense_null, tcp_usr_shutdown,
-       in_setsockaddr, sosend, soreceive, sopoll
+       in_setsockaddr, sosend, soreceive, pru_sopoll_notsupp
 };
 
 #if INET6
@@ -723,7 +862,7 @@ struct pr_usrreqs tcp6_usrreqs = {
        tcp6_usr_connect, pru_connect2_notsupp, in6_control, tcp_usr_detach,
        tcp_usr_disconnect, tcp6_usr_listen, in6_mapped_peeraddr, tcp_usr_rcvd,
        tcp_usr_rcvoob, tcp_usr_send, pru_sense_null, tcp_usr_shutdown,
-       in6_mapped_sockaddr, sosend, soreceive, sopoll
+       in6_mapped_sockaddr, sosend, soreceive, pru_sopoll_notsupp
 };
 #endif /* INET6 */
 
@@ -736,6 +875,20 @@ struct pr_usrreqs tcp6_usrreqs = {
  * sending CC options and if the connection duration was < MSL, then
  * truncate the previous TIME-WAIT state and proceed.
  * Initialize connection parameters and enter SYN-SENT state.
+ *
+ * Returns:    0                       Success
+ *             EADDRINUSE
+ *             EINVAL
+ *     in_pcbbind:EADDRNOTAVAIL        Address not available.
+ *     in_pcbbind:EINVAL               Invalid argument
+ *     in_pcbbind:EAFNOSUPPORT         Address family not supported [notdef]
+ *     in_pcbbind:EACCES               Permission denied
+ *     in_pcbbind:EADDRINUSE           Address in use
+ *     in_pcbbind:EAGAIN               Resource unavailable, try again
+ *     in_pcbbind:EPERM                Operation not permitted
+ *     in_pcbladdr:EINVAL              Invalid argument
+ *     in_pcbladdr:EAFNOSUPPORT        Address family not supported
+ *     in_pcbladdr:EADDRNOTAVAIL       Address not available
  */
 static int
 tcp_connect(tp, nam, p)
@@ -747,10 +900,11 @@ tcp_connect(tp, nam, p)
        struct socket *so = inp->inp_socket;
        struct tcpcb *otp;
        struct sockaddr_in *sin = (struct sockaddr_in *)nam;
-       struct sockaddr_in *ifaddr;
+       struct sockaddr_in ifaddr;
        struct rmxp_tao *taop;
        struct rmxp_tao tao_noncached;
        int error;
+       unsigned int outif = 0;
 
        if (inp->inp_lport == 0) {
                error = in_pcbbind(inp, (struct sockaddr *)0, p);
@@ -763,44 +917,88 @@ tcp_connect(tp, nam, p)
         * earlier incarnation of this same connection still in
         * TIME_WAIT state, creating an ADDRINUSE error.
         */
-       error = in_pcbladdr(inp, nam, &ifaddr);
+       error = in_pcbladdr(inp, nam, &ifaddr, &outif);
        if (error)
                return error;
+
+       tcp_unlock(inp->inp_socket, 0, 0);
        oinp = in_pcblookup_hash(inp->inp_pcbinfo,
            sin->sin_addr, sin->sin_port,
            inp->inp_laddr.s_addr != INADDR_ANY ? inp->inp_laddr
-                                               : ifaddr->sin_addr,
+                                               : ifaddr.sin_addr,
            inp->inp_lport,  0, NULL);
+
+       tcp_lock(inp->inp_socket, 0, 0);
        if (oinp) {
+               if (oinp != inp) /* 4143933: avoid deadlock if inp == oinp */
+                       tcp_lock(oinp->inp_socket, 1, 0);
+               if (in_pcb_checkstate(oinp, WNT_RELEASE, 1) == WNT_STOPUSING) {
+                       if (oinp != inp)
+                               tcp_unlock(oinp->inp_socket, 1, 0);
+                       goto skip_oinp;
+               }
+
                if (oinp != inp && (otp = intotcpcb(oinp)) != NULL &&
                otp->t_state == TCPS_TIME_WAIT &&
-                   otp->t_starttime < tcp_msl &&
+                   ((int)(tcp_now - otp->t_starttime)) < tcp_msl &&
                    (otp->t_flags & TF_RCVD_CC))
                        otp = tcp_close(otp);
-               else
+               else {
+                       printf("tcp_connect: inp=%p err=EADDRINUSE\n", inp);
+                       if (oinp != inp)
+                               tcp_unlock(oinp->inp_socket, 1, 0);
                        return EADDRINUSE;
+               }
+               if (oinp != inp)
+                       tcp_unlock(oinp->inp_socket, 1, 0);
        }
-       if ((inp->inp_laddr.s_addr == INADDR_ANY ? ifaddr->sin_addr.s_addr :
+skip_oinp:
+       if ((inp->inp_laddr.s_addr == INADDR_ANY ? ifaddr.sin_addr.s_addr :
                 inp->inp_laddr.s_addr) == sin->sin_addr.s_addr &&
            inp->inp_lport == sin->sin_port)
                        return EINVAL;
-       if (inp->inp_laddr.s_addr == INADDR_ANY)
-               inp->inp_laddr = ifaddr->sin_addr;
+       if (!lck_rw_try_lock_exclusive(inp->inp_pcbinfo->mtx)) {
+               /*lock inversion issue, mostly with udp multicast packets */
+               socket_unlock(inp->inp_socket, 0);
+               lck_rw_lock_exclusive(inp->inp_pcbinfo->mtx);
+               socket_lock(inp->inp_socket, 0);
+       }
+       if (inp->inp_laddr.s_addr == INADDR_ANY) {
+               inp->inp_laddr = ifaddr.sin_addr;
+               inp->inp_last_outif = outif;
+       }
        inp->inp_faddr = sin->sin_addr;
        inp->inp_fport = sin->sin_port;
        in_pcbrehash(inp);
+       lck_rw_done(inp->inp_pcbinfo->mtx);
 
-       /* Compute window scaling to request.  */
+       /* Compute window scaling to requesti according to sb_hiwat
+        * or leave us some room to increase potentially increase the window size depending
+        * on the default win scale
+        */
        while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
-           (TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.sb_hiwat)
+        (TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.sb_hiwat)
                tp->request_r_scale++;
 
+       /*
+        * Inflate window size only if no setsockopt was performed on the recv sockbuf and
+        * if we're not over our number of active pcbs.
+        */
+
+       if (((so->so_rcv.sb_flags & SB_USRSIZE) == 0) && (inp->inp_pcbinfo->ipi_count < tcp_sockthreshold)) {
+               tp->request_r_scale = max(tcp_win_scale, tp->request_r_scale);
+               so->so_rcv.sb_hiwat = min(TCP_MAXWIN << tp->request_r_scale, (sb_max / (MSIZE+MCLBYTES)) * MCLBYTES);  
+       }
+
        soisconnecting(so);
        tcpstat.tcps_connattempt++;
        tp->t_state = TCPS_SYN_SENT;
-       tp->t_timer[TCPT_KEEP] = tcp_keepinit;
+       tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp, 
+               tp->t_keepinit ? tp->t_keepinit : tcp_keepinit);
        tp->iss = tcp_new_isn(tp);
        tcp_sendseqinit(tp);
+       if (nstat_collect)
+               nstat_route_connect_attempt(inp->inp_route.ro_rt);
 
        /*
         * Generate a CC value for this connection and
@@ -834,10 +1032,11 @@ tcp6_connect(tp, nam, p)
        struct socket *so = inp->inp_socket;
        struct tcpcb *otp;
        struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
-       struct in6_addr *addr6;
+       struct in6_addr addr6;
        struct rmxp_tao *taop;
        struct rmxp_tao tao_noncached;
        int error;
+       unsigned int outif = 0;
 
        if (inp->inp_lport == 0) {
                error = in6_pcbbind(inp, (struct sockaddr *)0, p);
@@ -850,31 +1049,42 @@ tcp6_connect(tp, nam, p)
         * earlier incarnation of this same connection still in
         * TIME_WAIT state, creating an ADDRINUSE error.
         */
-       error = in6_pcbladdr(inp, nam, &addr6);
+       error = in6_pcbladdr(inp, nam, &addr6, &outif);
        if (error)
                return error;
+       tcp_unlock(inp->inp_socket, 0, 0);
        oinp = in6_pcblookup_hash(inp->inp_pcbinfo,
                                  &sin6->sin6_addr, sin6->sin6_port,
                                  IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)
-                                 ? addr6
+                                 ? &addr6
                                  : &inp->in6p_laddr,
                                  inp->inp_lport,  0, NULL);
+       tcp_lock(inp->inp_socket, 0, 0);
        if (oinp) {
                if (oinp != inp && (otp = intotcpcb(oinp)) != NULL &&
                    otp->t_state == TCPS_TIME_WAIT &&
-                   otp->t_starttime < tcp_msl &&
+                   ((int)(tcp_now - otp->t_starttime)) < tcp_msl &&
                    (otp->t_flags & TF_RCVD_CC))
                        otp = tcp_close(otp);
                else
                        return EADDRINUSE;
        }
-       if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
-               inp->in6p_laddr = *addr6;
+       if (!lck_rw_try_lock_exclusive(inp->inp_pcbinfo->mtx)) {
+               /*lock inversion issue, mostly with udp multicast packets */
+               socket_unlock(inp->inp_socket, 0);
+               lck_rw_lock_exclusive(inp->inp_pcbinfo->mtx);
+               socket_lock(inp->inp_socket, 0);
+       }
+       if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
+               inp->in6p_laddr = addr6;
+               inp->in6p_last_outif = outif;
+       }
        inp->in6p_faddr = sin6->sin6_addr;
        inp->inp_fport = sin6->sin6_port;
-       if ((sin6->sin6_flowinfo & IPV6_FLOWINFO_MASK) != NULL)
+       if ((sin6->sin6_flowinfo & IPV6_FLOWINFO_MASK) != 0)
                inp->in6p_flowinfo = sin6->sin6_flowinfo;
        in_pcbrehash(inp);
+       lck_rw_done(inp->inp_pcbinfo->mtx);
 
        /* Compute window scaling to request.  */
        while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
@@ -884,9 +1094,12 @@ tcp6_connect(tp, nam, p)
        soisconnecting(so);
        tcpstat.tcps_connattempt++;
        tp->t_state = TCPS_SYN_SENT;
-       tp->t_timer[TCPT_KEEP] = tcp_keepinit;
+       tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp, 
+               tp->t_keepinit ? tp->t_keepinit : tcp_keepinit);
        tp->iss = tcp_new_isn(tp);
        tcp_sendseqinit(tp);
+       if (nstat_collect)
+               nstat_route_connect_attempt(inp->inp_route.ro_rt);
 
        /*
         * Generate a CC value for this connection and
@@ -910,6 +1123,132 @@ tcp6_connect(tp, nam, p)
 }
 #endif /* INET6 */
 
+/*
+ * Export TCP internal state information via a struct tcp_info
+ */
+__private_extern__ void
+tcp_fill_info(struct tcpcb *tp, struct tcp_info *ti)
+{
+       bzero(ti, sizeof(*ti));
+
+       ti->tcpi_state = tp->t_state;
+       
+    if (tp->t_state > TCPS_LISTEN) {
+               if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
+                       ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
+               if (tp->t_flags & TF_SACK_PERMIT)
+                       ti->tcpi_options |= TCPI_OPT_SACK;
+               if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
+                       ti->tcpi_options |= TCPI_OPT_WSCALE;
+                       ti->tcpi_snd_wscale = tp->snd_scale;
+                       ti->tcpi_rcv_wscale = tp->rcv_scale;
+               }
+               
+               ti->tcpi_snd_mss = tp->t_maxseg;
+               ti->tcpi_rcv_mss = tp->t_maxseg;
+
+               ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
+               ti->tcpi_snd_cwnd = tp->snd_cwnd;
+       
+               ti->tcpi_rcv_space = tp->rcv_wnd;
+
+               ti->tcpi_snd_wnd = tp->snd_wnd;
+               ti->tcpi_snd_bwnd = tp->snd_bwnd;
+               ti->tcpi_snd_nxt = tp->snd_nxt;
+               ti->tcpi_rcv_nxt = tp->rcv_nxt;
+               
+               ti->tcpi_last_outif = tp->t_inpcb->inp_last_outif;
+       }
+}
+
+__private_extern__ errno_t
+tcp_fill_info_for_info_tuple(struct info_tuple *itpl, struct tcp_info *ti)
+{
+       struct inpcbinfo *pcbinfo = NULL;
+       struct inpcb *inp = NULL;
+       struct socket *so;
+       struct tcpcb *tp;
+       
+       if (itpl->itpl_proto == IPPROTO_TCP)
+               pcbinfo = &tcbinfo;
+       else
+               return EINVAL;
+       
+       if (itpl->itpl_local_sa.sa_family == AF_INET &&
+               itpl->itpl_remote_sa.sa_family == AF_INET) {
+               inp = in_pcblookup_hash(pcbinfo, 
+                                                               itpl->itpl_remote_sin.sin_addr,
+                                                               itpl->itpl_remote_sin.sin_port,
+                                                               itpl->itpl_local_sin.sin_addr,
+                                                               itpl->itpl_local_sin.sin_port,
+                                                               0, NULL);
+       } else if (itpl->itpl_local_sa.sa_family == AF_INET6 &&
+               itpl->itpl_remote_sa.sa_family == AF_INET6) {
+               struct in6_addr ina6_local;
+               struct in6_addr ina6_remote;
+               
+               ina6_local = itpl->itpl_local_sin6.sin6_addr;
+               if (IN6_IS_SCOPE_LINKLOCAL(&ina6_local) && itpl->itpl_local_sin6.sin6_scope_id)
+                       ina6_local.s6_addr16[1] = htons(itpl->itpl_local_sin6.sin6_scope_id);
+
+               ina6_remote = itpl->itpl_remote_sin6.sin6_addr;
+               if (IN6_IS_SCOPE_LINKLOCAL(&ina6_remote) && itpl->itpl_remote_sin6.sin6_scope_id)
+                       ina6_remote.s6_addr16[1] = htons(itpl->itpl_remote_sin6.sin6_scope_id);
+               
+               inp = in6_pcblookup_hash(pcbinfo, 
+                                                               &ina6_remote,
+                                                               itpl->itpl_remote_sin6.sin6_port,
+                                                               &ina6_local,
+                                                               itpl->itpl_local_sin6.sin6_port,
+                                                               0, NULL);
+       } else
+               return EINVAL;
+       if (inp == NULL || (so = inp->inp_socket) == NULL)
+               return ENOENT;
+
+       socket_lock(so, 0);
+       if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
+               socket_unlock(so, 0);
+               return ENOENT;
+       }
+       tp = intotcpcb(inp);
+
+       tcp_fill_info(tp, ti);
+       socket_unlock(so, 0);
+
+       return 0;
+}
+
+
+__private_extern__ int 
+tcp_sysctl_info(__unused struct sysctl_oid *oidp, __unused void *arg1, __unused int arg2, struct sysctl_req *req)
+{
+       int error;
+       struct tcp_info ti;
+       struct info_tuple itpl;
+       
+       if (req->newptr == USER_ADDR_NULL) {
+               return EINVAL;
+       }
+       if (req->newlen < sizeof(struct info_tuple)) {
+               return EINVAL;
+       }
+       error = SYSCTL_IN(req, &itpl, sizeof(struct info_tuple));
+       if (error != 0) {
+               return error;
+       }
+       error = tcp_fill_info_for_info_tuple(&itpl, &ti);
+       if (error != 0) {
+               return error;
+       }
+       error = SYSCTL_OUT(req, &ti, sizeof(struct tcp_info));
+       if (error != 0) {
+               return error;
+       }
+       
+       return 0;
+}
+
 /*
  * The new sockopt interface makes it possible for us to block in the
  * copyin/out step (if we take a page fault).  Taking a page fault at
@@ -922,15 +1261,13 @@ tcp_ctloutput(so, sopt)
        struct socket *so;
        struct sockopt *sopt;
 {
-       int     error, opt, optval, s;
+       int     error, opt, optval;
        struct  inpcb *inp;
        struct  tcpcb *tp;
 
        error = 0;
-       s = splnet();           /* XXX */
        inp = sotoinpcb(so);
        if (inp == NULL) {
-               splx(s);
                return (ECONNRESET);
        }
        if (sopt->sopt_level != IPPROTO_TCP) {
@@ -940,15 +1277,15 @@ tcp_ctloutput(so, sopt)
                else
 #endif /* INET6 */
                error = ip_ctloutput(so, sopt);
-               splx(s);
                return (error);
        }
        tp = intotcpcb(inp);
         if (tp == NULL) {
-                splx(s);
                 return (ECONNRESET);
         }
 
+       calculate_tcp_clock();
+
        switch (sopt->sopt_dir) {
        case SOPT_SET:
                switch (sopt->sopt_name) {
@@ -980,19 +1317,76 @@ tcp_ctloutput(so, sopt)
                        else
                                tp->t_flags &= ~opt;
                        break;
-
+               case TCP_RXT_FINDROP:
+                       error = sooptcopyin(sopt, &optval, sizeof optval,
+                               sizeof optval);
+                       if (error)
+                               break;
+                       opt = TF_RXTFINDROP;
+                       if (optval)
+                               tp->t_flagsext |= opt;
+                       else
+                               tp->t_flagsext &= ~opt;
+                       break;
                case TCP_MAXSEG:
                        error = sooptcopyin(sopt, &optval, sizeof optval,
                                            sizeof optval);
                        if (error)
                                break;
 
-                       if (optval > 0 && optval <= tp->t_maxseg)
+                       if (optval > 0 && optval <= tp->t_maxseg &&
+                           optval + 40 >= tcp_minmss)
                                tp->t_maxseg = optval;
                        else
                                error = EINVAL;
                        break;
 
+               case TCP_KEEPALIVE:
+                       error = sooptcopyin(sopt, &optval, sizeof optval,
+                                               sizeof optval);
+                       if (error)
+                               break;
+                       if (optval < 0)
+                               error = EINVAL;
+                       else {
+                               tp->t_keepidle = optval * TCP_RETRANSHZ;
+                               tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp, 
+                                       TCP_KEEPIDLE(tp)); /* reset the timer to new value */
+                               tcp_check_timer_state(tp);
+                       }
+                        break;
+
+               case TCP_CONNECTIONTIMEOUT:
+                       error = sooptcopyin(sopt, &optval, sizeof optval,
+                                               sizeof optval);
+                       if (error)
+                               break;
+                       if (optval < 0)
+                               error = EINVAL;
+                       else 
+                               tp->t_keepinit = optval * TCP_RETRANSHZ;
+                       break;
+               
+               case PERSIST_TIMEOUT:
+                       error = sooptcopyin(sopt, &optval, sizeof optval,
+                                               sizeof optval);
+                       if (error)
+                               break;
+                       if (optval < 0)
+                               error = EINVAL;
+                       else 
+                               tp->t_persist_timeout = optval * TCP_RETRANSHZ;
+                       break;
+               case TCP_RXT_CONNDROPTIME:
+                       error = sooptcopyin(sopt, &optval, sizeof(optval),
+                                       sizeof(optval));
+                       if (error)
+                               break;
+                       if (optval < 0)
+                               error = EINVAL;
+                       else
+                               tp->rxt_conndroptime = optval * TCP_RETRANSHZ;
+                       break;
                default:
                        error = ENOPROTOOPT;
                        break;
@@ -1007,12 +1401,34 @@ tcp_ctloutput(so, sopt)
                case TCP_MAXSEG:
                        optval = tp->t_maxseg;
                        break;
+               case TCP_KEEPALIVE:
+                       optval = tp->t_keepidle / TCP_RETRANSHZ;
+                       break;
                case TCP_NOOPT:
                        optval = tp->t_flags & TF_NOOPT;
                        break;
                case TCP_NOPUSH:
                        optval = tp->t_flags & TF_NOPUSH;
                        break;
+               case TCP_CONNECTIONTIMEOUT:
+                       optval = tp->t_keepinit / TCP_RETRANSHZ;
+                       break;
+               case PERSIST_TIMEOUT:
+                       optval = tp->t_persist_timeout / TCP_RETRANSHZ;
+                       break;
+               case TCP_RXT_CONNDROPTIME:
+                       optval = tp->rxt_conndroptime / TCP_RETRANSHZ;
+                       break;
+               case TCP_RXT_FINDROP:
+                       optval = tp->t_flagsext & TF_RXTFINDROP;
+                       break; 
+               case TCP_INFO: {
+                       struct tcp_info ti;
+
+                       tcp_fill_info(tp, &ti);
+                       error = sooptcopyout(sopt, &ti, sizeof(struct tcp_info));
+                       goto done;
+               }
                default:
                        error = ENOPROTOOPT;
                        break;
@@ -1021,7 +1437,7 @@ tcp_ctloutput(so, sopt)
                        error = sooptcopyout(sopt, &optval, sizeof optval);
                break;
        }
-       splx(s);
+done:
        return (error);
 }
 
@@ -1030,17 +1446,59 @@ tcp_ctloutput(so, sopt)
  * sizes, respectively.  These are obsolescent (this information should
  * be set by the route).
  */
-u_long tcp_sendspace = 1024*16;
-SYSCTL_INT(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLFLAG_RW, 
-    &tcp_sendspace , 0, "Maximum outgoing TCP datagram size");
-u_long tcp_recvspace = 1024*16;
-SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_RW, 
-    &tcp_recvspace , 0, "Maximum incoming TCP datagram size");
+u_int32_t      tcp_sendspace = 1448*256;
+u_int32_t      tcp_recvspace = 1448*384;
+
+/* During attach, the size of socket buffer allocated is limited to
+ * sb_max in sbreserve. Disallow setting the tcp send and recv space
+ * to be more than sb_max because that will cause tcp_attach to fail
+ * (see radar 5713060)
+ */  
+static int
+sysctl_tcp_sospace(struct sysctl_oid *oidp, __unused void *arg1,
+       __unused int arg2, struct sysctl_req *req) {
+       u_int32_t new_value = 0, *space_p = NULL;
+       int changed = 0, error = 0;
+       u_quad_t sb_effective_max = (sb_max / (MSIZE+MCLBYTES)) * MCLBYTES;
+
+       switch (oidp->oid_number) {
+               case TCPCTL_SENDSPACE:
+                       space_p = &tcp_sendspace;
+                       break;
+               case TCPCTL_RECVSPACE:
+                       space_p = &tcp_recvspace;
+                       break;
+               default:
+                       return EINVAL;
+       }
+       error = sysctl_io_number(req, *space_p, sizeof(u_int32_t),
+               &new_value, &changed);
+       if (changed) {
+               if (new_value > 0 && new_value <= sb_effective_max) {
+                       *space_p = new_value;
+               } else {
+                       error = ERANGE;
+               }
+       }
+       return error;
+}
+
+SYSCTL_PROC(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
+    &tcp_sendspace , 0, &sysctl_tcp_sospace, "IU", "Maximum outgoing TCP datagram size");
+SYSCTL_PROC(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
+    &tcp_recvspace , 0, &sysctl_tcp_sospace, "IU", "Maximum incoming TCP datagram size");
+
 
 /*
  * Attach TCP protocol to socket, allocating
  * internet protocol control block, tcp control block,
  * bufer space, and entering LISTEN state if to accept connections.
+ *
+ * Returns:    0                       Success
+ *     in_pcballoc:ENOBUFS
+ *     in_pcballoc:ENOMEM
+ *     in_pcballoc:???                 [IPSEC specific]
+ *     soreserve:ENOBUFS
  */
 static int
 tcp_attach(so, p)
@@ -1050,19 +1508,40 @@ tcp_attach(so, p)
        register struct tcpcb *tp;
        struct inpcb *inp;
        int error;
+       u_long sb_effective_max;
 #if INET6
-       int isipv6 = INP_CHECK_SOCKAF(so, AF_INET6) != NULL;
+       int isipv6 = INP_CHECK_SOCKAF(so, AF_INET6) != 0;
 #endif
 
-       if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
-               error = soreserve(so, tcp_sendspace, tcp_recvspace);
-               if (error)
-                       return (error);
-       }
        error = in_pcballoc(so, &tcbinfo, p);
        if (error)
                return (error);
+
        inp = sotoinpcb(so);
+
+       if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
+               /*
+                * The goal is to let clients machines use large send/rcv default windows to compensate for link
+                * latency and make sure the receiver is not constraining the sender window.
+                * But we doon't want to have a few connections use all our mbuf space for servers.
+                * This is done by watching a threshold of tcpcbs in use and bumping the default send and rcvspace
+                * only if that threshold isn't reached.
+                * We're also advertising a much bigger window size (tuneable by sysctl) in correlation with                             * the max socket buffer size if 
+                * we consider that we have enough ressources for it. This window will be adjusted depending on the
+                * global socket layer buffer use with the use of tcp_sbpace
+                */
+
+               if (inp->inp_pcbinfo->ipi_count < tcp_sockthreshold) {
+                       sb_effective_max = (sb_max / (MSIZE+MCLBYTES)) * MCLBYTES;  
+                       error = soreserve(so, max(min((TCP_MAXWIN << tcp_win_scale)/4, sb_effective_max), tcp_sendspace),
+                                       max(min((TCP_MAXWIN << tcp_win_scale)/2, sb_effective_max), tcp_recvspace));
+               }
+               else    
+                       error = soreserve(so, tcp_sendspace, tcp_recvspace);
+               if (error)
+                       return (error);
+       }
+
 #if INET6
        if (isipv6) {
                inp->inp_vflag |= INP_IPV6;
@@ -1085,6 +1564,9 @@ tcp_attach(so, p)
                so->so_state |= nofd;
                return (ENOBUFS);
        }
+       if (nstat_collect) {
+               nstat_tcp_new_pcb(inp);
+       }
        tp->t_state = TCPS_CLOSED;
        return (0);
 }
@@ -1157,8 +1639,21 @@ tcp_usrclosed(tp)
                soisdisconnected(tp->t_inpcb->inp_socket);
                /* To prevent the connection hanging in FIN_WAIT_2 forever. */
                if (tp->t_state == TCPS_FIN_WAIT_2)
-                       tp->t_timer[TCPT_2MSL] = tcp_maxidle;
+                       tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp, tcp_maxidle);
        }
        return (tp);
 }
 
+void
+tcp_in_cksum_stats(u_int32_t len)
+{
+       tcps_in_sw_cksum++;
+       tcps_in_sw_cksum_bytes += len;
+}
+
+void
+tcp_out_cksum_stats(u_int32_t len)
+{
+       tcps_out_sw_cksum++;
+       tcps_out_sw_cksum_bytes += len;
+}