1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
extern crate clap;
extern crate fnv;
extern crate time;
#[macro_use]
extern crate slog;
extern crate portus;

use fnv::FnvHashMap as HashMap;
use portus::ipc::Ipc;
use portus::lang::Scope;
use portus::{CongAlg, Datapath, DatapathInfo, DatapathTrait, Report};

pub mod cubic;
pub mod reno;

mod bin_helper;
pub use bin_helper::{make_args, start};

pub const DEFAULT_SS_THRESH: u32 = 0x7fff_ffff;

pub struct GenericCongAvoidMeasurements {
    pub acked: u32,
    pub was_timeout: bool,
    pub sacked: u32,
    pub loss: u32,
    pub rtt: u32,
    pub inflight: u32,
}

#[derive(Debug, Clone, Copy)]
pub enum GenericCongAvoidConfigReport {
    Ack,
    Rtt,
    Interval(time::Duration),
}

#[derive(Debug, Clone, Copy)]
pub enum GenericCongAvoidConfigSS {
    Datapath,
    Ccp,
}

pub trait GenericCongAvoidFlow {
    fn curr_cwnd(&self) -> u32;
    fn set_cwnd(&mut self, cwnd: u32);
    fn increase(&mut self, m: &GenericCongAvoidMeasurements);
    fn reduction(&mut self, m: &GenericCongAvoidMeasurements);
    fn reset(&mut self) {}
}

pub trait GenericCongAvoidAlg {
    type Flow: GenericCongAvoidFlow;

    fn name() -> &'static str;
    fn args<'a, 'b>() -> Vec<clap::Arg<'a, 'b>> {
        vec![]
    }
    fn with_args(matches: clap::ArgMatches) -> Self;
    fn new_flow(&self, logger: Option<slog::Logger>, init_cwnd: u32, mss: u32) -> Self::Flow;
}

pub struct Alg<A: GenericCongAvoidAlg> {
    pub deficit_timeout: u32,
    pub init_cwnd: u32,
    pub report_option: GenericCongAvoidConfigReport,
    pub ss: GenericCongAvoidConfigSS,
    pub ss_thresh: u32,
    pub use_compensation: bool,
    pub logger: Option<slog::Logger>,
    pub alg: A,
}

impl<T: Ipc, A: GenericCongAvoidAlg> CongAlg<T> for Alg<A> {
    type Flow = Flow<T, A::Flow>;

