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