xref: /freebsd/sys/netpfil/ipfw/ip_dn_io.c (revision c1d255d3)
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 | CTLFLAG_VNET, DC(io_fast), 0, "Enable fast dummynet io.");
173 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug,
174     CTLFLAG_RW | CTLFLAG_VNET, 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 | CTLFLAG_VNET, 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 | CTLFLAG_VNET, 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 | CTLFLAG_VNET, 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 | CTLFLAG_VNET, 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 | CTLFLAG_VNET, DC(tick_delta_sum), 0, "Accumulated tick difference (usec).");
189 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_adjustment,
190     CTLFLAG_RD | CTLFLAG_VNET, DC(tick_adjustment), 0, "Tick adjustments done.");
191 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_diff,
192     CTLFLAG_RD | CTLFLAG_VNET, 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 | CTLFLAG_VNET, 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 | CTLFLAG_VNET, DC(expire), 0, "Expire empty queues/pipes");
201 SYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire_cycle,
202     CTLFLAG_RD | CTLFLAG_VNET, 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 | CTLFLAG_VNET, DC(schk_count), 0, "Number of schedulers");
207 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, si_count,
208     CTLFLAG_RD | CTLFLAG_VNET, DC(si_count), 0, "Number of scheduler instances");
209 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, fsk_count,
210     CTLFLAG_RD | CTLFLAG_VNET, DC(fsk_count), 0, "Number of flowsets");
211 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, queue_count,
212     CTLFLAG_RD | CTLFLAG_VNET, DC(queue_count), 0, "Number of queues");
213 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt,
214     CTLFLAG_RD | CTLFLAG_VNET, 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 | CTLFLAG_VNET, 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 | CTLFLAG_VNET, 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;
595 	uint32_t bw;
596 
597 	if (q == NULL) {
598 		q = &def_q;
599 		q->head = NULL;
600 	}
601 
602 	bw = s->link.bandwidth;
603 	si->kflags &= ~DN_ACTIVE;
604 
605 	if (bw > 0)
606 		si->credit += (now - si->sched_time) * bw;
607 	else
608 		si->credit = 0;
609 	si->sched_time = now;
610 	done = 0;
611 	while (si->credit >= 0 && (m = s->fp->dequeue(si)) != NULL) {
612 		uint64_t len_scaled;
613 
614 		done++;
615 		len_scaled = (bw == 0) ? 0 : hz *
616 			(m->m_pkthdr.len * 8 + extra_bits(m, s));
617 		si->credit -= len_scaled;
618 		/* Move packet in the delay line */
619 		dn_tag_get(m)->output_time = V_dn_cfg.curr_time + s->link.delay ;
620 		mq_append(&si->dline.mq, m);
621 	}
622 
623 	/*
624 	 * If credit >= 0 the instance is idle, mark time.
625 	 * Otherwise put back in the heap, and adjust the output
626 	 * time of the last inserted packet, m, which was too early.
627 	 */
628 	if (si->credit >= 0) {
629 		si->idle_time = now;
630 	} else {
631 		uint64_t t;
632 		KASSERT (bw > 0, ("bw=0 and credit<0 ?"));
633 		t = div64(bw - 1 - si->credit, bw);
634 		if (m)
635 			dn_tag_get(m)->output_time += t;
636 		si->kflags |= DN_ACTIVE;
637 		heap_insert(&V_dn_cfg.evheap, now + t, si);
638 	}
639 	if (delay_line_idle && done)
640 		transmit_event(q, &si->dline, now);
641 	return q->head;
642 }
643 
644 /*
645  * The timer handler for dummynet. Time is computed in ticks, but
646  * but the code is tolerant to the actual rate at which this is called.
647  * Once complete, the function reschedules itself for the next tick.
648  */
649 void
650 dummynet_task(void *context, int pending)
651 {
652 	struct timeval t;
653 	struct mq q = { NULL, NULL }; /* queue to accumulate results */
654 	struct epoch_tracker et;
655 
656 	VNET_ITERATOR_DECL(vnet_iter);
657 	VNET_LIST_RLOCK();
658 	NET_EPOCH_ENTER(et);
659 
660 	VNET_FOREACH(vnet_iter) {
661 		memset(&q, 0, sizeof(struct mq));
662 		CURVNET_SET(vnet_iter);
663 
664 		DN_BH_WLOCK();
665 
666 		/* Update number of lost(coalesced) ticks. */
667 		V_dn_cfg.tick_lost += pending - 1;
668 
669 		getmicrouptime(&t);
670 		/* Last tick duration (usec). */
671 		V_dn_cfg.tick_last = (t.tv_sec - V_dn_cfg.prev_t.tv_sec) * 1000000 +
672 		(t.tv_usec - V_dn_cfg.prev_t.tv_usec);
673 		/* Last tick vs standard tick difference (usec). */
674 		V_dn_cfg.tick_delta = (V_dn_cfg.tick_last * hz - 1000000) / hz;
675 		/* Accumulated tick difference (usec). */
676 		V_dn_cfg.tick_delta_sum += V_dn_cfg.tick_delta;
677 
678 		V_dn_cfg.prev_t = t;
679 
680 		/*
681 		* Adjust curr_time if the accumulated tick difference is
682 		* greater than the 'standard' tick. Since curr_time should
683 		* be monotonically increasing, we do positive adjustments
684 		* as required, and throttle curr_time in case of negative
685 		* adjustment.
686 		*/
687 		V_dn_cfg.curr_time++;
688 		if (V_dn_cfg.tick_delta_sum - tick >= 0) {
689 			int diff = V_dn_cfg.tick_delta_sum / tick;
690 
691 			V_dn_cfg.curr_time += diff;
692 			V_dn_cfg.tick_diff += diff;
693 			V_dn_cfg.tick_delta_sum %= tick;
694 			V_dn_cfg.tick_adjustment++;
695 		} else if (V_dn_cfg.tick_delta_sum + tick <= 0) {
696 			V_dn_cfg.curr_time--;
697 			V_dn_cfg.tick_diff--;
698 			V_dn_cfg.tick_delta_sum += tick;
699 			V_dn_cfg.tick_adjustment++;
700 		}
701 
702 		/* serve pending events, accumulate in q */
703 		for (;;) {
704 			struct dn_id *p;    /* generic parameter to handler */
705 
706 			if (V_dn_cfg.evheap.elements == 0 ||
707 			    DN_KEY_LT(V_dn_cfg.curr_time, HEAP_TOP(&V_dn_cfg.evheap)->key))
708 				break;
709 			p = HEAP_TOP(&V_dn_cfg.evheap)->object;
710 			heap_extract(&V_dn_cfg.evheap, NULL);
711 			if (p->type == DN_SCH_I) {
712 				serve_sched(&q, (struct dn_sch_inst *)p, V_dn_cfg.curr_time);
713 			} else { /* extracted a delay line */
714 				transmit_event(&q, (struct delay_line *)p, V_dn_cfg.curr_time);
715 			}
716 		}
717 		if (V_dn_cfg.expire && ++V_dn_cfg.expire_cycle >= V_dn_cfg.expire) {
718 			V_dn_cfg.expire_cycle = 0;
719 			dn_drain_scheduler();
720 			dn_drain_queue();
721 		}
722 		DN_BH_WUNLOCK();
723 		if (q.head != NULL)
724 			dummynet_send(q.head);
725 
726 		CURVNET_RESTORE();
727 	}
728 	NET_EPOCH_EXIT(et);
729 	VNET_LIST_RUNLOCK();
730 
731 	/* Schedule our next run. */
732 	dn_reschedule();
733 }
734 
735 /*
736  * forward a chain of packets to the proper destination.
737  * This runs outside the dummynet lock.
738  */
739 static void
740 dummynet_send(struct mbuf *m)
741 {
742 	struct mbuf *n;
743 
744 	NET_EPOCH_ASSERT();
745 
746 	for (; m != NULL; m = n) {
747 		struct ifnet *ifp = NULL;	/* gcc 3.4.6 complains */
748         	struct m_tag *tag;
749 		int dst;
750 
751 		n = m->m_nextpkt;
752 		m->m_nextpkt = NULL;
753 		tag = m_tag_first(m);
754 		if (tag == NULL) { /* should not happen */
755 			dst = DIR_DROP;
756 		} else {
757 			struct dn_pkt_tag *pkt = dn_tag_get(m);
758 			/* extract the dummynet info, rename the tag
759 			 * to carry reinject info.
760 			 */
761 			if (pkt->dn_dir == (DIR_OUT | PROTO_LAYER2) &&
762 				pkt->ifp == NULL) {
763 				dst = DIR_DROP;
764 			} else {
765 				dst = pkt->dn_dir;
766 				ifp = pkt->ifp;
767 				tag->m_tag_cookie = MTAG_IPFW_RULE;
768 				tag->m_tag_id = 0;
769 			}
770 		}
771 
772 		switch (dst) {
773 		case DIR_OUT:
774 			ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
775 			break ;
776 
777 		case DIR_IN :
778 			netisr_dispatch(NETISR_IP, m);
779 			break;
780 
781 #ifdef INET6
782 		case DIR_IN | PROTO_IPV6:
783 			netisr_dispatch(NETISR_IPV6, m);
784 			break;
785 
786 		case DIR_OUT | PROTO_IPV6:
787 			ip6_output(m, NULL, NULL, IPV6_FORWARDING, NULL, NULL, NULL);
788 			break;
789 #endif
790 
791 		case DIR_FWD | PROTO_IFB: /* DN_TO_IFB_FWD: */
792 			if (bridge_dn_p != NULL)
793 				((*bridge_dn_p)(m, ifp));
794 			else
795 				printf("dummynet: if_bridge not loaded\n");
796 
797 			break;
798 
799 		case DIR_IN | PROTO_LAYER2: /* DN_TO_ETH_DEMUX: */
800 			/*
801 			 * The Ethernet code assumes the Ethernet header is
802 			 * contiguous in the first mbuf header.
803 			 * Insure this is true.
804 			 */
805 			if (m->m_len < ETHER_HDR_LEN &&
806 			    (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
807 				printf("dummynet/ether: pullup failed, "
808 				    "dropping packet\n");
809 				break;
810 			}
811 			ether_demux(m->m_pkthdr.rcvif, m);
812 			break;
813 
814 		case DIR_OUT | PROTO_LAYER2: /* DN_TO_ETH_OUT: */
815 			ether_output_frame(ifp, m);
816 			break;
817 
818 		case DIR_DROP:
819 			/* drop the packet after some time */
820 			FREE_PKT(m);
821 			break;
822 
823 		default:
824 			printf("dummynet: bad switch %d!\n", dst);
825 			FREE_PKT(m);
826 			break;
827 		}
828 	}
829 }
830 
831 static inline int
832 tag_mbuf(struct mbuf *m, int dir, struct ip_fw_args *fwa)
833 {
834 	struct dn_pkt_tag *dt;
835 	struct m_tag *mtag;
836 
837 	mtag = m_tag_get(PACKET_TAG_DUMMYNET,
838 		    sizeof(*dt), M_NOWAIT | M_ZERO);
839 	if (mtag == NULL)
840 		return 1;		/* Cannot allocate packet header. */
841 	m_tag_prepend(m, mtag);		/* Attach to mbuf chain. */
842 	dt = (struct dn_pkt_tag *)(mtag + 1);
843 	dt->rule = fwa->rule;
844 	dt->rule.info &= IPFW_ONEPASS;	/* only keep this info */
845 	dt->dn_dir = dir;
846 	dt->ifp = fwa->flags & IPFW_ARGS_OUT ? fwa->ifp : NULL;
847 	/* dt->output tame is updated as we move through */
848 	dt->output_time = V_dn_cfg.curr_time;
849 	dt->iphdr_off = (dir & PROTO_LAYER2) ? ETHER_HDR_LEN : 0;
850 	return 0;
851 }
852 
853 /*
854  * dummynet hook for packets.
855  * We use the argument to locate the flowset fs and the sched_set sch
856  * associated to it. The we apply flow_mask and sched_mask to
857  * determine the queue and scheduler instances.
858  */
859 int
860 dummynet_io(struct mbuf **m0, struct ip_fw_args *fwa)
861 {
862 	struct mbuf *m = *m0;
863 	struct dn_fsk *fs = NULL;
864 	struct dn_sch_inst *si;
865 	struct dn_queue *q = NULL;	/* default */
866 	int fs_id, dir;
867 
868 	fs_id = (fwa->rule.info & IPFW_INFO_MASK) +
869 		((fwa->rule.info & IPFW_IS_PIPE) ? 2*DN_MAX_ID : 0);
870 	/* XXXGL: convert args to dir */
871 	if (fwa->flags & IPFW_ARGS_IN)
872 		dir = DIR_IN;
873 	else
874 		dir = DIR_OUT;
875 	if (fwa->flags & IPFW_ARGS_ETHER)
876 		dir |= PROTO_LAYER2;
877 	else if (fwa->flags & IPFW_ARGS_IP6)
878 		dir |= PROTO_IPV6;
879 	DN_BH_WLOCK();
880 	V_dn_cfg.io_pkt++;
881 	/* we could actually tag outside the lock, but who cares... */
882 	if (tag_mbuf(m, dir, fwa))
883 		goto dropit;
884 	/* XXX locate_flowset could be optimised with a direct ref. */
885 	fs = dn_ht_find(V_dn_cfg.fshash, fs_id, 0, NULL);
886 	if (fs == NULL)
887 		goto dropit;	/* This queue/pipe does not exist! */
888 	if (fs->sched == NULL)	/* should not happen */
889 		goto dropit;
890 	/* find scheduler instance, possibly applying sched_mask */
891 	si = ipdn_si_find(fs->sched, &(fwa->f_id));
892 	if (si == NULL)
893 		goto dropit;
894 	/*
895 	 * If the scheduler supports multiple queues, find the right one
896 	 * (otherwise it will be ignored by enqueue).
897 	 */
898 	if (fs->sched->fp->flags & DN_MULTIQUEUE) {
899 		q = ipdn_q_find(fs, si, &(fwa->f_id));
900 		if (q == NULL)
901 			goto dropit;
902 	}
903 	if (fs->sched->fp->enqueue(si, q, m)) {
904 		/* packet was dropped by enqueue() */
905 		m = *m0 = NULL;
906 
907 		/* dn_enqueue already increases io_pkt_drop */
908 		V_dn_cfg.io_pkt_drop--;
909 
910 		goto dropit;
911 	}
912 
913 	if (si->kflags & DN_ACTIVE) {
914 		m = *m0 = NULL; /* consumed */
915 		goto done; /* already active, nothing to do */
916 	}
917 
918 	/* compute the initial allowance */
919 	if (si->idle_time < V_dn_cfg.curr_time) {
920 	    /* Do this only on the first packet on an idle pipe */
921 	    struct dn_link *p = &fs->sched->link;
922 
923 	    si->sched_time = V_dn_cfg.curr_time;
924 	    si->credit = V_dn_cfg.io_fast ? p->bandwidth : 0;
925 	    if (p->burst) {
926 		uint64_t burst = (V_dn_cfg.curr_time - si->idle_time) * p->bandwidth;
927 		if (burst > p->burst)
928 			burst = p->burst;
929 		si->credit += burst;
930 	    }
931 	}
932 	/* pass through scheduler and delay line */
933 	m = serve_sched(NULL, si, V_dn_cfg.curr_time);
934 
935 	/* optimization -- pass it back to ipfw for immediate send */
936 	/* XXX Don't call dummynet_send() if scheduler return the packet
937 	 *     just enqueued. This avoid a lock order reversal.
938 	 *
939 	 */
940 	if (/*V_dn_cfg.io_fast &&*/ m == *m0 && (dir & PROTO_LAYER2) == 0 ) {
941 		/* fast io, rename the tag * to carry reinject info. */
942 		struct m_tag *tag = m_tag_first(m);
943 
944 		tag->m_tag_cookie = MTAG_IPFW_RULE;
945 		tag->m_tag_id = 0;
946 		V_dn_cfg.io_pkt_fast++;
947 		if (m->m_nextpkt != NULL) {
948 			printf("dummynet: fast io: pkt chain detected!\n");
949 			m->m_nextpkt = NULL;
950 		}
951 		m = NULL;
952 	} else {
953 		*m0 = NULL;
954 	}
955 done:
956 	DN_BH_WUNLOCK();
957 	if (m)
958 		dummynet_send(m);
959 	return 0;
960 
961 dropit:
962 	V_dn_cfg.io_pkt_drop++;
963 	DN_BH_WUNLOCK();
964 	if (m)
965 		FREE_PKT(m);
966 	*m0 = NULL;
967 	return (fs && (fs->fs.flags & DN_NOERROR)) ? 0 : ENOBUFS;
968 }
969