    fn name() -> &'static str {
        A::name()
    }

    fn datapath_programs(&self) -> HashMap<&'static str, String> {
        let mut h = HashMap::default();
        h.insert(
            "DatapathIntervalProg",
            "
                (def
                (Report
                    (volatile acked 0)
                    (volatile sacked 0)
                    (volatile loss 0)
                    (volatile timeout false)
                    (volatile rtt 0)
                    (volatile inflight 0)
                )
                (reportTime 0)
                )
                (when true
                    (:= Report.inflight Flow.packets_in_flight)
                    (:= Report.rtt Flow.rtt_sample_us)
                    (:= Report.acked (+ Report.acked Ack.bytes_acked))
                    (:= Report.sacked (+ Report.sacked Ack.packets_misordered))
                    (:= Report.loss Ack.lost_pkts_sample)
                    (:= Report.timeout Flow.was_timeout)
                    (fallthrough)
                )
                (when (|| Report.timeout (> Report.loss 0))
                    (report)
                    (:= Micros 0)
                )
                (when (> Micros reportTime)
                    (report)
                    (:= Micros 0)
                )
            "
            .to_string(),
        );

        h.insert(
            "DatapathIntervalRTTProg",
            "
                (def (Report
                    (volatile acked 0)
                    (volatile sacked 0) 
                    (volatile loss 0)
                    (volatile timeout false)
                    (volatile rtt 0)
                    (volatile inflight 0)
                ))
                (when true
                    (:= Report.inflight Flow.packets_in_flight)
                    (:= Report.rtt Flow.rtt_sample_us)
                    (:= Report.acked (+ Report.acked Ack.bytes_acked))
                    (:= Report.sacked (+ Report.sacked Ack.packets_misordered))
                    (:= Report.loss Ack.lost_pkts_sample)
                    (:= Report.timeout Flow.was_timeout)
                    (fallthrough)
                )
                (when (|| Report.timeout (> Report.loss 0))
                    (report)
                    (:= Micros 0)
                )
                (when (> Micros Flow.rtt_sample_us)
                    (report)
                    (:= Micros 0)
                )
            "
            .to_string(),
        );

        h.insert(
            "AckUpdateProg",
            "
                (def (Report
                    (volatile acked 0)
                    (volatile sacked 0)
                    (volatile loss 0)
                    (volatile timeout false)
                    (volatile rtt 0)
                    (volatile inflight 0)
                ))
                (when true
                    (:= Report.acked (+ Report.acked Ack.bytes_acked))
                    (:= Report.sacked (+ Report.sacked Ack.packets_misordered))
                    (:= Report.loss Ack.lost_pkts_sample)
                    (:= Report.timeout Flow.was_timeout)
                    (:= Report.rtt Flow.rtt_sample_us)
                    (:= Report.inflight Flow.packets_in_flight)
                    (report)
                )
            "
            .to_string(),
        );

        h.insert(
            "SSUpdateProg",
            "
                (def (Report
                    (volatile acked 0)
                    (volatile sacked 0)
                    (volatile loss 0)
                    (volatile timeout false)
                    (volatile rtt 0)
                    (volatile inflight 0)
                ))
                (when true
                    (:= Report.acked (+ Report.acked Ack.bytes_acked))
                    (:= Report.sacked (+ Report.sacked Ack.packets_misordered))
                    (:= Report.loss Ack.lost_pkts_sample)
                    (:= Report.timeout Flow.was_timeout)
                    (:= Report.rtt Flow.rtt_sample_us)
                    (:= Report.inflight Flow.packets_in_flight)
                    (:= Cwnd (+ Cwnd Ack.bytes_acked))
                    (fallthrough)
                )
                (when (|| Report.timeout (> Report.loss 0))
                    (report)
                )

            "
            .to_string(),
        );

        h
    }

    fn new_flow(&self, control: Datapath<T>, info: DatapathInfo) -> Self::Flow {
        let init_cwnd = if self.init_cwnd != 0 {
            self.init_cwnd
        } else {
            info.init_cwnd
        };

        let mut s = Flow {
            control_channel: control,
            logger: self.logger.clone(),
            report_option: self.report_option,
            sc: Default::default(),
            ss_thresh: self.ss_thresh,
            rtt: 0,
            in_startup: false,
            mss: info.mss,
            use_compensation: self.use_compensation,
            deficit_timeout: self.deficit_timeout,
            init_cwnd,
            curr_cwnd_reduction: 0,
            last_cwnd_reduction: time::now().to_timespec() - time::Duration::milliseconds(500),
            alg: self.alg.new_flow(self.logger.clone(), init_cwnd, info.mss),
        };

        match (self.ss, self.report_option) {
            (GenericCongAvoidConfigSS::Datapath, _) => {
                s.sc = s.install_ss_update();
                s.in_startup = true;
            }
            (GenericCongAvoidConfigSS::Ccp, GenericCongAvoidConfigReport::Ack) => {
                s.sc = s.install_ack_update();
            }
            (GenericCongAvoidConfigSS::Ccp, GenericCongAvoidConfigReport::Rtt) => {
                s.sc = s.install_datapath_interval_rtt();
            }
            (GenericCongAvoidConfigSS::Ccp, GenericCongAvoidConfigReport::Interval(i)) => {
                s.sc = s.install_datapath_interval(i);
            }
        }

        s
    }
}

pub struct Flow<T: Ipc, A: GenericCongAvoidFlow> {
    alg: A,
    deficit_timeout: u32,
    init_cwnd: u32,
    report_option: GenericCongAvoidConfigReport,
    ss_thresh: u32,
    use_compensation: bool,
    control_channel: Datapath<T>,
    logger: Option<slog::Logger>,

