1 #ifndef CTRS_H_ 2 #define CTRS_H_ 3 4 /* $FreeBSD$ */ 5 6 #include <sys/time.h> 7 8 /* counters to accumulate statistics */ 9 struct my_ctrs { 10 uint64_t pkts, bytes, events; 11 uint64_t drop, drop_bytes; 12 uint64_t min_space; 13 struct timeval t; 14 uint32_t oq_n; /* number of elements in overflow queue (used in lb) */ 15 }; 16 17 /* very crude code to print a number in normalized form. 18 * Caller has to make sure that the buffer is large enough. 19 */ 20 static const char * 21 norm2(char *buf, double val, const char *fmt, int normalize) 22 { 23 const char *units[] = { "", "K", "M", "G", "T" }; 24 u_int i; 25 if (normalize) 26 for (i = 0; val >=1000 && i < sizeof(units)/sizeof(const char *) - 1; i++) 27 val /= 1000; 28 else 29 i=0; 30 sprintf(buf, fmt, val, units[i]); 31 return buf; 32 } 33 34 static __inline const char * 35 norm(char *buf, double val, int normalize) 36 { 37 if (normalize) 38 return norm2(buf, val, "%.3f %s", normalize); 39 else 40 return norm2(buf, val, "%.0f %s", normalize); 41 } 42 43 static __inline int 44 timespec_ge(const struct timespec *a, const struct timespec *b) 45 { 46 47 if (a->tv_sec > b->tv_sec) 48 return (1); 49 if (a->tv_sec < b->tv_sec) 50 return (0); 51 if (a->tv_nsec >= b->tv_nsec) 52 return (1); 53 return (0); 54 } 55 56 static __inline struct timespec 57 timeval2spec(const struct timeval *a) 58 { 59 struct timespec ts = { 60 .tv_sec = a->tv_sec, 61 .tv_nsec = a->tv_usec * 1000 62 }; 63 return ts; 64 } 65 66 static __inline struct timeval 67 timespec2val(const struct timespec *a) 68 { 69 struct timeval tv = { 70 .tv_sec = a->tv_sec, 71 .tv_usec = a->tv_nsec / 1000 72 }; 73 return tv; 74 } 75 76 77 static __inline struct timespec 78 timespec_add(struct timespec a, struct timespec b) 79 { 80 struct timespec ret = { a.tv_sec + b.tv_sec, a.tv_nsec + b.tv_nsec }; 81 if (ret.tv_nsec >= 1000000000) { 82 ret.tv_sec++; 83 ret.tv_nsec -= 1000000000; 84 } 85 return ret; 86 } 87 88 static __inline struct timespec 89 timespec_sub(struct timespec a, struct timespec b) 90 { 91 struct timespec ret = { a.tv_sec - b.tv_sec, a.tv_nsec - b.tv_nsec }; 92 if (ret.tv_nsec < 0) { 93 ret.tv_sec--; 94 ret.tv_nsec += 1000000000; 95 } 96 return ret; 97 } 98 99 static __inline uint64_t 100 wait_for_next_report(struct timeval *prev, struct timeval *cur, 101 int report_interval) 102 { 103 struct timeval delta; 104 105 delta.tv_sec = report_interval/1000; 106 delta.tv_usec = (report_interval%1000)*1000; 107 if (select(0, NULL, NULL, NULL, &delta) < 0 && errno != EINTR) { 108 perror("select"); 109 abort(); 110 } 111 gettimeofday(cur, NULL); 112 timersub(cur, prev, &delta); 113 return delta.tv_sec* 1000000 + delta.tv_usec; 114 } 115 #endif /* CTRS_H_ */ 116 117