xref: /freebsd/sys/netpfil/ipfw/ip_dn_io.c (revision 8d20be1e22095c27faf8fe8b2f0d089739cc742e)
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 #include <netpfil/ipfw/dn_sched.h>
67 
68 /*
69  * We keep a private variable for the simulation time, but we could
70  * probably use an existing one ("softticks" in sys/kern/kern_timeout.c)
71  * instead of dn_cfg.curr_time
72  */
73 
74 struct dn_parms dn_cfg;
75 //VNET_DEFINE(struct dn_parms, _base_dn_cfg);
76 
77 static long tick_last;		/* Last tick duration (usec). */
78 static long tick_delta;		/* Last vs standard tick diff (usec). */
79 static long tick_delta_sum;	/* Accumulated tick difference (usec).*/
80 static long tick_adjustment;	/* Tick adjustments done. */
81 static long tick_lost;		/* Lost(coalesced) ticks number. */
82 /* Adjusted vs non-adjusted curr_time difference (ticks). */
83 static long tick_diff;
84 
85 static unsigned long	io_pkt;
86 static unsigned long	io_pkt_fast;
87 static unsigned long	io_pkt_drop;
88 
89 /*
90  * We use a heap to store entities for which we have pending timer events.
91  * The heap is checked at every tick and all entities with expired events
92  * are extracted.
93  */
94 
95 MALLOC_DEFINE(M_DUMMYNET, "dummynet", "dummynet heap");
96 
97 extern	void (*bridge_dn_p)(struct mbuf *, struct ifnet *);
98 
99 #ifdef SYSCTL_NODE
100 
101 /*
102  * Because of the way the SYSBEGIN/SYSEND macros work on other
103  * platforms, there should not be functions between them.
104  * So keep the handlers outside the block.
105  */
106 static int
107 sysctl_hash_size(SYSCTL_HANDLER_ARGS)
108 {
109 	int error, value;
110 
111 	value = dn_cfg.hash_size;
112 	error = sysctl_handle_int(oidp, &value, 0, req);
113 	if (error != 0 || req->newptr == NULL)
114 		return (error);
115 	if (value < 16 || value > 65536)
116 		return (EINVAL);
117 	dn_cfg.hash_size = value;
118 	return (0);
119 }
120 
121 static int
122 sysctl_limits(SYSCTL_HANDLER_ARGS)
123 {
124 	int error;
125 	long value;
126 
127 	if (arg2 != 0)
128 		value = dn_cfg.slot_limit;
129 	else
130 		value = dn_cfg.byte_limit;
131 	error = sysctl_handle_long(oidp, &value, 0, req);
132 
133 	if (error != 0 || req->newptr == NULL)
134 		return (error);
135 	if (arg2 != 0) {
136 		if (value < 1)
137 			return (EINVAL);
138 		dn_cfg.slot_limit = value;
139 	} else {
140 		if (value < 1500)
141 			return (EINVAL);
142 		dn_cfg.byte_limit = value;
143 	}
144 	return (0);
145 }
146 
147 SYSBEGIN(f4)
148 
149 SYSCTL_DECL(_net_inet);
150 SYSCTL_DECL(_net_inet_ip);
151 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet, CTLFLAG_RW, 0, "Dummynet");
152 
153 /* wrapper to pass dn_cfg fields to SYSCTL_* */
154 //#define DC(x)	(&(VNET_NAME(_base_dn_cfg).x))
155 #define DC(x)	(&(dn_cfg.x))
156 /* parameters */
157 
158 
159 SYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, hash_size,
160     CTLTYPE_INT | CTLFLAG_RW, 0, 0, sysctl_hash_size,
161     "I", "Default hash table size");
162 
163 
164 SYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, pipe_slot_limit,
165     CTLTYPE_LONG | CTLFLAG_RW, 0, 1, sysctl_limits,
166     "L", "Upper limit in slots for pipe queue.");
167 SYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, pipe_byte_limit,
168     CTLTYPE_LONG | CTLFLAG_RW, 0, 0, sysctl_limits,
169     "L", "Upper limit in bytes for pipe queue.");
170 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, io_fast,
171     CTLFLAG_RW, DC(io_fast), 0, "Enable fast dummynet io.");
172 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug,
173     CTLFLAG_RW, DC(debug), 0, "Dummynet debug level");
174 
175 /* RED parameters */
176 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
177     CTLFLAG_RD, DC(red_lookup_depth), 0, "Depth of RED lookup table");
178 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
179     CTLFLAG_RD, DC(red_avg_pkt_size), 0, "RED Medium packet size");
180 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
181     CTLFLAG_RD, DC(red_max_pkt_size), 0, "RED Max packet size");
182 
183 /* time adjustment */
184 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_delta,
185     CTLFLAG_RD, &tick_delta, 0, "Last vs standard tick difference (usec).");
186 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_delta_sum,
187     CTLFLAG_RD, &tick_delta_sum, 0, "Accumulated tick difference (usec).");
188 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_adjustment,
189     CTLFLAG_RD, &tick_adjustment, 0, "Tick adjustments done.");
190 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_diff,
191     CTLFLAG_RD, &tick_diff, 0,
192     "Adjusted vs non-adjusted curr_time difference (ticks).");
193 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_lost,
194     CTLFLAG_RD, &tick_lost, 0,
195     "Number of ticks coalesced by dummynet taskqueue.");
196 
197 /* Drain parameters */
198 SYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire,
199     CTLFLAG_RW, DC(expire), 0, "Expire empty queues/pipes");
200 SYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire_cycle,
201     CTLFLAG_RD, DC(expire_cycle), 0, "Expire cycle for queues/pipes");
202 
203 /* statistics */
204 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, schk_count,
205     CTLFLAG_RD, DC(schk_count), 0, "Number of schedulers");
206 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, si_count,
207     CTLFLAG_RD, DC(si_count), 0, "Number of scheduler instances");
208 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, fsk_count,
209     CTLFLAG_RD, DC(fsk_count), 0, "Number of flowsets");
210 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, queue_count,
211     CTLFLAG_RD, DC(queue_count), 0, "Number of queues");
212 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt,
213     CTLFLAG_RD, &io_pkt, 0,
214     "Number of packets passed to dummynet.");
215 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt_fast,
216     CTLFLAG_RD, &io_pkt_fast, 0,
217     "Number of packets bypassed dummynet scheduler.");
218 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt_drop,
219     CTLFLAG_RD, &io_pkt_drop, 0,
220     "Number of packets dropped by dummynet.");
221 #undef DC
222 SYSEND
223 
224 #endif
225 
226 static void	dummynet_send(struct mbuf *);
227 
228 /*
229  * Packets processed by dummynet have an mbuf tag associated with
230  * them that carries their dummynet state.
231  * Outside dummynet, only the 'rule' field is relevant, and it must
232  * be at the beginning of the structure.
233  */
234 struct dn_pkt_tag {
235 	struct ipfw_rule_ref rule;	/* matching rule	*/
236 
237 	/* second part, dummynet specific */
238 	int dn_dir;		/* action when packet comes out.*/
239 				/* see ip_fw_private.h		*/
240 	uint64_t output_time;	/* when the pkt is due for delivery*/
241 	struct ifnet *ifp;	/* interface, for ip_output	*/
242 	struct _ip6dn_args ip6opt;	/* XXX ipv6 options	*/
243 };
244 
245 /*
246  * Return the mbuf tag holding the dummynet state (it should
247  * be the first one on the list).
248  */
249 static struct dn_pkt_tag *
250 dn_tag_get(struct mbuf *m)
251 {
252 	struct m_tag *mtag = m_tag_first(m);
253 	KASSERT(mtag != NULL &&
254 	    mtag->m_tag_cookie == MTAG_ABI_COMPAT &&
255 	    mtag->m_tag_id == PACKET_TAG_DUMMYNET,
256 	    ("packet on dummynet queue w/o dummynet tag!"));
257 	return (struct dn_pkt_tag *)(mtag+1);
258 }
259 
260 static inline void
261 mq_append(struct mq *q, struct mbuf *m)
262 {
263 	if (q->head == NULL)
264 		q->head = m;
265 	else
266 		q->tail->m_nextpkt = m;
267 	q->tail = m;
268 	m->m_nextpkt = NULL;
269 }
270 
271 /*
272  * Dispose a list of packet. Use a functions so if we need to do
273  * more work, this is a central point to do it.
274  */
275 void dn_free_pkts(struct mbuf *mnext)
276 {
277         struct mbuf *m;
278 
279         while ((m = mnext) != NULL) {
280                 mnext = m->m_nextpkt;
281                 FREE_PKT(m);
282         }
283 }
284 
285 static int
286 red_drops (struct dn_queue *q, int len)
287 {
288 	/*
289 	 * RED algorithm
290 	 *
291 	 * RED calculates the average queue size (avg) using a low-pass filter
292 	 * with an exponential weighted (w_q) moving average:
293 	 * 	avg  <-  (1-w_q) * avg + w_q * q_size
294 	 * where q_size is the queue length (measured in bytes or * packets).
295 	 *
296 	 * If q_size == 0, we compute the idle time for the link, and set
297 	 *	avg = (1 - w_q)^(idle/s)
298 	 * where s is the time needed for transmitting a medium-sized packet.
299 	 *
300 	 * Now, if avg < min_th the packet is enqueued.
301 	 * If avg > max_th the packet is dropped. Otherwise, the packet is
302 	 * dropped with probability P function of avg.
303 	 */
304 
305 	struct dn_fsk *fs = q->fs;
306 	int64_t p_b = 0;
307 
308 	/* Queue in bytes or packets? */
309 	uint32_t q_size = (fs->fs.flags & DN_QSIZE_BYTES) ?
310 	    q->ni.len_bytes : q->ni.length;
311 
312 	/* Average queue size estimation. */
313 	if (q_size != 0) {
314 		/* Queue is not empty, avg <- avg + (q_size - avg) * w_q */
315 		int diff = SCALE(q_size) - q->avg;
316 		int64_t v = SCALE_MUL((int64_t)diff, (int64_t)fs->w_q);
317 
318 		q->avg += (int)v;
319 	} else {
320 		/*
321 		 * Queue is empty, find for how long the queue has been
322 		 * empty and use a lookup table for computing
323 		 * (1 - * w_q)^(idle_time/s) where s is the time to send a
324 		 * (small) packet.
325 		 * XXX check wraps...
326 		 */
327 		if (q->avg) {
328 			u_int t = div64((dn_cfg.curr_time - q->q_time), fs->lookup_step);
329 
330 			q->avg = (t < fs->lookup_depth) ?
331 			    SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
332 		}
333 	}
334 
335 	/* Should i drop? */
336 	if (q->avg < fs->min_th) {
337 		q->count = -1;
338 		return (0);	/* accept packet */
339 	}
340 	if (q->avg >= fs->max_th) {	/* average queue >=  max threshold */
341 		if (fs->fs.flags & DN_IS_GENTLE_RED) {
342 			/*
343 			 * According to Gentle-RED, if avg is greater than
344 			 * max_th the packet is dropped with a probability
345 			 *	 p_b = c_3 * avg - c_4
346 			 * where c_3 = (1 - max_p) / max_th
347 			 *       c_4 = 1 - 2 * max_p
348 			 */
349 			p_b = SCALE_MUL((int64_t)fs->c_3, (int64_t)q->avg) -
350 			    fs->c_4;
351 		} else {
352 			q->count = -1;
353 			return (1);
354 		}
355 	} else if (q->avg > fs->min_th) {
356 		/*
357 		 * We compute p_b using the linear dropping function
358 		 *	 p_b = c_1 * avg - c_2
359 		 * where c_1 = max_p / (max_th - min_th)
360 		 * 	 c_2 = max_p * min_th / (max_th - min_th)
361 		 */
362 		p_b = SCALE_MUL((int64_t)fs->c_1, (int64_t)q->avg) - fs->c_2;
363 	}
364 
365 	if (fs->fs.flags & DN_QSIZE_BYTES)
366 		p_b = div64((p_b * len) , fs->max_pkt_size);
367 	if (++q->count == 0)
368 		q->random = random() & 0xffff;
369 	else {
370 		/*
371 		 * q->count counts packets arrived since last drop, so a greater
372 		 * value of q->count means a greater packet drop probability.
373 		 */
374 		if (SCALE_MUL(p_b, SCALE((int64_t)q->count)) > q->random) {
375 			q->count = 0;
376 			/* After a drop we calculate a new random value. */
377 			q->random = random() & 0xffff;
378 			return (1);	/* drop */
379 		}
380 	}
381 	/* End of RED algorithm. */
382 
383 	return (0);	/* accept */
384 
385 }
386 
387 /*
388  * Enqueue a packet in q, subject to space and queue management policy
389  * (whose parameters are in q->fs).
390  * Update stats for the queue and the scheduler.
391  * Return 0 on success, 1 on drop. The packet is consumed anyways.
392  */
393 int
394 dn_enqueue(struct dn_queue *q, struct mbuf* m, int drop)
395 {
396 	struct dn_fs *f;
397 	struct dn_flow *ni;	/* stats for scheduler instance */
398 	uint64_t len;
399 
400 	if (q->fs == NULL || q->_si == NULL) {
401 		printf("%s fs %p si %p, dropping\n",
402 			__FUNCTION__, q->fs, q->_si);
403 		FREE_PKT(m);
404 		return 1;
405 	}
406 	f = &(q->fs->fs);
407 	ni = &q->_si->ni;
408 	len = m->m_pkthdr.len;
409 	/* Update statistics, then check reasons to drop pkt. */
410 	q->ni.tot_bytes += len;
411 	q->ni.tot_pkts++;
412 	ni->tot_bytes += len;
413 	ni->tot_pkts++;
414 	if (drop)
415 		goto drop;
416 	if (f->plr && random() < f->plr)
417 		goto drop;
418 	if (f->flags & DN_IS_RED && red_drops(q, m->m_pkthdr.len))
419 		goto drop;
420 	if (f->flags & DN_QSIZE_BYTES) {
421 		if (q->ni.len_bytes > f->qsize)
422 			goto drop;
423 	} else if (q->ni.length >= f->qsize) {
424 		goto drop;
425 	}
426 	mq_append(&q->mq, m);
427 	q->ni.length++;
428 	q->ni.len_bytes += len;
429 	ni->length++;
430 	ni->len_bytes += len;
431 	return 0;
432 
433 drop:
434 	io_pkt_drop++;
435 	q->ni.drops++;
436 	ni->drops++;
437 	FREE_PKT(m);
438 	return 1;
439 }
440 
441 /*
442  * Fetch packets from the delay line which are due now. If there are
443  * leftover packets, reinsert the delay line in the heap.
444  * Runs under scheduler lock.
445  */
446 static void
447 transmit_event(struct mq *q, struct delay_line *dline, uint64_t now)
448 {
449 	struct mbuf *m;
450 	struct dn_pkt_tag *pkt = NULL;
451 
452 	dline->oid.subtype = 0; /* not in heap */
453 	while ((m = dline->mq.head) != NULL) {
454 		pkt = dn_tag_get(m);
455 		if (!DN_KEY_LEQ(pkt->output_time, now))
456 			break;
457 		dline->mq.head = m->m_nextpkt;
458 		mq_append(q, m);
459 	}
460 	if (m != NULL) {
461 		dline->oid.subtype = 1; /* in heap */
462 		heap_insert(&dn_cfg.evheap, pkt->output_time, dline);
463 	}
464 }
465 
466 /*
467  * Convert the additional MAC overheads/delays into an equivalent
468  * number of bits for the given data rate. The samples are
469  * in milliseconds so we need to divide by 1000.
470  */
471 static uint64_t
472 extra_bits(struct mbuf *m, struct dn_schk *s)
473 {
474 	int index;
475 	uint64_t bits;
476 	struct dn_profile *pf = s->profile;
477 
478 	if (!pf || pf->samples_no == 0)
479 		return 0;
480 	index  = random() % pf->samples_no;
481 	bits = div64((uint64_t)pf->samples[index] * s->link.bandwidth, 1000);
482 	if (index >= pf->loss_level) {
483 		struct dn_pkt_tag *dt = dn_tag_get(m);
484 		if (dt)
485 			dt->dn_dir = DIR_DROP;
486 	}
487 	return bits;
488 }
489 
490 /*
491  * Send traffic from a scheduler instance due by 'now'.
492  * Return a pointer to the head of the queue.
493  */
494 static struct mbuf *
495 serve_sched(struct mq *q, struct dn_sch_inst *si, uint64_t now)
496 {
497 	struct mq def_q;
498 	struct dn_schk *s = si->sched;
499 	struct mbuf *m = NULL;
500 	int delay_line_idle = (si->dline.mq.head == NULL);
501 	int done, bw;
502 
503 	if (q == NULL) {
504 		q = &def_q;
505 		q->head = NULL;
506 	}
507 
508 	bw = s->link.bandwidth;
509 	si->kflags &= ~DN_ACTIVE;
510 
511 	if (bw > 0)
512 		si->credit += (now - si->sched_time) * bw;
513 	else
514 		si->credit = 0;
515 	si->sched_time = now;
516 	done = 0;
517 	while (si->credit >= 0 && (m = s->fp->dequeue(si)) != NULL) {
518 		uint64_t len_scaled;
519 
520 		done++;
521 		len_scaled = (bw == 0) ? 0 : hz *
522 			(m->m_pkthdr.len * 8 + extra_bits(m, s));
523 		si->credit -= len_scaled;
524 		/* Move packet in the delay line */
525 		dn_tag_get(m)->output_time = dn_cfg.curr_time + s->link.delay ;
526 		mq_append(&si->dline.mq, m);
527 	}
528 
529 	/*
530 	 * If credit >= 0 the instance is idle, mark time.
531 	 * Otherwise put back in the heap, and adjust the output
532 	 * time of the last inserted packet, m, which was too early.
533 	 */
534 	if (si->credit >= 0) {
535 		si->idle_time = now;
536 	} else {
537 		uint64_t t;
538 		KASSERT (bw > 0, ("bw=0 and credit<0 ?"));
539 		t = div64(bw - 1 - si->credit, bw);
540 		if (m)
541 			dn_tag_get(m)->output_time += t;
542 		si->kflags |= DN_ACTIVE;
543 		heap_insert(&dn_cfg.evheap, now + t, si);
544 	}
545 	if (delay_line_idle && done)
546 		transmit_event(q, &si->dline, now);
547 	return q->head;
548 }
549 
550 /*
551  * The timer handler for dummynet. Time is computed in ticks, but
552  * but the code is tolerant to the actual rate at which this is called.
553  * Once complete, the function reschedules itself for the next tick.
554  */
555 void
556 dummynet_task(void *context, int pending)
557 {
558 	struct timeval t;
559 	struct mq q = { NULL, NULL }; /* queue to accumulate results */
560 
561 	CURVNET_SET((struct vnet *)context);
562 
563 	DN_BH_WLOCK();
564 
565 	/* Update number of lost(coalesced) ticks. */
566 	tick_lost += pending - 1;
567 
568 	getmicrouptime(&t);
569 	/* Last tick duration (usec). */
570 	tick_last = (t.tv_sec - dn_cfg.prev_t.tv_sec) * 1000000 +
571 	(t.tv_usec - dn_cfg.prev_t.tv_usec);
572 	/* Last tick vs standard tick difference (usec). */
573 	tick_delta = (tick_last * hz - 1000000) / hz;
574 	/* Accumulated tick difference (usec). */
575 	tick_delta_sum += tick_delta;
576 
577 	dn_cfg.prev_t = t;
578 
579 	/*
580 	* Adjust curr_time if the accumulated tick difference is
581 	* greater than the 'standard' tick. Since curr_time should
582 	* be monotonically increasing, we do positive adjustments
583 	* as required, and throttle curr_time in case of negative
584 	* adjustment.
585 	*/
586 	dn_cfg.curr_time++;
587 	if (tick_delta_sum - tick >= 0) {
588 		int diff = tick_delta_sum / tick;
589 
590 		dn_cfg.curr_time += diff;
591 		tick_diff += diff;
592 		tick_delta_sum %= tick;
593 		tick_adjustment++;
594 	} else if (tick_delta_sum + tick <= 0) {
595 		dn_cfg.curr_time--;
596 		tick_diff--;
597 		tick_delta_sum += tick;
598 		tick_adjustment++;
599 	}
600 
601 	/* serve pending events, accumulate in q */
602 	for (;;) {
603 		struct dn_id *p;    /* generic parameter to handler */
604 
605 		if (dn_cfg.evheap.elements == 0 ||
606 		    DN_KEY_LT(dn_cfg.curr_time, HEAP_TOP(&dn_cfg.evheap)->key))
607 			break;
608 		p = HEAP_TOP(&dn_cfg.evheap)->object;
609 		heap_extract(&dn_cfg.evheap, NULL);
610 
611 		if (p->type == DN_SCH_I) {
612 			serve_sched(&q, (struct dn_sch_inst *)p, dn_cfg.curr_time);
613 		} else { /* extracted a delay line */
614 			transmit_event(&q, (struct delay_line *)p, dn_cfg.curr_time);
615 		}
616 	}
617 	if (dn_cfg.expire && ++dn_cfg.expire_cycle >= dn_cfg.expire) {
618 		dn_cfg.expire_cycle = 0;
619 		dn_drain_scheduler();
620 		dn_drain_queue();
621 	}
622 
623 	DN_BH_WUNLOCK();
624 	dn_reschedule();
625 	if (q.head != NULL)
626 		dummynet_send(q.head);
627 	CURVNET_RESTORE();
628 }
629 
630 /*
631  * forward a chain of packets to the proper destination.
632  * This runs outside the dummynet lock.
633  */
634 static void
635 dummynet_send(struct mbuf *m)
636 {
637 	struct mbuf *n;
638 
639 	for (; m != NULL; m = n) {
640 		struct ifnet *ifp = NULL;	/* gcc 3.4.6 complains */
641         	struct m_tag *tag;
642 		int dst;
643 
644 		n = m->m_nextpkt;
645 		m->m_nextpkt = NULL;
646 		tag = m_tag_first(m);
647 		if (tag == NULL) { /* should not happen */
648 			dst = DIR_DROP;
649 		} else {
650 			struct dn_pkt_tag *pkt = dn_tag_get(m);
651 			/* extract the dummynet info, rename the tag
652 			 * to carry reinject info.
653 			 */
654 			dst = pkt->dn_dir;
655 			ifp = pkt->ifp;
656 			tag->m_tag_cookie = MTAG_IPFW_RULE;
657 			tag->m_tag_id = 0;
658 		}
659 
660 		switch (dst) {
661 		case DIR_OUT:
662 			ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
663 			break ;
664 
665 		case DIR_IN :
666 			netisr_dispatch(NETISR_IP, m);
667 			break;
668 
669 #ifdef INET6
670 		case DIR_IN | PROTO_IPV6:
671 			netisr_dispatch(NETISR_IPV6, m);
672 			break;
673 
674 		case DIR_OUT | PROTO_IPV6:
675 			ip6_output(m, NULL, NULL, IPV6_FORWARDING, NULL, NULL, NULL);
676 			break;
677 #endif
678 
679 		case DIR_FWD | PROTO_IFB: /* DN_TO_IFB_FWD: */
680 			if (bridge_dn_p != NULL)
681 				((*bridge_dn_p)(m, ifp));
682 			else
683 				printf("dummynet: if_bridge not loaded\n");
684 
685 			break;
686 
687 		case DIR_IN | PROTO_LAYER2: /* DN_TO_ETH_DEMUX: */
688 			/*
689 			 * The Ethernet code assumes the Ethernet header is
690 			 * contiguous in the first mbuf header.
691 			 * Insure this is true.
692 			 */
693 			if (m->m_len < ETHER_HDR_LEN &&
694 			    (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
695 				printf("dummynet/ether: pullup failed, "
696 				    "dropping packet\n");
697 				break;
698 			}
699 			ether_demux(m->m_pkthdr.rcvif, m);
700 			break;
701 
702 		case DIR_OUT | PROTO_LAYER2: /* N_TO_ETH_OUT: */
703 			ether_output_frame(ifp, m);
704 			break;
705 
706 		case DIR_DROP:
707 			/* drop the packet after some time */
708 			FREE_PKT(m);
709 			break;
710 
711 		default:
712 			printf("dummynet: bad switch %d!\n", dst);
713 			FREE_PKT(m);
714 			break;
715 		}
716 	}
717 }
718 
719 static inline int
720 tag_mbuf(struct mbuf *m, int dir, struct ip_fw_args *fwa)
721 {
722 	struct dn_pkt_tag *dt;
723 	struct m_tag *mtag;
724 
725 	mtag = m_tag_get(PACKET_TAG_DUMMYNET,
726 		    sizeof(*dt), M_NOWAIT | M_ZERO);
727 	if (mtag == NULL)
728 		return 1;		/* Cannot allocate packet header. */
729 	m_tag_prepend(m, mtag);		/* Attach to mbuf chain. */
730 	dt = (struct dn_pkt_tag *)(mtag + 1);
731 	dt->rule = fwa->rule;
732 	dt->rule.info &= IPFW_ONEPASS;	/* only keep this info */
733 	dt->dn_dir = dir;
734 	dt->ifp = fwa->oif;
735 	/* dt->output tame is updated as we move through */
736 	dt->output_time = dn_cfg.curr_time;
737 	return 0;
738 }
739 
740 
741 /*
742  * dummynet hook for packets.
743  * We use the argument to locate the flowset fs and the sched_set sch
744  * associated to it. The we apply flow_mask and sched_mask to
745  * determine the queue and scheduler instances.
746  *
747  * dir		where shall we send the packet after dummynet.
748  * *m0		the mbuf with the packet
749  * ifp		the 'ifp' parameter from the caller.
750  *		NULL in ip_input, destination interface in ip_output,
751  */
752 int
753 dummynet_io(struct mbuf **m0, int dir, struct ip_fw_args *fwa)
754 {
755 	struct mbuf *m = *m0;
756 	struct dn_fsk *fs = NULL;
757 	struct dn_sch_inst *si;
758 	struct dn_queue *q = NULL;	/* default */
759 
760 	int fs_id = (fwa->rule.info & IPFW_INFO_MASK) +
761 		((fwa->rule.info & IPFW_IS_PIPE) ? 2*DN_MAX_ID : 0);
762 	DN_BH_WLOCK();
763 	io_pkt++;
764 	/* we could actually tag outside the lock, but who cares... */
765 	if (tag_mbuf(m, dir, fwa))
766 		goto dropit;
767 	if (dn_cfg.busy) {
768 		/* if the upper half is busy doing something expensive,
769 		 * lets queue the packet and move forward
770 		 */
771 		mq_append(&dn_cfg.pending, m);
772 		m = *m0 = NULL; /* consumed */
773 		goto done; /* already active, nothing to do */
774 	}
775 	/* XXX locate_flowset could be optimised with a direct ref. */
776 	fs = dn_ht_find(dn_cfg.fshash, fs_id, 0, NULL);
777 	if (fs == NULL)
778 		goto dropit;	/* This queue/pipe does not exist! */
779 	if (fs->sched == NULL)	/* should not happen */
780 		goto dropit;
781 	/* find scheduler instance, possibly applying sched_mask */
782 	si = ipdn_si_find(fs->sched, &(fwa->f_id));
783 	if (si == NULL)
784 		goto dropit;
785 	/*
786 	 * If the scheduler supports multiple queues, find the right one
787 	 * (otherwise it will be ignored by enqueue).
788 	 */
789 	if (fs->sched->fp->flags & DN_MULTIQUEUE) {
790 		q = ipdn_q_find(fs, si, &(fwa->f_id));
791 		if (q == NULL)
792 			goto dropit;
793 	}
794 	if (fs->sched->fp->enqueue(si, q, m)) {
795 		/* packet was dropped by enqueue() */
796 		m = *m0 = NULL;
797 		goto dropit;
798 	}
799 
800 	if (si->kflags & DN_ACTIVE) {
801 		m = *m0 = NULL; /* consumed */
802 		goto done; /* already active, nothing to do */
803 	}
804 
805 	/* compute the initial allowance */
806 	if (si->idle_time < dn_cfg.curr_time) {
807 	    /* Do this only on the first packet on an idle pipe */
808 	    struct dn_link *p = &fs->sched->link;
809 
810 	    si->sched_time = dn_cfg.curr_time;
811 	    si->credit = dn_cfg.io_fast ? p->bandwidth : 0;
812 	    if (p->burst) {
813 		uint64_t burst = (dn_cfg.curr_time - si->idle_time) * p->bandwidth;
814 		if (burst > p->burst)
815 			burst = p->burst;
816 		si->credit += burst;
817 	    }
818 	}
819 	/* pass through scheduler and delay line */
820 	m = serve_sched(NULL, si, dn_cfg.curr_time);
821 
822 	/* optimization -- pass it back to ipfw for immediate send */
823 	/* XXX Don't call dummynet_send() if scheduler return the packet
824 	 *     just enqueued. This avoid a lock order reversal.
825 	 *
826 	 */
827 	if (/*dn_cfg.io_fast &&*/ m == *m0 && (dir & PROTO_LAYER2) == 0 ) {
828 		/* fast io, rename the tag * to carry reinject info. */
829 		struct m_tag *tag = m_tag_first(m);
830 
831 		tag->m_tag_cookie = MTAG_IPFW_RULE;
832 		tag->m_tag_id = 0;
833 		io_pkt_fast++;
834 		if (m->m_nextpkt != NULL) {
835 			printf("dummynet: fast io: pkt chain detected!\n");
836 			m->m_nextpkt = NULL;
837 		}
838 		m = NULL;
839 	} else {
840 		*m0 = NULL;
841 	}
842 done:
843 	DN_BH_WUNLOCK();
844 	if (m)
845 		dummynet_send(m);
846 	return 0;
847 
848 dropit:
849 	io_pkt_drop++;
850 	DN_BH_WUNLOCK();
851 	if (m)
852 		FREE_PKT(m);
853 	*m0 = NULL;
854 	return (fs && (fs->fs.flags & DN_NOERROR)) ? 0 : ENOBUFS;
855 }
856