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