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: stable/12/sys/netpfil/ipfw/ip_dn_io.c 370413 2021-08-26 12:07:42Z kp $");
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  */
79 VNET_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 
88 MALLOC_DEFINE(M_DUMMYNET, "dummynet", "dummynet heap");
89 
90 extern	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  */
99 static int
sysctl_hash_size(SYSCTL_HANDLER_ARGS)100 sysctl_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 
114 static int
sysctl_limits(SYSCTL_HANDLER_ARGS)115 sysctl_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 
140 SYSBEGIN(f4)
141 
142 SYSCTL_DECL(_net_inet);
143 SYSCTL_DECL(_net_inet_ip);
144 #ifdef NEW_AQM
145 SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet, CTLFLAG_RW, 0, "Dummynet");
146 #else
147 static 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 
156 SYSCTL_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 
161 SYSCTL_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.");
164 SYSCTL_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.");
167 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, io_fast,
168     CTLFLAG_RW | CTLFLAG_VNET, DC(io_fast), 0, "Enable fast dummynet io.");
169 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug,
170     CTLFLAG_RW | CTLFLAG_VNET, DC(debug), 0, "Dummynet debug level");
171 
172 /* RED parameters */
173 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
174     CTLFLAG_RD | CTLFLAG_VNET, DC(red_lookup_depth), 0, "Depth of RED lookup table");
175 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
176     CTLFLAG_RD | CTLFLAG_VNET, DC(red_avg_pkt_size), 0, "RED Medium packet size");
177 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
178     CTLFLAG_RD | CTLFLAG_VNET, DC(red_max_pkt_size), 0, "RED Max packet size");
179 
180 /* time adjustment */
181 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_delta,
182     CTLFLAG_RD | CTLFLAG_VNET, DC(tick_delta), 0, "Last vs standard tick difference (usec).");
183 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_delta_sum,
184     CTLFLAG_RD | CTLFLAG_VNET, DC(tick_delta_sum), 0, "Accumulated tick difference (usec).");
185 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_adjustment,
186     CTLFLAG_RD | CTLFLAG_VNET, DC(tick_adjustment), 0, "Tick adjustments done.");
187 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_diff,
188     CTLFLAG_RD | CTLFLAG_VNET, DC(tick_diff), 0,
189     "Adjusted vs non-adjusted curr_time difference (ticks).");
190 SYSCTL_LONG(_net_inet_ip_dummynet, OID_AUTO, tick_lost,
191     CTLFLAG_RD | CTLFLAG_VNET, DC(tick_lost), 0,
192     "Number of ticks coalesced by dummynet taskqueue.");
193 
194 /* Drain parameters */
195 SYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire,
196     CTLFLAG_RW | CTLFLAG_VNET, DC(expire), 0, "Expire empty queues/pipes");
197 SYSCTL_UINT(_net_inet_ip_dummynet, OID_AUTO, expire_cycle,
198     CTLFLAG_RD | CTLFLAG_VNET, DC(expire_cycle), 0, "Expire cycle for queues/pipes");
199 
200 /* statistics */
201 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, schk_count,
202     CTLFLAG_RD | CTLFLAG_VNET, DC(schk_count), 0, "Number of schedulers");
203 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, si_count,
204     CTLFLAG_RD | CTLFLAG_VNET, DC(si_count), 0, "Number of scheduler instances");
205 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, fsk_count,
206     CTLFLAG_RD | CTLFLAG_VNET, DC(fsk_count), 0, "Number of flowsets");
207 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, queue_count,
208     CTLFLAG_RD | CTLFLAG_VNET, DC(queue_count), 0, "Number of queues");
209 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt,
210     CTLFLAG_RD | CTLFLAG_VNET, DC(io_pkt), 0,
211     "Number of packets passed to dummynet.");
212 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt_fast,
213     CTLFLAG_RD | CTLFLAG_VNET, DC(io_pkt_fast), 0,
214     "Number of packets bypassed dummynet scheduler.");
215 SYSCTL_ULONG(_net_inet_ip_dummynet, OID_AUTO, io_pkt_drop,
216     CTLFLAG_RD | CTLFLAG_VNET, DC(io_pkt_drop), 0,
217     "Number of packets dropped by dummynet.");
218 #undef DC
219 SYSEND
220 
221 #endif
222 
223 static 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  */
229 struct dn_pkt_tag *
dn_tag_get(struct mbuf * m)230 dn_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
249 static inline void
mq_append(struct mq * q,struct mbuf * m)250 mq_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  */
dn_free_pkts(struct mbuf * mnext)294 void 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 
304 static int
red_drops(struct dn_queue * q,int len)305 red_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
414 static
415 #endif
416 int
ecn_mark(struct mbuf * m)417 ecn_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  */
474 int
dn_enqueue(struct dn_queue * q,struct mbuf * m,int drop)475 dn_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 
521 drop:
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  */
534 static void
transmit_event(struct mq * q,struct delay_line * dline,uint64_t now)535 transmit_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  */
560 static uint64_t
extra_bits(struct mbuf * m,struct dn_schk * s)561 extra_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  */
583 static struct mbuf *
serve_sched(struct mq * q,struct dn_sch_inst * si,uint64_t now)584 serve_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;
591 	uint32_t bw;
592 
593 	if (q == NULL) {
594 		q = &def_q;
595 		q->head = NULL;
596 	}
597 
598 	bw = s->link.bandwidth;
599 	si->kflags &= ~DN_ACTIVE;
600 
601 	if (bw > 0)
602 		si->credit += (now - si->sched_time) * bw;
603 	else
604 		si->credit = 0;
605 	si->sched_time = now;
606 	done = 0;
607 	while (si->credit >= 0 && (m = s->fp->dequeue(si)) != NULL) {
608 		uint64_t len_scaled;
609 
610 		done++;
611 		len_scaled = (bw == 0) ? 0 : hz *
612 			(m->m_pkthdr.len * 8 + extra_bits(m, s));
613 		si->credit -= len_scaled;
614 		/* Move packet in the delay line */
615 		dn_tag_get(m)->output_time = V_dn_cfg.curr_time + s->link.delay ;
616 		mq_append(&si->dline.mq, m);
617 	}
618 
619 	/*
620 	 * If credit >= 0 the instance is idle, mark time.
621 	 * Otherwise put back in the heap, and adjust the output
622 	 * time of the last inserted packet, m, which was too early.
623 	 */
624 	if (si->credit >= 0) {
625 		si->idle_time = now;
626 	} else {
627 		uint64_t t;
628 		KASSERT (bw > 0, ("bw=0 and credit<0 ?"));
629 		t = div64(bw - 1 - si->credit, bw);
630 		if (m)
631 			dn_tag_get(m)->output_time += t;
632 		si->kflags |= DN_ACTIVE;
633 		heap_insert(&V_dn_cfg.evheap, now + t, si);
634 	}
635 	if (delay_line_idle && done)
636 		transmit_event(q, &si->dline, now);
637 	return q->head;
638 }
639 
640 /*
641  * The timer handler for dummynet. Time is computed in ticks, but
642  * but the code is tolerant to the actual rate at which this is called.
643  * Once complete, the function reschedules itself for the next tick.
644  */
645 void
dummynet_task(void * context,int pending)646 dummynet_task(void *context, int pending)
647 {
648 	struct timeval t;
649 	struct mq q = { NULL, NULL }; /* queue to accumulate results */
650 	struct epoch_tracker et;
651 
652 	VNET_ITERATOR_DECL(vnet_iter);
653 	VNET_LIST_RLOCK();
654 	NET_EPOCH_ENTER_ET(et);
655 
656 	VNET_FOREACH(vnet_iter) {
657 		memset(&q, 0, sizeof(struct mq));
658 		CURVNET_SET(vnet_iter);
659 
660 		DN_BH_WLOCK();
661 
662 		/* Update number of lost(coalesced) ticks. */
663 		V_dn_cfg.tick_lost += pending - 1;
664 
665 		getmicrouptime(&t);
666 		/* Last tick duration (usec). */
667 		V_dn_cfg.tick_last = (t.tv_sec - V_dn_cfg.prev_t.tv_sec) * 1000000 +
668 		(t.tv_usec - V_dn_cfg.prev_t.tv_usec);
669 		/* Last tick vs standard tick difference (usec). */
670 		V_dn_cfg.tick_delta = (V_dn_cfg.tick_last * hz - 1000000) / hz;
671 		/* Accumulated tick difference (usec). */
672 		V_dn_cfg.tick_delta_sum += V_dn_cfg.tick_delta;
673 
674 		V_dn_cfg.prev_t = t;
675 
676 		/*
677 		* Adjust curr_time if the accumulated tick difference is
678 		* greater than the 'standard' tick. Since curr_time should
679 		* be monotonically increasing, we do positive adjustments
680 		* as required, and throttle curr_time in case of negative
681 		* adjustment.
682 		*/
683 		V_dn_cfg.curr_time++;
684 		if (V_dn_cfg.tick_delta_sum - tick >= 0) {
685 			int diff = V_dn_cfg.tick_delta_sum / tick;
686 
687 			V_dn_cfg.curr_time += diff;
688 			V_dn_cfg.tick_diff += diff;
689 			V_dn_cfg.tick_delta_sum %= tick;
690 			V_dn_cfg.tick_adjustment++;
691 		} else if (V_dn_cfg.tick_delta_sum + tick <= 0) {
692 			V_dn_cfg.curr_time--;
693 			V_dn_cfg.tick_diff--;
694 			V_dn_cfg.tick_delta_sum += tick;
695 			V_dn_cfg.tick_adjustment++;
696 		}
697 
698 		/* serve pending events, accumulate in q */
699 		for (;;) {
700 			struct dn_id *p;    /* generic parameter to handler */
701 
702 			if (V_dn_cfg.evheap.elements == 0 ||
703 			    DN_KEY_LT(V_dn_cfg.curr_time, HEAP_TOP(&V_dn_cfg.evheap)->key))
704 				break;
705 			p = HEAP_TOP(&V_dn_cfg.evheap)->object;
706 			heap_extract(&V_dn_cfg.evheap, NULL);
707 			if (p->type == DN_SCH_I) {
708 				serve_sched(&q, (struct dn_sch_inst *)p, V_dn_cfg.curr_time);
709 			} else { /* extracted a delay line */
710 				transmit_event(&q, (struct delay_line *)p, V_dn_cfg.curr_time);
711 			}
712 		}
713 		if (V_dn_cfg.expire && ++V_dn_cfg.expire_cycle >= V_dn_cfg.expire) {
714 			V_dn_cfg.expire_cycle = 0;
715 			dn_drain_scheduler();
716 			dn_drain_queue();
717 		}
718 		DN_BH_WUNLOCK();
719 		if (q.head != NULL)
720 			dummynet_send(q.head);
721 
722 		CURVNET_RESTORE();
723 	}
724 	NET_EPOCH_EXIT_ET(et);
725 	VNET_LIST_RUNLOCK();
726 
727 	/* Schedule our next run. */
728 	dn_reschedule();
729 }
730 
731 /*
732  * forward a chain of packets to the proper destination.
733  * This runs outside the dummynet lock.
734  */
735 static void
dummynet_send(struct mbuf * m)736 dummynet_send(struct mbuf *m)
737 {
738 	struct mbuf *n;
739 
740 	for (; m != NULL; m = n) {
741 		struct ifnet *ifp = NULL;	/* gcc 3.4.6 complains */
742         	struct m_tag *tag;
743 		int dst;
744 
745 		n = m->m_nextpkt;
746 		m->m_nextpkt = NULL;
747 		tag = m_tag_first(m);
748 		if (tag == NULL) { /* should not happen */
749 			dst = DIR_DROP;
750 		} else {
751 			struct dn_pkt_tag *pkt = dn_tag_get(m);
752 			/* extract the dummynet info, rename the tag
753 			 * to carry reinject info.
754 			 */
755 			if (pkt->dn_dir == (DIR_OUT | PROTO_LAYER2) &&
756 				pkt->ifp == NULL) {
757 				dst = DIR_DROP;
758 			} else {
759 				dst = pkt->dn_dir;
760 				ifp = pkt->ifp;
761 				tag->m_tag_cookie = MTAG_IPFW_RULE;
762 				tag->m_tag_id = 0;
763 			}
764 		}
765 
766 		switch (dst) {
767 		case DIR_OUT:
768 			ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
769 			break ;
770 
771 		case DIR_IN :
772 			netisr_dispatch(NETISR_IP, m);
773 			break;
774 
775 #ifdef INET6
776 		case DIR_IN | PROTO_IPV6:
777 			netisr_dispatch(NETISR_IPV6, m);
778 			break;
779 
780 		case DIR_OUT | PROTO_IPV6:
781 			ip6_output(m, NULL, NULL, IPV6_FORWARDING, NULL, NULL, NULL);
782 			break;
783 #endif
784 
785 		case DIR_FWD | PROTO_IFB: /* DN_TO_IFB_FWD: */
786 			if (bridge_dn_p != NULL)
787 				((*bridge_dn_p)(m, ifp));
788 			else
789 				printf("dummynet: if_bridge not loaded\n");
790 
791 			break;
792 
793 		case DIR_IN | PROTO_LAYER2: /* DN_TO_ETH_DEMUX: */
794 			/*
795 			 * The Ethernet code assumes the Ethernet header is
796 			 * contiguous in the first mbuf header.
797 			 * Insure this is true.
798 			 */
799 			if (m->m_len < ETHER_HDR_LEN &&
800 			    (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
801 				printf("dummynet/ether: pullup failed, "
802 				    "dropping packet\n");
803 				break;
804 			}
805 			ether_demux(m->m_pkthdr.rcvif, m);
806 			break;
807 
808 		case DIR_OUT | PROTO_LAYER2: /* DN_TO_ETH_OUT: */
809 			ether_output_frame(ifp, m);
810 			break;
811 
812 		case DIR_DROP:
813 			/* drop the packet after some time */
814 			FREE_PKT(m);
815 			break;
816 
817 		default:
818 			printf("dummynet: bad switch %d!\n", dst);
819 			FREE_PKT(m);
820 			break;
821 		}
822 	}
823 }
824 
825 static inline int
tag_mbuf(struct mbuf * m,int dir,struct ip_fw_args * fwa)826 tag_mbuf(struct mbuf *m, int dir, struct ip_fw_args *fwa)
827 {
828 	struct dn_pkt_tag *dt;
829 	struct m_tag *mtag;
830 
831 	mtag = m_tag_get(PACKET_TAG_DUMMYNET,
832 		    sizeof(*dt), M_NOWAIT | M_ZERO);
833 	if (mtag == NULL)
834 		return 1;		/* Cannot allocate packet header. */
835 	m_tag_prepend(m, mtag);		/* Attach to mbuf chain. */
836 	dt = (struct dn_pkt_tag *)(mtag + 1);
837 	dt->rule = fwa->rule;
838 	dt->rule.info &= IPFW_ONEPASS;	/* only keep this info */
839 	dt->dn_dir = dir;
840 	dt->ifp = fwa->oif;
841 	/* dt->output tame is updated as we move through */
842 	dt->output_time = V_dn_cfg.curr_time;
843 	dt->iphdr_off = (dir & PROTO_LAYER2) ? ETHER_HDR_LEN : 0;
844 	return 0;
845 }
846 
847 
848 /*
849  * dummynet hook for packets.
850  * We use the argument to locate the flowset fs and the sched_set sch
851  * associated to it. The we apply flow_mask and sched_mask to
852  * determine the queue and scheduler instances.
853  *
854  * dir		where shall we send the packet after dummynet.
855  * *m0		the mbuf with the packet
856  * ifp		the 'ifp' parameter from the caller.
857  *		NULL in ip_input, destination interface in ip_output,
858  */
859 int
dummynet_io(struct mbuf ** m0,int dir,struct ip_fw_args * fwa)860 dummynet_io(struct mbuf **m0, int dir, struct ip_fw_args *fwa)
861 {
862 	struct mbuf *m = *m0;
863 	struct dn_fsk *fs = NULL;
864 	struct dn_sch_inst *si;
865 	struct dn_queue *q = NULL;	/* default */
866 
867 	int fs_id = (fwa->rule.info & IPFW_INFO_MASK) +
868 		((fwa->rule.info & IPFW_IS_PIPE) ? 2*DN_MAX_ID : 0);
869 	DN_BH_WLOCK();
870 	V_dn_cfg.io_pkt++;
871 	/* we could actually tag outside the lock, but who cares... */
872 	if (tag_mbuf(m, dir, fwa))
873 		goto dropit;
874 	/* XXX locate_flowset could be optimised with a direct ref. */
875 	fs = dn_ht_find(V_dn_cfg.fshash, fs_id, 0, NULL);
876 	if (fs == NULL)
877 		goto dropit;	/* This queue/pipe does not exist! */
878 	if (fs->sched == NULL)	/* should not happen */
879 		goto dropit;
880 	/* find scheduler instance, possibly applying sched_mask */
881 	si = ipdn_si_find(fs->sched, &(fwa->f_id));
882 	if (si == NULL)
883 		goto dropit;
884 	/*
885 	 * If the scheduler supports multiple queues, find the right one
886 	 * (otherwise it will be ignored by enqueue).
887 	 */
888 	if (fs->sched->fp->flags & DN_MULTIQUEUE) {
889 		q = ipdn_q_find(fs, si, &(fwa->f_id));
890 		if (q == NULL)
891 			goto dropit;
892 	}
893 	if (fs->sched->fp->enqueue(si, q, m)) {
894 		/* packet was dropped by enqueue() */
895 		m = *m0 = NULL;
896 
897 		/* dn_enqueue already increases io_pkt_drop */
898 		V_dn_cfg.io_pkt_drop--;
899 
900 		goto dropit;
901 	}
902 
903 	if (si->kflags & DN_ACTIVE) {
904 		m = *m0 = NULL; /* consumed */
905 		goto done; /* already active, nothing to do */
906 	}
907 
908 	/* compute the initial allowance */
909 	if (si->idle_time < V_dn_cfg.curr_time) {
910 	    /* Do this only on the first packet on an idle pipe */
911 	    struct dn_link *p = &fs->sched->link;
912 
913 	    si->sched_time = V_dn_cfg.curr_time;
914 	    si->credit = V_dn_cfg.io_fast ? p->bandwidth : 0;
915 	    if (p->burst) {
916 		uint64_t burst = (V_dn_cfg.curr_time - si->idle_time) * p->bandwidth;
917 		if (burst > p->burst)
918 			burst = p->burst;
919 		si->credit += burst;
920 	    }
921 	}
922 	/* pass through scheduler and delay line */
923 	m = serve_sched(NULL, si, V_dn_cfg.curr_time);
924 
925 	/* optimization -- pass it back to ipfw for immediate send */
926 	/* XXX Don't call dummynet_send() if scheduler return the packet
927 	 *     just enqueued. This avoid a lock order reversal.
928 	 *
929 	 */
930 	if (/*V_dn_cfg.io_fast &&*/ m == *m0 && (dir & PROTO_LAYER2) == 0 ) {
931 		/* fast io, rename the tag * to carry reinject info. */
932 		struct m_tag *tag = m_tag_first(m);
933 
934 		tag->m_tag_cookie = MTAG_IPFW_RULE;
935 		tag->m_tag_id = 0;
936 		V_dn_cfg.io_pkt_fast++;
937 		if (m->m_nextpkt != NULL) {
938 			printf("dummynet: fast io: pkt chain detected!\n");
939 			m->m_nextpkt = NULL;
940 		}
941 		m = NULL;
942 	} else {
943 		*m0 = NULL;
944 	}
945 done:
946 	DN_BH_WUNLOCK();
947 	if (m)
948 		dummynet_send(m);
949 	return 0;
950 
951 dropit:
952 	V_dn_cfg.io_pkt_drop++;
953 	DN_BH_WUNLOCK();
954 	if (m)
955 		FREE_PKT(m);
956 	*m0 = NULL;
957 	return (fs && (fs->fs.flags & DN_NOERROR)) ? 0 : ENOBUFS;
958 }
959