xref: /freebsd/sys/netpfil/ipfw/ip_dn_io.c (revision a812392203d7c4c3f0db9d8a0f3391374c49c71f)
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 #ifdef USERSPACE
264 	// buffers from netmap need to be copied
265 	// XXX note that the routine is not expected to fail
266 	ND("append %p to %p", m, q);
267 	if (m->m_flags & M_STACK) {
268 		struct mbuf *m_new;
269 		void *p;
270 		int l, ofs;
271 
272 		ofs = m->m_data - m->__m_extbuf;
273 		// XXX allocate
274 		MGETHDR(m_new, M_NOWAIT, MT_DATA);
275 		ND("*** WARNING, volatile buf %p ext %p %d dofs %d m_new %p",
276 			m, m->__m_extbuf, m->__m_extlen, ofs, m_new);
277 		p = m_new->__m_extbuf;	/* new pointer */
278 		l = m_new->__m_extlen;	/* new len */
279 		if (l <= m->__m_extlen) {
280 			panic("extlen too large");
281 		}
282 
283 		*m_new = *m;	// copy
284 		m_new->m_flags &= ~M_STACK;
285 		m_new->__m_extbuf = p; // point to new buffer
286 		_pkt_copy(m->__m_extbuf, p, m->__m_extlen);
287 		m_new->m_data = p + ofs;
288 		m = m_new;
289 	}
290 #endif /* USERSPACE */
291 	if (q->head == NULL)
292 		q->head = m;
293 	else
294 		q->tail->m_nextpkt = m;
295 	q->count++;
296 	q->tail = m;
297 	m->m_nextpkt = NULL;
298 }
299 
300 /*
301  * Dispose a list of packet. Use a functions so if we need to do
302  * more work, this is a central point to do it.
303  */
304 void dn_free_pkts(struct mbuf *mnext)
305 {
306         struct mbuf *m;
307 
308         while ((m = mnext) != NULL) {
309                 mnext = m->m_nextpkt;
310                 FREE_PKT(m);
311         }
312 }
313 
314 static int
315 red_drops (struct dn_queue *q, int len)
316 {
317 	/*
318 	 * RED algorithm
319 	 *
320 	 * RED calculates the average queue size (avg) using a low-pass filter
321 	 * with an exponential weighted (w_q) moving average:
322 	 * 	avg  <-  (1-w_q) * avg + w_q * q_size
323 	 * where q_size is the queue length (measured in bytes or * packets).
324 	 *
325 	 * If q_size == 0, we compute the idle time for the link, and set
326 	 *	avg = (1 - w_q)^(idle/s)
327 	 * where s is the time needed for transmitting a medium-sized packet.
328 	 *
329 	 * Now, if avg < min_th the packet is enqueued.
330 	 * If avg > max_th the packet is dropped. Otherwise, the packet is
331 	 * dropped with probability P function of avg.
332 	 */
333 
334 	struct dn_fsk *fs = q->fs;
335 	int64_t p_b = 0;
336 
337 	/* Queue in bytes or packets? */
338 	uint32_t q_size = (fs->fs.flags & DN_QSIZE_BYTES) ?
339 	    q->ni.len_bytes : q->ni.length;
340 
341 	/* Average queue size estimation. */
342 	if (q_size != 0) {
343 		/* Queue is not empty, avg <- avg + (q_size - avg) * w_q */
344 		int diff = SCALE(q_size) - q->avg;
345 		int64_t v = SCALE_MUL((int64_t)diff, (int64_t)fs->w_q);
346 
347 		q->avg += (int)v;
348 	} else {
349 		/*
350 		 * Queue is empty, find for how long the queue has been
351 		 * empty and use a lookup table for computing
352 		 * (1 - * w_q)^(idle_time/s) where s is the time to send a
353 		 * (small) packet.
354 		 * XXX check wraps...
355 		 */
356 		if (q->avg) {
357 			u_int t = div64((dn_cfg.curr_time - q->q_time), fs->lookup_step);
358 
359 			q->avg = (t < fs->lookup_depth) ?
360 			    SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
361 		}
362 	}
363 
364 	/* Should i drop? */
365 	if (q->avg < fs->min_th) {
366 		q->count = -1;
367 		return (0);	/* accept packet */
368 	}
369 	if (q->avg >= fs->max_th) {	/* average queue >=  max threshold */
370 		if (fs->fs.flags & DN_IS_ECN)
371 			return (1);
372 		if (fs->fs.flags & DN_IS_GENTLE_RED) {
373 			/*
374 			 * According to Gentle-RED, if avg is greater than
375 			 * max_th the packet is dropped with a probability
376 			 *	 p_b = c_3 * avg - c_4
377 			 * where c_3 = (1 - max_p) / max_th
378 			 *       c_4 = 1 - 2 * max_p
379 			 */
380 			p_b = SCALE_MUL((int64_t)fs->c_3, (int64_t)q->avg) -
381 			    fs->c_4;
382 		} else {
383 			q->count = -1;
384 			return (1);
385 		}
386 	} else if (q->avg > fs->min_th) {
387 		if (fs->fs.flags & DN_IS_ECN)
388 			return (1);
389 		/*
390 		 * We compute p_b using the linear dropping function
391 		 *	 p_b = c_1 * avg - c_2
392 		 * where c_1 = max_p / (max_th - min_th)
393 		 * 	 c_2 = max_p * min_th / (max_th - min_th)
394 		 */
395 		p_b = SCALE_MUL((int64_t)fs->c_1, (int64_t)q->avg) - fs->c_2;
396 	}
397 
398 	if (fs->fs.flags & DN_QSIZE_BYTES)
399 		p_b = div64((p_b * len) , fs->max_pkt_size);
400 	if (++q->count == 0)
401 		q->random = random() & 0xffff;
402 	else {
403 		/*
404 		 * q->count counts packets arrived since last drop, so a greater
405 		 * value of q->count means a greater packet drop probability.
406 		 */
407 		if (SCALE_MUL(p_b, SCALE((int64_t)q->count)) > q->random) {
408 			q->count = 0;
409 			/* After a drop we calculate a new random value. */
410 			q->random = random() & 0xffff;
411 			return (1);	/* drop */
412 		}
413 	}
414 	/* End of RED algorithm. */
415 
416 	return (0);	/* accept */
417 
418 }
419 
420 /*
421  * ECN/ECT Processing (partially adopted from altq)
422  */
423 static int
424 ecn_mark(struct mbuf* m)
425 {
426 	struct ip *ip;
427 	ip = mtod(m, struct ip *);
428 
429 	switch (ip->ip_v) {
430 	case IPVERSION:
431 	{
432 		u_int8_t otos;
433 		int sum;
434 
435 		if ((ip->ip_tos & IPTOS_ECN_MASK) == IPTOS_ECN_NOTECT)
436 			return (0);	/* not-ECT */
437 		if ((ip->ip_tos & IPTOS_ECN_MASK) == IPTOS_ECN_CE)
438 			return (1);	/* already marked */
439 
440 		/*
441 		 * ecn-capable but not marked,
442 		 * mark CE and update checksum
443 		 */
444 		otos = ip->ip_tos;
445 		ip->ip_tos |= IPTOS_ECN_CE;
446 		/*
447 		 * update checksum (from RFC1624)
448 		 *	   HC' = ~(~HC + ~m + m')
449 		 */
450 		sum = ~ntohs(ip->ip_sum) & 0xffff;
451 		sum += (~otos & 0xffff) + ip->ip_tos;
452 		sum = (sum >> 16) + (sum & 0xffff);
453 		sum += (sum >> 16);  /* add carry */
454 		ip->ip_sum = htons(~sum & 0xffff);
455 		return (1);
456 	}
457 #ifdef INET6
458 	case (IPV6_VERSION >> 4):
459 	{
460 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
461 		u_int32_t flowlabel;
462 
463 		flowlabel = ntohl(ip6->ip6_flow);
464 		if ((flowlabel >> 28) != 6)
465 			return (0);	/* version mismatch! */
466 		if ((flowlabel & (IPTOS_ECN_MASK << 20)) ==
467 		    (IPTOS_ECN_NOTECT << 20))
468 			return (0);	/* not-ECT */
469 		if ((flowlabel & (IPTOS_ECN_MASK << 20)) ==
470 		    (IPTOS_ECN_CE << 20))
471 			return (1);	/* already marked */
472 		/*
473 		 * ecn-capable but not marked, mark CE
474 		 */
475 		flowlabel |= (IPTOS_ECN_CE << 20);
476 		ip6->ip6_flow = htonl(flowlabel);
477 		return (1);
478 	}
479 #endif
480 	}
481 	return (0);
482 }
483 
484 /*
485  * Enqueue a packet in q, subject to space and queue management policy
486  * (whose parameters are in q->fs).
487  * Update stats for the queue and the scheduler.
488  * Return 0 on success, 1 on drop. The packet is consumed anyways.
489  */
490 int
491 dn_enqueue(struct dn_queue *q, struct mbuf* m, int drop)
492 {
493 	struct dn_fs *f;
494 	struct dn_flow *ni;	/* stats for scheduler instance */
495 	uint64_t len;
496 
497 	if (q->fs == NULL || q->_si == NULL) {
498 		printf("%s fs %p si %p, dropping\n",
499 			__FUNCTION__, q->fs, q->_si);
500 		FREE_PKT(m);
501 		return 1;
502 	}
503 	f = &(q->fs->fs);
504 	ni = &q->_si->ni;
505 	len = m->m_pkthdr.len;
506 	/* Update statistics, then check reasons to drop pkt. */
507 	q->ni.tot_bytes += len;
508 	q->ni.tot_pkts++;
509 	ni->tot_bytes += len;
510 	ni->tot_pkts++;
511 	if (drop)
512 		goto drop;
513 	if (f->plr && random() < f->plr)
514 		goto drop;
515 	if (f->flags & DN_IS_RED && red_drops(q, m->m_pkthdr.len)) {
516 		if (!(f->flags & DN_IS_ECN) || !ecn_mark(m))
517 			goto drop;
518 	}
519 	if (f->flags & DN_QSIZE_BYTES) {
520 		if (q->ni.len_bytes > f->qsize)
521 			goto drop;
522 	} else if (q->ni.length >= f->qsize) {
523 		goto drop;
524 	}
525 	mq_append(&q->mq, m);
526 	q->ni.length++;
527 	q->ni.len_bytes += len;
528 	ni->length++;
529 	ni->len_bytes += len;
530 	return (0);
531 
532 drop:
533 	io_pkt_drop++;
534 	q->ni.drops++;
535 	ni->drops++;
536 	FREE_PKT(m);
537 	return (1);
538 }
539 
540 /*
541  * Fetch packets from the delay line which are due now. If there are
542  * leftover packets, reinsert the delay line in the heap.
543  * Runs under scheduler lock.
544  */
545 static void
546 transmit_event(struct mq *q, struct delay_line *dline, uint64_t now)
547 {
548 	struct mbuf *m;
549 	struct dn_pkt_tag *pkt = NULL;
550 
551 	dline->oid.subtype = 0; /* not in heap */
552 	while ((m = dline->mq.head) != NULL) {
553 		pkt = dn_tag_get(m);
554 		if (!DN_KEY_LEQ(pkt->output_time, now))
555 			break;
556 		dline->mq.head = m->m_nextpkt;
557 		dline->mq.count--;
558 		mq_append(q, m);
559 	}
560 	if (m != NULL) {
561 		dline->oid.subtype = 1; /* in heap */
562 		heap_insert(&dn_cfg.evheap, pkt->output_time, dline);
563 	}
564 }
565 
566 /*
567  * Convert the additional MAC overheads/delays into an equivalent
568  * number of bits for the given data rate. The samples are
569  * in milliseconds so we need to divide by 1000.
570  */
571 static uint64_t
572 extra_bits(struct mbuf *m, struct dn_schk *s)
573 {
574 	int index;
575 	uint64_t bits;
576 	struct dn_profile *pf = s->profile;
577 
578 	if (!pf || pf->samples_no == 0)
579 		return 0;
580 	index  = random() % pf->samples_no;
581 	bits = div64((uint64_t)pf->samples[index] * s->link.bandwidth, 1000);
582 	if (index >= pf->loss_level) {
583 		struct dn_pkt_tag *dt = dn_tag_get(m);
584 		if (dt)
585 			dt->dn_dir = DIR_DROP;
586 	}
587 	return bits;
588 }
589 
590 /*
591  * Send traffic from a scheduler instance due by 'now'.
592  * Return a pointer to the head of the queue.
593  */
594 static struct mbuf *
595 serve_sched(struct mq *q, struct dn_sch_inst *si, uint64_t now)
596 {
597 	struct mq def_q;
598 	struct dn_schk *s = si->sched;
599 	struct mbuf *m = NULL;
600 	int delay_line_idle = (si->dline.mq.head == NULL);
601 	int done, bw;
602 
603 	if (q == NULL) {
604 		q = &def_q;
605 		q->head = NULL;
606 	}
607 
608 	bw = s->link.bandwidth;
609 	si->kflags &= ~DN_ACTIVE;
610 
611 	if (bw > 0)
612 		si->credit += (now - si->sched_time) * bw;
613 	else
614 		si->credit = 0;
615 	si->sched_time = now;
616 	done = 0;
617 	while (si->credit >= 0 && (m = s->fp->dequeue(si)) != NULL) {
618 		uint64_t len_scaled;
619 
620 		done++;
621 		len_scaled = (bw == 0) ? 0 : hz *
622 			(m->m_pkthdr.len * 8 + extra_bits(m, s));
623 		si->credit -= len_scaled;
624 		/* Move packet in the delay line */
625 		dn_tag_get(m)->output_time = dn_cfg.curr_time + s->link.delay ;
626 		mq_append(&si->dline.mq, m);
627 	}
628 
629 	/*
630 	 * If credit >= 0 the instance is idle, mark time.
631 	 * Otherwise put back in the heap, and adjust the output
632 	 * time of the last inserted packet, m, which was too early.
633 	 */
634 	if (si->credit >= 0) {
635 		si->idle_time = now;
636 	} else {
637 		uint64_t t;
638 		KASSERT (bw > 0, ("bw=0 and credit<0 ?"));
639 		t = div64(bw - 1 - si->credit, bw);
640 		if (m)
641 			dn_tag_get(m)->output_time += t;
642 		si->kflags |= DN_ACTIVE;
643 		heap_insert(&dn_cfg.evheap, now + t, si);
644 	}
645 	if (delay_line_idle && done)
646 		transmit_event(q, &si->dline, now);
647 	return q->head;
648 }
649 
650 /*
651  * The timer handler for dummynet. Time is computed in ticks, but
652  * but the code is tolerant to the actual rate at which this is called.
653  * Once complete, the function reschedules itself for the next tick.
654  */
655 void
656 dummynet_task(void *context, int pending)
657 {
658 	struct timeval t;
659 	struct mq q = { NULL, NULL }; /* queue to accumulate results */
660 
661 	CURVNET_SET((struct vnet *)context);
662 
663 	DN_BH_WLOCK();
664 
665 	/* Update number of lost(coalesced) ticks. */
666 	tick_lost += pending - 1;
667 
668 	getmicrouptime(&t);
669 	/* Last tick duration (usec). */
670 	tick_last = (t.tv_sec - dn_cfg.prev_t.tv_sec) * 1000000 +
671 	(t.tv_usec - dn_cfg.prev_t.tv_usec);
672 	/* Last tick vs standard tick difference (usec). */
673 	tick_delta = (tick_last * hz - 1000000) / hz;
674 	/* Accumulated tick difference (usec). */
675 	tick_delta_sum += tick_delta;
676 
677 	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 	dn_cfg.curr_time++;
687 	if (tick_delta_sum - tick >= 0) {
688 		int diff = tick_delta_sum / tick;
689 
690 		dn_cfg.curr_time += diff;
691 		tick_diff += diff;
692 		tick_delta_sum %= tick;
693 		tick_adjustment++;
694 	} else if (tick_delta_sum + tick <= 0) {
695 		dn_cfg.curr_time--;
696 		tick_diff--;
697 		tick_delta_sum += tick;
698 		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 (dn_cfg.evheap.elements == 0 ||
706 		    DN_KEY_LT(dn_cfg.curr_time, HEAP_TOP(&dn_cfg.evheap)->key))
707 			break;
708 		p = HEAP_TOP(&dn_cfg.evheap)->object;
709 		heap_extract(&dn_cfg.evheap, NULL);
710 
711 		if (p->type == DN_SCH_I) {
712 			serve_sched(&q, (struct dn_sch_inst *)p, dn_cfg.curr_time);
713 		} else { /* extracted a delay line */
714 			transmit_event(&q, (struct delay_line *)p, dn_cfg.curr_time);
715 		}
716 	}
717 	if (dn_cfg.expire && ++dn_cfg.expire_cycle >= dn_cfg.expire) {
718 		dn_cfg.expire_cycle = 0;
719 		dn_drain_scheduler();
720 		dn_drain_queue();
721 	}
722 
723 	DN_BH_WUNLOCK();
724 	dn_reschedule();
725 	if (q.head != NULL)
726 		dummynet_send(q.head);
727 	CURVNET_RESTORE();
728 }
729 
730 /*
731  * forward a chain of packets to the proper destination.
732  * This runs outside the dummynet lock.
733  */
734 static void
735 dummynet_send(struct mbuf *m)
736 {
737 	struct mbuf *n;
738 
739 	for (; m != NULL; m = n) {
740 		struct ifnet *ifp = NULL;	/* gcc 3.4.6 complains */
741         	struct m_tag *tag;
742 		int dst;
743 
744 		n = m->m_nextpkt;
745 		m->m_nextpkt = NULL;
746 		tag = m_tag_first(m);
747 		if (tag == NULL) { /* should not happen */
748 			dst = DIR_DROP;
749 		} else {
750 			struct dn_pkt_tag *pkt = dn_tag_get(m);
751 			/* extract the dummynet info, rename the tag
752 			 * to carry reinject info.
753 			 */
754 			if (pkt->dn_dir == (DIR_OUT | PROTO_LAYER2) &&
755 				pkt->ifp == NULL) {
756 				dst = DIR_DROP;
757 			} else {
758 				dst = pkt->dn_dir;
759 				ifp = pkt->ifp;
760 				tag->m_tag_cookie = MTAG_IPFW_RULE;
761 				tag->m_tag_id = 0;
762 			}
763 		}
764 
765 		switch (dst) {
766 		case DIR_OUT:
767 			ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
768 			break ;
769 
770 		case DIR_IN :
771 			netisr_dispatch(NETISR_IP, m);
772 			break;
773 
774 #ifdef INET6
775 		case DIR_IN | PROTO_IPV6:
776 			netisr_dispatch(NETISR_IPV6, m);
777 			break;
778 
779 		case DIR_OUT | PROTO_IPV6:
780 			ip6_output(m, NULL, NULL, IPV6_FORWARDING, NULL, NULL, NULL);
781 			break;
782 #endif
783 
784 		case DIR_FWD | PROTO_IFB: /* DN_TO_IFB_FWD: */
785 			if (bridge_dn_p != NULL)
786 				((*bridge_dn_p)(m, ifp));
787 			else
788 				printf("dummynet: if_bridge not loaded\n");
789 
790 			break;
791 
792 		case DIR_IN | PROTO_LAYER2: /* DN_TO_ETH_DEMUX: */
793 			/*
794 			 * The Ethernet code assumes the Ethernet header is
795 			 * contiguous in the first mbuf header.
796 			 * Insure this is true.
797 			 */
798 			if (m->m_len < ETHER_HDR_LEN &&
799 			    (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
800 				printf("dummynet/ether: pullup failed, "
801 				    "dropping packet\n");
802 				break;
803 			}
804 			ether_demux(m->m_pkthdr.rcvif, m);
805 			break;
806 
807 		case DIR_OUT | PROTO_LAYER2: /* N_TO_ETH_OUT: */
808 			ether_output_frame(ifp, m);
809 			break;
810 
811 		case DIR_DROP:
812 			/* drop the packet after some time */
813 			FREE_PKT(m);
814 			break;
815 
816 		default:
817 			printf("dummynet: bad switch %d!\n", dst);
818 			FREE_PKT(m);
819 			break;
820 		}
821 	}
822 }
823 
824 static inline int
825 tag_mbuf(struct mbuf *m, int dir, struct ip_fw_args *fwa)
826 {
827 	struct dn_pkt_tag *dt;
828 	struct m_tag *mtag;
829 
830 	mtag = m_tag_get(PACKET_TAG_DUMMYNET,
831 		    sizeof(*dt), M_NOWAIT | M_ZERO);
832 	if (mtag == NULL)
833 		return 1;		/* Cannot allocate packet header. */
834 	m_tag_prepend(m, mtag);		/* Attach to mbuf chain. */
835 	dt = (struct dn_pkt_tag *)(mtag + 1);
836 	dt->rule = fwa->rule;
837 	dt->rule.info &= IPFW_ONEPASS;	/* only keep this info */
838 	dt->dn_dir = dir;
839 	dt->ifp = fwa->oif;
840 	/* dt->output tame is updated as we move through */
841 	dt->output_time = dn_cfg.curr_time;
842 	return 0;
843 }
844 
845 
846 /*
847  * dummynet hook for packets.
848  * We use the argument to locate the flowset fs and the sched_set sch
849  * associated to it. The we apply flow_mask and sched_mask to
850  * determine the queue and scheduler instances.
851  *
852  * dir		where shall we send the packet after dummynet.
853  * *m0		the mbuf with the packet
854  * ifp		the 'ifp' parameter from the caller.
855  *		NULL in ip_input, destination interface in ip_output,
856  */
857 int
858 dummynet_io(struct mbuf **m0, int dir, struct ip_fw_args *fwa)
859 {
860 	struct mbuf *m = *m0;
861 	struct dn_fsk *fs = NULL;
862 	struct dn_sch_inst *si;
863 	struct dn_queue *q = NULL;	/* default */
864 
865 	int fs_id = (fwa->rule.info & IPFW_INFO_MASK) +
866 		((fwa->rule.info & IPFW_IS_PIPE) ? 2*DN_MAX_ID : 0);
867 	DN_BH_WLOCK();
868 	io_pkt++;
869 	/* we could actually tag outside the lock, but who cares... */
870 	if (tag_mbuf(m, dir, fwa))
871 		goto dropit;
872 	if (dn_cfg.busy) {
873 		/* if the upper half is busy doing something expensive,
874 		 * lets queue the packet and move forward
875 		 */
876 		mq_append(&dn_cfg.pending, m);
877 		m = *m0 = NULL; /* consumed */
878 		goto done; /* already active, nothing to do */
879 	}
880 	/* XXX locate_flowset could be optimised with a direct ref. */
881 	fs = dn_ht_find(dn_cfg.fshash, fs_id, 0, NULL);
882 	if (fs == NULL)
883 		goto dropit;	/* This queue/pipe does not exist! */
884 	if (fs->sched == NULL)	/* should not happen */
885 		goto dropit;
886 	/* find scheduler instance, possibly applying sched_mask */
887 	si = ipdn_si_find(fs->sched, &(fwa->f_id));
888 	if (si == NULL)
889 		goto dropit;
890 	/*
891 	 * If the scheduler supports multiple queues, find the right one
892 	 * (otherwise it will be ignored by enqueue).
893 	 */
894 	if (fs->sched->fp->flags & DN_MULTIQUEUE) {
895 		q = ipdn_q_find(fs, si, &(fwa->f_id));
896 		if (q == NULL)
897 			goto dropit;
898 	}
899 	if (fs->sched->fp->enqueue(si, q, m)) {
900 		/* packet was dropped by enqueue() */
901 		m = *m0 = NULL;
902 		goto dropit;
903 	}
904 
905 	if (si->kflags & DN_ACTIVE) {
906 		m = *m0 = NULL; /* consumed */
907 		goto done; /* already active, nothing to do */
908 	}
909 
910 	/* compute the initial allowance */
911 	if (si->idle_time < dn_cfg.curr_time) {
912 	    /* Do this only on the first packet on an idle pipe */
913 	    struct dn_link *p = &fs->sched->link;
914 
915 	    si->sched_time = dn_cfg.curr_time;
916 	    si->credit = dn_cfg.io_fast ? p->bandwidth : 0;
917 	    if (p->burst) {
918 		uint64_t burst = (dn_cfg.curr_time - si->idle_time) * p->bandwidth;
919 		if (burst > p->burst)
920 			burst = p->burst;
921 		si->credit += burst;
922 	    }
923 	}
924 	/* pass through scheduler and delay line */
925 	m = serve_sched(NULL, si, dn_cfg.curr_time);
926 
927 	/* optimization -- pass it back to ipfw for immediate send */
928 	/* XXX Don't call dummynet_send() if scheduler return the packet
929 	 *     just enqueued. This avoid a lock order reversal.
930 	 *
931 	 */
932 	if (/*dn_cfg.io_fast &&*/ m == *m0 && (dir & PROTO_LAYER2) == 0 ) {
933 		/* fast io, rename the tag * to carry reinject info. */
934 		struct m_tag *tag = m_tag_first(m);
935 
936 		tag->m_tag_cookie = MTAG_IPFW_RULE;
937 		tag->m_tag_id = 0;
938 		io_pkt_fast++;
939 		if (m->m_nextpkt != NULL) {
940 			printf("dummynet: fast io: pkt chain detected!\n");
941 			m->m_nextpkt = NULL;
942 		}
943 		m = NULL;
944 	} else {
945 		*m0 = NULL;
946 	}
947 done:
948 	DN_BH_WUNLOCK();
949 	if (m)
950 		dummynet_send(m);
951 	return 0;
952 
953 dropit:
954 	io_pkt_drop++;
955 	DN_BH_WUNLOCK();
956 	if (m)
957 		FREE_PKT(m);
958 	*m0 = NULL;
959 	return (fs && (fs->fs.flags & DN_NOERROR)) ? 0 : ENOBUFS;
960 }
961