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