sch_netem.c 26.8 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3 4 5 6
/*
 * net/sched/sch_netem.c	Network emulator
 *
 * 		This program is free software; you can redistribute it and/or
 * 		modify it under the terms of the GNU General Public License
 * 		as published by the Free Software Foundation; either version
7
 * 		2 of the License.
L
Linus Torvalds 已提交
8 9
 *
 *  		Many of the algorithms and ideas for this came from
10
 *		NIST Net which is not copyrighted.
L
Linus Torvalds 已提交
11 12 13 14 15
 *
 * Authors:	Stephen Hemminger <shemminger@osdl.org>
 *		Catalin(ux aka Dino) BOIE <catab at umbrella dot ro>
 */

16
#include <linux/mm.h>
L
Linus Torvalds 已提交
17
#include <linux/module.h>
18
#include <linux/slab.h>
L
Linus Torvalds 已提交
19 20 21 22
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/skbuff.h>
23
#include <linux/vmalloc.h>
L
Linus Torvalds 已提交
24
#include <linux/rtnetlink.h>
25
#include <linux/reciprocal_div.h>
26
#include <linux/rbtree.h>
L
Linus Torvalds 已提交
27

28
#include <net/netlink.h>
L
Linus Torvalds 已提交
29
#include <net/pkt_sched.h>
E
Eric Dumazet 已提交
30
#include <net/inet_ecn.h>
L
Linus Torvalds 已提交
31

32
#define VERSION "1.3"
S
Stephen Hemminger 已提交
33

L
Linus Torvalds 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
/*	Network Emulation Queuing algorithm.
	====================================

	Sources: [1] Mark Carson, Darrin Santay, "NIST Net - A Linux-based
		 Network Emulation Tool
		 [2] Luigi Rizzo, DummyNet for FreeBSD

	 ----------------------------------------------------------------

	 This started out as a simple way to delay outgoing packets to
	 test TCP but has grown to include most of the functionality
	 of a full blown network emulator like NISTnet. It can delay
	 packets and add random jitter (and correlation). The random
	 distribution can be loaded from a table as well to provide
	 normal, Pareto, or experimental curves. Packet loss,
	 duplication, and reordering can also be emulated.

	 This qdisc does not do classification that can be handled in
	 layering other disciplines.  It does not need to do bandwidth
	 control either since that can be handled by using token
	 bucket or other rate control.
55 56 57 58 59 60 61 62 63 64 65 66 67 68

     Correlated Loss Generator models

	Added generation of correlated loss according to the
	"Gilbert-Elliot" model, a 4-state markov model.

	References:
	[1] NetemCLG Home http://netgroup.uniroma2.it/NetemCLG
	[2] S. Salsano, F. Ludovici, A. Ordine, "Definition of a general
	and intuitive loss model for packet networks and its implementation
	in the Netem module in the Linux kernel", available in [1]

	Authors: Stefano Salsano <stefano.salsano at uniroma2.it
		 Fabio Ludovici <fabio.ludovici at yahoo.it>
L
Linus Torvalds 已提交
69 70 71
*/

struct netem_sched_data {
72 73
	/* internal t(ime)fifo qdisc uses t_root and sch->limit */
	struct rb_root t_root;
E
Eric Dumazet 已提交
74 75

	/* optional qdisc for classful handling (NULL at netem init) */
L
Linus Torvalds 已提交
76
	struct Qdisc	*qdisc;
E
Eric Dumazet 已提交
77

78
	struct qdisc_watchdog watchdog;
L
Linus Torvalds 已提交
79

80 81 82
	psched_tdiff_t latency;
	psched_tdiff_t jitter;

L
Linus Torvalds 已提交
83
	u32 loss;
E
Eric Dumazet 已提交
84
	u32 ecn;
L
Linus Torvalds 已提交
85 86 87 88
	u32 limit;
	u32 counter;
	u32 gap;
	u32 duplicate;
89
	u32 reorder;
90
	u32 corrupt;
Y
Yang Yingliang 已提交
91
	u64 rate;
92 93
	s32 packet_overhead;
	u32 cell_size;
94
	struct reciprocal_value cell_size_reciprocal;
95
	s32 cell_overhead;
L
Linus Torvalds 已提交
96 97

	struct crndstate {
98 99
		u32 last;
		u32 rho;
100
	} delay_cor, loss_cor, dup_cor, reorder_cor, corrupt_cor;
L
Linus Torvalds 已提交
101 102 103 104 105

	struct disttable {
		u32  size;
		s16 table[0];
	} *delay_dist;
106 107 108 109 110 111 112

	enum  {
		CLG_RANDOM,
		CLG_4_STATES,
		CLG_GILB_ELL,
	} loss_model;

113 114 115 116 117 118 119
	enum {
		TX_IN_GAP_PERIOD = 1,
		TX_IN_BURST_PERIOD,
		LOST_IN_GAP_PERIOD,
		LOST_IN_BURST_PERIOD,
	} _4_state_model;

120 121 122 123 124
	enum {
		GOOD_STATE = 1,
		BAD_STATE,
	} GE_state_model;

125 126 127 128 129 130 131 132 133 134 135 136 137
	/* Correlated Loss Generation models */
	struct clgstate {
		/* state of the Markov chain */
		u8 state;

		/* 4-states and Gilbert-Elliot models */
		u32 a1;	/* p13 for 4-states or p for GE */
		u32 a2;	/* p31 for 4-states or r for GE */
		u32 a3;	/* p32 for 4-states or h for GE */
		u32 a4;	/* p14 for 4-states or 1-k for GE */
		u32 a5; /* p23 used only in 4-states */
	} clg;

L
Linus Torvalds 已提交
138 139
};

E
Eric Dumazet 已提交
140 141 142
/* Time stamp put into socket buffer control block
 * Only valid when skbs are in our internal t(ime)fifo queue.
 */
