1#!/bin/bash 2# SPDX-License-Identifier: GPL-2.0 3# 4# This test installs a TC bpf program that throttles a TCP flow 5# with dst port = 9000 down to 5MBps. Then it measures actual 6# throughput of the flow. 7 8if [[ $EUID -ne 0 ]]; then 9 echo "This script must be run as root" 10 echo "FAIL" 11 exit 1 12fi 13 14# check that nc, dd, and timeout are present 15command -v nc >/dev/null 2>&1 || \ 16 { echo >&2 "nc is not available"; exit 1; } 17command -v dd >/dev/null 2>&1 || \ 18 { echo >&2 "nc is not available"; exit 1; } 19command -v timeout >/dev/null 2>&1 || \ 20 { echo >&2 "timeout is not available"; exit 1; } 21 22readonly NS_SRC="ns-src-$(mktemp -u XXXXXX)" 23readonly NS_DST="ns-dst-$(mktemp -u XXXXXX)" 24 25readonly IP_SRC="172.16.1.100" 26readonly IP_DST="172.16.2.100" 27 28cleanup() 29{ 30 ip netns del ${NS_SRC} 31 ip netns del ${NS_DST} 32} 33 34trap cleanup EXIT 35 36set -e # exit on error 37 38ip netns add "${NS_SRC}" 39ip netns add "${NS_DST}" 40ip link add veth_src type veth peer name veth_dst 41ip link set veth_src netns ${NS_SRC} 42ip link set veth_dst netns ${NS_DST} 43 44ip -netns ${NS_SRC} addr add ${IP_SRC}/24 dev veth_src 45ip -netns ${NS_DST} addr add ${IP_DST}/24 dev veth_dst 46 47ip -netns ${NS_SRC} link set dev veth_src up 48ip -netns ${NS_DST} link set dev veth_dst up 49 50ip -netns ${NS_SRC} route add ${IP_DST}/32 dev veth_src 51ip -netns ${NS_DST} route add ${IP_SRC}/32 dev veth_dst 52 53# set up TC on TX 54ip netns exec ${NS_SRC} tc qdisc add dev veth_src root fq 55ip netns exec ${NS_SRC} tc qdisc add dev veth_src clsact 56ip netns exec ${NS_SRC} tc filter add dev veth_src egress \ 57 bpf da obj test_tc_edt.o sec cls_test 58 59 60# start the listener 61ip netns exec ${NS_DST} bash -c \ 62 "nc -4 -l -p 9000 >/dev/null &" 63declare -i NC_PID=$! 64sleep 1 65 66declare -ir TIMEOUT=20 67declare -ir EXPECTED_BPS=5000000 68 69# run the load, capture RX bytes on DST 70declare -ir RX_BYTES_START=$( ip netns exec ${NS_DST} \ 71 cat /sys/class/net/veth_dst/statistics/rx_bytes ) 72 73set +e 74ip netns exec ${NS_SRC} bash -c "timeout ${TIMEOUT} dd if=/dev/zero \ 75 bs=1000 count=1000000 > /dev/tcp/${IP_DST}/9000 2>/dev/null" 76set -e 77 78declare -ir RX_BYTES_END=$( ip netns exec ${NS_DST} \ 79 cat /sys/class/net/veth_dst/statistics/rx_bytes ) 80 81declare -ir ACTUAL_BPS=$(( ($RX_BYTES_END - $RX_BYTES_START) / $TIMEOUT )) 82 83echo $TIMEOUT $ACTUAL_BPS $EXPECTED_BPS | \ 84 awk '{printf "elapsed: %d sec; bps difference: %.2f%%\n", 85 $1, ($2-$3)*100.0/$3}' 86 87# Pass the test if the actual bps is within 1% of the expected bps. 88# The difference is usually about 0.1% on a 20-sec test, and ==> zero 89# the longer the test runs. 90declare -ir RES=$( echo $ACTUAL_BPS $EXPECTED_BPS | \ 91 awk 'function abs(x){return ((x < 0.0) ? -x : x)} 92 {if (abs(($1-$2)*100.0/$2) > 1.0) { print "1" } 93 else { print "0"} }' ) 94if [ "${RES}" == "0" ] ; then 95 echo "PASS" 96else 97 echo "FAIL" 98 exit 1 99fi 100