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