/* TCP-Fusion written by Kazumi Kaneko
 *
 * Copyright (c) 2007, Katto Lab., Waseda University.
 * All rights reserved.
 */

#include <linux/config.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/inet_diag.h>
#include <net/tcp.h>

static int fusion_rtt_mod = 4000;
static int fusion_min_inc = 4;
static int fusion_debug = 0;

module_param(fusion_rtt_mod, int, 0644);
MODULE_PARM_DESC(fusion_rtt_mod, "rtt modification");
module_param(fusion_min_inc, int, 0644);
MODULE_PARM_DESC(fusion_min_inc, "minimum increment");
module_param(fusion_debug, int, 0644);
MODULE_PARM_DESC(fusion_debug, "debug");

/* TCP-Fusion structure */
struct westwood {
        u32    bw_ns_est;        /* first bandwidth estimation..not too smoothed 8) */
        u32    bw_est;           /* bandwidth estimate */
        u32    rtt_win_sx;       /* here starts a new evaluation... */
        u32    bk;
        u32    snd_una;          /* used for evaluating the number of acked bytes */
        u32    cumul_ack;
        u32    accounted;
        u32    rtt;
        u32    rtt_min;          /* minimum observed RTT */
        u32    reno_snd_cwnd;    /*TCP-Reno like congestion window size*/
        
        /*Vegas parameter*/
    //  u32 beg_snd_nxt;
    //  u32 beg_snd_una;
    //  u32 beg_snd_cwnd;
    //  u16 cntRTT;
        u32 minRTT;   /*usec*/
        u32 baseRTT;  /*usec*/
};


/* TCP Westwood functions and constants */
#define TCP_WESTWOOD_RTT_MIN   (HZ/20)  /* 50ms */
#define TCP_WESTWOOD_INIT_RTT  (20*HZ)  /* maybe too conservative?! */

/*
 * @tcp_westwood_create
 * This function initializes fields used in TCP Westwood+,
 * it is called after the initial SYN, so the sequence numbers
 * are correct but new passive connections we have no
 * information about RTTmin at this time so we simply set it to
 * TCP_WESTWOOD_INIT_RTT. This value was chosen to be too conservative
 * since in this way we're sure it will be updated in a consistent
 * way as soon as possible. It will reasonably happen within the first
 * RTT period of the connection lifetime.
 */
static void tcp_fusion_init(struct sock *sk)
{
        struct tcp_sock *tp = tcp_sk(sk);
        struct westwood *fusion = inet_csk_ca(sk);

        fusion->bk = 0;
        fusion->bw_ns_est = 0;
        fusion->bw_est = 0;
        fusion->accounted = 0;
        fusion->cumul_ack = 0;
        fusion->rtt_min = fusion->rtt = TCP_WESTWOOD_INIT_RTT;
        fusion->rtt_win_sx = tcp_time_stamp;
        fusion->snd_una = tcp_sk(sk)->snd_una;
        
        fusion->reno_snd_cwnd = tp->snd_cwnd;   
        
        fusion->baseRTT = 0x7fffffff;
        fusion->minRTT = 0x7fffffff;
       // tcp_sk(sk)->snd_ssthresh = 100;
        
    
}

/*
 * @westwood_do_filter
 * Low-pass filter. Implemented using constant coefficients.
 */
static inline u32 fusion_do_filter(u32 a, u32 b)
{
        return (((7 * a) + b) >> 3);
       
}

static inline void fusion_filter(struct westwood *fusion, u32 delta)
{
        fusion->bw_ns_est = fusion_do_filter(fusion->bw_ns_est, fusion->bk / delta);
        fusion->bw_est = fusion_do_filter(fusion->bw_est, fusion->bw_ns_est);

}

/*
 * @westwood_pkts_acked
 * Called after processing group of packets.
 * but all westwood needs is the last sample of srtt.
 */
static void tcp_fusion_pkts_acked(struct sock *sk, u32 cnt)
{
        struct westwood *fusion = inet_csk_ca(sk);
        if (cnt > 0)
                fusion->rtt = tcp_sk(sk)->srtt;
     
}

/*
 * @westwood_update_window
 * It updates RTT evaluation window if it is the right moment to do
 * it. If so it calls filter for evaluating bandwidth.
 */
static void fusion_update_window(struct sock *sk)
{
        struct westwood *fusion = inet_csk_ca(sk);
        s32 delta = tcp_time_stamp - fusion->rtt_win_sx;

    
        /*
         * See if a RTT-window has passed.
         * Be careful since if RTT is less than
         * 50ms we don't filter but we continue 'building the sample'.
         * This minimum limit was chosen since an estimation on small
         * time intervals is better to avoid...
         * Obviously on a LAN we reasonably will always have
         * right_bound = left_bound + WESTWOOD_RTT_MIN
         */
        if (fusion->rtt && delta > max_t(u32, fusion->rtt>>3, TCP_WESTWOOD_RTT_MIN)) {
                fusion_filter(fusion, delta);

                fusion->bk = 0;
                fusion->rtt_win_sx = tcp_time_stamp;
        }
}