L
Linus Torvalds 已提交
143 144
struct netem_skb_cb {
	psched_time_t	time_to_send;
145
	ktime_t		tstamp_save;
L
Linus Torvalds 已提交
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
/* Because space in skb->cb[] is tight, netem overloads skb->next/prev/tstamp
 * to hold a rb_node structure.
 *
 * If struct sk_buff layout is changed, the following checks will complain.
 */
static struct rb_node *netem_rb_node(struct sk_buff *skb)
{
	BUILD_BUG_ON(offsetof(struct sk_buff, next) != 0);
	BUILD_BUG_ON(offsetof(struct sk_buff, prev) !=
		     offsetof(struct sk_buff, next) + sizeof(skb->next));
	BUILD_BUG_ON(offsetof(struct sk_buff, tstamp) !=
		     offsetof(struct sk_buff, prev) + sizeof(skb->prev));
	BUILD_BUG_ON(sizeof(struct rb_node) > sizeof(skb->next) +
					      sizeof(skb->prev) +
					      sizeof(skb->tstamp));
	return (struct rb_node *)&skb->next;
}

static struct sk_buff *netem_rb_to_skb(struct rb_node *rb)
{
	return (struct sk_buff *)rb;
}

171 172
static inline struct netem_skb_cb *netem_skb_cb(struct sk_buff *skb)
{
173
	/* we assume we can use skb next/prev/tstamp as storage for rb_node */
174
	qdisc_cb_private_validate(skb, sizeof(struct netem_skb_cb));
175
	return (struct netem_skb_cb *)qdisc_skb_cb(skb)->data;
176 177
}

L
Linus Torvalds 已提交
178 179 180 181 182 183
/* init_crandom - initialize correlated random number generator
 * Use entropy source for initial seed.
 */
static void init_crandom(struct crndstate *state, unsigned long rho)
{
	state->rho = rho;
184
	state->last = prandom_u32();
L
Linus Torvalds 已提交
185 186 187 188 189 190
}

/* get_crandom - correlated random number generator
 * Next number depends on last value.
 * rho is scaled to avoid floating point.
 */
191
static u32 get_crandom(struct crndstate *state)
L
Linus Torvalds 已提交
192 193 194 195
{
	u64 value, rho;
	unsigned long answer;

S
Stephen Hemminger 已提交
196
	if (state->rho == 0)	/* no correlation */
197
		return prandom_u32();
L
Linus Torvalds 已提交
198

199
	value = prandom_u32();
L
Linus Torvalds 已提交
200 201 202 203 204 205
	rho = (u64)state->rho + 1;
	answer = (value * ((1ull<<32) - rho) + state->last * rho) >> 32;
	state->last = answer;
	return answer;
}

206 207 208 209 210 211 212
/* loss_4state - 4-state model loss generator
 * Generates losses according to the 4-state Markov chain adopted in
 * the GI (General and Intuitive) loss model.
 */
static bool loss_4state(struct netem_sched_data *q)
{
	struct clgstate *clg = &q->clg;
213
	u32 rnd = prandom_u32();
214 215

	/*
L
Lucas De Marchi 已提交
216
	 * Makes a comparison between rnd and the transition
217 218 219
	 * probabilities outgoing from the current state, then decides the
	 * next state and if the next packet has to be transmitted or lost.
	 * The four states correspond to:
220 221 222 223
	 *   TX_IN_GAP_PERIOD => successfully transmitted packets within a gap period
	 *   LOST_IN_BURST_PERIOD => isolated losses within a gap period
	 *   LOST_IN_GAP_PERIOD => lost packets within a burst period
	 *   TX_IN_GAP_PERIOD => successfully transmitted packets within a burst period
224 225
	 */
	switch (clg->state) {
226
	case TX_IN_GAP_PERIOD:
227
		if (rnd < clg->a4) {
228
			clg->state = LOST_IN_BURST_PERIOD;
229
			return true;
S
stephen hemminger 已提交
230
		} else if (clg->a4 < rnd && rnd < clg->a1 + clg->a4) {
231
			clg->state = LOST_IN_GAP_PERIOD;
232
			return true;
233 234 235
		} else if (clg->a1 + clg->a4 < rnd) {
			clg->state = TX_IN_GAP_PERIOD;
		}
236 237

		break;
238
	case TX_IN_BURST_PERIOD:
239
		if (rnd < clg->a5) {
240
			clg->state = LOST_IN_GAP_PERIOD;
241
			return true;
242 243 244
		} else {
			clg->state = TX_IN_BURST_PERIOD;
		}
245 246

		break;
247
	case LOST_IN_GAP_PERIOD:
248
		if (rnd < clg->a3)
249
			clg->state = TX_IN_BURST_PERIOD;
250
		else if (clg->a3 < rnd && rnd < clg->a2 + clg->a3) {
251
			clg->state = TX_IN_GAP_PERIOD;
252
		} else if (clg->a2 + clg->a3 < rnd) {
253
			clg->state = LOST_IN_GAP_PERIOD;
254 255 256
			return true;
		}
		break;
257 258
	case LOST_IN_BURST_PERIOD:
		clg->state = TX_IN_GAP_PERIOD;
259 260 261 262 263 264 265 266 267 268
		break;
	}

	return false;
}

/* loss_gilb_ell - Gilbert-Elliot model loss generator
 * Generates losses according to the Gilbert-Elliot loss model or
 * its special cases  (Gilbert or Simple Gilbert)
 *
L
Lucas De Marchi 已提交
269
 * Makes a comparison between random number and the transition
270
 * probabilities outgoing from the current state, then decides the
L
Lucas De Marchi 已提交
271
 * next state. A second random number is extracted and the comparison
272 273 274 275 276 277 278 279
 * with the loss probability of the current state decides if the next
 * packet will be transmitted or lost.
 */
static bool loss_gilb_ell(struct netem_sched_data *q)
{
	struct clgstate *clg = &q->clg;

	switch (clg->state) {
280
	case GOOD_STATE:
281
		if (prandom_u32() < clg->a1)
282
			clg->state = BAD_STATE;
283
		if (prandom_u32() < clg->a4)
284
			return true;
285
		break;
286
	case BAD_STATE:
287
		if (prandom_u32() < clg->a2)
288
			clg->state = GOOD_STATE;
289
		if (prandom_u32() > clg->a3)
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
			return true;
	}

	return false;
}

static bool loss_event(struct netem_sched_data *q)
{
	switch (q->loss_model) {
	case CLG_RANDOM:
		/* Random packet drop 0 => none, ~0 => all */
		return q->loss && q->loss >= get_crandom(&q->loss_cor);

	case CLG_4_STATES:
		/* 4state loss model algorithm (used also for GI model)
		* Extracts a value from the markov 4 state loss generator,
		* if it is 1 drops a packet and if needed writes the event in
		* the kernel logs
		*/
		return loss_4state(q);

	case CLG_GILB_ELL:
		/* Gilbert-Elliot loss model algorithm
		* Extracts a value from the Gilbert-Elliot loss generator,
		* if it is 1 drops a packet and if needed writes the event in
		* the kernel logs
		*/
		return loss_gilb_ell(q);
	}

	return false;	/* not reached */
}


L
Linus Torvalds 已提交
324 325 326 327
/* tabledist - return a pseudo-randomly distributed value with mean mu and
 * std deviation sigma.  Uses table lookup to approximate the desired
 * distribution, and a uniformly-distributed pseudo-random source.
 */
328 329 330
static psched_tdiff_t tabledist(psched_tdiff_t mu, psched_tdiff_t sigma,
				struct crndstate *state,
				const struct disttable *dist)
L
Linus Torvalds 已提交
331
{
332 333 334
	psched_tdiff_t x;
	long t;
	u32 rnd;
L
Linus Torvalds 已提交
335 336 337 338 339 340 341

	if (sigma == 0)
		return mu;

	rnd = get_crandom(state);

	/* default uniform distribution */
342
	if (dist == NULL)
L
Linus Torvalds 已提交
343 344 345 346 347 348 349 350 351 352 353 354
		return (rnd % (2*sigma)) - sigma + mu;

	t = dist->table[rnd % dist->size];
	x = (sigma % NETEM_DIST_SCALE) * t;
	if (x >= 0)
		x += NETEM_DIST_SCALE/2;
	else
		x -= NETEM_DIST_SCALE/2;

	return  x / NETEM_DIST_SCALE + (sigma / NETEM_DIST_SCALE) * t + mu;
}

355
static psched_time_t packet_len_2_sched_time(unsigned int len, struct netem_sched_data *q)
H
Hagen Paul Pfeifer 已提交
356
{
357
	u64 ticks;
358

359 360 361 362 363 364 365 366 367 368 369 370 371
	len += q->packet_overhead;

	if (q->cell_size) {
		u32 cells = reciprocal_divide(len, q->cell_size_reciprocal);

		if (len > cells * q->cell_size)	/* extra cell needed for remainder */
			cells++;
		len = cells * (q->cell_size + q->cell_overhead);
	}

	ticks = (u64)len * NSEC_PER_SEC;

	do_div(ticks, q->rate);
372
	return PSCHED_NS2TICKS(ticks);
H
Hagen Paul Pfeifer 已提交
373 374
}

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
static void tfifo_reset(struct Qdisc *sch)
{
	struct netem_sched_data *q = qdisc_priv(sch);
	struct rb_node *p;

	while ((p = rb_first(&q->t_root))) {
		struct sk_buff *skb = netem_rb_to_skb(p);

		rb_erase(p, &q->t_root);
		skb->next = NULL;
		skb->prev = NULL;
		kfree_skb(skb);
	}
}

390
static void tfifo_enqueue(struct sk_buff *nskb, struct Qdisc *sch)
E
Eric Dumazet 已提交
391
{
392
	struct netem_sched_data *q = qdisc_priv(sch);
E
Eric Dumazet 已提交
393
	psched_time_t tnext = netem_skb_cb(nskb)->time_to_send;
394
	struct rb_node **p = &q->t_root.rb_node, *parent = NULL;
E
Eric Dumazet 已提交
395

396 397
	while (*p) {
		struct sk_buff *skb;
E
Eric Dumazet 已提交
398

399 400
		parent = *p;
		skb = netem_rb_to_skb(parent);
401
		if (tnext >= netem_skb_cb(skb)->time_to_send)
402 403 404
			p = &parent->rb_right;
		else
			p = &parent->rb_left;
E
Eric Dumazet 已提交
405
	}
406 407 408
	rb_link_node(netem_rb_node(nskb), parent, p);
	rb_insert_color(netem_rb_node(nskb), &q->t_root);
	sch->q.qlen++;
E
Eric Dumazet 已提交
409 410
}

411 412 413 414 415 416
/*
 * Insert one skb into qdisc.
 * Note: parent depends on return value to account for queue length.
 * 	NET_XMIT_DROP: queue length didn't change.
 *      NET_XMIT_SUCCESS: one skb was queued.
 */
L
Linus Torvalds 已提交
417 418 419
static int netem_enqueue(struct sk_buff *skb, struct Qdisc *sch)
{
	struct netem_sched_data *q = qdisc_priv(sch);
420 421
	/* We don't fill cb now as skb_unshare() may invalidate it */
	struct netem_skb_cb *cb;
422 423
	struct sk_buff *skb2;
	int count = 1;
L
Linus Torvalds 已提交
424

425 426 427 428
	/* Random duplication */
	if (q->duplicate && q->duplicate >= get_crandom(&q->dup_cor))
		++count;

429
	/* Drop packet? */
E
Eric Dumazet 已提交
430 431 432 433 434 435
	if (loss_event(q)) {
		if (q->ecn && INET_ECN_set_ce(skb))
			sch->qstats.drops++; /* mark packet */
		else
			--count;
	}
436
	if (count == 0) {
L
Linus Torvalds 已提交
437 438
		sch->qstats.drops++;
		kfree_skb(skb);
439
		return NET_XMIT_SUCCESS | __NET_XMIT_BYPASS;
L
Linus Torvalds 已提交
440 441
	}

E
Eric Dumazet 已提交
442 443 444 445
	/* If a delay is expected, orphan the skb. (orphaning usually takes
	 * place at TX completion time, so _before_ the link transit delay)
	 */
	if (q->latency || q->jitter)
446
		skb_orphan_partial(skb);
447

448 449 450 451 452 453
	/*
	 * If we need to duplicate packet, then re-insert at top of the
	 * qdisc tree, since parent queuer expects that only one
	 * skb will be queued.
	 */
	if (count > 1 && (skb2 = skb_clone(skb, GFP_ATOMIC)) != NULL) {
454
		struct Qdisc *rootq = qdisc_root(sch);
455 456 457
		u32 dupsave = q->duplicate; /* prevent duplicating a dup... */
		q->duplicate = 0;

458
		qdisc_enqueue_root(skb2, rootq);
459
		q->duplicate = dupsave;
L
Linus Torvalds 已提交
460 461
	}

462 463 464 465 466 467 468
	/*
	 * Randomized packet corruption.
	 * Make copy if needed since we are modifying
	 * If packet is going to be hardware checksummed, then
	 * do it now in software before we mangle it.
	 */
	if (q->corrupt && q->corrupt >= get_crandom(&q->corrupt_cor)) {
469 470
		if (!(skb = skb_unshare(skb, GFP_ATOMIC)) ||
		    (skb->ip_summed == CHECKSUM_PARTIAL &&
E
Eric Dumazet 已提交
471 472
		     skb_checksum_help(skb)))
			return qdisc_drop(skb, sch);
473

474 475
		skb->data[prandom_u32() % skb_headlen(skb)] ^=
			1<<(prandom_u32() % 8);
476 477
	}

478 479 480 481 482
	if (unlikely(skb_queue_len(&sch->q) >= sch->limit))
		return qdisc_reshape_fail(skb, sch);

	sch->qstats.backlog += qdisc_pkt_len(skb);

483
	cb = netem_skb_cb(skb);
E
Eric Dumazet 已提交
484
	if (q->gap == 0 ||		/* not doing reordering */
485
	    q->counter < q->gap - 1 ||	/* inside last reordering gap */
486
	    q->reorder < get_crandom(&q->reorder_cor)) {
487
		psched_time_t now;
S
Stephen Hemminger 已提交
488 489 490 491 492
		psched_tdiff_t delay;

		delay = tabledist(q->latency, q->jitter,
				  &q->delay_cor, q->delay_dist);

493
		now = psched_get_time();
H
Hagen Paul Pfeifer 已提交
494 495

		if (q->rate) {
496
			struct sk_buff *last;
H
Hagen Paul Pfeifer 已提交
497

498 499 500 501 502
			if (!skb_queue_empty(&sch->q))
				last = skb_peek_tail(&sch->q);
			else
				last = netem_rb_to_skb(rb_last(&q->t_root));
			if (last) {
H
Hagen Paul Pfeifer 已提交
503
				/*
504 505
				 * Last packet in queue is reference point (now),
				 * calculate this time bonus and subtract
H
Hagen Paul Pfeifer 已提交
506 507
				 * from delay.
				 */
508
				delay -= netem_skb_cb(last)->time_to_send - now;
509
				delay = max_t(psched_tdiff_t, 0, delay);
510
				now = netem_skb_cb(last)->time_to_send;
H
Hagen Paul Pfeifer 已提交
511
			}
512

513
			delay += packet_len_2_sched_time(qdisc_pkt_len(skb), q);
H
Hagen Paul Pfeifer 已提交
514 515
		}

516
		cb->time_to_send = now + delay;
517
		cb->tstamp_save = skb->tstamp;
L
Linus Torvalds 已提交
518
		++q->counter;
519
		tfifo_enqueue(skb, sch);
L
Linus Torvalds 已提交
520
	} else {
521
		/*
522 523 524
		 * Do re-ordering by putting one out of N packets at the front
		 * of the queue.
		 */
525
		cb->time_to_send = psched_get_time();
526
		q->counter = 0;
527

E
Eric Dumazet 已提交
528
		__skb_queue_head(&sch->q, skb);
529
		sch->qstats.requeues++;
530
	}
L
Linus Torvalds 已提交
531

532
	return NET_XMIT_SUCCESS;
L
Linus Torvalds 已提交
533 534
}

E
Eric Dumazet 已提交
535
static unsigned int netem_drop(struct Qdisc *sch)
L
Linus Torvalds 已提交
536 537
{
	struct netem_sched_data *q = qdisc_priv(sch);
E
Eric Dumazet 已提交
538
	unsigned int len;
L
Linus Torvalds 已提交
539

E
Eric Dumazet 已提交
540
	len = qdisc_queue_drop(sch);
541 542 543 544 545 546 547 548 549 550 551 552

	if (!len) {
		struct rb_node *p = rb_first(&q->t_root);

		if (p) {
			struct sk_buff *skb = netem_rb_to_skb(p);

			rb_erase(p, &q->t_root);
			sch->q.qlen--;
			skb->next = NULL;
			skb->prev = NULL;
			len = qdisc_pkt_len(skb);
553
			sch->qstats.backlog -= len;
554 555 556
			kfree_skb(skb);
		}
	}
E
Eric Dumazet 已提交
557 558 559
	if (!len && q->qdisc && q->qdisc->ops->drop)
	    len = q->qdisc->ops->drop(q->qdisc);
	if (len)
L
Linus Torvalds 已提交
560
		sch->qstats.drops++;
E
Eric Dumazet 已提交
561

L
Linus Torvalds 已提交
562 563 564 565 566 567 568
	return len;
}

static struct sk_buff *netem_dequeue(struct Qdisc *sch)
{
	struct netem_sched_data *q = qdisc_priv(sch);
	struct sk_buff *skb;
569
	struct rb_node *p;
L
Linus Torvalds 已提交
570

571
	if (qdisc_is_throttled(sch))
572 573
		return NULL;

E
Eric Dumazet 已提交
574
tfifo_dequeue:
575
	skb = __skb_dequeue(&sch->q);
576
	if (skb) {
577 578 579 580 581 582 583 584
deliver:
		sch->qstats.backlog -= qdisc_pkt_len(skb);
		qdisc_unthrottled(sch);
		qdisc_bstats_update(sch, skb);
		return skb;
	}
	p = rb_first(&q->t_root);
	if (p) {
585 586
		psched_time_t time_to_send;

587
		skb = netem_rb_to_skb(p);
588 589

		/* if more time remaining? */
590 591
		time_to_send = netem_skb_cb(skb)->time_to_send;
		if (time_to_send <= psched_get_time()) {
592 593 594 595 596 597
			rb_erase(p, &q->t_root);

			sch->q.qlen--;
			skb->next = NULL;
			skb->prev = NULL;
			skb->tstamp = netem_skb_cb(skb)->tstamp_save;
598

599 600 601 602 603 604 605 606
#ifdef CONFIG_NET_CLS_ACT
			/*
			 * If it's at ingress let's pretend the delay is
			 * from the network (tstamp will be updated).
			 */
			if (G_TC_FROM(skb->tc_verd) & AT_INGRESS)
				skb->tstamp.tv64 = 0;
#endif
607

E
Eric Dumazet 已提交
608 609 610 611 612 613 614 615 616 617 618
			if (q->qdisc) {
				int err = qdisc_enqueue(skb, q->qdisc);

				if (unlikely(err != NET_XMIT_SUCCESS)) {
					if (net_xmit_drop_count(err)) {
						sch->qstats.drops++;
						qdisc_tree_decrease_qlen(sch, 1);
					}
				}
				goto tfifo_dequeue;
			}
619
			goto deliver;
S
Stephen Hemminger 已提交
620
		}
621

E
Eric Dumazet 已提交
622 623 624 625 626
		if (q->qdisc) {
			skb = q->qdisc->ops->dequeue(q->qdisc);
			if (skb)
				goto deliver;
		}
627
		qdisc_watchdog_schedule(&q->watchdog, time_to_send);
628 629
	}

E
Eric Dumazet 已提交
630 631 632 633 634
	if (q->qdisc) {
		skb = q->qdisc->ops->dequeue(q->qdisc);
		if (skb)
			goto deliver;
	}
635
	return NULL;
L
Linus Torvalds 已提交
636 637 638 639 640 641
}

static void netem_reset(struct Qdisc *sch)
{
	struct netem_sched_data *q = qdisc_priv(sch);

E
Eric Dumazet 已提交
642
	qdisc_reset_queue(sch);
643
	tfifo_reset(sch);
E
Eric Dumazet 已提交
644 645
	if (q->qdisc)
		qdisc_reset(q->qdisc);
646
	qdisc_watchdog_cancel(&q->watchdog);
L
Linus Torvalds 已提交
647 648
}

649 650
static void dist_free(struct disttable *d)
{
W
WANG Cong 已提交
651
	kvfree(d);
652 653
}

L
Linus Torvalds 已提交
654 655 656 657
/*
 * Distribution data is a variable size payload containing
 * signed 16 bit values.
 */
658
static int get_dist_table(struct Qdisc *sch, const struct nlattr *attr)
L
Linus Torvalds 已提交
659 660
{
	struct netem_sched_data *q = qdisc_priv(sch);
661
	size_t n = nla_len(attr)/sizeof(__s16);
662
	const __s16 *data = nla_data(attr);
663
	spinlock_t *root_lock;
L
Linus Torvalds 已提交
664 665
	struct disttable *d;
	int i;
666
	size_t s;
L
Linus Torvalds 已提交
667

S
stephen hemminger 已提交
668
	if (n > NETEM_DIST_MAX)
L
Linus Torvalds 已提交
669 670
		return -EINVAL;

671
	s = sizeof(struct disttable) + n * sizeof(s16);
672
	d = kmalloc(s, GFP_KERNEL | __GFP_NOWARN);
673 674
	if (!d)
		d = vmalloc(s);
L
Linus Torvalds 已提交
675 676 677 678 679 680
	if (!d)
		return -ENOMEM;

	d->size = n;
	for (i = 0; i < n; i++)
		d->table[i] = data[i];
681

682
	root_lock = qdisc_root_sleeping_lock(sch);
683 684

	spin_lock_bh(root_lock);
685
	swap(q->delay_dist, d);
686
	spin_unlock_bh(root_lock);
687 688

	dist_free(d);
L
Linus Torvalds 已提交
689 690 691
	return 0;
}

692
static void get_correlation(struct netem_sched_data *q, const struct nlattr *attr)
L
Linus Torvalds 已提交
693
{
694
	const struct tc_netem_corr *c = nla_data(attr);
L
Linus Torvalds 已提交
695 696 697 698 699 700

	init_crandom(&q->delay_cor, c->delay_corr);
	init_crandom(&q->loss_cor, c->loss_corr);
	init_crandom(&q->dup_cor, c->dup_corr);
}

701
static void get_reorder(struct netem_sched_data *q, const struct nlattr *attr)
702
{
703
	const struct tc_netem_reorder *r = nla_data(attr);
704 705 706 707 708

	q->reorder = r->probability;
	init_crandom(&q->reorder_cor, r->correlation);
}

709
static void get_corrupt(struct netem_sched_data *q, const struct nlattr *attr)
710
{
711
	const struct tc_netem_corrupt *r = nla_data(attr);
712 713 714 715 716

	q->corrupt = r->probability;
	init_crandom(&q->corrupt_cor, r->correlation);
}

717
static void get_rate(struct netem_sched_data *q, const struct nlattr *attr)
H
Hagen Paul Pfeifer 已提交
718 719 720 721
{
	const struct tc_netem_rate *r = nla_data(attr);

	q->rate = r->rate;
722 723
	q->packet_overhead = r->packet_overhead;
	q->cell_size = r->cell_size;
724
	q->cell_overhead = r->cell_overhead;
725 726
	if (q->cell_size)
		q->cell_size_reciprocal = reciprocal_value(q->cell_size);
727 728
	else
		q->cell_size_reciprocal = (struct reciprocal_value) { 0 };
H
Hagen Paul Pfeifer 已提交
729 730
}

731
static int get_loss_clg(struct netem_sched_data *q, const struct nlattr *attr)
732 733 734 735 736 737 738
{
	const struct nlattr *la;
	int rem;

	nla_for_each_nested(la, attr, rem) {
		u16 type = nla_type(la);

739
		switch (type) {
740 741 742
		case NETEM_LOSS_GI: {
			const struct tc_netem_gimodel *gi = nla_data(la);

S
stephen hemminger 已提交
743
			if (nla_len(la) < sizeof(struct tc_netem_gimodel)) {
744 745 746 747 748 749
				pr_info("netem: incorrect gi model size\n");
				return -EINVAL;
			}

			q->loss_model = CLG_4_STATES;

750
			q->clg.state = TX_IN_GAP_PERIOD;
751 752 753 754 755 756 757 758 759 760 761
			q->clg.a1 = gi->p13;
			q->clg.a2 = gi->p31;
			q->clg.a3 = gi->p32;
			q->clg.a4 = gi->p14;
			q->clg.a5 = gi->p23;
			break;
		}

		case NETEM_LOSS_GE: {
			const struct tc_netem_gemodel *ge = nla_data(la);

S
stephen hemminger 已提交
762 763
			if (nla_len(la) < sizeof(struct tc_netem_gemodel)) {
				pr_info("netem: incorrect ge model size\n");
764 765 766 767
				return -EINVAL;
			}

			q->loss_model = CLG_GILB_ELL;
768
			q->clg.state = GOOD_STATE;
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
			q->clg.a1 = ge->p;
			q->clg.a2 = ge->r;
			q->clg.a3 = ge->h;
			q->clg.a4 = ge->k1;
			break;
		}

		default:
			pr_info("netem: unknown loss type %u\n", type);
			return -EINVAL;
		}
	}

	return 0;
}

785 786 787 788
static const struct nla_policy netem_policy[TCA_NETEM_MAX + 1] = {
	[TCA_NETEM_CORR]	= { .len = sizeof(struct tc_netem_corr) },
	[TCA_NETEM_REORDER]	= { .len = sizeof(struct tc_netem_reorder) },
	[TCA_NETEM_CORRUPT]	= { .len = sizeof(struct tc_netem_corrupt) },
H
Hagen Paul Pfeifer 已提交
789
	[TCA_NETEM_RATE]	= { .len = sizeof(struct tc_netem_rate) },
790
	[TCA_NETEM_LOSS]	= { .type = NLA_NESTED },
E
Eric Dumazet 已提交
791
	[TCA_NETEM_ECN]		= { .type = NLA_U32 },
Y
Yang Yingliang 已提交
792
	[TCA_NETEM_RATE64]	= { .type = NLA_U64 },
793 794
};

795 796 797 798 799
static int parse_attr(struct nlattr *tb[], int maxtype, struct nlattr *nla,
		      const struct nla_policy *policy, int len)
{
	int nested_len = nla_len(nla) - NLA_ALIGN(len);

800 801
	if (nested_len < 0) {
		pr_info("netem: invalid attributes len %d\n", nested_len);
802
		return -EINVAL;
803 804
	}

805 806 807
	if (nested_len >= nla_attr_size(0))
		return nla_parse(tb, maxtype, nla_data(nla) + NLA_ALIGN(len),
				 nested_len, policy);
808

809 810 811 812
	memset(tb, 0, sizeof(struct nlattr *) * (maxtype + 1));
	return 0;
}

813
/* Parse netlink message to set options */
814
static int netem_change(struct Qdisc *sch, struct nlattr *opt)
L
Linus Torvalds 已提交
815 816
{
	struct netem_sched_data *q = qdisc_priv(sch);
817
	struct nlattr *tb[TCA_NETEM_MAX + 1];
L
Linus Torvalds 已提交
818
	struct tc_netem_qopt *qopt;
819 820
	struct clgstate old_clg;
	int old_loss_model = CLG_RANDOM;
L
Linus Torvalds 已提交
821
	int ret;
822

823
	if (opt == NULL)
L
Linus Torvalds 已提交
824 825
		return -EINVAL;

826 827
	qopt = nla_data(opt);
	ret = parse_attr(tb, TCA_NETEM_MAX, opt, netem_policy, sizeof(*qopt));
828 829 830
	if (ret < 0)
		return ret;

831 832 833 834 835
	/* backup q->clg and q->loss_model */
	old_clg = q->clg;
	old_loss_model = q->loss_model;

	if (tb[TCA_NETEM_LOSS]) {
836
		ret = get_loss_clg(q, tb[TCA_NETEM_LOSS]);
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
		if (ret) {
			q->loss_model = old_loss_model;
			return ret;
		}
	} else {
		q->loss_model = CLG_RANDOM;
	}

	if (tb[TCA_NETEM_DELAY_DIST]) {
		ret = get_dist_table(sch, tb[TCA_NETEM_DELAY_DIST]);
		if (ret) {
			/* recover clg and loss_model, in case of
			 * q->clg and q->loss_model were modified
			 * in get_loss_clg()
			 */
			q->clg = old_clg;
			q->loss_model = old_loss_model;
			return ret;
		}
	}

E
Eric Dumazet 已提交
858
	sch->limit = qopt->limit;
859

L
Linus Torvalds 已提交
860 861 862 863
	q->latency = qopt->latency;
	q->jitter = qopt->jitter;
	q->limit = qopt->limit;
	q->gap = qopt->gap;
864
	q->counter = 0;
L
Linus Torvalds 已提交
865 866 867
	q->loss = qopt->loss;
	q->duplicate = qopt->duplicate;

S
Stephen Hemminger 已提交
868 869
	/* for compatibility with earlier versions.
	 * if gap is set, need to assume 100% probability
870
	 */
871 872
	if (q->gap)
		q->reorder = ~0;
873

874
	if (tb[TCA_NETEM_CORR])
875
		get_correlation(q, tb[TCA_NETEM_CORR]);
L
Linus Torvalds 已提交
876

877
	if (tb[TCA_NETEM_REORDER])
878
		get_reorder(q, tb[TCA_NETEM_REORDER]);
L
Linus Torvalds 已提交
879

880
	if (tb[TCA_NETEM_CORRUPT])
881
		get_corrupt(q, tb[TCA_NETEM_CORRUPT]);
L
Linus Torvalds 已提交
882

H
Hagen Paul Pfeifer 已提交
883
	if (tb[TCA_NETEM_RATE])
884
		get_rate(q, tb[TCA_NETEM_RATE]);
H
Hagen Paul Pfeifer 已提交
885

Y
Yang Yingliang 已提交
886 887 888 889
	if (tb[TCA_NETEM_RATE64])
		q->rate = max_t(u64, q->rate,
				nla_get_u64(tb[TCA_NETEM_RATE64]));

E
Eric Dumazet 已提交
890 891 892
	if (tb[TCA_NETEM_ECN])
		q->ecn = nla_get_u32(tb[TCA_NETEM_ECN]);

893
	return ret;
L
Linus Torvalds 已提交
894 895
}

896
static int netem_init(struct Qdisc *sch, struct nlattr *opt)
L
Linus Torvalds 已提交
897 898 899 900 901 902 903
{
	struct netem_sched_data *q = qdisc_priv(sch);
	int ret;

	if (!opt)
		return -EINVAL;

904
	qdisc_watchdog_init(&q->watchdog, sch);
L
Linus Torvalds 已提交
905

906
	q->loss_model = CLG_RANDOM;
L
Linus Torvalds 已提交
907
	ret = netem_change(sch, opt);
E
Eric Dumazet 已提交
908
	if (ret)
909
		pr_info("netem: change failed\n");
L
Linus Torvalds 已提交
910 911 912 913 914 915 916
	return ret;
}

static void netem_destroy(struct Qdisc *sch)
{
	struct netem_sched_data *q = qdisc_priv(sch);

917
	qdisc_watchdog_cancel(&q->watchdog);
E
Eric Dumazet 已提交
918 919
	if (q->qdisc)
		qdisc_destroy(q->qdisc);
920
	dist_free(q->delay_dist);
L
Linus Torvalds 已提交
921 922
}

923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
static int dump_loss_model(const struct netem_sched_data *q,
			   struct sk_buff *skb)
{
	struct nlattr *nest;

