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