xref: /freebsd/sys/netpfil/ipfw/ip_dn_io.c (revision 999c1fd64b489eda8c04f1e1529f828ebe5c7794)
1 /*-
2  * Copyright (c) 2010 Luigi Rizzo, Riccardo Panicucci, Universita` di Pisa
3  * All rights reserved
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * Dummynet portions related to packet handling.
29  */
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_inet6.h"
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/mbuf.h>
39 #include <sys/kernel.h>
40 #include <sys/lock.h>
41 #include <sys/module.h>
42 #include <sys/mutex.h>
43 #include <sys/priv.h>
44 #include <sys/proc.h>
45 #include <sys/rwlock.h>
46 #include <sys/socket.h>
47 #include <sys/time.h>
48 #include <sys/sysctl.h>
49 
50 #include <net/if.h>	/* IFNAMSIZ, struct ifaddr, ifq head, lock.h mutex.h */
51 #include <net/netisr.h>
52 #include <net/vnet.h>
53 
54 #include <netinet/in.h>
55 #include <netinet/ip.h>		/* ip_len, ip_off */
56 #include <netinet/ip_var.h>	/* ip_output(), IP_FORWARDING */
57 #include <netinet/ip_fw.h>
58 #include <netinet/ip_dummynet.h>
59 #include <netinet/if_ether.h> /* various ether_* routines */
60 #include <netinet/ip6.h>       /* for ip6_input, ip6_output prototypes */
61 #include <netinet6/ip6_var.h>
62 
63 #include <netpfil/ipfw/ip_fw_private.h>
64 #include <netpfil/ipfw/dn_heap.h>
65 #include <netpfil/ipfw/ip_dn_private.h>
66 #ifdef NEW_AQM
67 #include <netpfil/ipfw/dn_aqm.h>
68 #endif
69 #include <netpfil/ipfw/dn_sched.h>
70 
71 /*
72  * We keep a private variable for the simulation time, but we could
73  * probably use an existing one ("softticks" in sys/kern/kern_timeout.c)
74  * instead of dn_cfg.curr_time
75  */
76 
77 struct dn_parms dn_cfg;
78 //VNET_DEFINE(struct dn_parms, _base_dn_cfg);
79 
80 static long tick_last;		/* Last tick duration (usec). */
81 static long tick_delta;		/* Last vs standard tick diff (usec). */
82 static long tick_delta_sum;	/* Accumulated tick difference (usec).*/
83 static long tick_adjustment;	/* Tick adjustments done. */
84 static long tick_lost;		/* Lost(coalesced) ticks number. */
85 /* Adjusted vs non-adjusted curr_time difference (ticks). */
86 static long tick_diff;
87 
88 static unsigned long	io_pkt;
89 static unsigned long	io_pkt_fast;
90 
91 #ifdef NEW_AQM
92 unsigned long	io_pkt_drop;
93 #else
94 static unsigned long	io_pkt_drop;
95 #endif
96 /*
97  * We use a heap to store entities for which we have pending timer events.
98  * The heap is checked at every tick and all entities with expired events
99  * are extracted.
100  */
101 
102 MALLOC_DEFINE(M_DUMMYNET, "dummynet", "dummynet heap");
103 
104 extern	void (*bridge_dn_p)(struct mbuf *, struct ifnet *);
105 
106 #ifdef SYSCTL_NODE
107 
108 /*
109  * Because of the way the SYSBEGIN/SYSEND macros work on other
110  * platforms, there should not be functions between them.
111  * So keep the handlers outside the block.
112  */
113 static int
114 sysctl_hash_size(SYSCTL_HANDLER_ARGS)
115 {
116 	int error, value;
117 
118 	value = dn_cfg.hash_size;
119 	error = sysctl_handle_int(oidp, &value, 0, req);
120 	if (error != 0 || req->newptr == NULL)
121 		return (error);
122 	if (value < 16 || value > 65536)
123 		return (EINVAL);
124 	dn_cfg.hash_size = value;
125 	return (0);
126 }
127 
128 static int
129 sysctl_limits(SYSCTL_HANDLER_ARGS)
130 {
131 	int error;
132 	long value;
133 
134 	if (arg2 != 0)
135 		value = dn_cfg.slot_limit;
136 	else
137 		value = dn_cfg.byte_limit;
138 	error = sysctl_handle_long(oidp, &value, 0, req);
139 
140 	if (error != 0 || req->newptr == NULL)
141 		return (error);
142 	if (arg2 != 0) {
143 		if (value < 1)
144 			return (EINVAL);
145 		dn_cfg.slot_limit = value;
146 	} else {
147 		if (value < 1500)
148 			return (EINVAL);
149 		dn_cfg.byte_limit = value;
150 	}
151 	return (0);
152 }
153 
154 SYSBEGIN(f4)
155 
156 SYSCTL_DECL(_net_inet);
157 SYSCTL_DECL(_net_inet_ip);
158 #ifdef NEW_AQM
159 SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet, CTLFLAG_RW, 0, "Dummynet");
160 #else
161 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet, CTLFLAG_RW, 0, "Dummynet");
162 #endif
163 
164 /* wrapper to pass dn_cfg fields to SYSCTL_* */
165 //#define DC(x)	(&(VNET_NAME(_base_dn_cfg).x))
166 #define DC(x)	(&(dn_cfg.x))
167 /* parameters */
168 
169 
170 SYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, hash_size,
171     CTLTYPE_INT | CTLFLAG_RW, 0, 0, sysctl_hash_size,
172     "I", "Default hash table size");
173 
174 
175 SYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, pipe_slot_limit,
176     CTLTYPE_LONG | CTLFLAG_RW, 0, 1, sysctl_limits,
177     "L", "Upper limit in slots for pipe queue.");
178 SYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, pipe_byte_limit,
179     CTLTYPE_LONG | CTLFLAG_RW, 0, 0, sysctl_limits,
180     "L", "Upper limit in bytes for pipe queue.");
181 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, io_fast,
182     CTLFLAG_RW, DC(io_fast), 0, "Enable fast dummynet io.");
183 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug,
184     CTLFLAG_RW, DC(debug), 0, "Dummynet debug level");
185 
186 /* RED parameters */
187 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
188     CTLFLAG_RD, DC(red_lookup_depth), 0, "Depth of RED lookup table");
189 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
190     CTLFLAG_RD, DC(red_avg_pkt_size), 0, "RED Medium packet size");
191 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
192     CTLFLAG_RD, DC(red_max_pkt_size), 0, "RED Max packet size");
193 
194 /* time adjustment */
195 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_delta,
196     CTLFLAG_RD, &tick_delta, 0, "Last vs standard tick difference (usec).");
197 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_delta_sum,
198     CTLFLAG_RD, &tick_delta_sum, 0, "Accumulated tick difference (usec).");
199 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_adjustment,
200     CTLFLAG_RD, &tick_adjustment, 0, "Tick adjustments done.");
201 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_diff,
202     CTLFLAG_RD, &tick_diff, 0,
203     "Adjusted vs non-adjusted curr_time difference (ticks).");
204 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_lost,
205     CTLFLAG_RD, &tick_lost, 0,
206     "Number of ticks coalesced by dummynet taskqueue.");
207 
208 /* Drain parameters */
209 SYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire,
210     CTLFLAG_RW, DC(expire), 0, "Expire empty queues/pipes");
211 SYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire_cycle,
212     CTLFLAG_RD, DC(expire_cycle), 0, "Expire cycle for queues/pipes");
213 
214 /* statistics */
215 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, schk_count,
216     CTLFLAG_RD, DC(schk_count), 0, "Number of schedulers");
217 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, si_count,
218     CTLFLAG_RD, DC(si_count), 0, "Number of scheduler instances");
219 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, fsk_count,
220     CTLFLAG_RD, DC(fsk_count), 0, "Number of flowsets");
221 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, queue_count,
222     CTLFLAG_RD, DC(queue_count), 0, "Number of queues");
223 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt,
224     CTLFLAG_RD, &io_pkt, 0,
225     "Number of packets passed to dummynet.");
226 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt_fast,
227     CTLFLAG_RD, &io_pkt_fast, 0,
228     "Number of packets bypassed dummynet scheduler.");
229 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt_drop,
230     CTLFLAG_RD, &io_pkt_drop, 0,
231     "Number of packets dropped by dummynet.");
232 #undef DC
233 SYSEND
234 
235 #endif
236 
237 static void	dummynet_send(struct mbuf *);
238 
239 /*
240  * Packets processed by dummynet have an mbuf tag associated with
241  * them that carries their dummynet state.
242  * Outside dummynet, only the 'rule' field is relevant, and it must
243  * be at the beginning of the structure.
244  */
245 struct dn_pkt_tag {
246 	struct ipfw_rule_ref rule;	/* matching rule	*/
247 
248 	/* second part, dummynet specific */
249 	int dn_dir;		/* action when packet comes out.*/
250 				/* see ip_fw_private.h		*/
251 	uint64_t output_time;	/* when the pkt is due for delivery*/
252 	struct ifnet *ifp;	/* interface, for ip_output	*/
253 	struct _ip6dn_args ip6opt;	/* XXX ipv6 options	*/
254 };
255 
256 /*
257  * Return the mbuf tag holding the dummynet state (it should
258  * be the first one on the list).
259  */
260 static struct dn_pkt_tag *
261 dn_tag_get(struct mbuf *m)
262 {
263 	struct m_tag *mtag = m_tag_first(m);
264 #ifdef NEW_AQM
265 	/* XXX: to skip ts m_tag. For Debugging only*/
266 	if (mtag != NULL && mtag->m_tag_id == DN_AQM_MTAG_TS) {
267 		m_tag_delete(m,mtag);
268 		mtag = m_tag_first(m);
269 		D("skip TS tag");
270 	}
271 #endif
272 	KASSERT(mtag != NULL &&
273 	    mtag->m_tag_cookie == MTAG_ABI_COMPAT &&
274 	    mtag->m_tag_id == PACKET_TAG_DUMMYNET,
275 	    ("packet on dummynet queue w/o dummynet tag!"));
276 	return (struct dn_pkt_tag *)(mtag+1);
277 }
278 
279 #ifndef NEW_AQM
280 static inline void
281 mq_append(struct mq *q, struct mbuf *m)
282 {
283 #ifdef USERSPACE
284 	// buffers from netmap need to be copied
285 	// XXX note that the routine is not expected to fail
286 	ND("append %p to %p", m, q);
287 	if (m->m_flags & M_STACK) {
288 		struct mbuf *m_new;
289 		void *p;
290 		int l, ofs;
291 
292 		ofs = m->m_data - m->__m_extbuf;
293 		// XXX allocate
294 		MGETHDR(m_new, M_NOWAIT, MT_DATA);
295 		ND("*** WARNING, volatile buf %p ext %p %d dofs %d m_new %p",
296 			m, m->__m_extbuf, m->__m_extlen, ofs, m_new);
297 		p = m_new->__m_extbuf;	/* new pointer */
298 		l = m_new->__m_extlen;	/* new len */
299 		if (l <= m->__m_extlen) {
300 			panic("extlen too large");
301 		}
302 
303 		*m_new = *m;	// copy
304 		m_new->m_flags &= ~M_STACK;
305 		m_new->__m_extbuf = p; // point to new buffer
306 		_pkt_copy(m->__m_extbuf, p, m->__m_extlen);
307 		m_new->m_data = p + ofs;
308 		m = m_new;
309 	}
310 #endif /* USERSPACE */
311 	if (q->head == NULL)
312 		q->head = m;
313 	else
314 		q->tail->m_nextpkt = m;
315 	q->count++;
316 	q->tail = m;
317 	m->m_nextpkt = NULL;
318 }
319 #endif
320 
321 /*
322  * Dispose a list of packet. Use a functions so if we need to do
323  * more work, this is a central point to do it.
324  */
325 void dn_free_pkts(struct mbuf *mnext)
326 {
327         struct mbuf *m;
328 
329         while ((m = mnext) != NULL) {
330                 mnext = m->m_nextpkt;
331                 FREE_PKT(m);
332         }
333 }
334 
335 static int
336 red_drops (struct dn_queue *q, int len)
337 {
338 	/*
339 	 * RED algorithm
340 	 *
341 	 * RED calculates the average queue size (avg) using a low-pass filter
342 	 * with an exponential weighted (w_q) moving average:
343 	 * 	avg  <-  (1-w_q) * avg + w_q * q_size
344 	 * where q_size is the queue length (measured in bytes or * packets).
345 	 *
346 	 * If q_size == 0, we compute the idle time for the link, and set
347 	 *	avg = (1 - w_q)^(idle/s)
348 	 * where s is the time needed for transmitting a medium-sized packet.
349 	 *
350 	 * Now, if avg < min_th the packet is enqueued.
351 	 * If avg > max_th the packet is dropped. Otherwise, the packet is
352 	 * dropped with probability P function of avg.
353 	 */
354 
355 	struct dn_fsk *fs = q->fs;
356 	int64_t p_b = 0;
357 
358 	/* Queue in bytes or packets? */
359 	uint32_t q_size = (fs->fs.flags & DN_QSIZE_BYTES) ?
360 	    q->ni.len_bytes : q->ni.length;
361 
362 	/* Average queue size estimation. */
363 	if (q_size != 0) {
364 		/* Queue is not empty, avg <- avg + (q_size - avg) * w_q */
365 		int diff = SCALE(q_size) - q->avg;
366 		int64_t v = SCALE_MUL((int64_t)diff, (int64_t)fs->w_q);
367 
368 		q->avg += (int)v;
369 	} else {
370 		/*
371 		 * Queue is empty, find for how long the queue has been
372 		 * empty and use a lookup table for computing
373 		 * (1 - * w_q)^(idle_time/s) where s is the time to send a
374 		 * (small) packet.
375 		 * XXX check wraps...
376 		 */
377 		if (q->avg) {
378 			u_int t = div64((dn_cfg.curr_time - q->q_time), fs->lookup_step);
379 
380 			q->avg = (t < fs->lookup_depth) ?
381 			    SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
382 		}
383 	}
384 
385 	/* Should i drop? */
386 	if (q->avg < fs->min_th) {
387 		q->count = -1;
388 		return (0);	/* accept packet */
389 	}
390 	if (q->avg >= fs->max_th) {	/* average queue >=  max threshold */
391 		if (fs->fs.flags & DN_IS_ECN)
392 			return (1);
393 		if (fs->fs.flags & DN_IS_GENTLE_RED) {
394 			/*
395 			 * According to Gentle-RED, if avg is greater than
396 			 * max_th the packet is dropped with a probability
397 			 *	 p_b = c_3 * avg - c_4
398 			 * where c_3 = (1 - max_p) / max_th
399 			 *       c_4 = 1 - 2 * max_p
400 			 */
401 			p_b = SCALE_MUL((int64_t)fs->c_3, (int64_t)q->avg) -
402 			    fs->c_4;
403 		} else {
404 			q->count = -1;
405 			return (1);
406 		}
407 	} else if (q->avg > fs->min_th) {
408 		if (fs->fs.flags & DN_IS_ECN)
409 			return (1);
410 		/*
411 		 * We compute p_b using the linear dropping function
412 		 *	 p_b = c_1 * avg - c_2
413 		 * where c_1 = max_p / (max_th - min_th)
414 		 * 	 c_2 = max_p * min_th / (max_th - min_th)
415 		 */
416 		p_b = SCALE_MUL((int64_t)fs->c_1, (int64_t)q->avg) - fs->c_2;
417 	}
418 
419 	if (fs->fs.flags & DN_QSIZE_BYTES)
420 		p_b = div64((p_b * len) , fs->max_pkt_size);
421 	if (++q->count == 0)
422 		q->random = random() & 0xffff;
423 	else {
424 		/*
425 		 * q->count counts packets arrived since last drop, so a greater
426 		 * value of q->count means a greater packet drop probability.
427 		 */
428 		if (SCALE_MUL(p_b, SCALE((int64_t)q->count)) > q->random) {
429 			q->count = 0;
430 			/* After a drop we calculate a new random value. */
431 			q->random = random() & 0xffff;
432 			return (1);	/* drop */
433 		}
434 	}
435 	/* End of RED algorithm. */
436 
437 	return (0);	/* accept */
438 
439 }
440 
441 /*
442  * ECN/ECT Processing (partially adopted from altq)
443  */
444 #ifndef NEW_AQM
445 static
446 #endif
447 int
448 ecn_mark(struct mbuf* m)
449 {
450 	struct ip *ip;
451 	ip = mtod(m, struct ip *);
452 
453 	switch (ip->ip_v) {
454 	case IPVERSION:
455 	{
456 		uint16_t old;
457 
458 		if ((ip->ip_tos & IPTOS_ECN_MASK) == IPTOS_ECN_NOTECT)
459 			return (0);	/* not-ECT */
460 		if ((ip->ip_tos & IPTOS_ECN_MASK) == IPTOS_ECN_CE)
461 			return (1);	/* already marked */
462 
463 		/*
464 		 * ecn-capable but not marked,
465 		 * mark CE and update checksum
466 		 */
467 		old = *(uint16_t *)ip;
468 		ip->ip_tos |= IPTOS_ECN_CE;
469 		ip->ip_sum = cksum_adjust(ip->ip_sum, old, *(uint16_t *)ip);
470 		return (1);
471 	}
472 #ifdef INET6
473 	case (IPV6_VERSION >> 4):
474 	{
475 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
476 		u_int32_t flowlabel;
477 
478 		flowlabel = ntohl(ip6->ip6_flow);
479 		if ((flowlabel >> 28) != 6)
480 			return (0);	/* version mismatch! */
481 		if ((flowlabel & (IPTOS_ECN_MASK << 20)) ==
482 		    (IPTOS_ECN_NOTECT << 20))
483 			return (0);	/* not-ECT */
484 		if ((flowlabel & (IPTOS_ECN_MASK << 20)) ==
485 		    (IPTOS_ECN_CE << 20))
486 			return (1);	/* already marked */
487 		/*
488 		 * ecn-capable but not marked, mark CE
489 		 */
490 		flowlabel |= (IPTOS_ECN_CE << 20);
491 		ip6->ip6_flow = htonl(flowlabel);
492 		return (1);
493 	}
494 #endif
495 	}
496 	return (0);
497 }
498 
499 /*
500  * Enqueue a packet in q, subject to space and queue management policy
501  * (whose parameters are in q->fs).
502  * Update stats for the queue and the scheduler.
503  * Return 0 on success, 1 on drop. The packet is consumed anyways.
504  */
505 int
506 dn_enqueue(struct dn_queue *q, struct mbuf* m, int drop)
507 {
508 	struct dn_fs *f;
509 	struct dn_flow *ni;	/* stats for scheduler instance */
510 	uint64_t len;
511 
512 	if (q->fs == NULL || q->_si == NULL) {
513 		printf("%s fs %p si %p, dropping\n",
514 			__FUNCTION__, q->fs, q->_si);
515 		FREE_PKT(m);
516 		return 1;
517 	}
518 	f = &(q->fs->fs);
519 	ni = &q->_si->ni;
520 	len = m->m_pkthdr.len;
521 	/* Update statistics, then check reasons to drop pkt. */
522 	q->ni.tot_bytes += len;
523 	q->ni.tot_pkts++;
524 	ni->tot_bytes += len;
525 	ni->tot_pkts++;
526 	if (drop)
527 		goto drop;
528 	if (f->plr && random() < f->plr)
529 		goto drop;
530 #ifdef NEW_AQM
531 	/* Call AQM enqueue function */
532 	if (q->fs->aqmfp)
533 		return q->fs->aqmfp->enqueue(q ,m);
534 #endif
535 	if (f->flags & DN_IS_RED && red_drops(q, m->m_pkthdr.len)) {
536 		if (!(f->flags & DN_IS_ECN) || !ecn_mark(m))
537 			goto drop;
538 	}
539 	if (f->flags & DN_QSIZE_BYTES) {
540 		if (q->ni.len_bytes > f->qsize)
541 			goto drop;
542 	} else if (q->ni.length >= f->qsize) {
543 		goto drop;
544 	}
545 	mq_append(&q->mq, m);
546 	q->ni.length++;
547 	q->ni.len_bytes += len;
548 	ni->length++;
549 	ni->len_bytes += len;
550 	return (0);
551 
552 drop:
553 	io_pkt_drop++;
554 	q->ni.drops++;
555 	ni->drops++;
556 	FREE_PKT(m);
557 	return (1);
558 }
559 
560 /*
561  * Fetch packets from the delay line which are due now. If there are
562  * leftover packets, reinsert the delay line in the heap.
563  * Runs under scheduler lock.
564  */
565 static void
566 transmit_event(struct mq *q, struct delay_line *dline, uint64_t now)
567 {
568 	struct mbuf *m;
569 	struct dn_pkt_tag *pkt = NULL;
570 
571 	dline->oid.subtype = 0; /* not in heap */
572 	while ((m = dline->mq.head) != NULL) {
573 		pkt = dn_tag_get(m);
574 		if (!DN_KEY_LEQ(pkt->output_time, now))
575 			break;
576 		dline->mq.head = m->m_nextpkt;
577 		dline->mq.count--;
578 		mq_append(q, m);
579 	}
580 	if (m != NULL) {
581 		dline->oid.subtype = 1; /* in heap */
582 		heap_insert(&dn_cfg.evheap, pkt->output_time, dline);
583 	}
584 }
585 
586 /*
587  * Convert the additional MAC overheads/delays into an equivalent
588  * number of bits for the given data rate. The samples are
589  * in milliseconds so we need to divide by 1000.
590  */
591 static uint64_t
592 extra_bits(struct mbuf *m, struct dn_schk *s)
593 {
594 	int index;
595 	uint64_t bits;
596 	struct dn_profile *pf = s->profile;
597 
598 	if (!pf || pf->samples_no == 0)
599 		return 0;
600 	index  = random() % pf->samples_no;
601 	bits = div64((uint64_t)pf->samples[index] * s->link.bandwidth, 1000);
602 	if (index >= pf->loss_level) {
603 		struct dn_pkt_tag *dt = dn_tag_get(m);
604 		if (dt)
605 			dt->dn_dir = DIR_DROP;
606 	}
607 	return bits;
608 }
609 
610 /*
611  * Send traffic from a scheduler instance due by 'now'.
612  * Return a pointer to the head of the queue.
613  */
614 static struct mbuf *
615 serve_sched(struct mq *q, struct dn_sch_inst *si, uint64_t now)
616 {
617 	struct mq def_q;
618 	struct dn_schk *s = si->sched;
619 	struct mbuf *m = NULL;
620 	int delay_line_idle = (si->dline.mq.head == NULL);
621 	int done, bw;
622 
623 	if (q == NULL) {
624 		q = &def_q;
625 		q->head = NULL;
626 	}
627 
628 	bw = s->link.bandwidth;
629 	si->kflags &= ~DN_ACTIVE;
630 
631 	if (bw > 0)
632 		si->credit += (now - si->sched_time) * bw;
633 	else
634 		si->credit = 0;
635 	si->sched_time = now;
636 	done = 0;
637 	while (si->credit >= 0 && (m = s->fp->dequeue(si)) != NULL) {
638 		uint64_t len_scaled;
639 
640 		done++;
641 		len_scaled = (bw == 0) ? 0 : hz *
642 			(m->m_pkthdr.len * 8 + extra_bits(m, s));
643 		si->credit -= len_scaled;
644 		/* Move packet in the delay line */
645 		dn_tag_get(m)->output_time = dn_cfg.curr_time + s->link.delay ;
646 		mq_append(&si->dline.mq, m);
647 	}
648 
649 	/*
650 	 * If credit >= 0 the instance is idle, mark time.
651 	 * Otherwise put back in the heap, and adjust the output
652 	 * time of the last inserted packet, m, which was too early.
653 	 */
654 	if (si->credit >= 0) {
655 		si->idle_time = now;
656 	} else {
657 		uint64_t t;
658 		KASSERT (bw > 0, ("bw=0 and credit<0 ?"));
659 		t = div64(bw - 1 - si->credit, bw);
660 		if (m)
661 			dn_tag_get(m)->output_time += t;
662 		si->kflags |= DN_ACTIVE;
663 		heap_insert(&dn_cfg.evheap, now + t, si);
664 	}
665 	if (delay_line_idle && done)
666 		transmit_event(q, &si->dline, now);
667 	return q->head;
668 }
669 
670 /*
671  * The timer handler for dummynet. Time is computed in ticks, but
672  * but the code is tolerant to the actual rate at which this is called.
673  * Once complete, the function reschedules itself for the next tick.
674  */
675 void
676 dummynet_task(void *context, int pending)
677 {
678 	struct timeval t;
679 	struct mq q = { NULL, NULL }; /* queue to accumulate results */
680 
681 	CURVNET_SET((struct vnet *)context);
682 
683 	DN_BH_WLOCK();
684 
685 	/* Update number of lost(coalesced) ticks. */
686 	tick_lost += pending - 1;
687 
688 	getmicrouptime(&t);
689 	/* Last tick duration (usec). */
690 	tick_last = (t.tv_sec - dn_cfg.prev_t.tv_sec) * 1000000 +
691 	(t.tv_usec - dn_cfg.prev_t.tv_usec);
692 	/* Last tick vs standard tick difference (usec). */
693 	tick_delta = (tick_last * hz - 1000000) / hz;
694 	/* Accumulated tick difference (usec). */
695 	tick_delta_sum += tick_delta;
696 
697 	dn_cfg.prev_t = t;
698 
699 	/*
700 	* Adjust curr_time if the accumulated tick difference is
701 	* greater than the 'standard' tick. Since curr_time should
702 	* be monotonically increasing, we do positive adjustments
703 	* as required, and throttle curr_time in case of negative
704 	* adjustment.
705 	*/
706 	dn_cfg.curr_time++;
707 	if (tick_delta_sum - tick >= 0) {
708 		int diff = tick_delta_sum / tick;
709 
710 		dn_cfg.curr_time += diff;
711 		tick_diff += diff;
712 		tick_delta_sum %= tick;
713 		tick_adjustment++;
714 	} else if (tick_delta_sum + tick <= 0) {
715 		dn_cfg.curr_time--;
716 		tick_diff--;
717 		tick_delta_sum += tick;
718 		tick_adjustment++;
719 	}
720 
721 	/* serve pending events, accumulate in q */
722 	for (;;) {
723 		struct dn_id *p;    /* generic parameter to handler */
724 
725 		if (dn_cfg.evheap.elements == 0 ||
726 		    DN_KEY_LT(dn_cfg.curr_time, HEAP_TOP(&dn_cfg.evheap)->key))
727 			break;
728 		p = HEAP_TOP(&dn_cfg.evheap)->object;
729 		heap_extract(&dn_cfg.evheap, NULL);
730 
731 		if (p->type == DN_SCH_I) {
732 			serve_sched(&q, (struct dn_sch_inst *)p, dn_cfg.curr_time);
733 		} else { /* extracted a delay line */
734 			transmit_event(&q, (struct delay_line *)p, dn_cfg.curr_time);
735 		}
736 	}
737 	if (dn_cfg.expire && ++dn_cfg.expire_cycle >= dn_cfg.expire) {
738 		dn_cfg.expire_cycle = 0;
739 		dn_drain_scheduler();
740 		dn_drain_queue();
741 	}
742 
743 	dn_reschedule();
744 	DN_BH_WUNLOCK();
745 	if (q.head != NULL)
746 		dummynet_send(q.head);
747 	CURVNET_RESTORE();
748 }
749 
750 /*
751  * forward a chain of packets to the proper destination.
752  * This runs outside the dummynet lock.
753  */
754 static void
755 dummynet_send(struct mbuf *m)
756 {
757 	struct mbuf *n;
758 
759 	for (; m != NULL; m = n) {
760 		struct ifnet *ifp = NULL;	/* gcc 3.4.6 complains */
761         	struct m_tag *tag;
762 		int dst;
763 
764 		n = m->m_nextpkt;
765 		m->m_nextpkt = NULL;
766 		tag = m_tag_first(m);
767 		if (tag == NULL) { /* should not happen */
768 			dst = DIR_DROP;
769 		} else {
770 			struct dn_pkt_tag *pkt = dn_tag_get(m);
771 			/* extract the dummynet info, rename the tag
772 			 * to carry reinject info.
773 			 */
774 			if (pkt->dn_dir == (DIR_OUT | PROTO_LAYER2) &&
775 				pkt->ifp == NULL) {
776 				dst = DIR_DROP;
777 			} else {
778 				dst = pkt->dn_dir;
779 				ifp = pkt->ifp;
780 				tag->m_tag_cookie = MTAG_IPFW_RULE;
781 				tag->m_tag_id = 0;
782 			}
783 		}
784 
785 		switch (dst) {
786 		case DIR_OUT:
787 			ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
788 			break ;
789 
790 		case DIR_IN :
791 			netisr_dispatch(NETISR_IP, m);
792 			break;
793 
794 #ifdef INET6
795 		case DIR_IN | PROTO_IPV6:
796 			netisr_dispatch(NETISR_IPV6, m);
797 			break;
798 
799 		case DIR_OUT | PROTO_IPV6:
800 			ip6_output(m, NULL, NULL, IPV6_FORWARDING, NULL, NULL, NULL);
801 			break;
802 #endif
803 
804 		case DIR_FWD | PROTO_IFB: /* DN_TO_IFB_FWD: */
805 			if (bridge_dn_p != NULL)
806 				((*bridge_dn_p)(m, ifp));
807 			else
808 				printf("dummynet: if_bridge not loaded\n");
809 
810 			break;
811 
812 		case DIR_IN | PROTO_LAYER2: /* DN_TO_ETH_DEMUX: */
813 			/*
814 			 * The Ethernet code assumes the Ethernet header is
815 			 * contiguous in the first mbuf header.
816 			 * Insure this is true.
817 			 */
818 			if (m->m_len < ETHER_HDR_LEN &&
819 			    (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
820 				printf("dummynet/ether: pullup failed, "
821 				    "dropping packet\n");
822 				break;
823 			}
824 			ether_demux(m->m_pkthdr.rcvif, m);
825 			break;
826 
827 		case DIR_OUT | PROTO_LAYER2: /* N_TO_ETH_OUT: */
828 			ether_output_frame(ifp, m);
829 			break;
830 
831 		case DIR_DROP:
832 			/* drop the packet after some time */
833 			FREE_PKT(m);
834 			break;
835 
836 		default:
837 			printf("dummynet: bad switch %d!\n", dst);
838 			FREE_PKT(m);
839 			break;
840 		}
841 	}
842 }
843 
844 static inline int
845 tag_mbuf(struct mbuf *m, int dir, struct ip_fw_args *fwa)
846 {
847 	struct dn_pkt_tag *dt;
848 	struct m_tag *mtag;
849 
850 	mtag = m_tag_get(PACKET_TAG_DUMMYNET,
851 		    sizeof(*dt), M_NOWAIT | M_ZERO);
852 	if (mtag == NULL)
853 		return 1;		/* Cannot allocate packet header. */
854 	m_tag_prepend(m, mtag);		/* Attach to mbuf chain. */
855 	dt = (struct dn_pkt_tag *)(mtag + 1);
856 	dt->rule = fwa->rule;
857 	dt->rule.info &= IPFW_ONEPASS;	/* only keep this info */
858 	dt->dn_dir = dir;
859 	dt->ifp = fwa->oif;
860 	/* dt->output tame is updated as we move through */
861 	dt->output_time = dn_cfg.curr_time;
862 	return 0;
863 }
864 
865 
866 /*
867  * dummynet hook for packets.
868  * We use the argument to locate the flowset fs and the sched_set sch
869  * associated to it. The we apply flow_mask and sched_mask to
870  * determine the queue and scheduler instances.
871  *
872  * dir		where shall we send the packet after dummynet.
873  * *m0		the mbuf with the packet
874  * ifp		the 'ifp' parameter from the caller.
875  *		NULL in ip_input, destination interface in ip_output,
876  */
877 int
878 dummynet_io(struct mbuf **m0, int dir, struct ip_fw_args *fwa)
879 {
880 	struct mbuf *m = *m0;
881 	struct dn_fsk *fs = NULL;
882 	struct dn_sch_inst *si;
883 	struct dn_queue *q = NULL;	/* default */
884 
885 	int fs_id = (fwa->rule.info & IPFW_INFO_MASK) +
886 		((fwa->rule.info & IPFW_IS_PIPE) ? 2*DN_MAX_ID : 0);
887 	DN_BH_WLOCK();
888 	io_pkt++;
889 	/* we could actually tag outside the lock, but who cares... */
890 	if (tag_mbuf(m, dir, fwa))
891 		goto dropit;
892 	if (dn_cfg.busy) {
893 		/* if the upper half is busy doing something expensive,
894 		 * lets queue the packet and move forward
895 		 */
896 		mq_append(&dn_cfg.pending, m);
897 		m = *m0 = NULL; /* consumed */
898 		goto done; /* already active, nothing to do */
899 	}
900 	/* XXX locate_flowset could be optimised with a direct ref. */
901 	fs = dn_ht_find(dn_cfg.fshash, fs_id, 0, NULL);
902 	if (fs == NULL)
903 		goto dropit;	/* This queue/pipe does not exist! */
904 	if (fs->sched == NULL)	/* should not happen */
905 		goto dropit;
906 	/* find scheduler instance, possibly applying sched_mask */
907 	si = ipdn_si_find(fs->sched, &(fwa->f_id));
908 	if (si == NULL)
909 		goto dropit;
910 	/*
911 	 * If the scheduler supports multiple queues, find the right one
912 	 * (otherwise it will be ignored by enqueue).
913 	 */
914 	if (fs->sched->fp->flags & DN_MULTIQUEUE) {
915 		q = ipdn_q_find(fs, si, &(fwa->f_id));
916 		if (q == NULL)
917 			goto dropit;
918 	}
919 	if (fs->sched->fp->enqueue(si, q, m)) {
920 		/* packet was dropped by enqueue() */
921 		m = *m0 = NULL;
922 
923 		/* dn_enqueue already increases io_pkt_drop */
924 		io_pkt_drop--;
925 
926 		goto dropit;
927 	}
928 
929 	if (si->kflags & DN_ACTIVE) {
930 		m = *m0 = NULL; /* consumed */
931 		goto done; /* already active, nothing to do */
932 	}
933 
934 	/* compute the initial allowance */
935 	if (si->idle_time < dn_cfg.curr_time) {
936 	    /* Do this only on the first packet on an idle pipe */
937 	    struct dn_link *p = &fs->sched->link;
938 
939 	    si->sched_time = dn_cfg.curr_time;
940 	    si->credit = dn_cfg.io_fast ? p->bandwidth : 0;
941 	    if (p->burst) {
942 		uint64_t burst = (dn_cfg.curr_time - si->idle_time) * p->bandwidth;
943 		if (burst > p->burst)
944 			burst = p->burst;
945 		si->credit += burst;
946 	    }
947 	}
948 	/* pass through scheduler and delay line */
949 	m = serve_sched(NULL, si, dn_cfg.curr_time);
950 
951 	/* optimization -- pass it back to ipfw for immediate send */
952 	/* XXX Don't call dummynet_send() if scheduler return the packet
953 	 *     just enqueued. This avoid a lock order reversal.
954 	 *
955 	 */
956 	if (/*dn_cfg.io_fast &&*/ m == *m0 && (dir & PROTO_LAYER2) == 0 ) {
957 		/* fast io, rename the tag * to carry reinject info. */
958 		struct m_tag *tag = m_tag_first(m);
959 
960 		tag->m_tag_cookie = MTAG_IPFW_RULE;
961 		tag->m_tag_id = 0;
962 		io_pkt_fast++;
963 		if (m->m_nextpkt != NULL) {
964 			printf("dummynet: fast io: pkt chain detected!\n");
965 			m->m_nextpkt = NULL;
966 		}
967 		m = NULL;
968 	} else {
969 		*m0 = NULL;
970 	}
971 done:
972 	DN_BH_WUNLOCK();
973 	if (m)
974 		dummynet_send(m);
975 	return 0;
976 
977 dropit:
978 	io_pkt_drop++;
979 	DN_BH_WUNLOCK();
980 	if (m)
981 		FREE_PKT(m);
982 	*m0 = NULL;
983 	return (fs && (fs->fs.flags & DN_NOERROR)) ? 0 : ENOBUFS;
984 }
985