tc_core.c revision 57a800d45a5f8f46c9ce4950599f17545413c82d
1/* 2 * tc_core.c TC core library. 3 * 4 * This program is free software; you can redistribute it and/or 5 * modify it under the terms of the GNU General Public License 6 * as published by the Free Software Foundation; either version 7 * 2 of the License, or (at your option) any later version. 8 * 9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> 10 * 11 */ 12 13#include <stdio.h> 14#include <stdlib.h> 15#include <unistd.h> 16#include <syslog.h> 17#include <fcntl.h> 18#include <math.h> 19#include <sys/socket.h> 20#include <netinet/in.h> 21#include <arpa/inet.h> 22#include <string.h> 23 24#include "tc_core.h" 25 26static double tick_in_usec = 1; 27static double clock_factor = 1; 28 29int tc_core_time2big(long time) 30{ 31 __u64 t = time; 32 33 t *= tick_in_usec; 34 return (t >> 32) != 0; 35} 36 37 38unsigned tc_core_time2tick(unsigned time) 39{ 40 return time*tick_in_usec; 41} 42 43unsigned tc_core_tick2time(unsigned tick) 44{ 45 return tick/tick_in_usec; 46} 47 48unsigned tc_core_time2ktime(unsigned time) 49{ 50 return time * clock_factor; 51} 52 53unsigned tc_core_ktime2time(unsigned ktime) 54{ 55 return ktime / clock_factor; 56} 57 58unsigned tc_calc_xmittime(unsigned rate, unsigned size) 59{ 60 return tc_core_time2tick(TIME_UNITS_PER_SEC*((double)size/rate)); 61} 62 63unsigned tc_calc_xmitsize(unsigned rate, unsigned ticks) 64{ 65 return ((double)rate*tc_core_tick2time(ticks))/TIME_UNITS_PER_SEC; 66} 67 68/* 69 rtab[pkt_len>>cell_log] = pkt_xmit_time 70 */ 71 72int tc_calc_rtable(unsigned bps, __u32 *rtab, int cell_log, unsigned mtu, 73 unsigned mpu) 74{ 75 int i; 76 unsigned overhead = (mpu >> 8) & 0xFF; 77 mpu = mpu & 0xFF; 78 79 if (mtu == 0) 80 mtu = 2047; 81 82 if (cell_log < 0) { 83 cell_log = 0; 84 while ((mtu>>cell_log) > 255) 85 cell_log++; 86 } 87 for (i=0; i<256; i++) { 88 unsigned sz = (i<<cell_log); 89 if (overhead) 90 sz += overhead; 91 if (sz < mpu) 92 sz = mpu; 93 rtab[i] = tc_calc_xmittime(bps, sz); 94 } 95 return cell_log; 96} 97 98int tc_core_init() 99{ 100 FILE *fp; 101 __u32 clock_res; 102 __u32 t2us; 103 __u32 us2t; 104 105 fp = fopen("/proc/net/psched", "r"); 106 if (fp == NULL) 107 return -1; 108 109 if (fscanf(fp, "%08x%08x%08x", &t2us, &us2t, &clock_res) != 3) { 110 fclose(fp); 111 return -1; 112 } 113 fclose(fp); 114 115 /* compatibility hack: for old iproute binaries (ignoring 116 * the kernel clock resolution) the kernel advertises a 117 * tick multiplier of 1000 in case of nano-second resolution, 118 * which really is 1. */ 119 if (clock_res == 1000000000) 120 t2us = us2t; 121 122 clock_factor = (double)clock_res / TIME_UNITS_PER_SEC; 123 tick_in_usec = (double)t2us / us2t * clock_factor; 124 return 0; 125} 126