    curr_cwnd_reduction: u32,
    last_cwnd_reduction: time::Timespec,

    in_startup: bool,
    mss: u32,
    rtt: u32,
    sc: Scope,
}

impl<I: Ipc, A: GenericCongAvoidFlow> portus::Flow for Flow<I, A> {
    fn on_report(&mut self, _sock_id: u32, m: Report) {
        let mut ms = self.get_fields(&m);

        if self.in_startup {
            // install new fold
            match self.report_option {
                GenericCongAvoidConfigReport::Ack => {
                    self.sc = self.install_ack_update();
                }
                GenericCongAvoidConfigReport::Rtt => {
                    self.sc = self.install_datapath_interval_rtt();
                }
                GenericCongAvoidConfigReport::Interval(i) => {
                    self.sc = self.install_datapath_interval(i);
                }
            }

            self.alg.set_cwnd(ms.inflight * self.mss);
            self.in_startup = false;
        }

        self.rtt = ms.rtt;
        if ms.was_timeout {
            self.handle_timeout();
            return;
        }

        ms.acked = self.slow_start_increase(ms.acked);

        // increase the cwnd corresponding to new in-order cumulative ACKs
        self.alg.increase(&ms);
        self.maybe_reduce_cwnd(&ms);
        if self.curr_cwnd_reduction > 0 {
            self.logger.as_ref().map(|log| {
                debug!(log, "in cwnd reduction"; "acked" => ms.acked / self.mss, "deficit" => self.curr_cwnd_reduction);
            });
            return;
        }

        self.update_cwnd();

        self.logger.as_ref().map(|log| {
            debug!(log, "got ack"; 
                "acked(pkts)" => ms.acked / self.mss,
                "curr_cwnd (pkts)" => self.alg.curr_cwnd() / self.mss,
                "inflight (pkts)" => ms.inflight,
                "loss" => ms.loss,
                "ssthresh" => self.ss_thresh,
                "rtt" => ms.rtt,
            );
        });
    }
}

impl<T: Ipc, A: GenericCongAvoidFlow> Flow<T, A> {
    /// Make no updates in the datapath, and send a report after an interval
    fn install_datapath_interval(&mut self, interval: time::Duration) -> Scope {
        self.control_channel
            .set_program(
                "DatapathIntervalProg",
                Some(&[("reportTime", interval.num_microseconds().unwrap() as u32)][..]),
            )
            .unwrap()
    }

    /// Make no updates in the datapath, and send a report after each RTT
    fn install_datapath_interval_rtt(&mut self) -> Scope {
        self.control_channel
            .set_program("DatapathIntervalRTTProg", None)
            .unwrap()
    }

    /// Make no updates in the datapath, but send a report on every ack.
    fn install_ack_update(&mut self) -> Scope {
        self.control_channel
            .set_program("AckUpdateProg", None)
            .unwrap()
    }

    /// Don't update acked, since those acks are already accounted for in slow start.
    /// Send a report once there is a drop or timeout.
    fn install_ss_update(&mut self) -> Scope {
        self.control_channel
            .set_program("SSUpdateProg", None)
            .unwrap()
    }

    fn update_cwnd(&self) {
        if let Err(e) = self
            .control_channel
            .update_field(&self.sc, &[("Cwnd", self.alg.curr_cwnd())])
        {
            self.logger.as_ref().map(|log| {
                warn!(log, "Cwnd update error";
                      "err" => ?e,
                );
            });
        }
    }