	nest = nla_nest_start(skb, TCA_NETEM_LOSS);
	if (nest == NULL)
		goto nla_put_failure;

	switch (q->loss_model) {
	case CLG_RANDOM:
		/* legacy loss model */
		nla_nest_cancel(skb, nest);
		return 0;	/* no data */

	case CLG_4_STATES: {
		struct tc_netem_gimodel gi = {
			.p13 = q->clg.a1,
			.p31 = q->clg.a2,
			.p32 = q->clg.a3,
			.p14 = q->clg.a4,
			.p23 = q->clg.a5,
		};

947 948
		if (nla_put(skb, NETEM_LOSS_GI, sizeof(gi), &gi))
			goto nla_put_failure;
949 950 951 952 953 954 955 956 957 958
		break;
	}
	case CLG_GILB_ELL: {
		struct tc_netem_gemodel ge = {
			.p = q->clg.a1,
			.r = q->clg.a2,
			.h = q->clg.a3,
			.k1 = q->clg.a4,
		};

959 960
		if (nla_put(skb, NETEM_LOSS_GE, sizeof(ge), &ge))
			goto nla_put_failure;
961 962 963 964 965 966 967 968 969 970 971 972
		break;
	}
	}

	nla_nest_end(skb, nest);
	return 0;

nla_put_failure:
	nla_nest_cancel(skb, nest);
	return -1;
}

L
Linus Torvalds 已提交
973 974 975
static int netem_dump(struct Qdisc *sch, struct sk_buff *skb)
{
	const struct netem_sched_data *q = qdisc_priv(sch);
S
stephen hemminger 已提交
976
	struct nlattr *nla = (struct nlattr *) skb_tail_pointer(skb);
L
Linus Torvalds 已提交
977 978
	struct tc_netem_qopt qopt;
	struct tc_netem_corr cor;
979
	struct tc_netem_reorder reorder;
980
	struct tc_netem_corrupt corrupt;
H
Hagen Paul Pfeifer 已提交
981
	struct tc_netem_rate rate;
L
Linus Torvalds 已提交
982 983 984 985 986 987 988

	qopt.latency = q->latency;
	qopt.jitter = q->jitter;
	qopt.limit = q->limit;
	qopt.loss = q->loss;
	qopt.gap = q->gap;
	qopt.duplicate = q->duplicate;
989 990
	if (nla_put(skb, TCA_OPTIONS, sizeof(qopt), &qopt))
		goto nla_put_failure;
L
Linus Torvalds 已提交
991 992 993 994

	cor.delay_corr = q->delay_cor.rho;
	cor.loss_corr = q->loss_cor.rho;
	cor.dup_corr = q->dup_cor.rho;
995 996
	if (nla_put(skb, TCA_NETEM_CORR, sizeof(cor), &cor))
		goto nla_put_failure;
997 998 999

	reorder.probability = q->reorder;
	reorder.correlation = q->reorder_cor.rho;
1000 1001
	if (nla_put(skb, TCA_NETEM_REORDER, sizeof(reorder), &reorder))
		goto nla_put_failure;
1002

1003 1004
	corrupt.probability = q->corrupt;
	corrupt.correlation = q->corrupt_cor.rho;
1005 1006
	if (nla_put(skb, TCA_NETEM_CORRUPT, sizeof(corrupt), &corrupt))
		goto nla_put_failure;
1007

Y
Yang Yingliang 已提交
1008 1009 1010 1011 1012 1013 1014
	if (q->rate >= (1ULL << 32)) {
		if (nla_put_u64(skb, TCA_NETEM_RATE64, q->rate))
			goto nla_put_failure;
		rate.rate = ~0U;
	} else {
		rate.rate = q->rate;
	}
1015 1016 1017
	rate.packet_overhead = q->packet_overhead;
	rate.cell_size = q->cell_size;
	rate.cell_overhead = q->cell_overhead;
1018 1019
	if (nla_put(skb, TCA_NETEM_RATE, sizeof(rate), &rate))
		goto nla_put_failure;
H
Hagen Paul Pfeifer 已提交
1020

E
Eric Dumazet 已提交
1021 1022 1023
	if (q->ecn && nla_put_u32(skb, TCA_NETEM_ECN, q->ecn))
		goto nla_put_failure;

1024 1025 1026
	if (dump_loss_model(q, skb) != 0)
		goto nla_put_failure;

S
stephen hemminger 已提交
1027
	return nla_nest_end(skb, nla);
L
Linus Torvalds 已提交
1028

1029
nla_put_failure:
S
stephen hemminger 已提交
1030
	nlmsg_trim(skb, nla);
L
Linus Torvalds 已提交
1031 1032 1033
	return -1;
}

1034 1035 1036 1037 1038
static int netem_dump_class(struct Qdisc *sch, unsigned long cl,
			  struct sk_buff *skb, struct tcmsg *tcm)
{
	struct netem_sched_data *q = qdisc_priv(sch);

E
Eric Dumazet 已提交
1039
	if (cl != 1 || !q->qdisc) 	/* only one class */
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
		return -ENOENT;

