summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--btpd/btpd.c8
-rw-r--r--btpd/btpd.h5
-rw-r--r--btpd/net.c26
-rw-r--r--btpd/net.h1
4 files changed, 37 insertions, 3 deletions
diff --git a/btpd/btpd.c b/btpd/btpd.c
index 8828291..9082648 100644
--- a/btpd/btpd.c
+++ b/btpd/btpd.c
@@ -124,6 +124,10 @@ btpd_init(void)
     btpd.port = 6881;
 
     btpd.bw_hz = 8;
+    btpd.bwcalls = 0;
+    for (int i = 0; i < BWCALLHISTORY; i++)
+	btpd.bwrate[i] = 0;
+
     btpd.obwlim = 0;
     btpd.ibwlim = 0;
     btpd.obw_left = 0;
@@ -190,10 +194,12 @@ heartbeat_cb(int sd, short type, void *arg)
 
     btpd.seconds++;
 
+    net_bw_rate();
+
     BTPDQ_FOREACH(tp, &btpd.cm_list, entry)
 	cm_by_second(tp);
 
-    evtimer_add(&btpd.heartbeat, (& (struct timeval) { 0, 1000000 }));
+    evtimer_add(&btpd.heartbeat, (& (struct timeval) { 1, 0 }));
 }
 
 static void
diff --git a/btpd/btpd.h b/btpd/btpd.h
index 86b1614..cd53e76 100644
--- a/btpd/btpd.h
+++ b/btpd/btpd.h
@@ -25,6 +25,8 @@
 
 #define BTPD_VERSION (PACKAGE_NAME "/" PACKAGE_VERSION)
 
+#define BWCALLHISTORY 5
+
 struct child {
     pid_t pid;
     void *data;
@@ -56,6 +58,9 @@ struct btpd {
     int ipc_sd;
 
     unsigned bw_hz;
+    double bw_hz_avg;
+    unsigned bwcalls;
+    unsigned bwrate[BWCALLHISTORY];
     unsigned long obwlim, ibwlim;
     unsigned long ibw_left, obw_left;
     struct event bwlim;    
diff --git a/btpd/net.c b/btpd/net.c
index f3037b8..924668d 100644
--- a/btpd/net.c
+++ b/btpd/net.c
@@ -847,12 +847,34 @@ net_by_second(void)
 }
 
 void
+net_bw_rate(void)
+{
+    unsigned sum = 0;
+    for (int i = 0; i < BWCALLHISTORY - 1; i++) {
+	btpd.bwrate[i] = btpd.bwrate[i + 1];
+	sum += btpd.bwrate[i];
+    }
+    btpd.bwrate[BWCALLHISTORY - 1] = btpd.bwcalls;
+    sum += btpd.bwrate[BWCALLHISTORY - 1];
+    btpd.bwcalls = 0;
+    btpd.bw_hz_avg = sum / 5.0;
+}
+
+void
 net_bw_cb(int sd, short type, void *arg)    
 {
     struct peer *p;
 
-    btpd.obw_left = btpd.obwlim / btpd.bw_hz;
-    btpd.ibw_left = btpd.ibwlim / btpd.bw_hz;
+    btpd.bwcalls++;
+
+    double avg_hz;
+    if (btpd.seconds < BWCALLHISTORY)
+	avg_hz = btpd.bw_hz;
+    else
+	avg_hz = btpd.bw_hz_avg;
+
+    btpd.obw_left = btpd.obwlim / avg_hz;
+    btpd.ibw_left = btpd.ibwlim / avg_hz;
 
     if (btpd.ibwlim > 0) {
 	while ((p = BTPDQ_FIRST(&btpd.readq)) != NULL && btpd.ibw_left > 0) {
diff --git a/btpd/net.h b/btpd/net.h
index 1c5ab9e..af01607 100644
--- a/btpd/net.h
+++ b/btpd/net.h
@@ -74,6 +74,7 @@ struct piece_req {
 BTPDQ_HEAD(piece_req_tq, piece_req);
 
 void net_connection_cb(int sd, short type, void *arg);
+void net_bw_rate(void);
 void net_bw_cb(int sd, short type, void *arg);
 
 struct peer;