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