1204591Sluigi/*-
2204591Sluigi * Copyright (c) 2010 Luigi Rizzo, Riccardo Panicucci, Universita` di Pisa
3204591Sluigi * All rights reserved
4204591Sluigi *
5204591Sluigi * Redistribution and use in source and binary forms, with or without
6204591Sluigi * modification, are permitted provided that the following conditions
7204591Sluigi * are met:
8204591Sluigi * 1. Redistributions of source code must retain the above copyright
9204591Sluigi *    notice, this list of conditions and the following disclaimer.
10204591Sluigi * 2. Redistributions in binary form must reproduce the above copyright
11204591Sluigi *    notice, this list of conditions and the following disclaimer in the
12204591Sluigi *    documentation and/or other materials provided with the distribution.
13204591Sluigi *
14204591Sluigi * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15204591Sluigi * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16204591Sluigi * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17204591Sluigi * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18204591Sluigi * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19204591Sluigi * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20204591Sluigi * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21204591Sluigi * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22204591Sluigi * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23204591Sluigi * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24204591Sluigi * SUCH DAMAGE.
25204591Sluigi */
26204591Sluigi
27204591Sluigi/*
28204591Sluigi * Dummynet portions related to packet handling.
29204591Sluigi */
30204591Sluigi#include <sys/cdefs.h>
31204591Sluigi__FBSDID("$FreeBSD$");
32204591Sluigi
33204591Sluigi#include "opt_inet6.h"
34204591Sluigi
35204591Sluigi#include <sys/param.h>
36204591Sluigi#include <sys/systm.h>
37204591Sluigi#include <sys/malloc.h>
38204591Sluigi#include <sys/mbuf.h>
39204591Sluigi#include <sys/kernel.h>
40204591Sluigi#include <sys/lock.h>
41204591Sluigi#include <sys/module.h>
42204591Sluigi#include <sys/priv.h>
43204591Sluigi#include <sys/proc.h>
44204591Sluigi#include <sys/rwlock.h>
45204591Sluigi#include <sys/socket.h>
46204591Sluigi#include <sys/time.h>
47204591Sluigi#include <sys/sysctl.h>
48206461Sbz
49204591Sluigi#include <net/if.h>	/* IFNAMSIZ, struct ifaddr, ifq head, lock.h mutex.h */
50204591Sluigi#include <net/netisr.h>
51206461Sbz#include <net/vnet.h>
52206461Sbz
53204591Sluigi#include <netinet/in.h>
54204591Sluigi#include <netinet/ip.h>		/* ip_len, ip_off */
55204591Sluigi#include <netinet/ip_var.h>	/* ip_output(), IP_FORWARDING */
56204591Sluigi#include <netinet/ip_fw.h>
57204591Sluigi#include <netinet/ip_dummynet.h>
58204591Sluigi#include <netinet/if_ether.h> /* various ether_* routines */
59204591Sluigi#include <netinet/ip6.h>       /* for ip6_input, ip6_output prototypes */
60204591Sluigi#include <netinet6/ip6_var.h>
61204591Sluigi
62240494Sglebius#include <netpfil/ipfw/ip_fw_private.h>
63240494Sglebius#include <netpfil/ipfw/dn_heap.h>
64240494Sglebius#include <netpfil/ipfw/ip_dn_private.h>
65240494Sglebius#include <netpfil/ipfw/dn_sched.h>
66240494Sglebius
67204591Sluigi/*
68204591Sluigi * We keep a private variable for the simulation time, but we could
69204591Sluigi * probably use an existing one ("softticks" in sys/kern/kern_timeout.c)
70204591Sluigi * instead of dn_cfg.curr_time
71204591Sluigi */
72204591Sluigi
73204591Sluigistruct dn_parms dn_cfg;
74206428Sluigi//VNET_DEFINE(struct dn_parms, _base_dn_cfg);
75204591Sluigi
76204591Sluigistatic long tick_last;		/* Last tick duration (usec). */
77204591Sluigistatic long tick_delta;		/* Last vs standard tick diff (usec). */
78204591Sluigistatic long tick_delta_sum;	/* Accumulated tick difference (usec).*/
79204591Sluigistatic long tick_adjustment;	/* Tick adjustments done. */
80204591Sluigistatic long tick_lost;		/* Lost(coalesced) ticks number. */
81204591Sluigi/* Adjusted vs non-adjusted curr_time difference (ticks). */
82204591Sluigistatic long tick_diff;
83204591Sluigi
84204591Sluigistatic unsigned long	io_pkt;
85204591Sluigistatic unsigned long	io_pkt_fast;
86204591Sluigistatic unsigned long	io_pkt_drop;
87204591Sluigi
88204591Sluigi/*
89204591Sluigi * We use a heap to store entities for which we have pending timer events.
90204591Sluigi * The heap is checked at every tick and all entities with expired events
91204591Sluigi * are extracted.
92204591Sluigi */
93204591Sluigi
94204591SluigiMALLOC_DEFINE(M_DUMMYNET, "dummynet", "dummynet heap");
95204591Sluigi
96204591Sluigiextern	void (*bridge_dn_p)(struct mbuf *, struct ifnet *);
97204591Sluigi
98204591Sluigi#ifdef SYSCTL_NODE
99204591Sluigi
100239093Sluigi/*
101239093Sluigi * Because of the way the SYSBEGIN/SYSEND macros work on other
102239093Sluigi * platforms, there should not be functions between them.
103239093Sluigi * So keep the handlers outside the block.
104239093Sluigi */
105220832Saestatic int
106220832Saesysctl_hash_size(SYSCTL_HANDLER_ARGS)
107220832Sae{
108220832Sae	int error, value;
109220832Sae
110220832Sae	value = dn_cfg.hash_size;
111220832Sae	error = sysctl_handle_int(oidp, &value, 0, req);
112220832Sae	if (error != 0 || req->newptr == NULL)
113220832Sae		return (error);
114220832Sae	if (value < 16 || value > 65536)
115220832Sae		return (EINVAL);
116220832Sae	dn_cfg.hash_size = value;
117220832Sae	return (0);
118220832Sae}
119220832Sae
120220832Saestatic int
121220832Saesysctl_limits(SYSCTL_HANDLER_ARGS)
122220832Sae{
123220832Sae	int error;
124220832Sae	long value;
125220832Sae
126220832Sae	if (arg2 != 0)
127220832Sae		value = dn_cfg.slot_limit;
128220832Sae	else
129220832Sae		value = dn_cfg.byte_limit;
130220832Sae	error = sysctl_handle_long(oidp, &value, 0, req);
131220832Sae
132220832Sae	if (error != 0 || req->newptr == NULL)
133220832Sae		return (error);
134220832Sae	if (arg2 != 0) {
135220832Sae		if (value < 1)
136220832Sae			return (EINVAL);
137220832Sae		dn_cfg.slot_limit = value;
138220832Sae	} else {
139220832Sae		if (value < 1500)
140220832Sae			return (EINVAL);
141220832Sae		dn_cfg.byte_limit = value;
142220832Sae	}
143220832Sae	return (0);
144220832Sae}
145220832Sae
146239093SluigiSYSBEGIN(f4)
147239093Sluigi
148239093SluigiSYSCTL_DECL(_net_inet);
149239093SluigiSYSCTL_DECL(_net_inet_ip);
150239093Sluigistatic SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet, CTLFLAG_RW, 0, "Dummynet");
151239093Sluigi
152239093Sluigi/* wrapper to pass dn_cfg fields to SYSCTL_* */
153239093Sluigi//#define DC(x)	(&(VNET_NAME(_base_dn_cfg).x))
154239093Sluigi#define DC(x)	(&(dn_cfg.x))
155239093Sluigi/* parameters */
156239093Sluigi
157239093Sluigi
158239093SluigiSYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, hash_size,
159239093Sluigi    CTLTYPE_INT | CTLFLAG_RW, 0, 0, sysctl_hash_size,
160239093Sluigi    "I", "Default hash table size");
161239093Sluigi
162239093Sluigi
163220832SaeSYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, pipe_slot_limit,
164220832Sae    CTLTYPE_LONG | CTLFLAG_RW, 0, 1, sysctl_limits,
165220832Sae    "L", "Upper limit in slots for pipe queue.");
166220832SaeSYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, pipe_byte_limit,
167220832Sae    CTLTYPE_LONG | CTLFLAG_RW, 0, 0, sysctl_limits,
168220832Sae    "L", "Upper limit in bytes for pipe queue.");
169204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, io_fast,
170206428Sluigi    CTLFLAG_RW, DC(io_fast), 0, "Enable fast dummynet io.");
171204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug,
172206428Sluigi    CTLFLAG_RW, DC(debug), 0, "Dummynet debug level");
173204591Sluigi
174204591Sluigi/* RED parameters */
175204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
176206428Sluigi    CTLFLAG_RD, DC(red_lookup_depth), 0, "Depth of RED lookup table");
177204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
178206428Sluigi    CTLFLAG_RD, DC(red_avg_pkt_size), 0, "RED Medium packet size");
179204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
180206428Sluigi    CTLFLAG_RD, DC(red_max_pkt_size), 0, "RED Max packet size");
181204591Sluigi
182204591Sluigi/* time adjustment */
183204591SluigiSYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_delta,
184204591Sluigi    CTLFLAG_RD, &tick_delta, 0, "Last vs standard tick difference (usec).");
185204591SluigiSYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_delta_sum,
186204591Sluigi    CTLFLAG_RD, &tick_delta_sum, 0, "Accumulated tick difference (usec).");
187204591SluigiSYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_adjustment,
188204591Sluigi    CTLFLAG_RD, &tick_adjustment, 0, "Tick adjustments done.");
189204591SluigiSYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_diff,
190204591Sluigi    CTLFLAG_RD, &tick_diff, 0,
191204591Sluigi    "Adjusted vs non-adjusted curr_time difference (ticks).");
192204591SluigiSYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_lost,
193204591Sluigi    CTLFLAG_RD, &tick_lost, 0,
194204591Sluigi    "Number of ticks coalesced by dummynet taskqueue.");
195204591Sluigi
196213267Sluigi/* Drain parameters */
197217322SmdfSYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire,
198213267Sluigi    CTLFLAG_RW, DC(expire), 0, "Expire empty queues/pipes");
199217322SmdfSYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire_cycle,
200213267Sluigi    CTLFLAG_RD, DC(expire_cycle), 0, "Expire cycle for queues/pipes");
201213267Sluigi
202204591Sluigi/* statistics */
203204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, schk_count,
204206428Sluigi    CTLFLAG_RD, DC(schk_count), 0, "Number of schedulers");
205204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, si_count,
206206428Sluigi    CTLFLAG_RD, DC(si_count), 0, "Number of scheduler instances");
207204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, fsk_count,
208206428Sluigi    CTLFLAG_RD, DC(fsk_count), 0, "Number of flowsets");
209204591SluigiSYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, queue_count,
210206428Sluigi    CTLFLAG_RD, DC(queue_count), 0, "Number of queues");
211204591SluigiSYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt,
212204591Sluigi    CTLFLAG_RD, &io_pkt, 0,
213204591Sluigi    "Number of packets passed to dummynet.");
214204591SluigiSYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt_fast,
215204591Sluigi    CTLFLAG_RD, &io_pkt_fast, 0,
216204591Sluigi    "Number of packets bypassed dummynet scheduler.");
217204591SluigiSYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt_drop,
218204591Sluigi    CTLFLAG_RD, &io_pkt_drop, 0,
219204591Sluigi    "Number of packets dropped by dummynet.");
220206428Sluigi#undef DC
221204591SluigiSYSEND
222204591Sluigi
223204591Sluigi#endif
224204591Sluigi
225204591Sluigistatic void	dummynet_send(struct mbuf *);
226204591Sluigi
227204591Sluigi/*
228204591Sluigi * Packets processed by dummynet have an mbuf tag associated with
229204591Sluigi * them that carries their dummynet state.
230204591Sluigi * Outside dummynet, only the 'rule' field is relevant, and it must
231204591Sluigi * be at the beginning of the structure.
232204591Sluigi */
233204591Sluigistruct dn_pkt_tag {
234204591Sluigi	struct ipfw_rule_ref rule;	/* matching rule	*/
235204591Sluigi
236204591Sluigi	/* second part, dummynet specific */
237204591Sluigi	int dn_dir;		/* action when packet comes out.*/
238204591Sluigi				/* see ip_fw_private.h		*/
239204591Sluigi	uint64_t output_time;	/* when the pkt is due for delivery*/
240204591Sluigi	struct ifnet *ifp;	/* interface, for ip_output	*/
241204591Sluigi	struct _ip6dn_args ip6opt;	/* XXX ipv6 options	*/
242204591Sluigi};
243204591Sluigi
244204591Sluigi/*
245204591Sluigi * Return the mbuf tag holding the dummynet state (it should
246204591Sluigi * be the first one on the list).
247204591Sluigi */
248204591Sluigistatic struct dn_pkt_tag *
249204591Sluigidn_tag_get(struct mbuf *m)
250204591Sluigi{
251204591Sluigi	struct m_tag *mtag = m_tag_first(m);
252204591Sluigi	KASSERT(mtag != NULL &&
253204591Sluigi	    mtag->m_tag_cookie == MTAG_ABI_COMPAT &&
254204591Sluigi	    mtag->m_tag_id == PACKET_TAG_DUMMYNET,
255204591Sluigi	    ("packet on dummynet queue w/o dummynet tag!"));
256204591Sluigi	return (struct dn_pkt_tag *)(mtag+1);
257204591Sluigi}
258204591Sluigi
259204591Sluigistatic inline void
260204591Sluigimq_append(struct mq *q, struct mbuf *m)
261204591Sluigi{
262204591Sluigi	if (q->head == NULL)
263204591Sluigi		q->head = m;
264204591Sluigi	else
265204591Sluigi		q->tail->m_nextpkt = m;
266204591Sluigi	q->tail = m;
267204591Sluigi	m->m_nextpkt = NULL;
268204591Sluigi}
269204591Sluigi
270204591Sluigi/*
271204591Sluigi * Dispose a list of packet. Use a functions so if we need to do
272204591Sluigi * more work, this is a central point to do it.
273204591Sluigi */
274204591Sluigivoid dn_free_pkts(struct mbuf *mnext)
275204591Sluigi{
276204591Sluigi        struct mbuf *m;
277204591Sluigi
278204591Sluigi        while ((m = mnext) != NULL) {
279204591Sluigi                mnext = m->m_nextpkt;
280204591Sluigi                FREE_PKT(m);
281204591Sluigi        }
282204591Sluigi}
283204591Sluigi
284204591Sluigistatic int
285204591Sluigired_drops (struct dn_queue *q, int len)
286204591Sluigi{
287204591Sluigi	/*
288204591Sluigi	 * RED algorithm
289204591Sluigi	 *
290204591Sluigi	 * RED calculates the average queue size (avg) using a low-pass filter
291204591Sluigi	 * with an exponential weighted (w_q) moving average:
292204591Sluigi	 * 	avg  <-  (1-w_q) * avg + w_q * q_size
293204591Sluigi	 * where q_size is the queue length (measured in bytes or * packets).
294204591Sluigi	 *
295204591Sluigi	 * If q_size == 0, we compute the idle time for the link, and set
296204591Sluigi	 *	avg = (1 - w_q)^(idle/s)
297204591Sluigi	 * where s is the time needed for transmitting a medium-sized packet.
298204591Sluigi	 *
299204591Sluigi	 * Now, if avg < min_th the packet is enqueued.
300204591Sluigi	 * If avg > max_th the packet is dropped. Otherwise, the packet is
301204591Sluigi	 * dropped with probability P function of avg.
302204591Sluigi	 */
303204591Sluigi
304204591Sluigi	struct dn_fsk *fs = q->fs;
305204591Sluigi	int64_t p_b = 0;
306204591Sluigi
307204591Sluigi	/* Queue in bytes or packets? */
308204591Sluigi	uint32_t q_size = (fs->fs.flags & DN_QSIZE_BYTES) ?
309204591Sluigi	    q->ni.len_bytes : q->ni.length;
310204591Sluigi
311204591Sluigi	/* Average queue size estimation. */
312204591Sluigi	if (q_size != 0) {
313204591Sluigi		/* Queue is not empty, avg <- avg + (q_size - avg) * w_q */
314204591Sluigi		int diff = SCALE(q_size) - q->avg;
315204591Sluigi		int64_t v = SCALE_MUL((int64_t)diff, (int64_t)fs->w_q);
316204591Sluigi
317204591Sluigi		q->avg += (int)v;
318204591Sluigi	} else {
319204591Sluigi		/*
320204591Sluigi		 * Queue is empty, find for how long the queue has been
321204591Sluigi		 * empty and use a lookup table for computing
322204591Sluigi		 * (1 - * w_q)^(idle_time/s) where s is the time to send a
323204591Sluigi		 * (small) packet.
324204591Sluigi		 * XXX check wraps...
325204591Sluigi		 */
326204591Sluigi		if (q->avg) {
327204591Sluigi			u_int t = div64((dn_cfg.curr_time - q->q_time), fs->lookup_step);
328204591Sluigi
329204591Sluigi			q->avg = (t < fs->lookup_depth) ?
330204591Sluigi			    SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
331204591Sluigi		}
332204591Sluigi	}
333204591Sluigi
334204591Sluigi	/* Should i drop? */
335204591Sluigi	if (q->avg < fs->min_th) {
336204591Sluigi		q->count = -1;
337204591Sluigi		return (0);	/* accept packet */
338204591Sluigi	}
339204591Sluigi	if (q->avg >= fs->max_th) {	/* average queue >=  max threshold */
340204591Sluigi		if (fs->fs.flags & DN_IS_GENTLE_RED) {
341204591Sluigi			/*
342204591Sluigi			 * According to Gentle-RED, if avg is greater than
343204591Sluigi			 * max_th the packet is dropped with a probability
344204591Sluigi			 *	 p_b = c_3 * avg - c_4
345204591Sluigi			 * where c_3 = (1 - max_p) / max_th
346204591Sluigi			 *       c_4 = 1 - 2 * max_p
347204591Sluigi			 */
348204591Sluigi			p_b = SCALE_MUL((int64_t)fs->c_3, (int64_t)q->avg) -
349204591Sluigi			    fs->c_4;
350204591Sluigi		} else {
351204591Sluigi			q->count = -1;
352204591Sluigi			return (1);
353204591Sluigi		}
354204591Sluigi	} else if (q->avg > fs->min_th) {
355204591Sluigi		/*
356204591Sluigi		 * We compute p_b using the linear dropping function
357204591Sluigi		 *	 p_b = c_1 * avg - c_2
358204591Sluigi		 * where c_1 = max_p / (max_th - min_th)
359204591Sluigi		 * 	 c_2 = max_p * min_th / (max_th - min_th)
360204591Sluigi		 */
361204591Sluigi		p_b = SCALE_MUL((int64_t)fs->c_1, (int64_t)q->avg) - fs->c_2;
362204591Sluigi	}
363204591Sluigi
364204591Sluigi	if (fs->fs.flags & DN_QSIZE_BYTES)
365204591Sluigi		p_b = div64((p_b * len) , fs->max_pkt_size);
366204591Sluigi	if (++q->count == 0)
367204591Sluigi		q->random = random() & 0xffff;
368204591Sluigi	else {
369204591Sluigi		/*
370204591Sluigi		 * q->count counts packets arrived since last drop, so a greater
371204591Sluigi		 * value of q->count means a greater packet drop probability.
372204591Sluigi		 */
373204591Sluigi		if (SCALE_MUL(p_b, SCALE((int64_t)q->count)) > q->random) {
374204591Sluigi			q->count = 0;
375204591Sluigi			/* After a drop we calculate a new random value. */
376204591Sluigi			q->random = random() & 0xffff;
377204591Sluigi			return (1);	/* drop */
378204591Sluigi		}
379204591Sluigi	}
380204591Sluigi	/* End of RED algorithm. */
381204591Sluigi
382204591Sluigi	return (0);	/* accept */
383204591Sluigi
384204591Sluigi}
385204591Sluigi
386204591Sluigi/*
387204591Sluigi * Enqueue a packet in q, subject to space and queue management policy
388204591Sluigi * (whose parameters are in q->fs).
389204591Sluigi * Update stats for the queue and the scheduler.
390204591Sluigi * Return 0 on success, 1 on drop. The packet is consumed anyways.
391204591Sluigi */
392204591Sluigiint
393204591Sluigidn_enqueue(struct dn_queue *q, struct mbuf* m, int drop)
394204591Sluigi{
395204591Sluigi	struct dn_fs *f;
396204591Sluigi	struct dn_flow *ni;	/* stats for scheduler instance */
397204591Sluigi	uint64_t len;
398204591Sluigi
399204591Sluigi	if (q->fs == NULL || q->_si == NULL) {
400204591Sluigi		printf("%s fs %p si %p, dropping\n",
401204591Sluigi			__FUNCTION__, q->fs, q->_si);
402204591Sluigi		FREE_PKT(m);
403204591Sluigi		return 1;
404204591Sluigi	}
405204591Sluigi	f = &(q->fs->fs);
406204591Sluigi	ni = &q->_si->ni;
407204591Sluigi	len = m->m_pkthdr.len;
408204591Sluigi	/* Update statistics, then check reasons to drop pkt. */
409204591Sluigi	q->ni.tot_bytes += len;
410204591Sluigi	q->ni.tot_pkts++;
411204591Sluigi	ni->tot_bytes += len;
412204591Sluigi	ni->tot_pkts++;
413204591Sluigi	if (drop)
414204591Sluigi		goto drop;
415204591Sluigi	if (f->plr && random() < f->plr)
416204591Sluigi		goto drop;
417204591Sluigi	if (f->flags & DN_IS_RED && red_drops(q, m->m_pkthdr.len))
418204591Sluigi		goto drop;
419204591Sluigi	if (f->flags & DN_QSIZE_BYTES) {
420204591Sluigi		if (q->ni.len_bytes > f->qsize)
421204591Sluigi			goto drop;
422204591Sluigi	} else if (q->ni.length >= f->qsize) {
423204591Sluigi		goto drop;
424204591Sluigi	}
425204591Sluigi	mq_append(&q->mq, m);
426204591Sluigi	q->ni.length++;
427204591Sluigi	q->ni.len_bytes += len;
428204591Sluigi	ni->length++;
429204591Sluigi	ni->len_bytes += len;
430204591Sluigi	return 0;
431204591Sluigi
432204591Sluigidrop:
433204591Sluigi	io_pkt_drop++;
434204591Sluigi	q->ni.drops++;
435204591Sluigi	ni->drops++;
436204591Sluigi	FREE_PKT(m);
437204591Sluigi	return 1;
438204591Sluigi}
439204591Sluigi
440204591Sluigi/*
441204591Sluigi * Fetch packets from the delay line which are due now. If there are
442204591Sluigi * leftover packets, reinsert the delay line in the heap.
443204591Sluigi * Runs under scheduler lock.
444204591Sluigi */
445204591Sluigistatic void
446204591Sluigitransmit_event(struct mq *q, struct delay_line *dline, uint64_t now)
447204591Sluigi{
448204591Sluigi	struct mbuf *m;
449204591Sluigi	struct dn_pkt_tag *pkt = NULL;
450204591Sluigi
451204591Sluigi	dline->oid.subtype = 0; /* not in heap */
452204591Sluigi	while ((m = dline->mq.head) != NULL) {
453204591Sluigi		pkt = dn_tag_get(m);
454204591Sluigi		if (!DN_KEY_LEQ(pkt->output_time, now))
455204591Sluigi			break;
456204591Sluigi		dline->mq.head = m->m_nextpkt;
457204591Sluigi		mq_append(q, m);
458204591Sluigi	}
459204591Sluigi	if (m != NULL) {
460204591Sluigi		dline->oid.subtype = 1; /* in heap */
461204591Sluigi		heap_insert(&dn_cfg.evheap, pkt->output_time, dline);
462204591Sluigi	}
463204591Sluigi}
464204591Sluigi
465204591Sluigi/*
466204591Sluigi * Convert the additional MAC overheads/delays into an equivalent
467204591Sluigi * number of bits for the given data rate. The samples are
468204591Sluigi * in milliseconds so we need to divide by 1000.
469204591Sluigi */
470204591Sluigistatic uint64_t
471204591Sluigiextra_bits(struct mbuf *m, struct dn_schk *s)
472204591Sluigi{
473204591Sluigi	int index;
474204591Sluigi	uint64_t bits;
475204591Sluigi	struct dn_profile *pf = s->profile;
476204591Sluigi
477204591Sluigi	if (!pf || pf->samples_no == 0)
478204591Sluigi		return 0;
479204591Sluigi	index  = random() % pf->samples_no;
480204591Sluigi	bits = div64((uint64_t)pf->samples[index] * s->link.bandwidth, 1000);
481204591Sluigi	if (index >= pf->loss_level) {
482204591Sluigi		struct dn_pkt_tag *dt = dn_tag_get(m);
483204591Sluigi		if (dt)
484204591Sluigi			dt->dn_dir = DIR_DROP;
485204591Sluigi	}
486204591Sluigi	return bits;
487204591Sluigi}
488204591Sluigi
489204591Sluigi/*
490204591Sluigi * Send traffic from a scheduler instance due by 'now'.
491204591Sluigi * Return a pointer to the head of the queue.
492204591Sluigi */
493204591Sluigistatic struct mbuf *
494204591Sluigiserve_sched(struct mq *q, struct dn_sch_inst *si, uint64_t now)
495204591Sluigi{
496204591Sluigi	struct mq def_q;
497204591Sluigi	struct dn_schk *s = si->sched;
498204591Sluigi	struct mbuf *m = NULL;
499204591Sluigi	int delay_line_idle = (si->dline.mq.head == NULL);
500204591Sluigi	int done, bw;
501204591Sluigi
502204591Sluigi	if (q == NULL) {
503204591Sluigi		q = &def_q;
504204591Sluigi		q->head = NULL;
505204591Sluigi	}
506204591Sluigi
507204591Sluigi	bw = s->link.bandwidth;
508204591Sluigi	si->kflags &= ~DN_ACTIVE;
509204591Sluigi
510204591Sluigi	if (bw > 0)
511204591Sluigi		si->credit += (now - si->sched_time) * bw;
512204591Sluigi	else
513204591Sluigi		si->credit = 0;
514204591Sluigi	si->sched_time = now;
515204591Sluigi	done = 0;
516204591Sluigi	while (si->credit >= 0 && (m = s->fp->dequeue(si)) != NULL) {
517204591Sluigi		uint64_t len_scaled;
518213267Sluigi
519204591Sluigi		done++;
520204591Sluigi		len_scaled = (bw == 0) ? 0 : hz *
521213267Sluigi			(m->m_pkthdr.len * 8 + extra_bits(m, s));
522204591Sluigi		si->credit -= len_scaled;
523204591Sluigi		/* Move packet in the delay line */
524218360Sluigi		dn_tag_get(m)->output_time = dn_cfg.curr_time + s->link.delay ;
525204591Sluigi		mq_append(&si->dline.mq, m);
526204591Sluigi	}
527213267Sluigi
528204591Sluigi	/*
529204591Sluigi	 * If credit >= 0 the instance is idle, mark time.
530204591Sluigi	 * Otherwise put back in the heap, and adjust the output
531204591Sluigi	 * time of the last inserted packet, m, which was too early.
532204591Sluigi	 */
533204591Sluigi	if (si->credit >= 0) {
534204591Sluigi		si->idle_time = now;
535204591Sluigi	} else {
536204591Sluigi		uint64_t t;
537204591Sluigi		KASSERT (bw > 0, ("bw=0 and credit<0 ?"));
538204591Sluigi		t = div64(bw - 1 - si->credit, bw);
539204591Sluigi		if (m)
540204591Sluigi			dn_tag_get(m)->output_time += t;
541204591Sluigi		si->kflags |= DN_ACTIVE;
542204591Sluigi		heap_insert(&dn_cfg.evheap, now + t, si);
543204591Sluigi	}
544204591Sluigi	if (delay_line_idle && done)
545204591Sluigi		transmit_event(q, &si->dline, now);
546204591Sluigi	return q->head;
547204591Sluigi}
548204591Sluigi
549204591Sluigi/*
550204591Sluigi * The timer handler for dummynet. Time is computed in ticks, but
551204591Sluigi * but the code is tolerant to the actual rate at which this is called.
552204591Sluigi * Once complete, the function reschedules itself for the next tick.
553204591Sluigi */
554204591Sluigivoid
555204591Sluigidummynet_task(void *context, int pending)
556204591Sluigi{
557204591Sluigi	struct timeval t;
558204591Sluigi	struct mq q = { NULL, NULL }; /* queue to accumulate results */
559204591Sluigi
560206461Sbz	CURVNET_SET((struct vnet *)context);
561206428Sluigi
562204591Sluigi	DN_BH_WLOCK();
563204591Sluigi
564204591Sluigi	/* Update number of lost(coalesced) ticks. */
565204591Sluigi	tick_lost += pending - 1;
566204591Sluigi
567204591Sluigi	getmicrouptime(&t);
568204591Sluigi	/* Last tick duration (usec). */
569204591Sluigi	tick_last = (t.tv_sec - dn_cfg.prev_t.tv_sec) * 1000000 +
570204591Sluigi	(t.tv_usec - dn_cfg.prev_t.tv_usec);
571204591Sluigi	/* Last tick vs standard tick difference (usec). */
572204591Sluigi	tick_delta = (tick_last * hz - 1000000) / hz;
573204591Sluigi	/* Accumulated tick difference (usec). */
574204591Sluigi	tick_delta_sum += tick_delta;
575204591Sluigi
576204591Sluigi	dn_cfg.prev_t = t;
577204591Sluigi
578204591Sluigi	/*
579204591Sluigi	* Adjust curr_time if the accumulated tick difference is
580204591Sluigi	* greater than the 'standard' tick. Since curr_time should
581204591Sluigi	* be monotonically increasing, we do positive adjustments
582204591Sluigi	* as required, and throttle curr_time in case of negative
583204591Sluigi	* adjustment.
584204591Sluigi	*/
585204591Sluigi	dn_cfg.curr_time++;
586204591Sluigi	if (tick_delta_sum - tick >= 0) {
587204591Sluigi		int diff = tick_delta_sum / tick;
588204591Sluigi
589204591Sluigi		dn_cfg.curr_time += diff;
590204591Sluigi		tick_diff += diff;
591204591Sluigi		tick_delta_sum %= tick;
592204591Sluigi		tick_adjustment++;
593204591Sluigi	} else if (tick_delta_sum + tick <= 0) {
594204591Sluigi		dn_cfg.curr_time--;
595204591Sluigi		tick_diff--;
596204591Sluigi		tick_delta_sum += tick;
597204591Sluigi		tick_adjustment++;
598204591Sluigi	}
599204591Sluigi
600204591Sluigi	/* serve pending events, accumulate in q */
601204591Sluigi	for (;;) {
602204591Sluigi		struct dn_id *p;    /* generic parameter to handler */
603204591Sluigi
604204591Sluigi		if (dn_cfg.evheap.elements == 0 ||
605204591Sluigi		    DN_KEY_LT(dn_cfg.curr_time, HEAP_TOP(&dn_cfg.evheap)->key))
606204591Sluigi			break;
607204591Sluigi		p = HEAP_TOP(&dn_cfg.evheap)->object;
608204591Sluigi		heap_extract(&dn_cfg.evheap, NULL);
609204591Sluigi
610204591Sluigi		if (p->type == DN_SCH_I) {
611204591Sluigi			serve_sched(&q, (struct dn_sch_inst *)p, dn_cfg.curr_time);
612204591Sluigi		} else { /* extracted a delay line */
613204591Sluigi			transmit_event(&q, (struct delay_line *)p, dn_cfg.curr_time);
614204591Sluigi		}
615204591Sluigi	}
616205173Sluigi	if (dn_cfg.expire && ++dn_cfg.expire_cycle >= dn_cfg.expire) {
617205173Sluigi		dn_cfg.expire_cycle = 0;
618205173Sluigi		dn_drain_scheduler();
619205173Sluigi		dn_drain_queue();
620205173Sluigi	}
621204591Sluigi
622204591Sluigi	DN_BH_WUNLOCK();
623204591Sluigi	dn_reschedule();
624204591Sluigi	if (q.head != NULL)
625204591Sluigi		dummynet_send(q.head);
626206428Sluigi	CURVNET_RESTORE();
627204591Sluigi}
628204591Sluigi
629204591Sluigi/*
630204591Sluigi * forward a chain of packets to the proper destination.
631204591Sluigi * This runs outside the dummynet lock.
632204591Sluigi */
633204591Sluigistatic void
634204591Sluigidummynet_send(struct mbuf *m)
635204591Sluigi{
636204591Sluigi	struct mbuf *n;
637204591Sluigi
638204591Sluigi	for (; m != NULL; m = n) {
639204591Sluigi		struct ifnet *ifp = NULL;	/* gcc 3.4.6 complains */
640204591Sluigi        	struct m_tag *tag;
641204591Sluigi		int dst;
642204591Sluigi
643204591Sluigi		n = m->m_nextpkt;
644204591Sluigi		m->m_nextpkt = NULL;
645204591Sluigi		tag = m_tag_first(m);
646204591Sluigi		if (tag == NULL) { /* should not happen */
647204591Sluigi			dst = DIR_DROP;
648204591Sluigi		} else {
649204591Sluigi			struct dn_pkt_tag *pkt = dn_tag_get(m);
650204591Sluigi			/* extract the dummynet info, rename the tag
651204591Sluigi			 * to carry reinject info.
652204591Sluigi			 */
653204591Sluigi			dst = pkt->dn_dir;
654204591Sluigi			ifp = pkt->ifp;
655204591Sluigi			tag->m_tag_cookie = MTAG_IPFW_RULE;
656204591Sluigi			tag->m_tag_id = 0;
657204591Sluigi		}
658204591Sluigi
659204591Sluigi		switch (dst) {
660204591Sluigi		case DIR_OUT:
661204591Sluigi			ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
662204591Sluigi			break ;
663204591Sluigi
664204591Sluigi		case DIR_IN :
665204591Sluigi			netisr_dispatch(NETISR_IP, m);
666204591Sluigi			break;
667204591Sluigi
668204591Sluigi#ifdef INET6
669204591Sluigi		case DIR_IN | PROTO_IPV6:
670204591Sluigi			netisr_dispatch(NETISR_IPV6, m);
671204591Sluigi			break;
672204591Sluigi
673204591Sluigi		case DIR_OUT | PROTO_IPV6:
674204591Sluigi			ip6_output(m, NULL, NULL, IPV6_FORWARDING, NULL, NULL, NULL);
675204591Sluigi			break;
676204591Sluigi#endif
677204591Sluigi
678204591Sluigi		case DIR_FWD | PROTO_IFB: /* DN_TO_IFB_FWD: */
679204591Sluigi			if (bridge_dn_p != NULL)
680204591Sluigi				((*bridge_dn_p)(m, ifp));
681204591Sluigi			else
682204591Sluigi				printf("dummynet: if_bridge not loaded\n");
683204591Sluigi
684204591Sluigi			break;
685204591Sluigi
686204591Sluigi		case DIR_IN | PROTO_LAYER2: /* DN_TO_ETH_DEMUX: */
687204591Sluigi			/*
688204591Sluigi			 * The Ethernet code assumes the Ethernet header is
689204591Sluigi			 * contiguous in the first mbuf header.
690204591Sluigi			 * Insure this is true.
691204591Sluigi			 */
692204591Sluigi			if (m->m_len < ETHER_HDR_LEN &&
693204591Sluigi			    (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
694204591Sluigi				printf("dummynet/ether: pullup failed, "
695204591Sluigi				    "dropping packet\n");
696204591Sluigi				break;
697204591Sluigi			}
698204591Sluigi			ether_demux(m->m_pkthdr.rcvif, m);
699204591Sluigi			break;
700204591Sluigi
701204591Sluigi		case DIR_OUT | PROTO_LAYER2: /* N_TO_ETH_OUT: */
702204591Sluigi			ether_output_frame(ifp, m);
703204591Sluigi			break;
704204591Sluigi
705204591Sluigi		case DIR_DROP:
706204591Sluigi			/* drop the packet after some time */
707204591Sluigi			FREE_PKT(m);
708204591Sluigi			break;
709204591Sluigi
710204591Sluigi		default:
711204591Sluigi			printf("dummynet: bad switch %d!\n", dst);
712204591Sluigi			FREE_PKT(m);
713204591Sluigi			break;
714204591Sluigi		}
715204591Sluigi	}
716204591Sluigi}
717204591Sluigi
718204591Sluigistatic inline int
719204591Sluigitag_mbuf(struct mbuf *m, int dir, struct ip_fw_args *fwa)
720204591Sluigi{
721204591Sluigi	struct dn_pkt_tag *dt;
722204591Sluigi	struct m_tag *mtag;
723204591Sluigi
724204591Sluigi	mtag = m_tag_get(PACKET_TAG_DUMMYNET,
725204591Sluigi		    sizeof(*dt), M_NOWAIT | M_ZERO);
726204591Sluigi	if (mtag == NULL)
727204591Sluigi		return 1;		/* Cannot allocate packet header. */
728204591Sluigi	m_tag_prepend(m, mtag);		/* Attach to mbuf chain. */
729204591Sluigi	dt = (struct dn_pkt_tag *)(mtag + 1);
730204591Sluigi	dt->rule = fwa->rule;
731204591Sluigi	dt->rule.info &= IPFW_ONEPASS;	/* only keep this info */
732204591Sluigi	dt->dn_dir = dir;
733204591Sluigi	dt->ifp = fwa->oif;
734204591Sluigi	/* dt->output tame is updated as we move through */
735204591Sluigi	dt->output_time = dn_cfg.curr_time;
736204591Sluigi	return 0;
737204591Sluigi}
738204591Sluigi
739204591Sluigi
740204591Sluigi/*
741204591Sluigi * dummynet hook for packets.
742204591Sluigi * We use the argument to locate the flowset fs and the sched_set sch
743204591Sluigi * associated to it. The we apply flow_mask and sched_mask to
744204591Sluigi * determine the queue and scheduler instances.
745204591Sluigi *
746204591Sluigi * dir		where shall we send the packet after dummynet.
747204591Sluigi * *m0		the mbuf with the packet
748204591Sluigi * ifp		the 'ifp' parameter from the caller.
749204591Sluigi *		NULL in ip_input, destination interface in ip_output,
750204591Sluigi */
751204591Sluigiint
752204591Sluigidummynet_io(struct mbuf **m0, int dir, struct ip_fw_args *fwa)
753204591Sluigi{
754204591Sluigi	struct mbuf *m = *m0;
755204591Sluigi	struct dn_fsk *fs = NULL;
756204591Sluigi	struct dn_sch_inst *si;
757204591Sluigi	struct dn_queue *q = NULL;	/* default */
758204591Sluigi
759204591Sluigi	int fs_id = (fwa->rule.info & IPFW_INFO_MASK) +
760204591Sluigi		((fwa->rule.info & IPFW_IS_PIPE) ? 2*DN_MAX_ID : 0);
761204591Sluigi	DN_BH_WLOCK();
762204591Sluigi	io_pkt++;
763204591Sluigi	/* we could actually tag outside the lock, but who cares... */
764204591Sluigi	if (tag_mbuf(m, dir, fwa))
765204591Sluigi		goto dropit;
766204591Sluigi	if (dn_cfg.busy) {
767204591Sluigi		/* if the upper half is busy doing something expensive,
768204591Sluigi		 * lets queue the packet and move forward
769204591Sluigi		 */
770204591Sluigi		mq_append(&dn_cfg.pending, m);
771204591Sluigi		m = *m0 = NULL; /* consumed */
772204591Sluigi		goto done; /* already active, nothing to do */
773204591Sluigi	}
774204591Sluigi	/* XXX locate_flowset could be optimised with a direct ref. */
775204591Sluigi	fs = dn_ht_find(dn_cfg.fshash, fs_id, 0, NULL);
776204591Sluigi	if (fs == NULL)
777204591Sluigi		goto dropit;	/* This queue/pipe does not exist! */
778204591Sluigi	if (fs->sched == NULL)	/* should not happen */
779204591Sluigi		goto dropit;
780204591Sluigi	/* find scheduler instance, possibly applying sched_mask */
781204591Sluigi	si = ipdn_si_find(fs->sched, &(fwa->f_id));
782204591Sluigi	if (si == NULL)
783204591Sluigi		goto dropit;
784204591Sluigi	/*
785204591Sluigi	 * If the scheduler supports multiple queues, find the right one
786204591Sluigi	 * (otherwise it will be ignored by enqueue).
787204591Sluigi	 */
788204591Sluigi	if (fs->sched->fp->flags & DN_MULTIQUEUE) {
789204591Sluigi		q = ipdn_q_find(fs, si, &(fwa->f_id));
790204591Sluigi		if (q == NULL)
791204591Sluigi			goto dropit;
792204591Sluigi	}
793204591Sluigi	if (fs->sched->fp->enqueue(si, q, m)) {
794204591Sluigi		/* packet was dropped by enqueue() */
795204591Sluigi		m = *m0 = NULL;
796204591Sluigi		goto dropit;
797204591Sluigi	}
798204591Sluigi
799204591Sluigi	if (si->kflags & DN_ACTIVE) {
800204591Sluigi		m = *m0 = NULL; /* consumed */
801204591Sluigi		goto done; /* already active, nothing to do */
802204591Sluigi	}
803204591Sluigi
804204591Sluigi	/* compute the initial allowance */
805213265Sluigi	if (si->idle_time < dn_cfg.curr_time) {
806213265Sluigi	    /* Do this only on the first packet on an idle pipe */
807204591Sluigi	    struct dn_link *p = &fs->sched->link;
808213265Sluigi
809213329Sluigi	    si->sched_time = dn_cfg.curr_time;
810204591Sluigi	    si->credit = dn_cfg.io_fast ? p->bandwidth : 0;
811204591Sluigi	    if (p->burst) {
812204591Sluigi		uint64_t burst = (dn_cfg.curr_time - si->idle_time) * p->bandwidth;
813204591Sluigi		if (burst > p->burst)
814204591Sluigi			burst = p->burst;
815204591Sluigi		si->credit += burst;
816204591Sluigi	    }
817204591Sluigi	}
818204591Sluigi	/* pass through scheduler and delay line */
819204591Sluigi	m = serve_sched(NULL, si, dn_cfg.curr_time);
820204591Sluigi
821204591Sluigi	/* optimization -- pass it back to ipfw for immediate send */
822204591Sluigi	/* XXX Don't call dummynet_send() if scheduler return the packet
823204591Sluigi	 *     just enqueued. This avoid a lock order reversal.
824204591Sluigi	 *
825204591Sluigi	 */
826204591Sluigi	if (/*dn_cfg.io_fast &&*/ m == *m0 && (dir & PROTO_LAYER2) == 0 ) {
827205602Sluigi		/* fast io, rename the tag * to carry reinject info. */
828205602Sluigi		struct m_tag *tag = m_tag_first(m);
829205602Sluigi
830205602Sluigi		tag->m_tag_cookie = MTAG_IPFW_RULE;
831205602Sluigi		tag->m_tag_id = 0;
832204591Sluigi		io_pkt_fast++;
833204591Sluigi		if (m->m_nextpkt != NULL) {
834204591Sluigi			printf("dummynet: fast io: pkt chain detected!\n");
835204591Sluigi			m->m_nextpkt = NULL;
836204591Sluigi		}
837204591Sluigi		m = NULL;
838204591Sluigi	} else {
839204591Sluigi		*m0 = NULL;
840204591Sluigi	}
841204591Sluigidone:
842204591Sluigi	DN_BH_WUNLOCK();
843204591Sluigi	if (m)
844204591Sluigi		dummynet_send(m);
845204591Sluigi	return 0;
846204591Sluigi
847204591Sluigidropit:
848204591Sluigi	io_pkt_drop++;
849204591Sluigi	DN_BH_WUNLOCK();
850204591Sluigi	if (m)
851204591Sluigi		FREE_PKT(m);
852204591Sluigi	*m0 = NULL;
853204591Sluigi	return (fs && (fs->fs.flags & DN_NOERROR)) ? 0 : ENOBUFS;
854204591Sluigi}
855