/*
 * @westwood_fast_bw
 * It is called when we are in fast path. In particular it is called when
 * header prediction is successful. In such case in fact update is
 * straight forward and doesn't need any particular care.
 */
static inline void fusion_fast_bw(struct sock *sk)
{
        const struct tcp_sock *tp = tcp_sk(sk);
        struct westwood *fusion = inet_csk_ca(sk);

        fusion_update_window(sk);

        fusion->bk += tp->snd_una - fusion->snd_una;
        fusion->snd_una = tp->snd_una;
        fusion->rtt_min = min(fusion->rtt, fusion->rtt_min);

       
}

/*
 * @westwood_acked_count
 * This function evaluates cumul_ack for evaluating bk in case of
 * delayed or partial acks.
 */
static inline u32 fusion_acked_count(struct sock *sk)
{
        const struct tcp_sock *tp = tcp_sk(sk);
        struct westwood *fusion = inet_csk_ca(sk);

        fusion->cumul_ack = tp->snd_una - fusion->snd_una;

        /* If cumul_ack is 0 this is a dupack since it's not moving
         * tp->snd_una.
         */
        if (!fusion->cumul_ack) {
                fusion->accounted += tp->mss_cache;
                fusion->cumul_ack = tp->mss_cache;
        }

        if (fusion->cumul_ack > tp->mss_cache) {
                /* Partial or delayed ack */
                if (fusion->accounted >= fusion->cumul_ack) {
                        fusion->accounted -= fusion->cumul_ack;
                        fusion->cumul_ack = tp->mss_cache;
                } else {
                        fusion->cumul_ack -= fusion->accounted;
                        fusion->accounted = 0;
                }
        }

        fusion->snd_una = tp->snd_una;

        return fusion->cumul_ack;
}

static u32 tcp_fusion_calc_ssthresh(struct sock *sk)
{
        const struct tcp_sock *tp = tcp_sk(sk);
        struct westwood *fusion = inet_csk_ca(sk);
       
        fusion->reno_snd_cwnd = max(tp->snd_cwnd >> 1U, 2U);
		
		if(fusion_debug)
        printk("Packetloss:snd_cwnd=%u,reno_cwnd=%u\n",
                tp->snd_cwnd*fusion->rtt_min/tp->srtt,fusion->reno_snd_cwnd);
       
       return max_t(u32, (tp->snd_cwnd * fusion->rtt_min / (tp->srtt)), fusion->reno_snd_cwnd);
    
}


/*
 * TCP Westwood
 * Here limit is evaluated as Bw estimation*RTTmin (for obtaining it
 * in packets we use mss_cache). Rttmin is guaranteed to be >= 2
 * so avoids ever returning 0.
 */
static u32 tcp_fusion_cwnd_min(struct sock *sk)
{
        const struct tcp_sock *tp = tcp_sk(sk);
       
        return tp->snd_ssthresh;
}


static void tcp_fusion_rtt_calc(struct sock *sk, u32 usrtt)
{
	struct westwood *fusion = inet_csk_ca(sk);
	u32 vrtt = usrtt + fusion_rtt_mod;
	
	if (vrtt < fusion->baseRTT)
		fusion->baseRTT = vrtt;
		
	fusion->minRTT = min(fusion->minRTT, usrtt);

        
}

 