    fn get_fields(&mut self, m: &Report) -> GenericCongAvoidMeasurements {
        let sc = &self.sc;
        let ack = m
            .get_field(&String::from("Report.acked"), sc)
            .expect("expected acked field in returned measurement") as u32;

        let sack = m
            .get_field(&String::from("Report.sacked"), sc)
            .expect("expected sacked field in returned measurement") as u32;

        let was_timeout =
            m.get_field(&String::from("Report.timeout"), sc)
                .expect("expected timeout field in returned measurement") as u32;

        let inflight =
            m.get_field(&String::from("Report.inflight"), sc)
                .expect("expected inflight field in returned measurement") as u32;

        let loss = m
            .get_field(&String::from("Report.loss"), sc)
            .expect("expected loss field in returned measurement") as u32;

        let rtt = m
            .get_field(&String::from("Report.rtt"), sc)
            .expect("expected rtt field in returned measurement") as u32;

        GenericCongAvoidMeasurements {
            acked: ack,
            was_timeout: was_timeout == 1,
            sacked: sack,
            loss,
            rtt,
            inflight,
        }
    }

    fn handle_timeout(&mut self) {
        self.ss_thresh /= 2;
        if self.ss_thresh < self.init_cwnd {
            self.ss_thresh = self.init_cwnd;
        }

        self.alg.reset();
        self.alg.set_cwnd(self.init_cwnd);
        self.curr_cwnd_reduction = 0;

        self.logger.as_ref().map(|log| {
            warn!(log, "timeout"; 
                "curr_cwnd (pkts)" => self.init_cwnd / self.mss, 
                "ssthresh" => self.ss_thresh,
            );
        });

        self.update_cwnd();
        return;
    }

    fn maybe_reduce_cwnd(&mut self, m: &GenericCongAvoidMeasurements) {
        if m.loss > 0 || m.sacked > 0 {
            if self.deficit_timeout > 0
                && ((time::now().to_timespec() - self.last_cwnd_reduction)
                    > time::Duration::microseconds(
                        (f64::from(self.rtt) * self.deficit_timeout as f64) as i64,
                    )) {
                self.curr_cwnd_reduction = 0;
            }

            // if loss indicator is nonzero
            // AND the losses in the lossy cwnd have not yet been accounted for
            // OR there is a partial ACK AND cwnd was probing ss_thresh
            if m.loss > 0 && self.curr_cwnd_reduction == 0
                || (m.acked > 0 && self.alg.curr_cwnd() == self.ss_thresh)
            {
                self.alg.reduction(m);
                self.last_cwnd_reduction = time::now().to_timespec();
                self.ss_thresh = self.alg.curr_cwnd();
                self.update_cwnd();
            }

            self.curr_cwnd_reduction += m.sacked + m.loss;
        } else if m.acked < self.curr_cwnd_reduction {
            self.curr_cwnd_reduction -= (m.acked as f32 / self.mss as f32) as u32;
        } else {
            self.curr_cwnd_reduction = 0;
        }
    }

    fn slow_start_increase(&mut self, acked: u32) -> u32 {
        let mut new_bytes_acked = acked;
        if self.alg.curr_cwnd() < self.ss_thresh {
            // increase cwnd by 1 per packet, until ssthresh
            if self.alg.curr_cwnd() + new_bytes_acked > self.ss_thresh {
                new_bytes_acked -= self.ss_thresh - self.alg.curr_cwnd();
                self.alg.set_cwnd(self.ss_thresh);
            } else {
                let curr_cwnd = self.alg.curr_cwnd();
                if self.use_compensation {
                    // use a compensating increase function: deliberately overshoot
                    // the "correct" update to keep account for lost throughput due to
                    // infrequent updates. Usually this doesn't matter, but it can when
                    // the window is increasing exponentially (slow start).
                    let delta = f64::from(new_bytes_acked) / (2.0_f64).ln();
                    self.alg.set_cwnd(curr_cwnd + delta as u32);
                // let ccp_rtt = (rtt_us + 10_000) as f64;
                // let delta = ccp_rtt * ccp_rtt / (rtt_us as f64 * rtt_us as f64);
                // self.cwnd += (new_bytes_acked as f64 * delta) as u32;
                } else {
                    self.alg.set_cwnd(curr_cwnd + new_bytes_acked);
                }

                new_bytes_acked = 0
            }
        }

        new_bytes_acked
    }
}