#!/bin/bash
#===============================================================================
#
#          FILE: tunetcp.sh
#
#         USAGE: tunetcp.sh
#
#   DESCRIPTION: Automatically tune the kernel space tcp parameters
#
#  REQUIREMENTS: UID 0
#
#         NOTES:
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Thu Jun  9 03:07:00 EDT 2011
#      REVISION: 1.0
#
#          TODO:
#
#===============================================================================

#set -o nounset                              # Treat unset variables as an error
#set -m                                      # Enable job control

PAGE_MAX=$(free -b|awk '/Mem:/ {print $2/'$(getconf PAGESIZE)'}')
PAGE_SIZE=$(getconf PAGE_SIZE)
MAX_MEM_SIZE=2147483647
BYTE_MAX=$(($PAGE_MAX*$PAGE_SIZE))
[ "$BYTE_MAX" -ge "$MAX_MEM_SIZE" ] && BYTE_MAX=2147483647

# auto-tuning the buffer size
echo 1 > /proc/sys/net/ipv4/tcp_moderate_rcvbuf

# dont cache metrics on closing connections
echo 1 > /proc/sys/net/ipv4/tcp_no_metrics_save

# maximum the number of packets, queued on the INPUT side
echo 300000 > /proc/sys/net/core/netdev_max_backlog

# disable tcp timestamps(for very busy network)
echo 0 > /proc/sys/net/ipv4/tcp_timestamps

# Turn on SACK
echo 1 > /proc/sys/net/ipv4/tcp_sack

# maximum the socket buffer size (in bytes)
echo "$(($BYTE_MAX/2))" > /proc/sys/net/core/wmem_max
echo "$(($BYTE_MAX/2))" > /proc/sys/net/core/rmem_max

# maximum the tcp buffer size (in pages)
echo "$(($PAGE_MAX/8)) $(($PAGE_MAX/4)) $PAGE_MAX" > /proc/sys/net/ipv4/tcp_mem

# maximum the tcp write/read buffer size (in bytes)
echo "4096 16384 $(($BYTE_MAX/2))" > /proc/sys/net/ipv4/tcp_wmem
echo "4096 16384 $(($BYTE_MAX/2))" > /proc/sys/net/ipv4/tcp_rmem

# maximem socket connections
echo 2147483647 > /proc/sys/net/core/somaxconn

# maximum amount of option memory buffers
echo 524287 > /proc/sys/net/core/optmem_max
