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