diff --git a/.seedbox_installation.sh b/.seedbox_installation.sh new file mode 100644 index 0000000..e2f9247 --- /dev/null +++ b/.seedbox_installation.sh @@ -0,0 +1,192 @@ +#!/bin/bash + +## Update Installed Packages & Installing Essential Packages +function Update { + tput setaf 2; echo "Updating installed packages and install prerequisite" + tput setaf 7 + apt-get -qqy update && apt-get -qqy upgrade + apt-get -qqy install sudo + apt-get -qqy install sysstat + cd $HOME + clear + tput setaf 1 +} + +## qBittorrent +function qBittorrent_download { + tput setaf 2; echo "Please enter your choice (qBittorrent Version - libtorrent Version):" + options=("qBittorrent 4.1.9 - libtorrent-1_1_14" "qBittorrent 4.1.9.1 - libtorrent-1_1_14" "qBittorrent 4.3.3 - libtorrent-v1.2.12-Lactency" "qBittorrent 4.3.3 - libtorrent-v1.2.13" "qBittorrent 4.3.4.1 - libtorrent-v1.2.13-Lactency" "qBittorrent 4.3.4.1 - libtorrent-v1.2.13") + select opt in "${options[@]}" + do + case $opt in + "qBittorrent 4.1.9 - libtorrent-1_1_14") + version=4.1.9; curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/qBittorrent/qBittorrent%204.1.9%20-%20libtorrent-1_1_14/qbittorrent-nox && chmod +x $HOME/qbittorrent-nox; break + ;; + "qBittorrent 4.1.9.1 - libtorrent-1_1_14") + version=4.1.9.1; curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/qBittorrent/qBittorrent%204.1.9.1%20-%20libtorrent-1_1_14/qbittorrent-nox && chmod +x $HOME/qbittorrent-nox; break + ;; + "qBittorrent 4.3.3 - libtorrent-v1.2.12-Lactency") + version=4.3.3; curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/qBittorrent/qBittorrent%204.3.3%20-%20libtorrent-v1.2.12-Lactency/qbittorrent-nox && chmod +x $HOME/qbittorrent-nox; break + ;; + "qBittorrent 4.3.3 - libtorrent-v1.2.13") + version=4.3.3; curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/qBittorrent/qBittorrent%204.3.3%20-%20libtorrent-v1.2.13/qbittorrent-nox && chmod +x $HOME/qbittorrent-nox; break + ;; + "qBittorrent 4.3.4.1 - libtorrent-v1.2.13-Lactency") + version=4.3.3; curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/qBittorrent/qBittorrent%204.3.4.1%20-%20libtorrent-v1.2.13-Lactency/qbittorrent-nox && chmod +x $HOME/qbittorrent-nox; break + ;; + "qBittorrent 4.3.4.1 - libtorrent-v1.2.13") + version=4.3.3; curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/qBittorrent/qBittorrent%204.3.4.1%20-%20libtorrent-v1.2.13/qbittorrent-nox && chmod +x $HOME/qbittorrent-nox; break + ;; + *) tput setaf 1; echo "Please choose a valid version";; + esac + done +} +function qBittorrent_install { + tput setaf 1 + test -e /usr/bin/qbittorrent-nox && rm /usr/bin/qbittorrent-nox + mv $HOME/qbittorrent-nox /usr/bin/qbittorrent-nox + test -e /etc/systemd/system/qbittorrent-nox@.service && rm /etc/systemd/system/qbittorrent-nox@.service + touch /etc/systemd/system/qbittorrent-nox@.service + cat << EOF >/etc/systemd/system/qbittorrent-nox@.service +[Unit] +Description=qBittorrent +After=network.target + +[Service] +Type=forking +User=$username +LimitNOFILE=infinity +ExecStart=/usr/bin/qbittorrent-nox -d +ExecStop=/usr/bin/killall -w -s 9 /usr/bin/qbittorrent-nox +Restart=on-failure +TimeoutStopSec=20 +RestartSec=10 + +[Install] +WantedBy=multi-user.target +EOF + sudo -u $username mkdir -p /home/$username/qbittorrent/Downloads + systemctl enable qbittorrent-nox@$username + systemctl start qbittorrent-nox@$username +} +function qBittorrent_config { + systemctl stop qbittorrent-nox@$username + if [[ "${version}" =~ "4.1." ]]; then + md5password=$(echo -n $password | md5sum | awk '{print $1}') + cat << EOF >/home/$username/.config/qBittorrent/qBittorrent.conf +[LegalNotice] +Accepted=true + +[Network] +Cookies=@Invalid() + +[Preferences] +Connection\PortRangeMin=45000 +Downloads\DiskWriteCacheSize=$Cache2 +Downloads\SavePath=/home/$username/qbittorrent/Downloads/ +Queueing\QueueingEnabled=false +WebUI\Password_ha1=@ByteArray($md5password) +WebUI\Port=8080 +WebUI\Username=$username +EOF + elif [[ "${version}" =~ "4.2."|"4.3." ]]; then + curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/Miscellaneous/qb_password_gen && chmod +x $HOME/qb_password_gen + PBKDF2password=$($HOME/qb_password_gen $password) + cat << EOF >/home/$username/.config/qBittorrent/qBittorrent.conf +[LegalNotice] +Accepted=true + +[Network]+ +Cookies=@Invalid() + +[Preferences] +Connection\PortRangeMin=45000 +Downloads\DiskWriteCacheSize=$Cache2 +Downloads\SavePath=/home/$username/qbittorrent/Downloads/ +Queueing\QueueingEnabled=false +WebUI\Password_PBKDF2="@ByteArray($PBKDF2password)" +WebUI\Port=8080 +WebUI\Username=$username +EOF + rm qb_password_gen + fi + systemctl start qbittorrent-nox@$username +} + +function qBittorrent { + qBittorrent_download + qBittorrent_install + qBittorrent_config + qbport=$(grep -F 'WebUI\Port' /home/$username/.config/qBittorrent/qBittorrent.conf | grep -Eo '[0-9]{1,5}') + clear + tput setaf 2 +} + +## Install autoremove-torrents +function Decision2 { + while true; do + tput setaf 2; read -p "Do you wish to config autoremove-torrents for $1? (Y/N):" yn + case $yn in + [Yy]* ) e=0; break;; + [Nn]* ) e=1; break;; + * ) tput setaf 1; echo "Please answer yes or no.";; + esac + done +} +function autoremove-torrents { + tput setaf 7 + apt-get -qqy install python3-distutils > /dev/null + apt-get -qqy install python3-apt > /dev/null + curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py + python3 get-pip.py + rm get-pip.py + pip -q install autoremove-torrents + clear + tput setaf 2 + read -p "Enter desired reserved storage (in GiB): " diskspace + read -p "Enter desired minimum seedtime (in Second): " seedtime + # qBittorrent + tput setaf 2 + unset e + if [ -z ${qbport+x} ]; then echo "Skipping qBittorrent since it is not installed"; else Decision2 qBittorrent; fi + if [ "${e}" == "0" ]; then + touch $HOME/.config.yml + cat << EOF >>$HOME/.config.yml +General-qb: + client: qbittorrent + host: http://127.0.0.1:$qbport + username: $username + password: $password + strategies: + Upload: + status: + - Uploading + remove: upload_speed < 1024 and seeding_time > $seedtime + Leech: + status: + - Downloading + remove: ratio < 1 and progress > 5 and download_speed > 20480 + Disk: + free_space: + min: $diskspace + path: / + action: remove-old-seeds + delete_data: true +EOF + fi + sed -i 's+127.0.0.1: +127.0.0.1:+g' $HOME/.config.yml + mkdir $HOME/.autoremove-torrents + chmod 777 $HOME/.autoremove-torrents + touch $HOME/.autoremove.sh + cat << EOF >$HOME/.autoremove.sh +#!/bin/sh + +while true; do + /usr/local/bin/autoremove-torrents --conf=$HOME/.config.yml --log=$HOME/.autoremove-torrents + sleep 5 +done +EOF + chmod +x $HOME/.autoremove.sh + apt-get -qqy install screen > /dev/null + screen -dmS autoremove-torrents $HOME/.autoremove.sh +} \ No newline at end of file diff --git a/.tweaking.sh b/.tweaking.sh new file mode 100644 index 0000000..ffc442f --- /dev/null +++ b/.tweaking.sh @@ -0,0 +1,646 @@ +#!/bin/sh + +## CPU +function CPU_Tweaking { + tput setaf 2; echo "Optimizing CPU" + apt-get -qqy install tuned > /dev/null + tput setaf 1 + mkdir /etc/tuned/profile + touch /etc/tuned/profile/tuned.conf + cat << EOF >/etc/tuned/profile/tuned.conf +[main] +#CPU & Scheduler Optimization +[cpu] +governor=performance +energy_perf_bias=performance +min_perf_pct=100 + +[disk] +readahead=4096 + +[bootloader] +cmdline=skew_tick=1 +EOF + + /sbin/tuned-adm profile profile +} + + +## Network +#NIC Config +function NIC_Tweaking { + tput setaf 2; echo "Optimizing NIC Configuration" + tput setaf 1; echo "Some Configurations might not be supported by the NIC" + interface=$(ip -o -4 route show to default | awk '{print $5}') + /sbin/ethtool -G $interface rx 1024 + sleep 1 + /sbin/ethtool -G $interface tx 2048 + sleep 1 + /sbin/ethtool -K $interface tso off gso off + sleep 1 +} +function Network_Other_Tweaking { + tput setaf 2; echo "Doing other Network Tweaking" + tput setaf 1 + #Other 1 + /sbin/ifconfig $interface txqueuelen 10000 + sleep 1 + #Other 2 + iproute=$(ip -o -4 route show to default) + ip route change $iproute initcwnd 25 initrwnd 25 +} + + +## Drive +#Scheduler +function Scheduler_Tweaking { + tput setaf 2; echo "Changing I/O Scheduler" + tput setaf 1 + i=1 + drive=() + disk=$(lsblk -nd --output NAME) + diskno=$(echo $disk | awk '{print NF}') + while [ $i -le $diskno ] + do + device=$(echo $disk | awk -v i=$i '{print $i}') + drive+=($device) + i=$(( $i + 1 )) + done + i=1 + x=0 + disktype=$(cat /sys/block/sda/queue/rotational) + if [ "${disktype}" == 0 ]; then + while [ $i -le $diskno ] + do + diskname=$(eval echo ${drive["$x"]}) + echo kyber > /sys/block/$diskname/queue/scheduler + i=$(( $i + 1 )) + x=$(( $x + 1 )) + done + else + while [ $i -le $diskno ] + do + diskname=$(eval echo ${drive["$x"]}) + echo mq-deadline > /sys/block/$diskname/queue/scheduler + i=$(( $i + 1 )) + x=$(( $x + 1 )) + done + fi +} + + +## File Open Limit +function file_open_limit_Tweaking { + tput setaf 2; echo "Configuring File Open Limit" + tput setaf 1 + username=$(ls /home/) + cat << EOF >>/etc/security/limits.conf +## Hard limit for max opened files +$username hard nofile 1048576 +## Soft limit for max opened files +$username soft nofile 1048576 +EOF +} + + +## sysctl.conf +function kernel_Tweaking { + tput setaf 2; echo "Configuring sysctl.conf" + tput setaf 1 + cat << EOF >/etc/sysctl.conf +###/proc/sys/kernel/ Variables: +##https://www.kernel.org/doc/Documentation/admin-guide/sysctl/kernel.rst + +# Allow for more PIDs +kernel.pid_max = 4194303 + +# Maximum size of an IPC queue +kernel.msgmnb = 65536 + +# maximum size of an IPC message +kernel.msgmax = 65536 + +## Process Scheduler Optimization +kernel.sched_migration_cost_ns = 5000000 +kernel.sched_autogroup_enabled = 0 +kernel.sched_min_granularity_ns = 10000000 +kernel.sched_wakeup_granularity_ns = 15000000 + + + + + +###/proc/sys/fs/ +##https://www.kernel.org/doc/Documentation/admin-guide/sysctl/fs.rst + +# Maximum number of file-handles that the Linux kernel will allocate +fs.file-max = 1048576 + +# Maximum number of file-handles a process can allocate +fs.nr_open = 1048576 + + + + + + + + +###/proc/sys/vm Variables: +##https://www.kernel.org/doc/Documentation/admin-guide/sysctl/vm.rst + +# Percentage of available system memory which when dirty then system can start writing data to the disks +# NOTE: The total available memory is not equal to total system memory +vm.dirty_background_ratio = 5 +# Percentage of available system memory which when dirty, the process doing writes would block and write out dirty pages to the disks +vm.dirty_ratio = 30 + +# Define when dirty inode is old enough to be eligible for writeback by the kernel flusher threads & interval to wakeup dirtytime_writeback thread +vm.dirty_expire_centisecs = 1000 +# Period between each wake up and write old data out to disk +vm.dirty_writeback_centisecs = 100 + +# Reduce swapping and keep memory pages in physical memory +vm.swappiness = 10 + +# Approaches to reclaim memory when a zone runs out of memory +# Disabled on workload that benefit from having their data cached +# Enable on workload that is partitioned such that each partition fits within a NUMA node and that accessing remote memory would cause a measurable performance reduction +# Walkserver enables it +# vm.zone_reclaim_mode = 1 + + + + + + + + +###/proc/sys/net/core - Network core options: +##https://www.kernel.org/doc/Documentation/admin-guide/sysctl/net.rst + + +# NOTE: Difference in polling and interrupt +# -Interrupt: Interrupt is a hardware mechanism in which, the device notices the CPU that it requires its attention./ +# Interrupt can take place at any time. So when CPU gets an interrupt signal trough the indication interrupt-request line,/ +# CPU stops the current process and respond to the interrupt by passing the control to interrupt handler which services device. +# -Polling: In polling is not a hardware mechanism, its a protocol in which CPU steadily checks whether the device needs attention./ +# Wherever device tells process unit that it desires hardware processing, #in polling process unit keeps asking the I/O device whether or not it desires CPU processing./ +# The CPU ceaselessly check every and each device hooked up thereto for sleuthing whether or not any device desires hardware attention. +# The Linux kernel uses the interrupt-driven mode by default and only switches to polling mode when the flow of incoming packets exceeds "net.core.dev_weight" number of data frames +# The maximum number of packets that kernel can handle on a NAPI interrupt, it's a Per-CPU variable +#net.core.dev_weight = 64 +# Scales the maximum number of packets that can be processed during a RX softirq cycle. Calculation is based on dev_weight (dev_weight * dev_weight_rx_bias) +#net.core.dev_weight_rx_bias = 1 +# Scales the maximum number of packets that can be processed during a TX softirq cycle. Calculation is based on dev_weight (dev_weight * dev_weight_tx_bias) +#net.core.dev_weight_tx_bias = 1 + +# NOTE: If the second column of "cat /proc/net/softnet_stat" is huge, there are frame drops and it might be wise to increase the value of net.core.netdev_max_backlog/ +#If the third column increases, there are SoftIRQ Misses and it might be wise to increase either or both net.core.netdev_budget and net.core.netdev_budget_usecs +# Maximum number of packets taken from all interfaces in one polling cycle (NAPI poll). +net.core.netdev_budget = 50000 +# Maximum number of microseconds in one polling cycle (NAPI poll). +# NOTE: Could reduce if you have a CPU with high single core performance, NIC that supports RSS +# NOTE: Setting a high number might cause CPU to stall and end in poor overall performance +net.core.netdev_budget_usecs = 8000 +# Maximum number of packets, queued on the INPUT side, when the interface receives packets faster than kernel can process them +net.core.netdev_max_backlog = 100000 + +# Low latency busy poll timeout for socket reads +# NOTE: Not supported by most NIC +#net.core.busy_read=50 +# Low latency busy poll timeout for poll and select +# NOTE: Not supported by most NIC +#net.core.busy_poll=50 + + +# Receive socket buffer size +net.core.rmem_default = 16777216 +net.core.rmem_max = 67108864 + +# Send socket buffer size +net.core.wmem_default = 16777216 +net.core.wmem_max = 67108864 + +# Maximum ancillary buffer size allowed per socket +net.core.optmem_max = 4194304 + + + + + + + + +###/proc/sys/net/ipv4/* Variables: +##https://www.kernel.org/doc/Documentation/networking/ip-sysctl.rst + +## Routing Settings +# Time, in seconds, that cached PMTU information is kept +net.ipv4.route.mtu_expires = 1800 + +# Lowest possible mss setting, actuall advertised MSS depends on the first hop route MTU +net.ipv4.route.min_adv_mss = 536 + +# Set PMTU to this value if fragmentation-required ICMP is received for that destination +# NOTE: Only necessary if "net.ipv4.ip_no_pmtu_disc" is set to mode 1 +#net.ipv4.route.min_pmtu = 1500 + + + + +## IP +# System IP port limits +net.ipv4.ip_local_port_range = 1024 65535 + +# Allow Path MTU Discovery +net.ipv4.ip_no_pmtu_disc = 0 + + + + +## ARP table settings +# The maximum number of bytes which may be used by packets queued for each unresolved address by other network layers +net.ipv4.neigh.default.unres_qlen_bytes = 16777216 + +# The maximum number of packets which may be queued for each unresolved address by other network layers +# NOTE: Deprecated in Linux 3.3 : use unres_qlen_bytes instead +#net.ipv4.neigh.default.unres_qlen = 1024 + + + + +## TCP variables +# Maximum queue length of completely established sockets waiting to be accepted +net.core.somaxconn = 500000 + +#Maximum queue length of incomplete sockets i.e. half-open connection +#NOTE: THis value should not be above "net.core.somaxconn", since that is also a hard open limit of maximum queue length of incomplete sockets/ +#Kernel will take the lower one out of two as the maximum queue length of incomplete sockets +net.ipv4.tcp_max_syn_backlog = 500000 + +# Recover and handle all requests instead of resetting them when system is overflowed with a burst of new connection attempts +net.ipv4.tcp_abort_on_overflow = 0 + +# Maximal number of TCP sockets not attached to any user file handle (i.e. orphaned connections), held by system. +# NOTE: each orphan eats up to ~64K of unswappable memory +net.ipv4.tcp_max_orphans = 262144 + +# Maximal number of time-wait sockets held by system simultaneously +net.ipv4.tcp_max_tw_buckets = 10000 + + +# Enable Path MTU Discovery, and use initial MSS of tcp_base_mss +net.ipv4.tcp_mtu_probing = 2 + +# Starting MSS used in Path MTU discovery +net.ipv4.tcp_base_mss = 1460 + +# Minimum MSS used in connection, cap it to this value even if advertised ADVMSS option is even lower +net.ipv4.tcp_min_snd_mss = 536 + + +# Enable select acknowledgments +net.ipv4.tcp_sack = 1 +# Send SACK more frequently +net.ipv4.tcp_comp_sack_delay_ns = 2500000 +# Reduce SACK that can be compressed +net.ipv4.tcp_comp_sack_nr = 10 + +# Allows TCP to send "duplicate" SACKs +net.ipv4.tcp_dsack = 1 + +# Enable Early Retransmit. ER lowers the threshold for triggering fast retransmit when the amount of outstanding data is small and when no previously unsent data can be transmitted +# Default Value +#net.ipv4.tcp_early_retrans = 3 + +# Disable ECN totally +net.ipv4.tcp_ecn = 0 + +# Enable Forward Acknowledgment +# NOTE: This is a legacy option, it has no effect anymore +# net.ipv4.tcp_fack = 1 + + +# TCP buffer size +# Values are measured in memory pages. Size of memory pages can be found by "getconf PAGESIZE". Normally it is 4096 bytes +# Vector of 3 INTEGERs: min, pressure, max +# min: below this number of pages TCP is not bothered about its +# memory appetite. +# +# pressure: when amount of memory allocated by TCP exceeds this number +# of pages, TCP moderates its memory consumption and enters memory +# pressure mode, which is exited when memory consumption falls +# under "min". +# +# max: number of pages allowed for queuing by all TCP sockets +net.ipv4.tcp_mem = 262144 1572864 2097152 + +# TCP sockets receive buffer +# Vector of 3 INTEGERs: min, default, max +# min: Minimal size of receive buffer used by TCP sockets. +# It is guaranteed to each TCP socket, even under moderate memory +# pressure. +# +# default: initial size of receive buffer used by TCP sockets. +# This value overrides net.core.rmem_default used by other protocols. +# +# max: maximal size of receive buffer allowed for automatically +# selected receiver buffers for TCP socket. This value does not override +# net.core.rmem_max. Calling setsockopt() with SO_RCVBUF disables +# automatic tuning of that socket's receive buffer size, in which +# case this value is ignored. +net.ipv4.tcp_rmem = 4194304 16777216 67108864 + +# Disable receive buffer auto-tuning +net.ipv4.tcp_moderate_rcvbuf = 0 + +# Distribution of socket receive buffer space between TCP window size(this is the size of the receive window advertised to the other end), and application buffer/ +#The overhead (application buffer) is counted as bytes/2^tcp_adv_win_scale i.e. Setting this 2 would mean we use 1/4 of socket buffer space as overhead +# NOTE: Overhead reduces the effective window size, which in turn reduces the maximum possible data in flight which is window size*RTT +# NOTE: Overhead helps isolating the network from scheduling and application latencies +net.ipv4.tcp_adv_win_scale = 2 + +# Max reserved byte of TCP window for application buffer. The value will be between window/2^tcp_app_win and mss +# See "https://www.programmersought.com/article/75001203063/" for more detail about tcp_app_win & tcp_adv_win_scale +# NOTE: This application buffer is different from the one assigned by tcp_adv_win_scale +# Default +#net.ipv4.tcp_app_win = 31 + +# TCP sockets send buffer +# Vector of 3 INTEGERs: min, default, max +# min: Amount of memory reserved for send buffers for TCP sockets. +# Each TCP socket has rights to use it due to fact of its birth. +# +# default: initial size of send buffer used by TCP sockets. This +# value overrides net.core.wmem_default used by other protocols. +# It is usually lower than net.core.wmem_default. +# +# max: Maximal amount of memory allowed for automatically tuned +# send buffers for TCP sockets. This value does not override +# net.core.wmem_max. Calling setsockopt() with SO_SNDBUF disables +# automatic tuning of that socket's send buffer size, in which case +# this value is ignored. +net.ipv4.tcp_wmem = 4194304 16777216 67108864 + + +# Reordering level of packets in a TCP stream +# NOTE: Reordering is costly but it happens quite a lot. Instead of declaring packet lost and requiring retransmit, try harder to reorder first +# Initial reordering level of packets in a TCP stream. TCP stack can then dynamically adjust flow reordering level between this initial value and tcp_max_reordering +net.ipv4.tcp_reordering = 10 +# Maximal reordering level of packets in a TCP stream +net.ipv4.tcp_max_reordering = 600 + + +# Number of times SYNACKs for a passive TCP connection attempt will be retransmitted +net.ipv4.tcp_synack_retries = 10 +# Number of times initial SYNs for an active TCP connection attempt will be retransmitted +net.ipv4.tcp_syn_retries = 7 + +# In seconds, time default value for connections to keep alive +net.ipv4.tcp_keepalive_time = 7200 +# How many keepalive probes TCP sends out, until it decides that the connection is broken +net.ipv4.tcp_keepalive_probes = 15 +# In seconds, how frequently the probes are send out +net.ipv4.tcp_keepalive_intvl = 60 + +# Number of retries before killing a TCP connection +# Time, after which TCP decides, that something is wrong due to unacknowledged RTO retransmissions, and reports this suspicion to the network layer. +net.ipv4.tcp_retries1 = 3 +# Time, after which TCP decides to timeout the TCP connection, when RTO retransmissions remain unacknowledged +net.ipv4.tcp_retries2 = 10 + +# How many times to retry to kill connections on the other side before killing it on our own side +net.ipv4.tcp_orphan_retries = 2 + +#Disable TCP auto corking, as it needlessly increasing latency when the application doesn't expect to send more data +net.ipv4.tcp_autocorking = 0 + +# Disables Forward RTO-Recovery, since we are not operating on a lossy wireless network +net.ipv4.tcp_frto = 0 + +# Protect Against TCP TIME-WAIT Assassination +net.ipv4.tcp_rfc1337 = 1 + +# Avoid falling back to slow start after a connection goes idle +net.ipv4.tcp_slow_start_after_idle = 0 + +# Enable both client support & server support of TCP Fast Open +net.ipv4.tcp_fastopen = 3 + +# Disable timestamps +net.ipv4.tcp_timestamps = 0 + +# Keep sockets in the state FIN-WAIT-2 for ultra short period if we were the one closing the socket, because this gives us no benefit and eats up memory +net.ipv4.tcp_fin_timeout = 5 + +# Do not cache metrics on closing connections +net.ipv4.tcp_no_metrics_save = 1 + +# Enable reuse of TIME-WAIT sockets for new connections +net.ipv4.tcp_tw_reuse = 1 + + +# Allows the use of a large window (> 64 kB) on a TCP connection +net.ipv4.tcp_window_scaling = 1 + +# Set maximum window size to MAX_TCP_WINDOW i.e. 32767 in times there is no received window scaling option +net.ipv4.tcp_workaround_signed_windows = 1 + + +# The maximum amount of unsent bytes in TCP socket write queue +net.ipv4.tcp_notsent_lowat = 983040 + +# Controls the amount of data in the Qdisc queue or device queue +net.ipv4.tcp_limit_output_bytes = 3276800 + +# Controls a per TCP socket cache of one socket buffer +# Use Huge amount of memory +#net.ipv4.tcp_rx_skb_cache = 1 + +# Congestion Control +EOF + /sbin/sysctl -p > /dev/null +} + + +## BBR +function BBR_Prepare { + ## Update Kernel + tput setaf 2; echo "Updating Kernel" + tput setaf 7 + echo "deb http://deb.debian.org/debian buster-backports main" | sudo tee -a /etc/apt/sources.list + apt-get -qqy update + apt-get -qqy install linux-image-5.9.0-0.bpo.5-amd64 + curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/BBR/BBR.sh && chmod +x BBR.sh + tput setaf 1 +} +function BBR_Tweaking { + ## This part of the script is modified from https://github.com/KozakaiAya/TCP_BBR + tput setaf 2; echo "Configuring BBR" + apt-get -qqy install dkms > /dev/null + apt-get -qqy install linux-headers-$(uname -r) > /dev/null + tput setaf 7 + curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/BBR/5.9.0/tcp_bbrx.c + kernel_ver=5.9.0 + algo=bbrx + bbr_file=tcp_$algo + bbr_src=$bbr_file.c + bbr_obj=$bbr_file.o + + mkdir -p $HOME/.bbr/src + cd $HOME/.bbr/src + + mv $HOME/$bbr_src $HOME/.bbr/src/$bbr_src + + # Create Makefile + cat > ./Makefile << EOF +obj-m:=$bbr_obj + +default: + make -C /lib/modules/\$(shell uname -r)/build M=\$(PWD)/src modules + +clean: + -rm modules.order + -rm Module.symvers + -rm .[!.]* ..?* + -rm $bbr_file.mod + -rm $bbr_file.mod.c + -rm *.o + -rm *.cmd +EOF + + # Create dkms.conf + cd .. + cat > ./dkms.conf << EOF +MAKE="'make' -C src/" +CLEAN="make -C src/ clean" +BUILT_MODULE_NAME=$bbr_file +BUILT_MODULE_LOCATION=src/ +DEST_MODULE_LOCATION=/updates/net/ipv4 +PACKAGE_NAME=$algo +PACKAGE_VERSION=$kernel_ver +REMAKE_INITRD=yes +EOF + + # Start dkms install + echo "===== Start installation =====" + + cp -R . /usr/src/$algo-$kernel_ver + + /sbin/dkms add -m $algo -v $kernel_ver + if [ ! $? -eq 0 ]; then + echo "DKMS add failed" + /sbin/dkms remove -m $algo/$kernel_ver --all + exit 1 + fi + + /sbin/dkms build -m $algo -v $kernel_ver + if [ ! $? -eq 0 ]; then + echo "DKMS build failed" + /sbin/dkms remove -m $algo/$kernel_ver --all + exit 1 + fi + + /sbin/dkms install -m $algo -v $kernel_ver + if [ ! $? -eq 0 ]; then + echo "DKMS install failed" + /sbin/dkms remove -m $algo/$kernel_ver --all + exit 1 + fi + + # Test loading module + /sbin/modprobe $bbr_file + + if [ ! $? -eq 0 ]; then + echo "modprobe failed, please check your environment" + echo "Please use \"dkms remove -m $algo/$kernel_ver --all\" to remove the dkms module" + exit 1 + fi + + # Auto-load kernel module at system startup + + echo $bbr_file | sudo tee -a /etc/modules + echo "net.core.default_qdisc = fq" >> /etc/sysctl.conf + echo "net.ipv4.tcp_congestion_control = $algo" >> /etc/sysctl.conf + /sbin/sysctl -p > /dev/null + + if [ ! $? -eq 0 ]; then + echo "sysctl failed, please check your environment" + echo "Please use \"dkms remove -m $algo/$kernel_ver --all\" to remove the dkms module" + exit 1 + fi + cd $HOME + rm -r $HOME/.bbr +} + +## Deluge + +#Deluge Libtorrent Config +function Deluge_libtorrent { + tput setaf 2; echo "Configuring Deluge Libtorrent Options" + tput setaf 1 + systemctl stop deluged@$username + cat << EOF >/home/$username/.config/deluge/ltconfig.conf +{ + "file": 1, + "format": 1 +}{ + "apply_on_start": true, + "settings": { + "default_cache_min_age": 10, + "connection_speed": 500, + "connections_limit": 500000, + "guided_read_cache": true, + "max_rejects": 100, + "inactivity_timeout": 120, + "active_seeds": -1, + "max_failcount": 20, + "allowed_fast_set_size": 0, + "max_allowed_in_request_queue": 10000, + "enable_incoming_utp": false, + "unchoke_slots_limit": -1, + "peer_timeout": 120, + "peer_connect_timeout": 30, + "handshake_timeout": 30, + "request_timeout": 5, + "allow_multiple_connections_per_ip": true, + "use_parole_mode": false, + "piece_timeout": 5, + "tick_interval": 100, + "active_limit": -1, + "connect_seed_every_n_download": 50, + "file_pool_size": 5000, + "cache_expiry": 300, + "seed_choking_algorithm": 1, + "max_out_request_queue": 10000, + "send_buffer_watermark": 10485760, + "send_buffer_watermark_factor": 200, + "active_tracker_limit": -1, + "send_buffer_low_watermark": 3145728, + "mixed_mode_algorithm": 0, + "max_queued_disk_bytes": 10485760, + "min_reconnect_time": 2, + "aio_threads": 4, + "write_cache_line_size": 256, + "torrent_connect_boost": 100, + "listen_queue_size": 3000, + "cache_buffer_chunk_size": 256, + "suggest_mode": 1, + "request_queue_time": 5, + "strict_end_game_mode": false, + "use_disk_cache_pool": true, + "predictive_piece_announce": 10, + "prefer_rc4": false, + "whole_pieces_threshold": 5, + "read_cache_line_size": 128, + "initial_picker_threshold": 10, + "enable_outgoing_utp": false, + "cache_size": $Cache1, + "low_prio_disk": false + } +} +EOF + systemctl start deluged@$username +} + diff --git a/BBR/5.9.0/tcp_bbrx.c b/BBR/5.9.0/tcp_bbrx.c new file mode 100644 index 0000000..1ae9609 --- /dev/null +++ b/BBR/5.9.0/tcp_bbrx.c @@ -0,0 +1,1174 @@ +/* Bottleneck Bandwidth and RTT (BBR) congestion control + * + * BBR congestion control computes the sending rate based on the delivery + * rate (throughput) estimated from ACKs. In a nutshell: + * + * On each ACK, update our model of the network path: + * bottleneck_bandwidth = windowed_max(delivered / elapsed, 10 round trips) + * min_rtt = windowed_min(rtt, 10 seconds) + * pacing_rate = pacing_gain * bottleneck_bandwidth + * cwnd = max(cwnd_gain * bottleneck_bandwidth * min_rtt, 4) + * + * The core algorithm does not react directly to packet losses or delays, + * although BBR may adjust the size of next send per ACK when loss is + * observed, or adjust the sending rate if it estimates there is a + * traffic policer, in order to keep the drop rate reasonable. + * + * Here is a state transition diagram for BBR: + * + * | + * V + * +---> STARTUP ----+ + * | | | + * | V | + * | DRAIN ----+ + * | | | + * | V | + * +---> PROBE_BW ----+ + * | ^ | | + * | | | | + * | +----+ | + * | | + * +---- PROBE_RTT <--+ + * + * A BBR flow starts in STARTUP, and ramps up its sending rate quickly. + * When it estimates the pipe is full, it enters DRAIN to drain the queue. + * In steady state a BBR flow only uses PROBE_BW and PROBE_RTT. + * A long-lived BBR flow spends the vast majority of its time remaining + * (repeatedly) in PROBE_BW, fully probing and utilizing the pipe's bandwidth + * in a fair manner, with a small, bounded queue. *If* a flow has been + * continuously sending for the entire min_rtt window, and hasn't seen an RTT + * sample that matches or decreases its min_rtt estimate for 10 seconds, then + * it briefly enters PROBE_RTT to cut inflight to a minimum value to re-probe + * the path's two-way propagation delay (min_rtt). When exiting PROBE_RTT, if + * we estimated that we reached the full bw of the pipe then we enter PROBE_BW; + * otherwise we enter STARTUP to try to fill the pipe. + * + * BBR is described in detail in: + * "BBR: Congestion-Based Congestion Control", + * Neal Cardwell, Yuchung Cheng, C. Stephen Gunn, Soheil Hassas Yeganeh, + * Van Jacobson. ACM Queue, Vol. 14 No. 5, September-October 2016. + * + * There is a public e-mail list for discussing BBR development and testing: + * https://groups.google.com/forum/#!forum/bbr-dev + * + * NOTE: BBR might be used with the fq qdisc ("man tc-fq") with pacing enabled, + * otherwise TCP stack falls back to an internal pacing using one high + * resolution timer per TCP socket and may use more resources. + */ +#include +#include +#include +#include +#include +#include + +/* Scale factor for rate in pkt/uSec unit to avoid truncation in bandwidth + * estimation. The rate unit ~= (1500 bytes / 1 usec / 2^24) ~= 715 bps. + * This handles bandwidths from 0.06pps (715bps) to 256Mpps (3Tbps) in a u32. + * Since the minimum window is >=4 packets, the lower bound isn't + * an issue. The upper bound isn't an issue with existing technologies. + */ +#define BW_SCALE 24 +#define BW_UNIT (1 << BW_SCALE) + +#define BBR_SCALE 8 /* scaling factor for fractions in BBR (e.g. gains) */ +#define BBR_UNIT (1 << BBR_SCALE) + +/* BBR has the following modes for deciding how fast to send: */ +enum bbr_mode { + BBR_STARTUP, /* ramp up sending rate rapidly to fill pipe */ + BBR_DRAIN, /* drain any queue created during startup */ + BBR_PROBE_BW, /* discover, share bw: pace around estimated bw */ + BBR_PROBE_RTT, /* cut inflight to min to probe min_rtt */ +}; + +/* BBR congestion control block */ +struct bbr { + u32 min_rtt_us; /* min RTT in min_rtt_win_sec window */ + u32 min_rtt_stamp; /* timestamp of min_rtt_us */ + u32 probe_rtt_done_stamp; /* end time for BBR_PROBE_RTT mode */ + struct minmax bw; /* Max recent delivery rate in pkts/uS << 24 */ + u32 rtt_cnt; /* count of packet-timed rounds elapsed */ + u32 next_rtt_delivered; /* scb->tx.delivered at end of round */ + u64 cycle_mstamp; /* time of this cycle phase start */ + u32 mode:3, /* current bbr_mode in state machine */ + prev_ca_state:3, /* CA state on previous ACK */ + packet_conservation:1, /* use packet conservation? */ + round_start:1, /* start of packet-timed tx->ack round? */ + idle_restart:1, /* restarting after idle? */ + probe_rtt_round_done:1, /* a BBR_PROBE_RTT round at 4 pkts? */ + unused:13, + lt_is_sampling:1, /* taking long-term ("LT") samples now? */ + lt_rtt_cnt:7, /* round trips in long-term interval */ + lt_use_bw:1; /* use lt_bw as our bw estimate? */ + u32 lt_bw; /* LT est delivery rate in pkts/uS << 24 */ + u32 lt_last_delivered; /* LT intvl start: tp->delivered */ + u32 lt_last_stamp; /* LT intvl start: tp->delivered_mstamp */ + u32 lt_last_lost; /* LT intvl start: tp->lost */ + u32 pacing_gain:10, /* current gain for setting pacing rate */ + cwnd_gain:10, /* current gain for setting cwnd */ + full_bw_reached:1, /* reached full bw in Startup? */ + full_bw_cnt:2, /* number of rounds without large bw gains */ + cycle_idx:3, /* current index in pacing_gain cycle array */ + has_seen_rtt:1, /* have we seen an RTT sample yet? */ + unused_b:5; + u32 prior_cwnd; /* prior cwnd upon entering loss recovery */ + u32 full_bw; /* recent bw, to estimate if pipe is full */ + + /* For tracking ACK aggregation: */ + u64 ack_epoch_mstamp; /* start of ACK sampling epoch */ + u16 extra_acked[2]; /* max excess data ACKed in epoch */ + u32 ack_epoch_acked:20, /* packets (S)ACKed in sampling epoch */ + extra_acked_win_rtts:5, /* age of extra_acked, in round trips */ + extra_acked_win_idx:1, /* current index in extra_acked array */ + unused_c:6; +}; + +#define CYCLE_LEN 8 /* number of phases in a pacing gain cycle */ + +/* Window length of bw filter (in rounds): */ +static const int bbr_bw_rtts = CYCLE_LEN + 2; +/* Window length of min_rtt filter (in sec): */ +static const u32 bbr_min_rtt_win_sec = 600; +/* Minimum time (in ms) spent at bbr_cwnd_min_target in BBR_PROBE_RTT mode: */ +static const u32 bbr_probe_rtt_mode_ms = 100; +/* Skip TSO below the following bandwidth (bits/sec): */ +static const int bbr_min_tso_rate = 1200000; + +/* Pace at ~1% below estimated bw, on average, to reduce queue at bottleneck. + * In order to help drive the network toward lower queues and low latency while + * maintaining high utilization, the average pacing rate aims to be slightly + * lower than the estimated bandwidth. This is an important aspect of the + * design. + */ +static const int bbr_pacing_margin_percent = 5; + +/* We use a high_gain value of 2/ln(2) because it's the smallest pacing gain + * that will allow a smoothly increasing pacing rate that will double each RTT + * and send the same number of packets per RTT that an un-paced, slow-starting + * Reno or CUBIC flow would: + */ +static const int bbr_high_gain = BBR_UNIT * 6000 / 1000 + 1; +/* The pacing gain of 1/high_gain in BBR_DRAIN is calculated to typically drain + * the queue created in BBR_STARTUP in a single round: + */ +static const int bbr_drain_gain = BBR_UNIT * 1000 / 2885; +/* The gain for deriving steady-state cwnd tolerates delayed/stretched ACKs: */ +static const int bbr_cwnd_gain = BBR_UNIT * 4; +/* The pacing_gain values for the PROBE_BW gain cycle, to discover/share bw: */ +static const int bbr_pacing_gain[] = { + BBR_UNIT * 8 / 4, /* probe for more available bw */ + BBR_UNIT * 6 / 4, /* drain queue and/or yield bw to other flows */ + BBR_UNIT * 6 / 4, BBR_UNIT * 5 / 6, BBR_UNIT * 6 / 4, /* cruise at 1.0*bw to utilize pipe, */ + BBR_UNIT * 6 / 4, BBR_UNIT * 5 / 6, BBR_UNIT * 6 / 4 /* without creating excess queue... */ +}; +/* Randomize the starting gain cycling phase over N phases: */ +static const u32 bbr_cycle_rand = 7; + +/* Try to keep at least this many packets in flight, if things go smoothly. For + * smooth functioning, a sliding window protocol ACKing every other packet + * needs at least 4 packets in flight: + */ +static const u32 bbr_cwnd_min_target = 200; + +/* To estimate if BBR_STARTUP mode (i.e. high_gain) has filled pipe... */ +/* If bw has increased significantly (1.25x), there may be more bw available: */ +static const u32 bbr_full_bw_thresh = BBR_UNIT * 105 / 100; +/* But after 3 rounds w/o significant bw growth, estimate pipe is full: */ +static const u32 bbr_full_bw_cnt = 10; + +/* "long-term" ("LT") bandwidth estimator parameters... */ +/* The minimum number of rounds in an LT bw sampling interval: */ +static const u32 bbr_lt_intvl_min_rtts = 1; +/* If lost/delivered ratio > 20%, interval is "lossy" and we may be policed: */ +static const u32 bbr_lt_loss_thresh = 50; +/* If 2 intervals have a bw ratio <= 1/8, their bw is "consistent": */ +static const u32 bbr_lt_bw_ratio = BBR_UNIT / 2; +/* If 2 intervals have a bw diff <= 4 Kbit/sec their bw is "consistent": */ +static const u32 bbr_lt_bw_diff = 4000000 / 8; +/* If we estimate we're policed, use lt_bw for this many round trips: */ +static const u32 bbr_lt_bw_max_rtts = 48; + +/* Gain factor for adding extra_acked to target cwnd: */ +static const int bbr_extra_acked_gain = BBR_UNIT * 6 / 4; +/* Window length of extra_acked window. */ +static const u32 bbr_extra_acked_win_rtts = 15; +/* Max allowed val for ack_epoch_acked, after which sampling epoch is reset */ +static const u32 bbr_ack_epoch_acked_reset_thresh = 1U << 20; +/* Time period for clamping cwnd increment due to ack aggregation */ +static const u32 bbr_extra_acked_max_us = 25 * 1000; + +static void bbr_check_probe_rtt_done(struct sock *sk); + +/* Do we estimate that STARTUP filled the pipe? */ +static bool bbr_full_bw_reached(const struct sock *sk) +{ + const struct bbr *bbr = inet_csk_ca(sk); + + return bbr->full_bw_reached; +} + +/* Return the windowed max recent bandwidth sample, in pkts/uS << BW_SCALE. */ +static u32 bbr_max_bw(const struct sock *sk) +{ + struct bbr *bbr = inet_csk_ca(sk); + + return minmax_get(&bbr->bw); +} + +/* Return the estimated bandwidth of the path, in pkts/uS << BW_SCALE. */ +static u32 bbr_bw(const struct sock *sk) +{ + struct bbr *bbr = inet_csk_ca(sk); + + return bbr->lt_use_bw ? bbr->lt_bw : bbr_max_bw(sk); +} + +/* Return maximum extra acked in past k-2k round trips, + * where k = bbr_extra_acked_win_rtts. + */ +static u16 bbr_extra_acked(const struct sock *sk) +{ + struct bbr *bbr = inet_csk_ca(sk); + + return max(bbr->extra_acked[0], bbr->extra_acked[1]); +} + +/* Return rate in bytes per second, optionally with a gain. + * The order here is chosen carefully to avoid overflow of u64. This should + * work for input rates of up to 2.9Tbit/sec and gain of 2.89x. + */ +static u64 bbr_rate_bytes_per_sec(struct sock *sk, u64 rate, int gain) +{ + unsigned int mss = tcp_sk(sk)->mss_cache; + + rate *= mss; + rate *= gain; + rate >>= BBR_SCALE; + rate *= USEC_PER_SEC / 100 * (100 + bbr_pacing_margin_percent); + return rate >> BW_SCALE; +} + +/* Convert a BBR bw and gain factor to a pacing rate in bytes per second. */ +static unsigned long bbr_bw_to_pacing_rate(struct sock *sk, u32 bw, int gain) +{ + u64 rate = bw; + + rate = bbr_rate_bytes_per_sec(sk, rate, gain); + rate = min_t(u64, rate, sk->sk_max_pacing_rate); + return rate; +} + +/* Initialize pacing rate to: high_gain * init_cwnd / RTT. */ +static void bbr_init_pacing_rate_from_rtt(struct sock *sk) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + u64 bw; + u32 rtt_us; + + if (tp->srtt_us) { /* any RTT sample yet? */ + rtt_us = max(tp->srtt_us >> 3, 1U); + bbr->has_seen_rtt = 1; + } else { /* no RTT sample yet */ + rtt_us = USEC_PER_MSEC; /* use nominal default RTT */ + } + bw = (u64)tp->snd_cwnd * BW_UNIT; + do_div(bw, rtt_us); + sk->sk_pacing_rate = bbr_bw_to_pacing_rate(sk, bw, bbr_high_gain); +} + +/* Pace using current bw estimate and a gain factor. */ +static void bbr_set_pacing_rate(struct sock *sk, u32 bw, int gain) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + unsigned long rate = bbr_bw_to_pacing_rate(sk, bw, gain); + + if (unlikely(!bbr->has_seen_rtt && tp->srtt_us)) + bbr_init_pacing_rate_from_rtt(sk); + if (bbr_full_bw_reached(sk) || rate > sk->sk_pacing_rate) + sk->sk_pacing_rate = rate; +} + +/* override sysctl_tcp_min_tso_segs */ +static u32 bbr_min_tso_segs(struct sock *sk) +{ + return sk->sk_pacing_rate < (bbr_min_tso_rate >> 3) ? 1 : 2; +} + +static u32 bbr_tso_segs_goal(struct sock *sk) +{ + struct tcp_sock *tp = tcp_sk(sk); + u32 segs, bytes; + + /* Sort of tcp_tso_autosize() but ignoring + * driver provided sk_gso_max_size. + */ + bytes = min_t(unsigned long, + sk->sk_pacing_rate >> READ_ONCE(sk->sk_pacing_shift), + GSO_MAX_SIZE - 1 - MAX_TCP_HEADER); + segs = max_t(u32, bytes / tp->mss_cache, bbr_min_tso_segs(sk)); + + return min(segs, 0x7FU); +} + +/* Save "last known good" cwnd so we can restore it after losses or PROBE_RTT */ +static void bbr_save_cwnd(struct sock *sk) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + + if (bbr->prev_ca_state < TCP_CA_Recovery && bbr->mode != BBR_PROBE_RTT) + bbr->prior_cwnd = tp->snd_cwnd; /* this cwnd is good enough */ + else /* loss recovery or BBR_PROBE_RTT have temporarily cut cwnd */ + bbr->prior_cwnd = max(bbr->prior_cwnd, tp->snd_cwnd); +} + +static void bbr_cwnd_event(struct sock *sk, enum tcp_ca_event event) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + + if (event == CA_EVENT_TX_START && tp->app_limited) { + bbr->idle_restart = 1; + bbr->ack_epoch_mstamp = tp->tcp_mstamp; + bbr->ack_epoch_acked = 0; + /* Avoid pointless buffer overflows: pace at est. bw if we don't + * need more speed (we're restarting from idle and app-limited). + */ + if (bbr->mode == BBR_PROBE_BW) + bbr_set_pacing_rate(sk, bbr_bw(sk), BBR_UNIT); + else if (bbr->mode == BBR_PROBE_RTT) + bbr_check_probe_rtt_done(sk); + } +} + +/* Calculate bdp based on min RTT and the estimated bottleneck bandwidth: + * + * bdp = ceil(bw * min_rtt * gain) + * + * The key factor, gain, controls the amount of queue. While a small gain + * builds a smaller queue, it becomes more vulnerable to noise in RTT + * measurements (e.g., delayed ACKs or other ACK compression effects). This + * noise may cause BBR to under-estimate the rate. + */ +static u32 bbr_bdp(struct sock *sk, u32 bw, int gain) +{ + struct bbr *bbr = inet_csk_ca(sk); + u32 bdp; + u64 w; + + /* If we've never had a valid RTT sample, cap cwnd at the initial + * default. This should only happen when the connection is not using TCP + * timestamps and has retransmitted all of the SYN/SYNACK/data packets + * ACKed so far. In this case, an RTO can cut cwnd to 1, in which + * case we need to slow-start up toward something safe: TCP_INIT_CWND. + */ + if (unlikely(bbr->min_rtt_us == ~0U)) /* no valid RTT samples yet? */ + return TCP_INIT_CWND; /* be safe: cap at default initial cwnd*/ + + w = (u64)bw * bbr->min_rtt_us; + + /* Apply a gain to the given value, remove the BW_SCALE shift, and + * round the value up to avoid a negative feedback loop. + */ + bdp = (((w * gain) >> BBR_SCALE) + BW_UNIT - 1) / BW_UNIT; + + return bdp; +} + +/* To achieve full performance in high-speed paths, we budget enough cwnd to + * fit full-sized skbs in-flight on both end hosts to fully utilize the path: + * - one skb in sending host Qdisc, + * - one skb in sending host TSO/GSO engine + * - one skb being received by receiver host LRO/GRO/delayed-ACK engine + * Don't worry, at low rates (bbr_min_tso_rate) this won't bloat cwnd because + * in such cases tso_segs_goal is 1. The minimum cwnd is 4 packets, + * which allows 2 outstanding 2-packet sequences, to try to keep pipe + * full even with ACK-every-other-packet delayed ACKs. + */ +static u32 bbr_quantization_budget(struct sock *sk, u32 cwnd) +{ + struct bbr *bbr = inet_csk_ca(sk); + + /* Allow enough full-sized skbs in flight to utilize end systems. */ + cwnd += 3 * bbr_tso_segs_goal(sk); + + /* Reduce delayed ACKs by rounding up cwnd to the next even number. */ + cwnd = (cwnd + 1) & ~1U; + + /* Ensure gain cycling gets inflight above BDP even for small BDPs. */ + if (bbr->mode == BBR_PROBE_BW && bbr->cycle_idx == 0) + cwnd += 2; + + return cwnd; +} + +/* Find inflight based on min RTT and the estimated bottleneck bandwidth. */ +static u32 bbr_inflight(struct sock *sk, u32 bw, int gain) +{ + u32 inflight; + + inflight = bbr_bdp(sk, bw, gain); + inflight = bbr_quantization_budget(sk, inflight); + + return inflight; +} + +/* With pacing at lower layers, there's often less data "in the network" than + * "in flight". With TSQ and departure time pacing at lower layers (e.g. fq), + * we often have several skbs queued in the pacing layer with a pre-scheduled + * earliest departure time (EDT). BBR adapts its pacing rate based on the + * inflight level that it estimates has already been "baked in" by previous + * departure time decisions. We calculate a rough estimate of the number of our + * packets that might be in the network at the earliest departure time for the + * next skb scheduled: + * in_network_at_edt = inflight_at_edt - (EDT - now) * bw + * If we're increasing inflight, then we want to know if the transmit of the + * EDT skb will push inflight above the target, so inflight_at_edt includes + * bbr_tso_segs_goal() from the skb departing at EDT. If decreasing inflight, + * then estimate if inflight will sink too low just before the EDT transmit. + */ +static u32 bbr_packets_in_net_at_edt(struct sock *sk, u32 inflight_now) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + u64 now_ns, edt_ns, interval_us; + u32 interval_delivered, inflight_at_edt; + + now_ns = tp->tcp_clock_cache; + edt_ns = max(tp->tcp_wstamp_ns, now_ns); + interval_us = div_u64(edt_ns - now_ns, NSEC_PER_USEC); + interval_delivered = (u64)bbr_bw(sk) * interval_us >> BW_SCALE; + inflight_at_edt = inflight_now; + if (bbr->pacing_gain > BBR_UNIT) /* increasing inflight */ + inflight_at_edt += bbr_tso_segs_goal(sk); /* include EDT skb */ + if (interval_delivered >= inflight_at_edt) + return 0; + return inflight_at_edt - interval_delivered; +} + +/* Find the cwnd increment based on estimate of ack aggregation */ +static u32 bbr_ack_aggregation_cwnd(struct sock *sk) +{ + u32 max_aggr_cwnd, aggr_cwnd = 0; + + if (bbr_extra_acked_gain && bbr_full_bw_reached(sk)) { + max_aggr_cwnd = ((u64)bbr_bw(sk) * bbr_extra_acked_max_us) + / BW_UNIT; + aggr_cwnd = (bbr_extra_acked_gain * bbr_extra_acked(sk)) + >> BBR_SCALE; + aggr_cwnd = min(aggr_cwnd, max_aggr_cwnd); + } + + return aggr_cwnd; +} + +/* An optimization in BBR to reduce losses: On the first round of recovery, we + * follow the packet conservation principle: send P packets per P packets acked. + * After that, we slow-start and send at most 2*P packets per P packets acked. + * After recovery finishes, or upon undo, we restore the cwnd we had when + * recovery started (capped by the target cwnd based on estimated BDP). + * + * TODO(ycheng/ncardwell): implement a rate-based approach. + */ +static bool bbr_set_cwnd_to_recover_or_restore( + struct sock *sk, const struct rate_sample *rs, u32 acked, u32 *new_cwnd) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + u8 prev_state = bbr->prev_ca_state, state = inet_csk(sk)->icsk_ca_state; + u32 cwnd = tp->snd_cwnd; + + /* An ACK for P pkts should release at most 2*P packets. We do this + * in two steps. First, here we deduct the number of lost packets. + * Then, in bbr_set_cwnd() we slow start up toward the target cwnd. + */ + if (rs->losses > 0) + cwnd = max_t(s32, cwnd - rs->losses, 1); + + if (state == TCP_CA_Recovery && prev_state != TCP_CA_Recovery) { + /* Starting 1st round of Recovery, so do packet conservation. */ + bbr->packet_conservation = 1; + bbr->next_rtt_delivered = tp->delivered; /* start round now */ + /* Cut unused cwnd from app behavior, TSQ, or TSO deferral: */ + cwnd = tcp_packets_in_flight(tp) + acked; + } else if (prev_state >= TCP_CA_Recovery && state < TCP_CA_Recovery) { + /* Exiting loss recovery; restore cwnd saved before recovery. */ + cwnd = max(cwnd, bbr->prior_cwnd); + bbr->packet_conservation = 0; + } + bbr->prev_ca_state = state; + + if (bbr->packet_conservation) { + *new_cwnd = max(cwnd, tcp_packets_in_flight(tp) + acked); + return true; /* yes, using packet conservation */ + } + *new_cwnd = cwnd; + return false; +} + +/* Slow-start up toward target cwnd (if bw estimate is growing, or packet loss + * has drawn us down below target), or snap down to target if we're above it. + */ +static void bbr_set_cwnd(struct sock *sk, const struct rate_sample *rs, + u32 acked, u32 bw, int gain) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + u32 cwnd = tp->snd_cwnd, target_cwnd = 0; + + if (!acked) + goto done; /* no packet fully ACKed; just apply caps */ + + if (bbr_set_cwnd_to_recover_or_restore(sk, rs, acked, &cwnd)) + goto done; + + target_cwnd = bbr_bdp(sk, bw, gain); + + /* Increment the cwnd to account for excess ACKed data that seems + * due to aggregation (of data and/or ACKs) visible in the ACK stream. + */ + target_cwnd += bbr_ack_aggregation_cwnd(sk); + target_cwnd = bbr_quantization_budget(sk, target_cwnd); + + /* If we're below target cwnd, slow start cwnd toward target cwnd. */ + if (bbr_full_bw_reached(sk)) /* only cut cwnd if we filled the pipe */ + cwnd = min(cwnd + acked, target_cwnd); + else if (cwnd < target_cwnd || tp->delivered < TCP_INIT_CWND) + cwnd = cwnd + acked; + cwnd = max(cwnd, bbr_cwnd_min_target); + +done: + tp->snd_cwnd = min(cwnd, tp->snd_cwnd_clamp); /* apply global cap */ + if (bbr->mode == BBR_PROBE_RTT) /* drain queue, refresh min_rtt */ + tp->snd_cwnd = min(tp->snd_cwnd, bbr_cwnd_min_target); +} + +/* End cycle phase if it's time and/or we hit the phase's in-flight target. */ +static bool bbr_is_next_cycle_phase(struct sock *sk, + const struct rate_sample *rs) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + bool is_full_length = + tcp_stamp_us_delta(tp->delivered_mstamp, bbr->cycle_mstamp) > + bbr->min_rtt_us; + u32 inflight, bw; + + /* The pacing_gain of 1.0 paces at the estimated bw to try to fully + * use the pipe without increasing the queue. + */ + if (bbr->pacing_gain == BBR_UNIT) + return is_full_length; /* just use wall clock time */ + + inflight = bbr_packets_in_net_at_edt(sk, rs->prior_in_flight); + bw = bbr_max_bw(sk); + + /* A pacing_gain > 1.0 probes for bw by trying to raise inflight to at + * least pacing_gain*BDP; this may take more than min_rtt if min_rtt is + * small (e.g. on a LAN). We do not persist if packets are lost, since + * a path with small buffers may not hold that much. + */ + if (bbr->pacing_gain > BBR_UNIT) + return is_full_length && + (rs->losses || /* perhaps pacing_gain*BDP won't fit */ + inflight >= bbr_inflight(sk, bw, bbr->pacing_gain)); + + /* A pacing_gain < 1.0 tries to drain extra queue we added if bw + * probing didn't find more bw. If inflight falls to match BDP then we + * estimate queue is drained; persisting would underutilize the pipe. + */ + return is_full_length || + inflight <= bbr_inflight(sk, bw, BBR_UNIT); +} + +static void bbr_advance_cycle_phase(struct sock *sk) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + + bbr->cycle_idx = (bbr->cycle_idx + 1) & (CYCLE_LEN - 1); + bbr->cycle_mstamp = tp->delivered_mstamp; +} + +/* Gain cycling: cycle pacing gain to converge to fair share of available bw. */ +static void bbr_update_cycle_phase(struct sock *sk, + const struct rate_sample *rs) +{ + struct bbr *bbr = inet_csk_ca(sk); + + if (bbr->mode == BBR_PROBE_BW && bbr_is_next_cycle_phase(sk, rs)) + bbr_advance_cycle_phase(sk); +} + +static void bbr_reset_startup_mode(struct sock *sk) +{ + struct bbr *bbr = inet_csk_ca(sk); + + bbr->mode = BBR_STARTUP; +} + +static void bbr_reset_probe_bw_mode(struct sock *sk) +{ + struct bbr *bbr = inet_csk_ca(sk); + + bbr->mode = BBR_PROBE_BW; + bbr->cycle_idx = CYCLE_LEN - 1 - prandom_u32_max(bbr_cycle_rand); + bbr_advance_cycle_phase(sk); /* flip to next phase of gain cycle */ +} + +static void bbr_reset_mode(struct sock *sk) +{ + if (!bbr_full_bw_reached(sk)) + bbr_reset_startup_mode(sk); + else + bbr_reset_probe_bw_mode(sk); +} + +/* Start a new long-term sampling interval. */ +static void bbr_reset_lt_bw_sampling_interval(struct sock *sk) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + + bbr->lt_last_stamp = div_u64(tp->delivered_mstamp, USEC_PER_MSEC); + bbr->lt_last_delivered = tp->delivered; + bbr->lt_last_lost = tp->lost; + bbr->lt_rtt_cnt = 0; +} + +/* Completely reset long-term bandwidth sampling. */ +static void bbr_reset_lt_bw_sampling(struct sock *sk) +{ + struct bbr *bbr = inet_csk_ca(sk); + + bbr->lt_bw = 0; + bbr->lt_use_bw = 0; + bbr->lt_is_sampling = false; + bbr_reset_lt_bw_sampling_interval(sk); +} + +/* Long-term bw sampling interval is done. Estimate whether we're policed. */ +static void bbr_lt_bw_interval_done(struct sock *sk, u32 bw) +{ + struct bbr *bbr = inet_csk_ca(sk); + u32 diff; + + if (bbr->lt_bw) { /* do we have bw from a previous interval? */ + /* Is new bw close to the lt_bw from the previous interval? */ + diff = abs(bw - bbr->lt_bw); + if ((diff * BBR_UNIT <= bbr_lt_bw_ratio * bbr->lt_bw) || + (bbr_rate_bytes_per_sec(sk, diff, BBR_UNIT) <= + bbr_lt_bw_diff)) { + /* All criteria are met; estimate we're policed. */ + bbr->lt_bw = (bw + bbr->lt_bw) >> 1; /* avg 2 intvls */ + bbr->lt_use_bw = 1; + bbr->pacing_gain = BBR_UNIT; /* try to avoid drops */ + bbr->lt_rtt_cnt = 0; + return; + } + } + bbr->lt_bw = bw; + bbr_reset_lt_bw_sampling_interval(sk); +} + +/* Token-bucket traffic policers are common (see "An Internet-Wide Analysis of + * Traffic Policing", SIGCOMM 2016). BBR detects token-bucket policers and + * explicitly models their policed rate, to reduce unnecessary losses. We + * estimate that we're policed if we see 2 consecutive sampling intervals with + * consistent throughput and high packet loss. If we think we're being policed, + * set lt_bw to the "long-term" average delivery rate from those 2 intervals. + */ +static void bbr_lt_bw_sampling(struct sock *sk, const struct rate_sample *rs) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + u32 lost, delivered; + u64 bw; + u32 t; + + if (bbr->lt_use_bw) { /* already using long-term rate, lt_bw? */ + if (bbr->mode == BBR_PROBE_BW && bbr->round_start && + ++bbr->lt_rtt_cnt >= bbr_lt_bw_max_rtts) { + bbr_reset_lt_bw_sampling(sk); /* stop using lt_bw */ + bbr_reset_probe_bw_mode(sk); /* restart gain cycling */ + } + return; + } + + /* Wait for the first loss before sampling, to let the policer exhaust + * its tokens and estimate the steady-state rate allowed by the policer. + * Starting samples earlier includes bursts that over-estimate the bw. + */ + if (!bbr->lt_is_sampling) { + if (!rs->losses) + return; + bbr_reset_lt_bw_sampling_interval(sk); + bbr->lt_is_sampling = true; + } + + /* To avoid underestimates, reset sampling if we run out of data. */ + if (rs->is_app_limited) { + bbr_reset_lt_bw_sampling(sk); + return; + } + + if (bbr->round_start) + bbr->lt_rtt_cnt++; /* count round trips in this interval */ + if (bbr->lt_rtt_cnt < bbr_lt_intvl_min_rtts) + return; /* sampling interval needs to be longer */ + if (bbr->lt_rtt_cnt > 4 * bbr_lt_intvl_min_rtts) { + bbr_reset_lt_bw_sampling(sk); /* interval is too long */ + return; + } + + /* End sampling interval when a packet is lost, so we estimate the + * policer tokens were exhausted. Stopping the sampling before the + * tokens are exhausted under-estimates the policed rate. + */ + if (!rs->losses) + return; + + /* Calculate packets lost and delivered in sampling interval. */ + lost = tp->lost - bbr->lt_last_lost; + delivered = tp->delivered - bbr->lt_last_delivered; + /* Is loss rate (lost/delivered) >= lt_loss_thresh? If not, wait. */ + if (!delivered || (lost << BBR_SCALE) < bbr_lt_loss_thresh * delivered) + return; + + /* Find average delivery rate in this sampling interval. */ + t = div_u64(tp->delivered_mstamp, USEC_PER_MSEC) - bbr->lt_last_stamp; + if ((s32)t < 1) + return; /* interval is less than one ms, so wait */ + /* Check if can multiply without overflow */ + if (t >= ~0U / USEC_PER_MSEC) { + bbr_reset_lt_bw_sampling(sk); /* interval too long; reset */ + return; + } + t *= USEC_PER_MSEC; + bw = (u64)delivered * BW_UNIT; + do_div(bw, t); + bbr_lt_bw_interval_done(sk, bw); +} + +/* Estimate the bandwidth based on how fast packets are delivered */ +static void bbr_update_bw(struct sock *sk, const struct rate_sample *rs) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + u64 bw; + + bbr->round_start = 0; + if (rs->delivered < 0 || rs->interval_us <= 0) + return; /* Not a valid observation */ + + /* See if we've reached the next RTT */ + if (!before(rs->prior_delivered, bbr->next_rtt_delivered)) { + bbr->next_rtt_delivered = tp->delivered; + bbr->rtt_cnt++; + bbr->round_start = 1; + bbr->packet_conservation = 0; + } + + bbr_lt_bw_sampling(sk, rs); + + /* Divide delivered by the interval to find a (lower bound) bottleneck + * bandwidth sample. Delivered is in packets and interval_us in uS and + * ratio will be <<1 for most connections. So delivered is first scaled. + */ + bw = div64_long((u64)rs->delivered * BW_UNIT, rs->interval_us); + + /* If this sample is application-limited, it is likely to have a very + * low delivered count that represents application behavior rather than + * the available network rate. Such a sample could drag down estimated + * bw, causing needless slow-down. Thus, to continue to send at the + * last measured network rate, we filter out app-limited samples unless + * they describe the path bw at least as well as our bw model. + * + * So the goal during app-limited phase is to proceed with the best + * network rate no matter how long. We automatically leave this + * phase when app writes faster than the network can deliver :) + */ + if (!rs->is_app_limited || bw >= bbr_max_bw(sk)) { + /* Incorporate new sample into our max bw filter. */ + minmax_running_max(&bbr->bw, bbr_bw_rtts, bbr->rtt_cnt, bw); + } +} + +/* Estimates the windowed max degree of ack aggregation. + * This is used to provision extra in-flight data to keep sending during + * inter-ACK silences. + * + * Degree of ack aggregation is estimated as extra data acked beyond expected. + * + * max_extra_acked = "maximum recent excess data ACKed beyond max_bw * interval" + * cwnd += max_extra_acked + * + * Max extra_acked is clamped by cwnd and bw * bbr_extra_acked_max_us (100 ms). + * Max filter is an approximate sliding window of 5-10 (packet timed) round + * trips. + */ +static void bbr_update_ack_aggregation(struct sock *sk, + const struct rate_sample *rs) +{ + u32 epoch_us, expected_acked, extra_acked; + struct bbr *bbr = inet_csk_ca(sk); + struct tcp_sock *tp = tcp_sk(sk); + + if (!bbr_extra_acked_gain || rs->acked_sacked <= 0 || + rs->delivered < 0 || rs->interval_us <= 0) + return; + + if (bbr->round_start) { + bbr->extra_acked_win_rtts = min(0x1F, + bbr->extra_acked_win_rtts + 1); + if (bbr->extra_acked_win_rtts >= bbr_extra_acked_win_rtts) { + bbr->extra_acked_win_rtts = 0; + bbr->extra_acked_win_idx = bbr->extra_acked_win_idx ? + 0 : 1; + bbr->extra_acked[bbr->extra_acked_win_idx] = 0; + } + } + + /* Compute how many packets we expected to be delivered over epoch. */ + epoch_us = tcp_stamp_us_delta(tp->delivered_mstamp, + bbr->ack_epoch_mstamp); + expected_acked = ((u64)bbr_bw(sk) * epoch_us) / BW_UNIT; + + /* Reset the aggregation epoch if ACK rate is below expected rate or + * significantly large no. of ack received since epoch (potentially + * quite old epoch). + */ + if (bbr->ack_epoch_acked <= expected_acked || + (bbr->ack_epoch_acked + rs->acked_sacked >= + bbr_ack_epoch_acked_reset_thresh)) { + bbr->ack_epoch_acked = 0; + bbr->ack_epoch_mstamp = tp->delivered_mstamp; + expected_acked = 0; + } + + /* Compute excess data delivered, beyond what was expected. */ + bbr->ack_epoch_acked = min_t(u32, 0xFFFFF, + bbr->ack_epoch_acked + rs->acked_sacked); + extra_acked = bbr->ack_epoch_acked - expected_acked; + extra_acked = min(extra_acked, tp->snd_cwnd); + if (extra_acked > bbr->extra_acked[bbr->extra_acked_win_idx]) + bbr->extra_acked[bbr->extra_acked_win_idx] = extra_acked; +} + +/* Estimate when the pipe is full, using the change in delivery rate: BBR + * estimates that STARTUP filled the pipe if the estimated bw hasn't changed by + * at least bbr_full_bw_thresh (25%) after bbr_full_bw_cnt (3) non-app-limited + * rounds. Why 3 rounds: 1: rwin autotuning grows the rwin, 2: we fill the + * higher rwin, 3: we get higher delivery rate samples. Or transient + * cross-traffic or radio noise can go away. CUBIC Hystart shares a similar + * design goal, but uses delay and inter-ACK spacing instead of bandwidth. + */ +static void bbr_check_full_bw_reached(struct sock *sk, + const struct rate_sample *rs) +{ + struct bbr *bbr = inet_csk_ca(sk); + u32 bw_thresh; + + if (bbr_full_bw_reached(sk) || !bbr->round_start || rs->is_app_limited) + return; + + bw_thresh = (u64)bbr->full_bw * bbr_full_bw_thresh >> BBR_SCALE; + if (bbr_max_bw(sk) >= bw_thresh) { + bbr->full_bw = bbr_max_bw(sk); + bbr->full_bw_cnt = 0; + return; + } + ++bbr->full_bw_cnt; + bbr->full_bw_reached = bbr->full_bw_cnt >= bbr_full_bw_cnt; +} + +/* If pipe is probably full, drain the queue and then enter steady-state. */ +static void bbr_check_drain(struct sock *sk, const struct rate_sample *rs) +{ + struct bbr *bbr = inet_csk_ca(sk); + + if (bbr->mode == BBR_STARTUP && bbr_full_bw_reached(sk)) { + bbr->mode = BBR_DRAIN; /* drain queue we created */ + tcp_sk(sk)->snd_ssthresh = + bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT); + } /* fall through to check if in-flight is already small: */ + if (bbr->mode == BBR_DRAIN && + bbr_packets_in_net_at_edt(sk, tcp_packets_in_flight(tcp_sk(sk))) <= + bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT)) + bbr_reset_probe_bw_mode(sk); /* we estimate queue is drained */ +} + +static void bbr_check_probe_rtt_done(struct sock *sk) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + + if (!(bbr->probe_rtt_done_stamp && + after(tcp_jiffies32, bbr->probe_rtt_done_stamp))) + return; + + bbr->min_rtt_stamp = tcp_jiffies32; /* wait a while until PROBE_RTT */ + tp->snd_cwnd = max(tp->snd_cwnd, bbr->prior_cwnd); + bbr_reset_mode(sk); +} + +/* The goal of PROBE_RTT mode is to have BBR flows cooperatively and + * periodically drain the bottleneck queue, to converge to measure the true + * min_rtt (unloaded propagation delay). This allows the flows to keep queues + * small (reducing queuing delay and packet loss) and achieve fairness among + * BBR flows. + * + * The min_rtt filter window is 10 seconds. When the min_rtt estimate expires, + * we enter PROBE_RTT mode and cap the cwnd at bbr_cwnd_min_target=4 packets. + * After at least bbr_probe_rtt_mode_ms=200ms and at least one packet-timed + * round trip elapsed with that flight size <= 4, we leave PROBE_RTT mode and + * re-enter the previous mode. BBR uses 200ms to approximately bound the + * performance penalty of PROBE_RTT's cwnd capping to roughly 2% (200ms/10s). + * + * Note that flows need only pay 2% if they are busy sending over the last 10 + * seconds. Interactive applications (e.g., Web, RPCs, video chunks) often have + * natural silences or low-rate periods within 10 seconds where the rate is low + * enough for long enough to drain its queue in the bottleneck. We pick up + * these min RTT measurements opportunistically with our min_rtt filter. :-) + */ +static void bbr_update_min_rtt(struct sock *sk, const struct rate_sample *rs) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + bool filter_expired; + + /* Track min RTT seen in the min_rtt_win_sec filter window: */ + filter_expired = after(tcp_jiffies32, + bbr->min_rtt_stamp + bbr_min_rtt_win_sec * HZ); + if (rs->rtt_us >= 0 && + (rs->rtt_us < bbr->min_rtt_us || + (filter_expired && !rs->is_ack_delayed))) { + bbr->min_rtt_us = rs->rtt_us; + bbr->min_rtt_stamp = tcp_jiffies32; + } + + if (bbr_probe_rtt_mode_ms > 0 && filter_expired && + !bbr->idle_restart && bbr->mode != BBR_PROBE_RTT) { + bbr->mode = BBR_PROBE_RTT; /* dip, drain queue */ + bbr_save_cwnd(sk); /* note cwnd so we can restore it */ + bbr->probe_rtt_done_stamp = 0; + } + + if (bbr->mode == BBR_PROBE_RTT) { + /* Ignore low rate samples during this mode. */ + tp->app_limited = + (tp->delivered + tcp_packets_in_flight(tp)) ? : 1; + /* Maintain min packets in flight for max(200 ms, 1 round). */ + if (!bbr->probe_rtt_done_stamp && + tcp_packets_in_flight(tp) <= bbr_cwnd_min_target) { + bbr->probe_rtt_done_stamp = tcp_jiffies32 + + msecs_to_jiffies(bbr_probe_rtt_mode_ms); + bbr->probe_rtt_round_done = 0; + bbr->next_rtt_delivered = tp->delivered; + } else if (bbr->probe_rtt_done_stamp) { + if (bbr->round_start) + bbr->probe_rtt_round_done = 1; + if (bbr->probe_rtt_round_done) + bbr_check_probe_rtt_done(sk); + } + } + /* Restart after idle ends only once we process a new S/ACK for data */ + if (rs->delivered > 0) + bbr->idle_restart = 0; +} + +static void bbr_update_gains(struct sock *sk) +{ + struct bbr *bbr = inet_csk_ca(sk); + + switch (bbr->mode) { + case BBR_STARTUP: + bbr->pacing_gain = bbr_high_gain; + bbr->cwnd_gain = bbr_high_gain; + break; + case BBR_DRAIN: + bbr->pacing_gain = bbr_drain_gain; /* slow, to drain */ + bbr->cwnd_gain = bbr_high_gain; /* keep cwnd */ + break; + case BBR_PROBE_BW: + bbr->pacing_gain = (bbr->lt_use_bw ? + BBR_UNIT : + bbr_pacing_gain[bbr->cycle_idx]); + bbr->cwnd_gain = bbr_cwnd_gain; + break; + case BBR_PROBE_RTT: + bbr->pacing_gain = BBR_UNIT; + bbr->cwnd_gain = BBR_UNIT; + break; + default: + WARN_ONCE(1, "BBR bad mode: %u\n", bbr->mode); + break; + } +} + +static void bbr_update_model(struct sock *sk, const struct rate_sample *rs) +{ + bbr_update_bw(sk, rs); + bbr_update_ack_aggregation(sk, rs); + bbr_update_cycle_phase(sk, rs); + bbr_check_full_bw_reached(sk, rs); + bbr_check_drain(sk, rs); + bbr_update_min_rtt(sk, rs); + bbr_update_gains(sk); +} + +static void bbr_main(struct sock *sk, const struct rate_sample *rs) +{ + struct bbr *bbr = inet_csk_ca(sk); + u32 bw; + + bbr_update_model(sk, rs); + + bw = bbr_bw(sk); + bbr_set_pacing_rate(sk, bw, bbr->pacing_gain); + bbr_set_cwnd(sk, rs, rs->acked_sacked, bw, bbr->cwnd_gain); +} + +static void bbr_init(struct sock *sk) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + + bbr->prior_cwnd = 0; + tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; + bbr->rtt_cnt = 0; + bbr->next_rtt_delivered = 0; + bbr->prev_ca_state = TCP_CA_Open; + bbr->packet_conservation = 0; + + bbr->probe_rtt_done_stamp = 0; + bbr->probe_rtt_round_done = 0; + bbr->min_rtt_us = tcp_min_rtt(tp); + bbr->min_rtt_stamp = tcp_jiffies32; + + minmax_reset(&bbr->bw, bbr->rtt_cnt, 0); /* init max bw to 0 */ + + bbr->has_seen_rtt = 0; + bbr_init_pacing_rate_from_rtt(sk); + + bbr->round_start = 0; + bbr->idle_restart = 0; + bbr->full_bw_reached = 0; + bbr->full_bw = 0; + bbr->full_bw_cnt = 0; + bbr->cycle_mstamp = 0; + bbr->cycle_idx = 0; + bbr_reset_lt_bw_sampling(sk); + bbr_reset_startup_mode(sk); + + bbr->ack_epoch_mstamp = tp->tcp_mstamp; + bbr->ack_epoch_acked = 0; + bbr->extra_acked_win_rtts = 0; + bbr->extra_acked_win_idx = 0; + bbr->extra_acked[0] = 0; + bbr->extra_acked[1] = 0; + + cmpxchg(&sk->sk_pacing_status, SK_PACING_NONE, SK_PACING_NEEDED); +} + +static u32 bbr_sndbuf_expand(struct sock *sk) +{ + /* Provision 3 * cwnd since BBR may slow-start even during recovery. */ + return 3; +} + +/* In theory BBR does not need to undo the cwnd since it does not + * always reduce cwnd on losses (see bbr_main()). Keep it for now. + */ +static u32 bbr_undo_cwnd(struct sock *sk) +{ + struct bbr *bbr = inet_csk_ca(sk); + + bbr->full_bw = 0; /* spurious slow-down; reset full pipe detection */ + bbr->full_bw_cnt = 0; + bbr_reset_lt_bw_sampling(sk); + return tcp_sk(sk)->snd_cwnd; +} + +/* Entering loss recovery, so save cwnd for when we exit or undo recovery. */ +static u32 bbr_ssthresh(struct sock *sk) +{ + bbr_save_cwnd(sk); + return tcp_sk(sk)->snd_ssthresh; +} + +static size_t bbr_get_info(struct sock *sk, u32 ext, int *attr, + union tcp_cc_info *info) +{ + if (ext & (1 << (INET_DIAG_BBRINFO - 1)) || + ext & (1 << (INET_DIAG_VEGASINFO - 1))) { + struct tcp_sock *tp = tcp_sk(sk); + struct bbr *bbr = inet_csk_ca(sk); + u64 bw = bbr_bw(sk); + + bw = bw * tp->mss_cache * USEC_PER_SEC >> BW_SCALE; + memset(&info->bbr, 0, sizeof(info->bbr)); + info->bbr.bbr_bw_lo = (u32)bw; + info->bbr.bbr_bw_hi = (u32)(bw >> 32); + info->bbr.bbr_min_rtt = bbr->min_rtt_us; + info->bbr.bbr_pacing_gain = bbr->pacing_gain; + info->bbr.bbr_cwnd_gain = bbr->cwnd_gain; + *attr = INET_DIAG_BBRINFO; + return sizeof(info->bbr); + } + return 0; +} + +static void bbr_set_state(struct sock *sk, u8 new_state) +{ + struct bbr *bbr = inet_csk_ca(sk); + + if (new_state == TCP_CA_Loss) { + struct rate_sample rs = { .losses = 1 }; + + bbr->prev_ca_state = TCP_CA_Loss; + bbr->full_bw = 0; + bbr->round_start = 1; /* treat RTO like end of a round */ + bbr_lt_bw_sampling(sk, &rs); + } +} + +static struct tcp_congestion_ops tcp_bbr_cong_ops __read_mostly = { + .flags = TCP_CONG_NON_RESTRICTED, + .name = "bbrx", + .owner = THIS_MODULE, + .init = bbr_init, + .cong_control = bbr_main, + .sndbuf_expand = bbr_sndbuf_expand, + .undo_cwnd = bbr_undo_cwnd, + .cwnd_event = bbr_cwnd_event, + .ssthresh = bbr_ssthresh, + .min_tso_segs = bbr_min_tso_segs, + .get_info = bbr_get_info, + .set_state = bbr_set_state, +}; + +static int __init bbr_register(void) +{ + BUILD_BUG_ON(sizeof(struct bbr) > ICSK_CA_PRIV_SIZE); + return tcp_register_congestion_control(&tcp_bbr_cong_ops); +} + +static void __exit bbr_unregister(void) +{ + tcp_unregister_congestion_control(&tcp_bbr_cong_ops); +} + +module_init(bbr_register); +module_exit(bbr_unregister); + +MODULE_AUTHOR("Van Jacobson "); +MODULE_AUTHOR("Neal Cardwell "); +MODULE_AUTHOR("Yuchung Cheng "); +MODULE_AUTHOR("Soheil Hassas Yeganeh "); +MODULE_LICENSE("Dual BSD/GPL"); +MODULE_DESCRIPTION("TCP BBR (Bottleneck Bandwidth and RTT)"); diff --git a/BBR/BBR.sh b/BBR/BBR.sh new file mode 100644 index 0000000..3d0ede5 --- /dev/null +++ b/BBR/BBR.sh @@ -0,0 +1,21 @@ +#!/bin/sh + +clear + +## Check Root Privilege +if [ $(id -u) -ne 0 ]; then + tput setaf 1; echo "This script needs root permission to run" + exit 1 +fi + +## Installing BBR +cd $HOME +clear +curl -s -O https://raw.githubusercontent.com/jerry048/Seedbox-Components/main/.tweaking.sh && source .tweaking.sh +BBR_Tweaking + +## Clear +rm BBR.sh +rm .tweaking.sh + +echo "Tweaked BBR Installation Complete" diff --git a/Miscellaneous/.boot-script.sh b/Miscellaneous/.boot-script.sh new file mode 100644 index 0000000..050b48a --- /dev/null +++ b/Miscellaneous/.boot-script.sh @@ -0,0 +1,57 @@ +#!/bin/sh + +function boot_script { + touch /etc/rc.local && chmod +x /etc/rc.local + cat <<'EOF' > /etc/rc.local +#!/bin/sh +## Network +#NIC Config +interface=$(/sbin/ip -o -4 route show to default | awk '{print $5}') +/sbin/ethtool -G $interface rx 1024 +sleep 1 +/sbin/ethtool -G $interface tx 2048 +sleep 1 +/sbin/ethtool -K $interface tso off gso off +sleep 1 +#Other 1 +/sbin/ifconfig $interface txqueuelen 10000 +sleep 1 +#Other 2 +iproute=$(/sbin/ip -o -4 route show to default) +/sbin/ip route change $iproute initcwnd 25 initrwnd 25 +## Drive +#Scheduler +i=1 +drive=() +disk=$(lsblk -nd --output NAME) +diskno=$(echo $disk | awk '{print NF}') +while [ $i -le $diskno ] +do + device=$(echo $disk | awk -v i=$i '{print $i}') + drive+=($device) + i=$(( $i + 1 )) +done +i=1 +x=0 +disktype=$(cat /sys/block/sda/queue/rotational) +if [ "${disktype}" == 0 ]; then + while [ $i -le $diskno ] + do + diskname=$(eval echo ${drive["$x"]}) + echo kyber > /sys/block/$diskname/queue/scheduler + i=$(( $i + 1 )) + x=$(( $x + 1 )) + done +else + while [ $i -le $diskno ] + do + diskname=$(eval echo ${drive["$x"]}) + echo mq-deadline > /sys/block/$diskname/queue/scheduler + i=$(( $i + 1 )) + x=$(( $x + 1 )) + done +fi +clear +exit 0 +EOF +} diff --git a/Miscellaneous/qb_password_gen b/Miscellaneous/qb_password_gen new file mode 100644 index 0000000..363b2c4 Binary files /dev/null and b/Miscellaneous/qb_password_gen differ diff --git a/README.md b/README.md index 3d268b7..0313577 100644 --- a/README.md +++ b/README.md @@ -1 +1,13 @@ -# Seedbox-Components \ No newline at end of file +# Seedbox-Install-Components +Components used for Seedbox Installation Script + https://github.com/jerry048/Dedicated-Seedbox + https://github.com/jerry048/Shared-Seedbox + +## Credit +qBittorrent Install - https://github.com/userdocs/qbittorrent-nox-static + +qBittorrent Password Set - https://github.com/KozakaiAya/libqbpasswd & https://amefs.net/archives/2027.html + +autoremove-torrents - https://github.com/jerrymakesjelly/autoremove-torrents + +BBR Install - https://github.com/KozakaiAya/TCP_BBR \ No newline at end of file diff --git a/qBittorrent/README.md b/qBittorrent/README.md new file mode 100644 index 0000000..79cee03 --- /dev/null +++ b/qBittorrent/README.md @@ -0,0 +1,9 @@ +# qBittorrent-nox static +#### Static build with modified libtorrent settings + +The patches used in compile can be found [here](https://github.com/jerry048/Patch) + +The script used to compile the build is [userdocs' script](https://github.com/userdocs/qbittorrent-nox-static) + +Could be used in both Dedicated Seedbox & Shared Seedbox + diff --git a/qBittorrent/qBittorrent 4.1.9 - libtorrent-1_1_14/qbittorrent-nox b/qBittorrent/qBittorrent 4.1.9 - libtorrent-1_1_14/qbittorrent-nox new file mode 100644 index 0000000..f19943b Binary files /dev/null and b/qBittorrent/qBittorrent 4.1.9 - libtorrent-1_1_14/qbittorrent-nox differ diff --git a/qBittorrent/qBittorrent 4.1.9.1 - libtorrent-1_1_14/qbittorrent-nox b/qBittorrent/qBittorrent 4.1.9.1 - libtorrent-1_1_14/qbittorrent-nox new file mode 100644 index 0000000..12f5fb3 Binary files /dev/null and b/qBittorrent/qBittorrent 4.1.9.1 - libtorrent-1_1_14/qbittorrent-nox differ diff --git a/qBittorrent/qBittorrent 4.3.3 - libtorrent-v1.2.12-Lactency/qbittorrent-nox b/qBittorrent/qBittorrent 4.3.3 - libtorrent-v1.2.12-Lactency/qbittorrent-nox new file mode 100644 index 0000000..6158835 Binary files /dev/null and b/qBittorrent/qBittorrent 4.3.3 - libtorrent-v1.2.12-Lactency/qbittorrent-nox differ diff --git a/qBittorrent/qBittorrent 4.3.3 - libtorrent-v1.2.13/qbittorrent-nox b/qBittorrent/qBittorrent 4.3.3 - libtorrent-v1.2.13/qbittorrent-nox new file mode 100644 index 0000000..3165f7a Binary files /dev/null and b/qBittorrent/qBittorrent 4.3.3 - libtorrent-v1.2.13/qbittorrent-nox differ diff --git a/qBittorrent/qBittorrent 4.3.4.1 - libtorrent-v1.2.13-Lactency/qbittorrent-nox b/qBittorrent/qBittorrent 4.3.4.1 - libtorrent-v1.2.13-Lactency/qbittorrent-nox new file mode 100644 index 0000000..4d226f9 Binary files /dev/null and b/qBittorrent/qBittorrent 4.3.4.1 - libtorrent-v1.2.13-Lactency/qbittorrent-nox differ diff --git a/qBittorrent/qBittorrent 4.3.4.1 - libtorrent-v1.2.13/qbittorrent-nox b/qBittorrent/qBittorrent 4.3.4.1 - libtorrent-v1.2.13/qbittorrent-nox new file mode 100644 index 0000000..8bcedc5 Binary files /dev/null and b/qBittorrent/qBittorrent 4.3.4.1 - libtorrent-v1.2.13/qbittorrent-nox differ