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