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