	tcm->tcm_handle |= TC_H_MIN(1);
	tcm->tcm_info = q->qdisc->handle;

	return 0;
}

static int netem_graft(struct Qdisc *sch, unsigned long arg, struct Qdisc *new,
		     struct Qdisc **old)
{
	struct netem_sched_data *q = qdisc_priv(sch);

	sch_tree_lock(sch);
	*old = q->qdisc;
	q->qdisc = new;
E
Eric Dumazet 已提交
1056 1057 1058 1059
	if (*old) {
		qdisc_tree_decrease_qlen(*old, (*old)->q.qlen);
		qdisc_reset(*old);
	}
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
	sch_tree_unlock(sch);

	return 0;
}

static struct Qdisc *netem_leaf(struct Qdisc *sch, unsigned long arg)
{
	struct netem_sched_data *q = qdisc_priv(sch);
	return q->qdisc;
}

static unsigned long netem_get(struct Qdisc *sch, u32 classid)
{
	return 1;
}

static void netem_put(struct Qdisc *sch, unsigned long arg)
{
}

static void netem_walk(struct Qdisc *sch, struct qdisc_walker *walker)
{
	if (!walker->stop) {
		if (walker->count >= walker->skip)
			if (walker->fn(sch, 1, walker) < 0) {
				walker->stop = 1;
				return;
			}
		walker->count++;
	}
}

static const struct Qdisc_class_ops netem_class_ops = {
	.graft		=	netem_graft,
	.leaf		=	netem_leaf,
	.get		=	netem_get,
	.put		=	netem_put,
	.walk		=	netem_walk,
	.dump		=	netem_dump_class,
};

1101
static struct Qdisc_ops netem_qdisc_ops __read_mostly = {
L
Linus Torvalds 已提交
1102
	.id		=	"netem",
1103
	.cl_ops		=	&netem_class_ops,
L
Linus Torvalds 已提交
1104 1105 1106
	.priv_size	=	sizeof(struct netem_sched_data),
	.enqueue	=	netem_enqueue,
	.dequeue	=	netem_dequeue,
1107
	.peek		=	qdisc_peek_dequeued,
L
Linus Torvalds 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
	.drop		=	netem_drop,
	.init		=	netem_init,
	.reset		=	netem_reset,
	.destroy	=	netem_destroy,
	.change		=	netem_change,
	.dump		=	netem_dump,
	.owner		=	THIS_MODULE,
};


static int __init netem_module_init(void)
{
S
Stephen Hemminger 已提交
1120
	pr_info("netem: version " VERSION "\n");
L
Linus Torvalds 已提交
1121 1122 1123 1124 1125 1126 1127 1128 1129
	return register_qdisc(&netem_qdisc_ops);
}
static void __exit netem_module_exit(void)
{
	unregister_qdisc(&netem_qdisc_ops);
}
module_init(netem_module_init)
module_exit(netem_module_exit)
MODULE_LICENSE("GPL");