/* TCP-Fusion algorithm */
static void tcp_fusion_cong_avoid(struct sock *sk, u32 ack, u32 seq_rtt, u32 in_flight, int flag)
{
	struct tcp_sock *tp = tcp_sk(sk);
	struct westwood *fusion = inet_csk_ca(sk);
	
     
   	if(fusion_debug)
        	printk("snd_cwnd=%u,reno_cwnd=%u,ssthresh=%u\n",
        			tp->snd_cwnd,fusion->reno_snd_cwnd, tp->snd_ssthresh);
	if ( tp->snd_cwnd < tp->snd_ssthresh) {
		/*Slow start*/
		if ( tp->snd_cwnd < tp->snd_cwnd_clamp){
			tp->snd_cwnd++;
			fusion->reno_snd_cwnd = tp->snd_cwnd;
                        
		}
	} else {
		/*Congestion Avoidance*/
		if (tp->snd_cwnd_cnt < tp->snd_cwnd ) {
			tp->snd_cwnd_cnt++;
		} else {
			u32 alpha, fusion_inc, target_cwnd, diff, last_cwnd;
            	
	       	last_cwnd = tp->snd_cwnd; 
    
          	if ( fusion->minRTT > fusion->baseRTT){
        		target_cwnd = last_cwnd * fusion->baseRTT / fusion->minRTT;
        		diff = last_cwnd - target_cwnd;
        	} else {
               	diff = 0;
               	target_cwnd = last_cwnd;
       		}
				alpha = fusion->bw_est / 1500;
				
           	if (alpha < fusion_min_inc)
              	alpha = fusion_min_inc;
               
        	fusion_inc = alpha >>2;
         	if(fusion_dubug)
               	printk("bw_est=%u,alpha=%u\n",fusion->bw_est, alpha);
         
                /* reno_cwnd update*/
			fusion->reno_snd_cwnd++;
			
			if (diff > (3*alpha)) {
				last_cwnd -= (diff-alpha); 
			} else if (diff <= alpha){
				last_cwnd += fusion_inc;
		  	} else {
				last_cwnd = last_cwnd;
			}	
                
          
          	fusion->minRTT = 0x7fffffff;
         	tp->snd_cwnd_cnt = 0;
			last_cwnd = max(last_cwnd, fusion->reno_snd_cwnd);
			tp->snd_cwnd = last_cwnd;
		}
    }
    
   	if(fusion_debug)
    	printk("snd_cwnd=%u, reno_cwnd=%u\n",tp->snd_cwnd, fusion->reno_snd_cwnd);

   	tp->snd_cwnd = min_t(u32, tp->snd_cwnd, tp->snd_cwnd_clamp);
    tp->snd_cwnd = max(tp->snd_cwnd, 2U);
}


static void tcp_fusion_event(struct sock *sk, enum tcp_ca_event event)
{
        struct tcp_sock *tp = tcp_sk(sk);
        struct westwood *fusion = inet_csk_ca(sk);

        switch(event) {
        case CA_EVENT_FAST_ACK:
                fusion_fast_bw(sk);
                break;
/*
        case CA_EVENT_COMPLETE_CWR:
               // fusion->reno_snd_cwnd = (tp->snd_cwnd >> 1U);
                tp->snd_cwnd = tp->snd_ssthresh = fusion_bw_rttmin(sk);
               // fusion->reno_snd_cwnd = (tp->snd_cwnd >>1U);
                break;
*/
        case CA_EVENT_FRTO:
                tp->snd_ssthresh = tp->snd_cwnd >> 1;
                fusion->reno_snd_cwnd = 2;
                break;

        case CA_EVENT_SLOW_ACK:
                fusion_update_window(sk);
                fusion->bk += fusion_acked_count(sk);
                fusion->rtt_min = min(fusion->rtt, fusion->rtt_min);
                break;

        default:
                /* don't care */
                break;
        }
}


/* Extract info for Tcp socket info provided via netlink. */

static void tcp_fusion_info(struct sock *sk, u32 ext,
                              struct sk_buff *skb)
{
        const struct westwood *ca = inet_csk_ca(sk);
        if (ext & (1 << (INET_DIAG_VEGASINFO - 1))) {
                struct rtattr *rta;
                struct tcpvegas_info *info;

                rta = __RTA_PUT(skb, INET_DIAG_VEGASINFO, sizeof(*info));
                info = RTA_DATA(rta);
                info->tcpv_enabled = 1;
                info->tcpv_rttcnt = 0;
                info->tcpv_rtt = jiffies_to_usecs(ca->rtt);
                info->tcpv_minrtt = jiffies_to_usecs(ca->rtt_min);
        rtattr_failure: ;
        }
}


static struct tcp_congestion_ops tcp_fusion = {
        .init           = tcp_fusion_init,
        .ssthresh       = tcp_fusion_calc_ssthresh,        
        .cong_avoid     = tcp_fusion_cong_avoid,
        .min_cwnd       = tcp_fusion_cwnd_min,
        .cwnd_event     = tcp_fusion_event,
        .get_info       = tcp_fusion_info,
        .pkts_acked     = tcp_fusion_pkts_acked,
        
     // .undo_cwnd      = fusion_bw_rttmin,
        .rtt_sample     = tcp_fusion_rtt_calc,

        .owner          = THIS_MODULE,
        .name           = "fusion"
};

static int __init tcp_fusion_register(void)
{
        BUG_ON(sizeof(struct westwood) > ICSK_CA_PRIV_SIZE);
        return tcp_register_congestion_control(&tcp_fusion);
}

static void __exit tcp_fusion_unregister(void)
{
        tcp_unregister_congestion_control(&tcp_fusion);
}

module_init(tcp_fusion_register);
module_exit(tcp_fusion_unregister);

MODULE_AUTHOR("Stephen Hemminger, Angelo Dell'Aera");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("TCP Fusion");
