Sync with the new ipfw3 version.
[ipfw.git] / dummynet2 / ip_dummynet.c
1 /*-
2  * Copyright (c) 1998-2002,2010 Luigi Rizzo, Universita` di Pisa
3  * Portions Copyright (c) 2000 Akamba Corp.
4  * All rights reserved
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD: user/luigi/ipfw3-head/sys/netinet/ipfw/ip_dummynet.c 203340 2010-02-01 12:06:37Z luigi $");
30
31 /*
32  * Configuration and internal object management for dummynet.
33  */
34
35 #include "opt_inet6.h"
36
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
40 #include <sys/mbuf.h>
41 #include <sys/kernel.h>
42 #include <sys/lock.h>
43 #include <sys/module.h>
44 #include <sys/priv.h>
45 #include <sys/proc.h>
46 #include <sys/rwlock.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/time.h>
50 #include <sys/taskqueue.h>
51 #include <net/if.h>     /* IFNAMSIZ, struct ifaddr, ifq head, lock.h mutex.h */
52 #include <netinet/in.h>
53 #include <netinet/ip_var.h>     /* ip_output(), IP_FORWARDING */
54 #include <netinet/ip_fw.h>
55 #include <netinet/ipfw/ip_fw_private.h>
56 #include <netinet/ipfw/dn_heap.h>
57 #include <netinet/ip_dummynet.h>
58 #include <netinet/ipfw/ip_dn_private.h>
59 #include <netinet/ipfw/dn_sched.h>
60
61 /* which objects to copy */
62 #define DN_C_LINK       0x01
63 #define DN_C_SCH        0x02
64 #define DN_C_FLOW       0x04
65 #define DN_C_FS         0x08
66 #define DN_C_QUEUE      0x10
67
68 /* we use this argument in case of a schk_new */
69 struct schk_new_arg {
70         struct dn_alg *fp;
71         struct dn_sch *sch;
72 };
73
74 /*---- callout hooks. ----*/
75 static struct callout dn_timeout;
76 static struct task      dn_task;
77 static struct taskqueue *dn_tq = NULL;
78
79 /* dummynet and ipfw_tick can't be static in windows */
80 void
81 dummynet(void * __unused unused)
82 {
83
84         taskqueue_enqueue(dn_tq, &dn_task);
85 }
86
87 void
88 dn_reschedule(void)
89 {
90         callout_reset(&dn_timeout, 1, dummynet, NULL);
91 }
92 /*----- end of callout hooks -----*/
93
94 /* Return a scheduler descriptor given the type or name. */
95 static struct dn_alg *
96 find_sched_type(int type, char *name)
97 {
98         struct dn_alg *d;
99
100         SLIST_FOREACH(d, &dn_cfg.schedlist, next) {
101                 if (d->type == type || (name && !strcmp(d->name, name)))
102                         return d;
103         }
104         return NULL; /* not found */
105 }
106
107 int
108 ipdn_bound_var(int *v, int dflt, int lo, int hi, const char *msg)
109 {
110         int oldv = *v;
111         const char *op = NULL;
112         if (oldv < lo) {
113                 *v = dflt;
114                 op = "Bump";
115         } else if (oldv > hi) {
116                 *v = hi;
117                 op = "Clamp";
118         } else
119                 return *v;
120         if (op && msg)
121                 printf("%s %s to %d (was %d)\n", op, msg, *v, oldv);
122         return *v;
123 }
124
125 /*---- flow_id mask, hash and compare functions ---*/
126 /*
127  * The flow_id includes the 5-tuple, the queue/pipe number
128  * which we store in the extra area in host order,
129  * and for ipv6 also the flow_id6.
130  * XXX see if we want the tos byte (can store in 'flags')
131  */
132 static struct ipfw_flow_id *
133 flow_id_mask(struct ipfw_flow_id *mask, struct ipfw_flow_id *id)
134 {
135         int is_v6 = IS_IP6_FLOW_ID(id);
136
137         id->dst_port &= mask->dst_port;
138         id->src_port &= mask->src_port;
139         id->proto &= mask->proto;
140         id->extra &= mask->extra;
141         if (is_v6) {
142                 APPLY_MASK(&id->dst_ip6, &mask->dst_ip6);
143                 APPLY_MASK(&id->src_ip6, &mask->src_ip6);
144                 id->flow_id6 &= mask->flow_id6;
145         } else {
146                 id->dst_ip &= mask->dst_ip;
147                 id->src_ip &= mask->src_ip;
148         }
149         return id;
150 }
151
152 /* computes an OR of two masks, result in dst and also returned */
153 static struct ipfw_flow_id *
154 flow_id_or(struct ipfw_flow_id *src, struct ipfw_flow_id *dst)
155 {
156         int is_v6 = IS_IP6_FLOW_ID(dst);
157
158         dst->dst_port |= src->dst_port;
159         dst->src_port |= src->src_port;
160         dst->proto |= src->proto;
161         dst->extra |= src->extra;
162         if (is_v6) {
163 #define OR_MASK(_d, _s)                          \
164     (_d)->__u6_addr.__u6_addr32[0] |= (_s)->__u6_addr.__u6_addr32[0]; \
165     (_d)->__u6_addr.__u6_addr32[1] |= (_s)->__u6_addr.__u6_addr32[1]; \
166     (_d)->__u6_addr.__u6_addr32[2] |= (_s)->__u6_addr.__u6_addr32[2]; \
167     (_d)->__u6_addr.__u6_addr32[3] |= (_s)->__u6_addr.__u6_addr32[3];
168                 OR_MASK(&dst->dst_ip6, &src->dst_ip6);
169                 OR_MASK(&dst->src_ip6, &src->src_ip6);
170 #undef OR_MASK
171                 dst->flow_id6 |= src->flow_id6;
172         } else {
173                 dst->dst_ip |= src->dst_ip;
174                 dst->src_ip |= src->src_ip;
175         }
176         return dst;
177 }
178
179 static int
180 nonzero_mask(struct ipfw_flow_id *m)
181 {
182         if (m->dst_port || m->src_port || m->proto || m->extra)
183                 return 1;
184         if (IS_IP6_FLOW_ID(m)) {
185                 return
186                         m->dst_ip6.__u6_addr.__u6_addr32[0] ||
187                         m->dst_ip6.__u6_addr.__u6_addr32[1] ||
188                         m->dst_ip6.__u6_addr.__u6_addr32[2] ||
189                         m->dst_ip6.__u6_addr.__u6_addr32[3] ||
190                         m->src_ip6.__u6_addr.__u6_addr32[0] ||
191                         m->src_ip6.__u6_addr.__u6_addr32[1] ||
192                         m->src_ip6.__u6_addr.__u6_addr32[2] ||
193                         m->src_ip6.__u6_addr.__u6_addr32[3] ||
194                         m->flow_id6;
195         } else {
196                 return m->dst_ip || m->src_ip;
197         }
198 }
199
200 /* XXX we may want a better hash function */
201 static uint32_t
202 flow_id_hash(struct ipfw_flow_id *id)
203 {
204     uint32_t i;
205
206     if (IS_IP6_FLOW_ID(id)) {
207         uint32_t *d = (uint32_t *)&id->dst_ip6;
208         uint32_t *s = (uint32_t *)&id->src_ip6;
209         i = (d[0]      ) ^ (d[1])       ^
210             (d[2]      ) ^ (d[3])       ^
211             (d[0] >> 15) ^ (d[1] >> 15) ^
212             (d[2] >> 15) ^ (d[3] >> 15) ^
213             (s[0] <<  1) ^ (s[1] <<  1) ^
214             (s[2] <<  1) ^ (s[3] <<  1) ^
215             (s[0] << 16) ^ (s[1] << 16) ^
216             (s[2] << 16) ^ (s[3] << 16) ^
217             (id->dst_port << 1) ^ (id->src_port) ^
218             (id->extra) ^
219             (id->proto ) ^ (id->flow_id6);
220     } else {
221         i = (id->dst_ip)        ^ (id->dst_ip >> 15) ^
222             (id->src_ip << 1)   ^ (id->src_ip >> 16) ^
223             (id->extra) ^
224             (id->dst_port << 1) ^ (id->src_port)     ^ (id->proto);
225     }
226     return i;
227 }
228
229 /* Like bcmp, returns 0 if ids match, 1 otherwise. */
230 static int
231 flow_id_cmp(struct ipfw_flow_id *id1, struct ipfw_flow_id *id2)
232 {
233         int is_v6 = IS_IP6_FLOW_ID(id1);
234
235         if (!is_v6) {
236             if (IS_IP6_FLOW_ID(id2))
237                 return 1; /* different address families */
238
239             return (id1->dst_ip == id2->dst_ip &&
240             id1->src_ip == id2->src_ip &&
241             id1->dst_port == id2->dst_port &&
242             id1->src_port == id2->src_port &&
243             id1->proto == id2->proto &&
244                     id1->extra == id2->extra) ? 0 : 1;
245         }
246         /* the ipv6 case */
247         return (
248             !bcmp(&id1->dst_ip6,&id2->dst_ip6, sizeof(id1->dst_ip6)) &&
249             !bcmp(&id1->src_ip6,&id2->src_ip6, sizeof(id1->src_ip6)) &&
250             id1->dst_port == id2->dst_port &&
251             id1->src_port == id2->src_port &&
252             id1->proto == id2->proto &&
253             id1->extra == id2->extra &&
254             id1->flow_id6 == id2->flow_id6) ? 0 : 1;
255 }
256 /*--------- end of flow-id mask, hash and compare ---------*/
257
258 /*--- support functions for the qht hashtable ----
259  * Entries are hashed by flow-id
260  */
261 static uint32_t
262 q_hash(uintptr_t key, int flags, void *arg)
263 {
264         /* compute the hash slot from the flow id */
265         struct ipfw_flow_id *id = (flags & DNHT_KEY_IS_OBJ) ?
266                 &((struct dn_queue *)key)->ni.fid :
267                 (struct ipfw_flow_id *)key;
268
269         return flow_id_hash(id);
270 }
271
272 static int
273 q_match(void *obj, uintptr_t key, int flags, void *arg)
274 {
275         struct dn_queue *o = (struct dn_queue *)obj;
276         struct ipfw_flow_id *id2;
277
278         if (flags & DNHT_KEY_IS_OBJ) {
279                 /* compare pointers */
280                 id2 = &((struct dn_queue *)key)->ni.fid;
281         } else {
282                 id2 = (struct ipfw_flow_id *)key;
283         }
284         return (0 == flow_id_cmp(&o->ni.fid,  id2));
285 }
286
287 /*
288  * create a new queue instance for the given 'key'.
289  */
290 static void *
291 q_new(uintptr_t key, int flags, void *arg)
292 {   
293         struct dn_queue *q, *template = arg;
294         struct dn_fsk *fs = template->fs;
295         int size = sizeof(*q) + fs->sched->fp->q_datalen;
296
297         q = malloc(size, M_DUMMYNET, M_NOWAIT | M_ZERO);
298         if (q == NULL) {
299                 D("no memory for new queue");
300                 return NULL;
301         }
302
303         set_oid(&q->ni.oid, DN_QUEUE, size);
304         if (fs->fs.flags & DN_QHT_HASH)
305                 q->ni.fid = *(struct ipfw_flow_id *)key;
306         q->fs = fs;
307         q->_si = template->_si;
308         q->_si->q_count++;
309
310         if (fs->sched->fp->new_queue)
311                 fs->sched->fp->new_queue(q);
312         dn_cfg.queue_count++;
313         return q;
314 }
315
316 /*
317  * Notify schedulers that a queue is going away.
318  * If (flags & DN_DESTROY), also free the packets.
319  * The version for callbacks is called q_delete_cb().
320  */
321 static void
322 dn_delete_queue(struct dn_queue *q, int flags)
323 {
324         struct dn_fsk *fs = q->fs;
325
326         // D("fs %p si %p\n", fs, q->_si);
327         /* notify the parent scheduler that the queue is going away */
328         if (fs && fs->sched->fp->free_queue)
329                 fs->sched->fp->free_queue(q);
330         q->_si->q_count--;
331         q->_si = NULL;
332         if (flags & DN_DESTROY) {
333                 if (q->mq.head)
334                         dn_free_pkts(q->mq.head);
335                 bzero(q, sizeof(*q));   // safety
336                 free(q, M_DUMMYNET);
337                 dn_cfg.queue_count--;
338         }
339 }
340
341 static int
342 q_delete_cb(void *q, void *arg)
343 {
344         int flags = (int)(uintptr_t)arg;
345         dn_delete_queue(q, flags);
346         return (flags & DN_DESTROY) ? DNHT_SCAN_DEL : 0;
347 }
348
349 /*
350  * calls dn_delete_queue/q_delete_cb on all queues,
351  * which notifies the parent scheduler and possibly drains packets.
352  * flags & DN_DESTROY: drains queues and destroy qht;
353  */
354 static void
355 qht_delete(struct dn_fsk *fs, int flags)
356 {
357         ND("fs %d start flags %d qht %p",
358                 fs->fs.fs_nr, flags, fs->qht);
359         if (!fs->qht)
360                 return;
361         if (fs->fs.flags & DN_QHT_HASH) {
362                 dn_ht_scan(fs->qht, q_delete_cb, (void *)(uintptr_t)flags);
363                 if (flags & DN_DESTROY) {
364                         dn_ht_free(fs->qht, 0);
365                         fs->qht = NULL;
366                 }
367         } else {
368                 dn_delete_queue((struct dn_queue *)(fs->qht), flags);
369                 if (flags & DN_DESTROY)
370                         fs->qht = NULL;
371         }
372 }
373
374 /*
375  * Find and possibly create the queue for a MULTIQUEUE scheduler.
376  * We never call it for !MULTIQUEUE (the queue is in the sch_inst).
377  */
378 struct dn_queue *
379 ipdn_q_find(struct dn_fsk *fs, struct dn_sch_inst *si,
380         struct ipfw_flow_id *id)
381 {
382         struct dn_queue template;
383
384         template._si = si;
385         template.fs = fs;
386
387         if (fs->fs.flags & DN_QHT_HASH) {
388                 struct ipfw_flow_id masked_id;
389                 if (fs->qht == NULL) {
390                         fs->qht = dn_ht_init(NULL, fs->fs.buckets,
391                                 offsetof(struct dn_queue, q_next),
392                                 q_hash, q_match, q_new);
393                         if (fs->qht == NULL)
394                                 return NULL;
395                 }
396                 masked_id = *id;
397                 flow_id_mask(&fs->fsk_mask, &masked_id);
398                 return dn_ht_find(fs->qht, (uintptr_t)&masked_id,
399                         DNHT_INSERT, &template);
400         } else {
401                 if (fs->qht == NULL)
402                         fs->qht = q_new(0, 0, &template);
403                 return (struct dn_queue *)fs->qht;
404         }
405 }
406 /*--- end of queue hash table ---*/
407
408 /*--- support functions for the sch_inst hashtable ----
409  *
410  * These are hashed by flow-id
411  */
412 static uint32_t
413 si_hash(uintptr_t key, int flags, void *arg)
414 {
415         /* compute the hash slot from the flow id */
416         struct ipfw_flow_id *id = (flags & DNHT_KEY_IS_OBJ) ?
417                 &((struct dn_sch_inst *)key)->ni.fid :
418                 (struct ipfw_flow_id *)key;
419
420         return flow_id_hash(id);
421 }
422
423 static int
424 si_match(void *obj, uintptr_t key, int flags, void *arg)
425 {
426         struct dn_sch_inst *o = obj;
427         struct ipfw_flow_id *id2;
428
429         id2 = (flags & DNHT_KEY_IS_OBJ) ?
430                 &((struct dn_sch_inst *)key)->ni.fid :
431                 (struct ipfw_flow_id *)key;
432         return flow_id_cmp(&o->ni.fid,  id2) == 0;
433 }
434
435 /*
436  * create a new instance for the given 'key'
437  * Allocate memory for instance, delay line and scheduler private data.
438  */
439 static void *
440 si_new(uintptr_t key, int flags, void *arg)
441 {
442         struct dn_schk *s = arg;
443         struct dn_sch_inst *si;
444         int l = sizeof(*si) + s->fp->si_datalen;
445
446         si = malloc(l, M_DUMMYNET, M_NOWAIT | M_ZERO);
447         if (si == NULL)
448                 goto error;
449         /* Set length only for the part passed up to userland. */
450         set_oid(&si->ni.oid, DN_SCH_I, sizeof(struct dn_flow));
451         set_oid(&(si->dline.oid), DN_DELAY_LINE,
452                 sizeof(struct delay_line));
453         /* mark si and dline as outside the event queue */
454         si->ni.oid.id = si->dline.oid.id = -1;
455
456         si->sched = s;
457         si->dline.si = si;
458
459         if (s->fp->new_sched && s->fp->new_sched(si)) {
460                 D("new_sched error");
461                 goto error;
462         }
463         if (s->sch.flags & DN_HAVE_MASK)
464                 si->ni.fid = *(struct ipfw_flow_id *)key;
465
466         dn_cfg.si_count++;
467         return si;
468
469 error:
470         if (si) {
471                 bzero(si, sizeof(*si)); // safety
472                 free(si, M_DUMMYNET);
473         }
474         return NULL;
475 }
476
477 /*
478  * Callback from siht to delete all scheduler instances. Remove
479  * si and delay line from the system heap, destroy all queues.
480  * We assume that all flowset have been notified and do not
481  * point to us anymore.
482  */
483 static int
484 si_destroy(void *_si, void *arg)
485 {
486         struct dn_sch_inst *si = _si;
487         struct dn_schk *s = si->sched;
488         struct delay_line *dl = &si->dline;
489
490         if (dl->oid.subtype) /* remove delay line from event heap */
491                 heap_extract(&dn_cfg.evheap, dl);
492         dn_free_pkts(dl->mq.head);      /* drain delay line */
493         if (si->kflags & DN_ACTIVE) /* remove si from event heap */
494                 heap_extract(&dn_cfg.evheap, si);
495         if (s->fp->free_sched)
496                 s->fp->free_sched(si);
497         bzero(si, sizeof(*si)); /* safety */
498         free(si, M_DUMMYNET);
499         dn_cfg.si_count--;
500         return DNHT_SCAN_DEL;
501 }
502
503 /*
504  * Find the scheduler instance for this packet. If we need to apply
505  * a mask, do on a local copy of the flow_id to preserve the original.
506  * Assume siht is always initialized if we have a mask.
507  */
508 struct dn_sch_inst *
509 ipdn_si_find(struct dn_schk *s, struct ipfw_flow_id *id)
510 {
511
512         if (s->sch.flags & DN_HAVE_MASK) {
513                 struct ipfw_flow_id id_t = *id;
514                 flow_id_mask(&s->sch.sched_mask, &id_t);
515                 return dn_ht_find(s->siht, (uintptr_t)&id_t,
516                         DNHT_INSERT, s);
517         }
518         if (!s->siht)
519                 s->siht = si_new(0, 0, s);
520         return (struct dn_sch_inst *)s->siht;
521 }
522
523 /* callback to flush credit for the scheduler instance */
524 static int
525 si_reset_credit(void *_si, void *arg)
526 {
527         struct dn_sch_inst *si = _si;
528         struct dn_link *p = &si->sched->link;
529
530         si->credit = p->burst + (dn_cfg.io_fast ?  p->bandwidth : 0);
531         return 0;
532 }
533
534 static void
535 schk_reset_credit(struct dn_schk *s)
536 {
537         if (s->sch.flags & DN_HAVE_MASK)
538                 dn_ht_scan(s->siht, si_reset_credit, NULL);
539         else if (s->siht)
540                 si_reset_credit(s->siht, NULL);
541 }
542 /*---- end of sch_inst hashtable ---------------------*/
543
544 /*-------------------------------------------------------
545  * flowset hash (fshash) support. Entries are hashed by fs_nr.
546  * New allocations are put in the fsunlinked list, from which
547  * they are removed when they point to a specific scheduler.
548  */
549 static uint32_t
550 fsk_hash(uintptr_t key, int flags, void *arg)
551 {
552         uint32_t i = !(flags & DNHT_KEY_IS_OBJ) ? key :
553                 ((struct dn_fsk *)key)->fs.fs_nr;
554
555         return ( (i>>8)^(i>>4)^i );
556 }
557
558 static int
559 fsk_match(void *obj, uintptr_t key, int flags, void *arg)
560 {
561         struct dn_fsk *fs = obj;
562         int i = !(flags & DNHT_KEY_IS_OBJ) ? key :
563                 ((struct dn_fsk *)key)->fs.fs_nr;
564
565         return (fs->fs.fs_nr == i);
566 }
567
568 static void *
569 fsk_new(uintptr_t key, int flags, void *arg)
570 {
571         struct dn_fsk *fs;
572
573         fs = malloc(sizeof(*fs), M_DUMMYNET, M_NOWAIT | M_ZERO);
574         if (fs) {
575                 set_oid(&fs->fs.oid, DN_FS, sizeof(fs->fs));
576                 dn_cfg.fsk_count++;
577                 fs->drain_bucket = 0;
578                 SLIST_INSERT_HEAD(&dn_cfg.fsu, fs, sch_chain);
579         }
580         return fs;
581 }
582
583 /*
584  * detach flowset from its current scheduler. Flags as follows:
585  * DN_DETACH removes from the fsk_list
586  * DN_DESTROY deletes individual queues
587  * DN_DELETE_FS destroys the flowset (otherwise goes in unlinked).
588  */
589 static void
590 fsk_detach(struct dn_fsk *fs, int flags)
591 {
592         if (flags & DN_DELETE_FS)
593                 flags |= DN_DESTROY;
594         ND("fs %d from sched %d flags %s %s %s",
595                 fs->fs.fs_nr, fs->fs.sched_nr,
596                 (flags & DN_DELETE_FS) ? "DEL_FS":"",
597                 (flags & DN_DESTROY) ? "DEL":"",
598                 (flags & DN_DETACH) ? "DET":"");
599         if (flags & DN_DETACH) { /* detach from the list */
600                 struct dn_fsk_head *h;
601                 h = fs->sched ? &fs->sched->fsk_list : &dn_cfg.fsu;
602                 SLIST_REMOVE(h, fs, dn_fsk, sch_chain);
603         }
604         /* Free the RED parameters, they will be recomputed on 
605          * subsequent attach if needed.
606          */
607         if (fs->w_q_lookup)
608                 free(fs->w_q_lookup, M_DUMMYNET);
609         fs->w_q_lookup = NULL;
610         qht_delete(fs, flags);
611         if (fs->sched && fs->sched->fp->free_fsk)
612                 fs->sched->fp->free_fsk(fs);
613         fs->sched = NULL;
614         if (flags & DN_DELETE_FS) {
615                 bzero(fs, sizeof(fs));  /* safety */
616                 free(fs, M_DUMMYNET);
617                 dn_cfg.fsk_count--;
618         } else {
619                 SLIST_INSERT_HEAD(&dn_cfg.fsu, fs, sch_chain);
620         }
621 }
622
623 /*
624  * Detach or destroy all flowsets in a list.
625  * flags specifies what to do:
626  * DN_DESTROY:  flush all queues
627  * DN_DELETE_FS:        DN_DESTROY + destroy flowset
628  *      DN_DELETE_FS implies DN_DESTROY
629  */
630 static void
631 fsk_detach_list(struct dn_fsk_head *h, int flags)
632 {
633         struct dn_fsk *fs;
634         int n = 0; /* only for stats */
635
636         ND("head %p flags %x", h, flags);
637         while ((fs = SLIST_FIRST(h))) {
638                 SLIST_REMOVE_HEAD(h, sch_chain);
639                 n++;
640                 fsk_detach(fs, flags);
641         }
642         ND("done %d flowsets", n);
643 }
644
645 /*
646  * called on 'queue X delete' -- removes the flowset from fshash,
647  * deletes all queues for the flowset, and removes the flowset.
648  */
649 static int
650 delete_fs(int i, int locked)
651 {
652         struct dn_fsk *fs;
653         int err = 0;
654
655         if (!locked)
656                 DN_BH_WLOCK();
657         fs = dn_ht_find(dn_cfg.fshash, i, DNHT_REMOVE, NULL);
658         ND("fs %d found %p", i, fs);
659         if (fs) {
660                 fsk_detach(fs, DN_DETACH | DN_DELETE_FS);
661                 err = 0;
662         } else
663                 err = EINVAL;
664         if (!locked)
665                 DN_BH_WUNLOCK();
666         return err;
667 }
668
669 /*----- end of flowset hashtable support -------------*/
670
671 /*------------------------------------------------------------
672  * Scheduler hash. When searching by index we pass sched_nr,
673  * otherwise we pass struct dn_sch * which is the first field in
674  * struct dn_schk so we can cast between the two. We use this trick
675  * because in the create phase (but it should be fixed).
676  */
677 static uint32_t
678 schk_hash(uintptr_t key, int flags, void *_arg)
679 {
680         uint32_t i = !(flags & DNHT_KEY_IS_OBJ) ? key :
681                 ((struct dn_schk *)key)->sch.sched_nr;
682         return ( (i>>8)^(i>>4)^i );
683 }
684
685 static int
686 schk_match(void *obj, uintptr_t key, int flags, void *_arg)
687 {
688         struct dn_schk *s = (struct dn_schk *)obj;
689         int i = !(flags & DNHT_KEY_IS_OBJ) ? key :
690                 ((struct dn_schk *)key)->sch.sched_nr;
691         return (s->sch.sched_nr == i);
692 }
693
694 /*
695  * Create the entry and intialize with the sched hash if needed.
696  * Leave s->fp unset so we can tell whether a dn_ht_find() returns
697  * a new object or a previously existing one.
698  */
699 static void *
700 schk_new(uintptr_t key, int flags, void *arg)
701 {
702         struct schk_new_arg *a = arg;
703         struct dn_schk *s;
704         int l = sizeof(*s) +a->fp->schk_datalen;
705
706         s = malloc(l, M_DUMMYNET, M_NOWAIT | M_ZERO);
707         if (s == NULL)
708                 return NULL;
709         set_oid(&s->link.oid, DN_LINK, sizeof(s->link));
710         s->sch = *a->sch; // copy initial values
711         s->link.link_nr = s->sch.sched_nr;
712         SLIST_INIT(&s->fsk_list);
713         /* initialize the hash table or create the single instance */
714         s->fp = a->fp;  /* si_new needs this */
715         s->drain_bucket = 0;
716         if (s->sch.flags & DN_HAVE_MASK) {
717                 s->siht = dn_ht_init(NULL, s->sch.buckets,
718                         offsetof(struct dn_sch_inst, si_next),
719                         si_hash, si_match, si_new);
720                 if (s->siht == NULL) {
721                         free(s, M_DUMMYNET);
722                         return NULL;
723                 }
724         }
725         s->fp = NULL;   /* mark as a new scheduler */
726         dn_cfg.schk_count++;
727         return s;
728 }
729
730 /*
731  * Callback for sched delete. Notify all attached flowsets to
732  * detach from the scheduler, destroy the internal flowset, and
733  * all instances. The scheduler goes away too.
734  * arg is 0 (only detach flowsets and destroy instances)
735  * DN_DESTROY (detach & delete queues, delete schk)
736  * or DN_DELETE_FS (delete queues and flowsets, delete schk)
737  */
738 static int
739 schk_delete_cb(void *obj, void *arg)
740 {
741         struct dn_schk *s = obj;
742 #if 0
743         int a = (int)arg;
744         ND("sched %d arg %s%s",
745                 s->sch.sched_nr,
746                 a&DN_DESTROY ? "DEL ":"",
747                 a&DN_DELETE_FS ? "DEL_FS":"");
748 #endif
749         fsk_detach_list(&s->fsk_list, arg ? DN_DESTROY : 0);
750         /* no more flowset pointing to us now */
751         if (s->sch.flags & DN_HAVE_MASK)
752                 dn_ht_scan(s->siht, si_destroy, NULL);
753         else if (s->siht)
754                 si_destroy(s->siht, NULL);
755         if (s->profile) {
756                 free(s->profile, M_DUMMYNET);
757                 s->profile = NULL;
758         }
759         s->siht = NULL;
760         if (s->fp->destroy)
761                 s->fp->destroy(s);
762         bzero(s, sizeof(*s));   // safety
763         free(obj, M_DUMMYNET);
764         dn_cfg.schk_count--;
765         return DNHT_SCAN_DEL;
766 }
767
768 /*
769  * called on a 'sched X delete' command. Deletes a single scheduler.
770  * This is done by removing from the schedhash, unlinking all
771  * flowsets and deleting their traffic.
772  */
773 static int
774 delete_schk(int i)
775 {
776         struct dn_schk *s;
777
778         s = dn_ht_find(dn_cfg.schedhash, i, DNHT_REMOVE, NULL);
779         ND("%d %p", i, s);
780         if (!s)
781                 return EINVAL;
782         delete_fs(i + DN_MAX_ID, 1); /* first delete internal fs */
783         /* then detach flowsets, delete traffic */
784         schk_delete_cb(s, (void*)(uintptr_t)DN_DESTROY);
785         return 0;
786 }
787 /*--- end of schk hashtable support ---*/
788
789 static int
790 copy_obj(char **start, char *end, void *_o, const char *msg, int i)
791 {
792         struct dn_id *o = _o;
793         int have = end - *start;
794
795         if (have < o->len || o->len == 0 || o->type == 0) {
796                 D("(WARN) type %d %s %d have %d need %d",
797                         o->type, msg, i, have, o->len);
798                 return 1;
799         }
800         ND("type %d %s %d len %d", o->type, msg, i, o->len);
801         bcopy(_o, *start, o->len);
802         if (o->type == DN_LINK) {
803                 /* Adjust burst parameter for link */
804                 struct dn_link *l = (struct dn_link *)*start;
805                 l->burst =  div64(l->burst, 8 * hz);
806         } else if (o->type == DN_SCH) {
807                 /* Set id->id to the number of instances */
808                 struct dn_schk *s = _o;
809                 struct dn_id *id = (struct dn_id *)(*start);
810                 id->id = (s->sch.flags & DN_HAVE_MASK) ?
811                         dn_ht_entries(s->siht) : (s->siht ? 1 : 0);
812         }
813         *start += o->len;
814         return 0;
815 }
816
817 /* Specific function to copy a queue.
818  * Copies only the user-visible part of a queue (which is in
819  * a struct dn_flow), and sets len accordingly.
820  */
821 static int
822 copy_obj_q(char **start, char *end, void *_o, const char *msg, int i)
823 {
824         struct dn_id *o = _o;
825         int have = end - *start;
826         int len = sizeof(struct dn_flow); /* see above comment */
827
828         if (have < len || o->len == 0 || o->type != DN_QUEUE) {
829                 D("ERROR type %d %s %d have %d need %d",
830                         o->type, msg, i, have, len);
831                 return 1;
832         }
833         ND("type %d %s %d len %d", o->type, msg, i, len);
834         bcopy(_o, *start, len);
835         ((struct dn_id*)(*start))->len = len;
836         *start += len;
837         return 0;
838 }
839
840 static int
841 copy_q_cb(void *obj, void *arg)
842 {
843         struct dn_queue *q = obj;
844         struct copy_args *a = arg;
845         struct dn_flow *ni = (struct dn_flow *)(*a->start);
846         if (copy_obj_q(a->start, a->end, &q->ni, "queue", -1))
847                 return DNHT_SCAN_END;
848         ni->oid.type = DN_FLOW; /* override the DN_QUEUE */
849         ni->oid.id = si_hash((uintptr_t)&ni->fid, 0, NULL);
850         return 0;
851 }
852
853 static int
854 copy_q(struct copy_args *a, struct dn_fsk *fs, int flags)
855 {
856         if (!fs->qht)
857                 return 0;
858         if (fs->fs.flags & DN_QHT_HASH)
859                 dn_ht_scan(fs->qht, copy_q_cb, a);
860         else
861                 copy_q_cb(fs->qht, a);
862         return 0;
863 }
864
865 /*
866  * This routine only copies the initial part of a profile ? XXX
867  */
868 static int
869 copy_profile(struct copy_args *a, struct dn_profile *p)
870 {
871         int have = a->end - *a->start;
872         /* XXX here we check for max length */
873         int profile_len = sizeof(struct dn_profile) - 
874                 ED_MAX_SAMPLES_NO*sizeof(int);
875
876         if (p == NULL)
877                 return 0;
878         if (have < profile_len) {
879                 D("error have %d need %d", have, profile_len);
880                 return 1;
881         }
882         bcopy(p, *a->start, profile_len);
883         ((struct dn_id *)(*a->start))->len = profile_len;
884         *a->start += profile_len;
885         return 0;
886 }
887
888 static int
889 copy_flowset(struct copy_args *a, struct dn_fsk *fs, int flags)
890 {
891         struct dn_fs *ufs = (struct dn_fs *)(*a->start);
892         if (!fs)
893                 return 0;
894         ND("flowset %d", fs->fs.fs_nr);
895         if (copy_obj(a->start, a->end, &fs->fs, "flowset", fs->fs.fs_nr))
896                 return DNHT_SCAN_END;
897         ufs->oid.id = (fs->fs.flags & DN_QHT_HASH) ?
898                 dn_ht_entries(fs->qht) : (fs->qht ? 1 : 0);
899         if (flags) {    /* copy queues */
900                 copy_q(a, fs, 0);
901         }
902         return 0;
903 }
904
905 static int
906 copy_si_cb(void *obj, void *arg)
907 {
908         struct dn_sch_inst *si = obj;
909         struct copy_args *a = arg;
910         struct dn_flow *ni = (struct dn_flow *)(*a->start);
911         if (copy_obj(a->start, a->end, &si->ni, "inst",
912                         si->sched->sch.sched_nr))
913                 return DNHT_SCAN_END;
914         ni->oid.type = DN_FLOW; /* override the DN_SCH_I */
915         ni->oid.id = si_hash((uintptr_t)si, DNHT_KEY_IS_OBJ, NULL);
916         return 0;
917 }
918
919 static int
920 copy_si(struct copy_args *a, struct dn_schk *s, int flags)
921 {
922         if (s->sch.flags & DN_HAVE_MASK)
923                 dn_ht_scan(s->siht, copy_si_cb, a);
924         else if (s->siht)
925                 copy_si_cb(s->siht, a);
926         return 0;
927 }
928
929 /*
930  * compute a list of children of a scheduler and copy up
931  */
932 static int
933 copy_fsk_list(struct copy_args *a, struct dn_schk *s, int flags)
934 {
935         struct dn_fsk *fs;
936         struct dn_id *o;
937         uint32_t *p;
938
939         int n = 0, space = sizeof(*o);
940         SLIST_FOREACH(fs, &s->fsk_list, sch_chain) {
941                 if (fs->fs.fs_nr < DN_MAX_ID)
942                         n++;
943         }
944         space += n * sizeof(uint32_t);
945         DX(3, "sched %d has %d flowsets", s->sch.sched_nr, n);
946         if (a->end - *(a->start) < space)
947                 return DNHT_SCAN_END;
948         o = (struct dn_id *)(*(a->start));
949         o->len = space;
950         *a->start += o->len;
951         o->type = DN_TEXT;
952         p = (uint32_t *)(o+1);
953         SLIST_FOREACH(fs, &s->fsk_list, sch_chain)
954                 if (fs->fs.fs_nr < DN_MAX_ID)
955                         *p++ = fs->fs.fs_nr;
956         return 0;
957 }
958
959 static int
960 copy_data_helper(void *_o, void *_arg)
961 {
962         struct copy_args *a = _arg;
963         uint32_t *r = a->extra->r; /* start of first range */
964         uint32_t *lim;  /* first invalid pointer */
965         int n;
966
967         lim = (uint32_t *)((char *)(a->extra) + a->extra->o.len);
968
969         if (a->type == DN_LINK || a->type == DN_SCH) {
970                 /* pipe|sched show, we receive a dn_schk */
971                 struct dn_schk *s = _o;
972
973                 n = s->sch.sched_nr;
974                 if (a->type == DN_SCH && n >= DN_MAX_ID)
975                         return 0;       /* not a scheduler */
976                 if (a->type == DN_LINK && n <= DN_MAX_ID)
977                     return 0;   /* not a pipe */
978
979                 /* see if the object is within one of our ranges */
980                 for (;r < lim; r+=2) {
981                         if (n < r[0] || n > r[1])
982                                 continue;
983                         /* Found a valid entry, copy and we are done */
984                 if (a->flags & DN_C_LINK) {
985                         if (copy_obj(a->start, a->end,
986                                     &s->link, "link", n))
987                                 return DNHT_SCAN_END;
988                         if (copy_profile(a, s->profile))
989                                 return DNHT_SCAN_END;
990                         if (copy_flowset(a, s->fs, 0))
991                                 return DNHT_SCAN_END;
992                 }
993                 if (a->flags & DN_C_SCH) {
994                         if (copy_obj(a->start, a->end,
995                                     &s->sch, "sched", n))
996                                 return DNHT_SCAN_END;
997                         /* list all attached flowsets */
998                         if (copy_fsk_list(a, s, 0))
999                                 return DNHT_SCAN_END;
1000                 }
1001                         if (a->flags & DN_C_FLOW)
1002                         copy_si(a, s, 0);
1003                         break;
1004                 }
1005         } else if (a->type == DN_FS) {
1006                 /* queue show, skip internal flowsets */
1007                 struct dn_fsk *fs = _o;
1008
1009                 n = fs->fs.fs_nr;
1010                 if (n >= DN_MAX_ID)
1011                         return 0;
1012                 /* see if the object is within one of our ranges */
1013                 for (;r < lim; r+=2) {
1014                         if (n < r[0] || n > r[1])
1015                                 continue;
1016                                 if (copy_flowset(a, fs, 0))
1017                                         return DNHT_SCAN_END;
1018                                 copy_q(a, fs, 0);
1019                         break; /* we are done */
1020                         }
1021                 }
1022         return 0;
1023 }
1024
1025 static inline struct dn_schk *
1026 locate_scheduler(int i)
1027 {
1028         return dn_ht_find(dn_cfg.schedhash, i, 0, NULL);
1029 }
1030
1031 /*
1032  * red parameters are in fixed point arithmetic.
1033  */
1034 static int
1035 config_red(struct dn_fsk *fs)
1036 {
1037         int64_t s, idle, weight, w0;
1038         int t, i;
1039
1040         fs->w_q = fs->fs.w_q;
1041         fs->max_p = fs->fs.max_p;
1042         D("called");
1043         /* Doing stuff that was in userland */
1044         i = fs->sched->link.bandwidth;
1045         s = (i <= 0) ? 0 :
1046                 hz * dn_cfg.red_avg_pkt_size * 8 * SCALE(1) / i;
1047
1048         idle = div64((s * 3) , fs->w_q); /* s, fs->w_q scaled; idle not scaled */
1049         fs->lookup_step = div64(idle , dn_cfg.red_lookup_depth);
1050         /* fs->lookup_step not scaled, */
1051         if (!fs->lookup_step)
1052                 fs->lookup_step = 1;
1053         w0 = weight = SCALE(1) - fs->w_q; //fs->w_q scaled
1054
1055         for (t = fs->lookup_step; t > 1; --t)
1056                 weight = SCALE_MUL(weight, w0);
1057         fs->lookup_weight = (int)(weight); // scaled
1058
1059         /* Now doing stuff that was in kerneland */
1060         fs->min_th = SCALE(fs->fs.min_th);
1061         fs->max_th = SCALE(fs->fs.max_th);
1062
1063         fs->c_1 = fs->max_p / (fs->fs.max_th - fs->fs.min_th);
1064         fs->c_2 = SCALE_MUL(fs->c_1, SCALE(fs->fs.min_th));
1065
1066         if (fs->fs.flags & DN_IS_GENTLE_RED) {
1067                 fs->c_3 = (SCALE(1) - fs->max_p) / fs->fs.max_th;
1068                 fs->c_4 = SCALE(1) - 2 * fs->max_p;
1069         }
1070
1071         /* If the lookup table already exist, free and create it again. */
1072         if (fs->w_q_lookup) {
1073                 free(fs->w_q_lookup, M_DUMMYNET);
1074                 fs->w_q_lookup = NULL;
1075         }
1076         if (dn_cfg.red_lookup_depth == 0) {
1077                 printf("\ndummynet: net.inet.ip.dummynet.red_lookup_depth"
1078                     "must be > 0\n");
1079                 fs->fs.flags &= ~DN_IS_RED;
1080                 fs->fs.flags &= ~DN_IS_GENTLE_RED;
1081                 return (EINVAL);
1082         }
1083         fs->lookup_depth = dn_cfg.red_lookup_depth;
1084         fs->w_q_lookup = (u_int *)malloc(fs->lookup_depth * sizeof(int),
1085             M_DUMMYNET, M_NOWAIT);
1086         if (fs->w_q_lookup == NULL) {
1087                 printf("dummynet: sorry, cannot allocate red lookup table\n");
1088                 fs->fs.flags &= ~DN_IS_RED;
1089                 fs->fs.flags &= ~DN_IS_GENTLE_RED;
1090                 return(ENOSPC);
1091         }
1092
1093         /* Fill the lookup table with (1 - w_q)^x */
1094         fs->w_q_lookup[0] = SCALE(1) - fs->w_q;
1095
1096         for (i = 1; i < fs->lookup_depth; i++)
1097                 fs->w_q_lookup[i] =
1098                     SCALE_MUL(fs->w_q_lookup[i - 1], fs->lookup_weight);
1099
1100         if (dn_cfg.red_avg_pkt_size < 1)
1101                 dn_cfg.red_avg_pkt_size = 512;
1102         fs->avg_pkt_size = dn_cfg.red_avg_pkt_size;
1103         if (dn_cfg.red_max_pkt_size < 1)
1104                 dn_cfg.red_max_pkt_size = 1500;
1105         fs->max_pkt_size = dn_cfg.red_max_pkt_size;
1106         D("exit");
1107         return 0;
1108 }
1109
1110 /* Scan all flowset attached to this scheduler and update red */
1111 static void
1112 update_red(struct dn_schk *s)
1113 {
1114         struct dn_fsk *fs;
1115         SLIST_FOREACH(fs, &s->fsk_list, sch_chain) {
1116                 if (fs && (fs->fs.flags & DN_IS_RED))
1117                         config_red(fs);
1118         }
1119 }
1120
1121 /* attach flowset to scheduler s, possibly requeue */
1122 static void
1123 fsk_attach(struct dn_fsk *fs, struct dn_schk *s)
1124 {
1125         ND("remove fs %d from fsunlinked, link to sched %d",
1126                 fs->fs.fs_nr, s->sch.sched_nr);
1127         SLIST_REMOVE(&dn_cfg.fsu, fs, dn_fsk, sch_chain);
1128         fs->sched = s;
1129         SLIST_INSERT_HEAD(&s->fsk_list, fs, sch_chain);
1130         if (s->fp->new_fsk)
1131                 s->fp->new_fsk(fs);
1132         /* XXX compute fsk_mask */
1133         fs->fsk_mask = fs->fs.flow_mask;
1134         if (fs->sched->sch.flags & DN_HAVE_MASK)
1135                 flow_id_or(&fs->sched->sch.sched_mask, &fs->fsk_mask);
1136         if (fs->qht) {
1137                 /*
1138                  * we must drain qht according to the old
1139                  * type, and reinsert according to the new one.
1140                  * The requeue is complex -- in general we need to
1141                  * reclassify every single packet.
1142                  * For the time being, let's hope qht is never set
1143                  * when we reach this point.
1144                  */
1145                 D("XXX TODO requeue from fs %d to sch %d",
1146                         fs->fs.fs_nr, s->sch.sched_nr);
1147                 fs->qht = NULL;
1148         }
1149         /* set the new type for qht */
1150         if (nonzero_mask(&fs->fsk_mask))
1151                 fs->fs.flags |= DN_QHT_HASH;
1152         else
1153                 fs->fs.flags &= ~DN_QHT_HASH;
1154
1155         /* XXX config_red() can fail... */
1156         if (fs->fs.flags & DN_IS_RED)
1157                 config_red(fs);
1158 }
1159
1160 /* update all flowsets which may refer to this scheduler */
1161 static void
1162 update_fs(struct dn_schk *s)
1163 {
1164         struct dn_fsk *fs, *tmp;
1165
1166         SLIST_FOREACH_SAFE(fs, &dn_cfg.fsu, sch_chain, tmp) {
1167                 if (s->sch.sched_nr != fs->fs.sched_nr) {
1168                         D("fs %d for sch %d not %d still unlinked",
1169                                 fs->fs.fs_nr, fs->fs.sched_nr,
1170                                 s->sch.sched_nr);
1171                         continue;
1172                 }
1173                 fsk_attach(fs, s);
1174         }
1175 }
1176
1177 /*
1178  * Configuration -- to preserve backward compatibility we use
1179  * the following scheme (N is 65536)
1180  *      NUMBER          SCHED   LINK    FLOWSET
1181  *         1 ..  N-1    (1)WFQ  (2)WFQ  (3)queue
1182  *       N+1 .. 2N-1    (4)FIFO (5)FIFO (6)FIFO for sched 1..N-1
1183  *      2N+1 .. 3N-1    --      --      (7)FIFO for sched N+1..2N-1
1184  *
1185  * "pipe i config" configures #1, #2 and #3
1186  * "sched i config" configures #1 and possibly #6
1187  * "queue i config" configures #3
1188  * #1 is configured with 'pipe i config' or 'sched i config'
1189  * #2 is configured with 'pipe i config', and created if not
1190  *      existing with 'sched i config'
1191  * #3 is configured with 'queue i config'
1192  * #4 is automatically configured after #1, can only be FIFO
1193  * #5 is automatically configured after #2
1194  * #6 is automatically created when #1 is !MULTIQUEUE,
1195  *      and can be updated.
1196  * #7 is automatically configured after #2
1197  */
1198
1199 /*
1200  * configure a link (and its FIFO instance)
1201  */
1202 static int
1203 config_link(struct dn_link *p, struct dn_id *arg)
1204 {
1205         int i;
1206
1207         if (p->oid.len != sizeof(*p)) {
1208                 D("invalid pipe len %d", p->oid.len);
1209                 return EINVAL;
1210         }
1211         i = p->link_nr;
1212         if (i <= 0 || i >= DN_MAX_ID)
1213                 return EINVAL;
1214         /*
1215          * The config program passes parameters as follows:
1216          * bw = bits/second (0 means no limits),
1217          * delay = ms, must be translated into ticks.
1218          * qsize = slots/bytes
1219          * burst ???
1220          */
1221         p->delay = (p->delay * hz) / 1000;
1222         /* Scale burst size: bytes -> bits * hz */
1223         p->burst *= 8 * hz;
1224
1225         DN_BH_WLOCK();
1226         /* do it twice, base link and FIFO link */
1227         for (; i < 2*DN_MAX_ID; i += DN_MAX_ID) {
1228             struct dn_schk *s = locate_scheduler(i);
1229             if (s == NULL) {
1230                 DN_BH_WUNLOCK();
1231                 D("sched %d not found", i);
1232                 return EINVAL;
1233             }
1234             /* remove profile if exists */
1235             if (s->profile) {
1236                 free(s->profile, M_DUMMYNET);
1237                 s->profile = NULL;
1238             }
1239             /* copy all parameters */
1240             s->link.oid = p->oid;
1241             s->link.link_nr = i;
1242             s->link.delay = p->delay;
1243             if (s->link.bandwidth != p->bandwidth) {
1244                 /* XXX bandwidth changes, need to update red params */
1245             s->link.bandwidth = p->bandwidth;
1246                 update_red(s);
1247             }
1248             s->link.burst = p->burst;
1249             schk_reset_credit(s);
1250         }
1251         dn_cfg.id++;
1252         DN_BH_WUNLOCK();
1253         return 0;
1254 }
1255
1256 /*
1257  * configure a flowset. Can be called from inside with locked=1,
1258  */
1259 static struct dn_fsk *
1260 config_fs(struct dn_fs *nfs, struct dn_id *arg, int locked)
1261 {
1262         int i;
1263         struct dn_fsk *fs;
1264
1265         if (nfs->oid.len != sizeof(*nfs)) {
1266                 D("invalid flowset len %d", nfs->oid.len);
1267                 return NULL;
1268         }
1269         i = nfs->fs_nr;
1270         if (i <= 0 || i >= 3*DN_MAX_ID)
1271                 return NULL;
1272         ND("flowset %d", i);
1273         /* XXX other sanity checks */
1274         if (nfs->flags & DN_QSIZE_BYTES) {
1275                 ipdn_bound_var(&nfs->qsize, 16384,
1276                     1500, dn_cfg.byte_limit, NULL); // "queue byte size");
1277         } else {
1278                 ipdn_bound_var(&nfs->qsize, 50,
1279                     1, dn_cfg.slot_limit, NULL); // "queue slot size");
1280         }
1281         if (nfs->flags & DN_HAVE_MASK) {
1282                 /* make sure we have some buckets */
1283                 ipdn_bound_var(&nfs->buckets, dn_cfg.hash_size,
1284                         1, dn_cfg.max_hash_size, "flowset buckets");
1285         } else {
1286                 nfs->buckets = 1;       /* we only need 1 */
1287         }
1288         if (!locked)
1289                 DN_BH_WLOCK();
1290         do { /* exit with break when done */
1291             struct dn_schk *s;
1292             int flags = nfs->sched_nr ? DNHT_INSERT : 0;
1293             int j;
1294             int oldc = dn_cfg.fsk_count;
1295             fs = dn_ht_find(dn_cfg.fshash, i, flags, NULL);
1296             if (fs == NULL) {
1297                 D("missing sched for flowset %d", i);
1298                 break;
1299             }
1300             /* grab some defaults from the existing one */
1301             if (nfs->sched_nr == 0) /* reuse */
1302                 nfs->sched_nr = fs->fs.sched_nr;
1303             for (j = 0; j < sizeof(nfs->par)/sizeof(nfs->par[0]); j++) {
1304                 if (nfs->par[j] == -1) /* reuse */
1305                     nfs->par[j] = fs->fs.par[j];
1306             }
1307             if (bcmp(&fs->fs, nfs, sizeof(*nfs)) == 0) {
1308                 ND("flowset %d unchanged", i);
1309                 break; /* no change, nothing to do */
1310             }
1311             if (oldc != dn_cfg.fsk_count)       /* new item */
1312                 dn_cfg.id++;
1313             s = locate_scheduler(nfs->sched_nr);
1314             /* detach from old scheduler if needed, preserving
1315              * queues if we need to reattach. Then update the
1316              * configuration, and possibly attach to the new sched.
1317              */
1318             DX(2, "fs %d changed sched %d@%p to %d@%p",
1319                 fs->fs.fs_nr,
1320                 fs->fs.sched_nr, fs->sched, nfs->sched_nr, s);
1321             if (fs->sched) {
1322                 int flags = s ? DN_DETACH : (DN_DETACH | DN_DESTROY);
1323                 flags |= DN_DESTROY; /* XXX temporary */
1324                 fsk_detach(fs, flags);
1325             }
1326             fs->fs = *nfs; /* copy configuration */
1327             if (s != NULL)
1328                 fsk_attach(fs, s);
1329         } while (0);
1330         if (!locked)
1331                 DN_BH_WUNLOCK();
1332         return fs;
1333 }
1334
1335 /*
1336  * config/reconfig a scheduler and its FIFO variant.
1337  * For !MULTIQUEUE schedulers, also set up the flowset.
1338  *
1339  * On reconfigurations (detected because s->fp is set),
1340  * detach existing flowsets preserving traffic, preserve link,
1341  * and delete the old scheduler creating a new one.
1342  */
1343 static int
1344 config_sched(struct dn_sch *_nsch, struct dn_id *arg)
1345 {
1346         struct dn_schk *s;
1347         struct schk_new_arg a; /* argument for schk_new */
1348         int i;
1349         struct dn_link p;       /* copy of oldlink */
1350         struct dn_profile *pf = NULL;   /* copy of old link profile */
1351         /* Used to preserv mask parameter */
1352         struct ipfw_flow_id new_mask;
1353         int new_buckets = 0;
1354         int new_flags = 0;
1355         int pipe_cmd;
1356         int err = ENOMEM;
1357
1358         a.sch = _nsch;
1359         if (a.sch->oid.len != sizeof(*a.sch)) {
1360                 D("bad sched len %d", a.sch->oid.len);
1361                 return EINVAL;
1362         }
1363         i = a.sch->sched_nr;
1364         if (i <= 0 || i >= DN_MAX_ID)
1365                 return EINVAL;
1366         /* make sure we have some buckets */
1367         if (a.sch->flags & DN_HAVE_MASK)
1368                 ipdn_bound_var(&a.sch->buckets, dn_cfg.hash_size,
1369                         1, dn_cfg.max_hash_size, "sched buckets");
1370         /* XXX other sanity checks */
1371         bzero(&p, sizeof(p));
1372
1373         pipe_cmd = a.sch->flags & DN_PIPE_CMD;
1374         a.sch->flags &= ~DN_PIPE_CMD; //XXX do it even if is not set?
1375         if (pipe_cmd) {
1376                 /* Copy mask parameter */
1377                 new_mask = a.sch->sched_mask;
1378                 new_buckets = a.sch->buckets;
1379                 new_flags = a.sch->flags;
1380         }
1381         DN_BH_WLOCK();
1382 again: /* run twice, for wfq and fifo */
1383         /*
1384          * lookup the type. If not supplied, use the previous one
1385          * or default to WF2Q+. Otherwise, return an error.
1386          */
1387         dn_cfg.id++;
1388         a.fp = find_sched_type(a.sch->oid.subtype, a.sch->name);
1389         if (a.fp != NULL) {
1390                 /* found. Lookup or create entry */
1391                 s = dn_ht_find(dn_cfg.schedhash, i, DNHT_INSERT, &a);
1392         } else if (a.sch->oid.subtype == 0 && !a.sch->name[0]) {
1393                 /* No type. search existing s* or retry with WF2Q+ */
1394                 s = dn_ht_find(dn_cfg.schedhash, i, 0, &a);
1395                 if (s != NULL) {
1396                         a.fp = s->fp;
1397                         /* Scheduler exists, skip to FIFO scheduler 
1398                          * if command was pipe config...
1399                          */
1400                         if (pipe_cmd)
1401                                 goto next;
1402                 } else {
1403                         /* New scheduler, create a wf2q+ with no mask
1404                          * if command was pipe config...
1405                          */
1406                         if (pipe_cmd) {
1407                                 /* clear mask parameter */
1408                                 bzero(&a.sch->sched_mask, sizeof(new_mask));
1409                                 a.sch->buckets = 0;
1410                                 a.sch->flags &= ~DN_HAVE_MASK;
1411                         }
1412                         a.sch->oid.subtype = DN_SCHED_WF2QP;
1413                         goto again;
1414                 }
1415         } else {
1416                 D("invalid scheduler type %d %s",
1417                         a.sch->oid.subtype, a.sch->name);
1418                 err = EINVAL;
1419                 goto error;
1420         }
1421         /* normalize name and subtype */
1422         a.sch->oid.subtype = a.fp->type;
1423         bzero(a.sch->name, sizeof(a.sch->name));
1424         strlcpy(a.sch->name, a.fp->name, sizeof(a.sch->name));
1425         if (s == NULL) {
1426                 D("cannot allocate scheduler %d", i);
1427                 goto error;
1428         }
1429         /* restore existing link if any */
1430         if (p.link_nr) {
1431                 s->link = p;
1432                 if (!pf || pf->link_nr != p.link_nr) { /* no saved value */
1433                         s->profile = NULL; /* XXX maybe not needed */
1434                 } else {
1435                         s->profile = malloc(sizeof(struct dn_profile),
1436                                              M_DUMMYNET, M_NOWAIT | M_ZERO);
1437                         if (s->profile == NULL) {
1438                                 D("cannot allocate profile");
1439                                 goto error; //XXX
1440                         }
1441                         bcopy(pf, s->profile, sizeof(*pf));
1442                 }
1443         }
1444         p.link_nr = 0;
1445         if (s->fp == NULL) {
1446                 DX(2, "sched %d new type %s", i, a.fp->name);
1447         } else if (s->fp != a.fp ||
1448                         bcmp(a.sch, &s->sch, sizeof(*a.sch)) ) {
1449                 /* already existing. */
1450                 DX(2, "sched %d type changed from %s to %s",
1451                         i, s->fp->name, a.fp->name);
1452                 DX(4, "   type/sub %d/%d -> %d/%d",
1453                         s->sch.oid.type, s->sch.oid.subtype, 
1454                         a.sch->oid.type, a.sch->oid.subtype);
1455                 if (s->link.link_nr == 0)
1456                         D("XXX WARNING link 0 for sched %d", i);
1457                 p = s->link;    /* preserve link */
1458                 if (s->profile) {/* preserve profile */
1459                         if (!pf)
1460                                 pf = malloc(sizeof(*pf),
1461                                     M_DUMMYNET, M_NOWAIT | M_ZERO);
1462                         if (pf) /* XXX should issue a warning otherwise */
1463                                 bcopy(s->profile, pf, sizeof(*pf));
1464                 }
1465                 /* remove from the hash */
1466                 dn_ht_find(dn_cfg.schedhash, i, DNHT_REMOVE, NULL);
1467                 /* Detach flowsets, preserve queues. */
1468                 // schk_delete_cb(s, NULL);
1469                 // XXX temporarily, kill queues
1470                 schk_delete_cb(s, (void *)DN_DESTROY);
1471                 goto again;
1472         } else {
1473                 DX(4, "sched %d unchanged type %s", i, a.fp->name);
1474         }
1475         /* complete initialization */
1476         s->sch = *a.sch;
1477         s->fp = a.fp;
1478         s->cfg = arg;
1479         // XXX schk_reset_credit(s);
1480         /* create the internal flowset if needed,
1481          * trying to reuse existing ones if available
1482          */
1483         if (!(s->fp->flags & DN_MULTIQUEUE) && !s->fs) {
1484                 s->fs = dn_ht_find(dn_cfg.fshash, i, 0, NULL);
1485                 if (!s->fs) {
1486                         struct dn_fs fs;
1487                         bzero(&fs, sizeof(fs));
1488                         set_oid(&fs.oid, DN_FS, sizeof(fs));
1489                         fs.fs_nr = i + DN_MAX_ID;
1490                         fs.sched_nr = i;
1491                         s->fs = config_fs(&fs, NULL, 1 /* locked */);
1492                 }
1493                 if (!s->fs) {
1494                         schk_delete_cb(s, (void *)DN_DESTROY);
1495                         D("error creating internal fs for %d", i);
1496                         goto error;
1497                 }
1498         }
1499         /* call init function after the flowset is created */
1500         if (s->fp->config)
1501                 s->fp->config(s);
1502         update_fs(s);
1503 next:
1504         if (i < DN_MAX_ID) { /* now configure the FIFO instance */
1505                 i += DN_MAX_ID;
1506                 if (pipe_cmd) {
1507                         /* Restore mask parameter for FIFO */
1508                         a.sch->sched_mask = new_mask;
1509                         a.sch->buckets = new_buckets;
1510                         a.sch->flags = new_flags;
1511                 } else {
1512                         /* sched config shouldn't modify the FIFO scheduler */
1513                         if (dn_ht_find(dn_cfg.schedhash, i, 0, &a) != NULL) {
1514                                 /* FIFO already exist, don't touch it */
1515                                 err = 0; /* and this is not an error */
1516                                 goto error;
1517                         }
1518                 }
1519                 a.sch->sched_nr = i;
1520                 a.sch->oid.subtype = DN_SCHED_FIFO;
1521                 bzero(a.sch->name, sizeof(a.sch->name));
1522                 goto again;
1523         }
1524         err = 0;
1525 error:
1526         DN_BH_WUNLOCK();
1527         if (pf)
1528                 free(pf, M_DUMMYNET);
1529         return err;
1530 }
1531
1532 /*
1533  * attach a profile to a link
1534  */
1535 static int
1536 config_profile(struct dn_profile *pf, struct dn_id *arg)
1537 {
1538         struct dn_schk *s;
1539         int i, olen, err = 0;
1540
1541         if (pf->oid.len < sizeof(*pf)) {
1542                 D("short profile len %d", pf->oid.len);
1543                 return EINVAL;
1544         }
1545         i = pf->link_nr;
1546         if (i <= 0 || i >= DN_MAX_ID)
1547                 return EINVAL;
1548         /* XXX other sanity checks */
1549         DN_BH_WLOCK();
1550         for (; i < 2*DN_MAX_ID; i += DN_MAX_ID) {
1551                 s = locate_scheduler(i);
1552
1553                 if (s == NULL) {
1554                         err = EINVAL;
1555                         break;
1556                 }
1557                 dn_cfg.id++;
1558                 /*
1559                  * If we had a profile and the new one does not fit,
1560                  * or it is deleted, then we need to free memory.
1561                  */
1562                 if (s->profile && (pf->samples_no == 0 ||
1563                     s->profile->oid.len < pf->oid.len)) {
1564                         free(s->profile, M_DUMMYNET);
1565                         s->profile = NULL;
1566                 }
1567                 if (pf->samples_no == 0)
1568                         continue;
1569                 /*
1570                  * new profile, possibly allocate memory
1571                  * and copy data.
1572                  */
1573                 if (s->profile == NULL)
1574                         s->profile = malloc(pf->oid.len,
1575                                     M_DUMMYNET, M_NOWAIT | M_ZERO);
1576                 if (s->profile == NULL) {
1577                         D("no memory for profile %d", i);
1578                         err = ENOMEM;
1579                         break;
1580                 }
1581                 /* preserve larger length XXX double check */
1582                 olen = s->profile->oid.len;
1583                 if (olen < pf->oid.len)
1584                         olen = pf->oid.len;
1585                 bcopy(pf, s->profile, pf->oid.len);
1586                 s->profile->oid.len = olen;
1587         }
1588         DN_BH_WUNLOCK();
1589         return err;
1590 }
1591
1592 /*
1593  * Delete all objects:
1594  */
1595 static void
1596 dummynet_flush(void)
1597 {
1598
1599         /* delete all schedulers and related links/queues/flowsets */
1600         dn_ht_scan(dn_cfg.schedhash, schk_delete_cb,
1601                 (void *)(uintptr_t)DN_DELETE_FS);
1602         /* delete all remaining (unlinked) flowsets */
1603         DX(4, "still %d unlinked fs", dn_cfg.fsk_count);
1604         dn_ht_free(dn_cfg.fshash, DNHT_REMOVE);
1605         fsk_detach_list(&dn_cfg.fsu, DN_DELETE_FS);
1606         /* Reinitialize system heap... */
1607         heap_init(&dn_cfg.evheap, 16, offsetof(struct dn_id, id));
1608 }
1609
1610 /*
1611  * Main handler for configuration. We are guaranteed to be called
1612  * with an oid which is at least a dn_id.
1613  * - the first object is the command (config, delete, flush, ...)
1614  * - config_link must be issued after the corresponding config_sched
1615  * - parameters (DN_TXT) for an object must preceed the object
1616  *   processed on a config_sched.
1617  */
1618 int
1619 do_config(void *p, int l)
1620 {
1621         struct dn_id *next, *o;
1622         int err = 0, err2 = 0;
1623         struct dn_id *arg = NULL;
1624         uintptr_t *a;
1625
1626         o = p;
1627         if (o->id != DN_API_VERSION) {
1628                 D("invalid api version got %d need %d",
1629                         o->id, DN_API_VERSION);
1630                 return EINVAL;
1631         }
1632         for (; l >= sizeof(*o); o = next) {
1633                 struct dn_id *prev = arg;
1634                 if (o->len < sizeof(*o) || l < o->len) {
1635                         D("bad len o->len %d len %d", o->len, l);
1636                         err = EINVAL;
1637                         break;
1638                 }
1639                 l -= o->len;
1640                 next = (struct dn_id *)((char *)o + o->len);
1641                 err = 0;
1642                 switch (o->type) {
1643                 default:
1644                         D("cmd %d not implemented", o->type);
1645                         break;
1646 #ifdef EMULATE_SYSCTL
1647                 /* sysctl emulation.
1648                  * if we recognize the command, jump to the correct
1649                  * handler and return
1650                  */
1651                 case DN_SYSCTL_SET:
1652                         err = kesysctl_emu_set(p,l);
1653                         return err;
1654 #endif
1655                 case DN_CMD_CONFIG: /* simply a header */
1656                         break;
1657
1658                 case DN_CMD_DELETE:
1659                         /* the argument is in the first uintptr_t after o */
1660                         a = (uintptr_t *)(o+1);
1661                         if (o->len < sizeof(*o) + sizeof(*a)) {
1662                                 err = EINVAL;
1663                                 break;
1664                         }
1665                         switch (o->subtype) {
1666                         case DN_LINK:
1667                                 /* delete base and derived schedulers */
1668                                 DN_BH_WLOCK();
1669                                 err = delete_schk(*a);
1670                                 err2 = delete_schk(*a + DN_MAX_ID);
1671                                 DN_BH_WUNLOCK();
1672                                 if (!err)
1673                                         err = err2;
1674                                 break;
1675
1676                         default:
1677                                 D("invalid delete type %d",
1678                                         o->subtype);
1679                                 err = EINVAL;
1680                                 break;
1681
1682                         case DN_FS:
1683                                 err = (*a <1 || *a >= DN_MAX_ID) ?
1684                                         EINVAL : delete_fs(*a, 0) ;
1685                                 break;
1686                         }
1687                         break;
1688
1689                 case DN_CMD_FLUSH:
1690                         DN_BH_WLOCK();
1691                         dummynet_flush();
1692                         DN_BH_WUNLOCK();
1693                         break;
1694                 case DN_TEXT:   /* store argument the next block */
1695                         prev = NULL;
1696                         arg = o;
1697                         break;
1698                 case DN_LINK:
1699                         err = config_link((struct dn_link *)o, arg);
1700                         break;
1701                 case DN_PROFILE:
1702                         err = config_profile((struct dn_profile *)o, arg);
1703                         break;
1704                 case DN_SCH:
1705                         err = config_sched((struct dn_sch *)o, arg);
1706                         break;
1707                 case DN_FS:
1708                         err = (NULL==config_fs((struct dn_fs *)o, arg, 0));
1709                         break;
1710                 }
1711                 if (prev)
1712                         arg = NULL;
1713                 if (err != 0)
1714                         break;
1715         }
1716         return err;
1717 }
1718
1719 static int
1720 compute_space(struct dn_id *cmd, struct copy_args *a)
1721 {
1722         int x = 0, need = 0;
1723         int profile_size = sizeof(struct dn_profile) - 
1724                 ED_MAX_SAMPLES_NO*sizeof(int);
1725
1726         /* NOTE about compute space:
1727          * NP   = dn_cfg.schk_count
1728          * NSI  = dn_cfg.si_count
1729          * NF   = dn_cfg.fsk_count
1730          * NQ   = dn_cfg.queue_count
1731          * - ipfw pipe show
1732          *   (NP/2)*(dn_link + dn_sch + dn_id + dn_fs) only half scheduler
1733          *                             link, scheduler template, flowset
1734          *                             integrated in scheduler and header
1735          *                             for flowset list
1736          *   (NSI)*(dn_flow) all scheduler instance (includes
1737          *                              the queue instance)
1738          * - ipfw sched show
1739          *   (NP/2)*(dn_link + dn_sch + dn_id + dn_fs) only half scheduler
1740          *                             link, scheduler template, flowset
1741          *                             integrated in scheduler and header
1742          *                             for flowset list
1743          *   (NSI * dn_flow) all scheduler instances
1744          *   (NF * sizeof(uint_32)) space for flowset list linked to scheduler
1745          *   (NQ * dn_queue) all queue [XXXfor now not listed]
1746          * - ipfw queue show
1747          *   (NF * dn_fs) all flowset
1748          *   (NQ * dn_queue) all queues
1749          */
1750         switch (cmd->subtype) {
1751         default:
1752                 return -1;
1753         /* XXX where do LINK and SCH differ ? */
1754         /* 'ipfw sched show' could list all queues associated to
1755          * a scheduler. This feature for now is disabled
1756          */
1757         case DN_LINK:   /* pipe show */
1758                 x = DN_C_LINK | DN_C_SCH | DN_C_FLOW;
1759                 need += dn_cfg.schk_count *
1760                         (sizeof(struct dn_fs) + profile_size) / 2;
1761                 need += dn_cfg.fsk_count * sizeof(uint32_t);
1762                 break;
1763         case DN_SCH:    /* sched show */
1764                 need += dn_cfg.schk_count *
1765                         (sizeof(struct dn_fs) + profile_size) / 2;
1766                 need += dn_cfg.fsk_count * sizeof(uint32_t);
1767                 x = DN_C_SCH | DN_C_LINK | DN_C_FLOW;
1768                 break;
1769         case DN_FS:     /* queue show */
1770                 x = DN_C_FS | DN_C_QUEUE;
1771                 break;
1772         case DN_GET_COMPAT:     /* compatibility mode */
1773                 need =  dn_compat_calc_size(); 
1774                 break;
1775         }
1776         a->flags = x;
1777         if (x & DN_C_SCH) {
1778                 need += dn_cfg.schk_count * sizeof(struct dn_sch) / 2;
1779                 /* NOT also, each fs might be attached to a sched */
1780                 need += dn_cfg.schk_count * sizeof(struct dn_id) / 2;
1781         }
1782         if (x & DN_C_FS)
1783                 need += dn_cfg.fsk_count * sizeof(struct dn_fs);
1784         if (x & DN_C_LINK) {
1785                 need += dn_cfg.schk_count * sizeof(struct dn_link) / 2;
1786         }
1787         /*
1788          * When exporting a queue to userland, only pass up the
1789          * struct dn_flow, which is the only visible part.
1790          */
1791
1792         if (x & DN_C_QUEUE)
1793                 need += dn_cfg.queue_count * sizeof(struct dn_flow);
1794         if (x & DN_C_FLOW)
1795                 need += dn_cfg.si_count * (sizeof(struct dn_flow));
1796         return need;
1797 }
1798
1799 /*
1800  * If compat != NULL dummynet_get is called in compatibility mode.
1801  * *compat will be the pointer to the buffer to pass to ipfw
1802  */
1803 int
1804 dummynet_get(struct sockopt *sopt, void **compat)
1805 {
1806         int have, i, need, error;
1807         char *start = NULL, *buf;
1808         size_t sopt_valsize;
1809         struct dn_id *cmd;
1810         struct copy_args a;
1811         struct copy_range r;
1812         int l = sizeof(struct dn_id);
1813
1814         bzero(&a, sizeof(a));
1815         bzero(&r, sizeof(r));
1816
1817         /* save and restore original sopt_valsize around copyin */
1818         sopt_valsize = sopt->sopt_valsize;
1819
1820         cmd = &r.o;
1821
1822         if (!compat) {
1823                 /* copy at least an oid, and possibly a full object */
1824                 error = sooptcopyin(sopt, cmd, sizeof(r), sizeof(*cmd));
1825                 sopt->sopt_valsize = sopt_valsize;
1826                 if (error)
1827                         goto done;
1828                 l = cmd->len;
1829 #ifdef EMULATE_SYSCTL
1830                 /* sysctl emulation. */
1831                 if (cmd->type == DN_SYSCTL_GET)
1832                         return kesysctl_emu_get(sopt);
1833 #endif
1834                 if (l > sizeof(r)) {
1835                         /* request larger than default, allocate buffer */
1836                         cmd = malloc(l,  M_DUMMYNET, M_WAIT);
1837                         if (cmd == NULL)
1838                                 return ENOMEM; //XXX
1839                         error = sooptcopyin(sopt, cmd, l, l);
1840                         sopt->sopt_valsize = sopt_valsize;
1841                         if (error)
1842                                 goto done;
1843                 }
1844         } else { /* compatibility */
1845                 error = 0;
1846                 cmd->type = DN_CMD_GET;
1847                 cmd->len = sizeof(struct dn_id);
1848                 cmd->subtype = DN_GET_COMPAT;
1849                 // cmd->id = sopt_valsize;
1850                 D("compatibility mode");
1851         }
1852         a.extra = (struct copy_range *)cmd;
1853         if (cmd->len == sizeof(*cmd)) { /* no range, create a default */
1854                 uint32_t *rp = (uint32_t *)(cmd + 1);
1855                 cmd->len += 2* sizeof(uint32_t);
1856                 rp[0] = 1;
1857                 rp[1] = DN_MAX_ID - 1;
1858                 if (cmd->subtype == DN_LINK) {
1859                         rp[0] += DN_MAX_ID;
1860                         rp[1] += DN_MAX_ID;
1861                 }
1862         }
1863         /* Count space (under lock) and allocate (outside lock).
1864          * Exit with lock held if we manage to get enough buffer.
1865          * Try a few times then give up.
1866          */
1867         for (have = 0, i = 0; i < 10; i++) {
1868                 DN_BH_WLOCK();
1869                 need = compute_space(cmd, &a);
1870
1871                 /* if there is a range, ignore value from compute_space() */
1872                 if (l > sizeof(*cmd))
1873                         need = sopt_valsize - sizeof(*cmd);
1874
1875                 if (need < 0) {
1876                         DN_BH_WUNLOCK();
1877                         error = EINVAL;
1878                         goto done;
1879                 }
1880                 need += sizeof(*cmd);
1881                 cmd->id = need;
1882                 if (have >= need)
1883                         break;
1884
1885                 DN_BH_WUNLOCK();
1886                 if (start)
1887                         free(start, M_DUMMYNET);
1888                 start = NULL;
1889                 if (need > sopt_valsize)
1890                         break;
1891
1892                 have = need;
1893                 start = malloc(have, M_DUMMYNET, M_WAITOK | M_ZERO);
1894                 if (start == NULL) {
1895                         error = ENOMEM;
1896                         goto done;
1897                 }
1898         }
1899
1900         if (start == NULL) {
1901                 if (compat) {
1902                         *compat = NULL;
1903                         error =  1; // XXX
1904                 } else {
1905                         error = sooptcopyout(sopt, cmd, sizeof(*cmd));
1906                 }
1907                 goto done;
1908         }
1909         ND("have %d:%d sched %d, %d:%d links %d, %d:%d flowsets %d, "
1910                 "%d:%d si %d, %d:%d queues %d",
1911                 dn_cfg.schk_count, sizeof(struct dn_sch), DN_SCH,
1912                 dn_cfg.schk_count, sizeof(struct dn_link), DN_LINK,
1913                 dn_cfg.fsk_count, sizeof(struct dn_fs), DN_FS,
1914                 dn_cfg.si_count, sizeof(struct dn_flow), DN_SCH_I,
1915                 dn_cfg.queue_count, sizeof(struct dn_queue), DN_QUEUE);
1916         sopt->sopt_valsize = sopt_valsize;
1917         a.type = cmd->subtype;
1918
1919         if (compat == NULL) {
1920                 bcopy(cmd, start, sizeof(*cmd));
1921                 ((struct dn_id*)(start))->len = sizeof(struct dn_id);
1922                 buf = start + sizeof(*cmd);
1923         } else
1924                 buf = start;
1925         a.start = &buf;
1926         a.end = start + have;
1927         /* start copying other objects */
1928         if (compat) {
1929                 a.type = DN_COMPAT_PIPE;
1930                 dn_ht_scan(dn_cfg.schedhash, copy_data_helper_compat, &a);
1931                 a.type = DN_COMPAT_QUEUE;
1932                 dn_ht_scan(dn_cfg.fshash, copy_data_helper_compat, &a);
1933         } else if (a.type == DN_FS) {
1934                 dn_ht_scan(dn_cfg.fshash, copy_data_helper, &a);
1935         } else {
1936                 dn_ht_scan(dn_cfg.schedhash, copy_data_helper, &a);
1937         }
1938         DN_BH_WUNLOCK();
1939
1940         if (compat) {
1941                 *compat = start;
1942                 sopt->sopt_valsize = buf - start;
1943                 /* free() is done by ip_dummynet_compat() */
1944                 start = NULL; //XXX hack
1945         } else {
1946                 error = sooptcopyout(sopt, start, buf - start);
1947         }
1948 done:
1949         if (cmd && cmd != &r.o)
1950                 free(cmd, M_DUMMYNET);
1951         if (start)
1952                 free(start, M_DUMMYNET);
1953         return error;
1954 }
1955
1956 /* Callback called on scheduler instance to delete it if idle */
1957 static int
1958 drain_scheduler_cb(void *_si, void *arg)
1959 {
1960         struct dn_sch_inst *si = _si;
1961
1962         if ((si->kflags & DN_ACTIVE) || si->dline.mq.head != NULL)
1963                 return 0;
1964
1965         if (si->sched->fp->flags & DN_MULTIQUEUE) {
1966                 if (si->q_count == 0)
1967                         return si_destroy(si, NULL);
1968                 else
1969                         return 0;
1970         } else { /* !DN_MULTIQUEUE */
1971                 if ((si+1)->ni.length == 0)
1972                         return si_destroy(si, NULL);
1973                 else
1974                         return 0;
1975         }
1976         return 0; /* unreachable */
1977 }
1978
1979 /* Callback called on scheduler to check if it has instances */
1980 static int
1981 drain_scheduler_sch_cb(void *_s, void *arg)
1982 {
1983         struct dn_schk *s = _s;
1984
1985         if (s->sch.flags & DN_HAVE_MASK) {
1986                 dn_ht_scan_bucket(s->siht, &s->drain_bucket,
1987                                 drain_scheduler_cb, NULL);
1988                 s->drain_bucket++;
1989         } else {
1990                 if (s->siht) {
1991                         if (drain_scheduler_cb(s->siht, NULL) == DNHT_SCAN_DEL)
1992                                 s->siht = NULL;
1993                 }
1994         }
1995         return 0;
1996 }
1997
1998 /* Called every tick, try to delete a 'bucket' of scheduler */
1999 void
2000 dn_drain_scheduler(void)
2001 {
2002         dn_ht_scan_bucket(dn_cfg.schedhash, &dn_cfg.drain_sch,
2003                            drain_scheduler_sch_cb, NULL);
2004         dn_cfg.drain_sch++;
2005 }
2006
2007 /* Callback called on queue to delete if it is idle */
2008 static int
2009 drain_queue_cb(void *_q, void *arg)
2010 {
2011         struct dn_queue *q = _q;
2012
2013         if (q->ni.length == 0) {
2014                 dn_delete_queue(q, DN_DESTROY);
2015                 return DNHT_SCAN_DEL; /* queue is deleted */
2016         }
2017
2018         return 0; /* queue isn't deleted */
2019 }
2020
2021 /* Callback called on flowset used to check if it has queues */
2022 static int
2023 drain_queue_fs_cb(void *_fs, void *arg)
2024 {
2025         struct dn_fsk *fs = _fs;
2026
2027         if (fs->fs.flags & DN_QHT_HASH) {
2028                 /* Flowset has a hash table for queues */
2029                 dn_ht_scan_bucket(fs->qht, &fs->drain_bucket,
2030                                 drain_queue_cb, NULL);
2031                 fs->drain_bucket++;
2032         } else {
2033                 /* No hash table for this flowset, null the pointer 
2034                  * if the queue is deleted
2035                  */
2036                 if (fs->qht) {
2037                         if (drain_queue_cb(fs->qht, NULL) == DNHT_SCAN_DEL)
2038                                 fs->qht = NULL;
2039                 }
2040         }
2041         return 0;
2042 }
2043
2044 /* Called every tick, try to delete a 'bucket' of queue */
2045 void
2046 dn_drain_queue(void)
2047 {
2048         /* scan a bucket of flowset */
2049         dn_ht_scan_bucket(dn_cfg.fshash, &dn_cfg.drain_fs,
2050                                drain_queue_fs_cb, NULL);
2051         dn_cfg.drain_fs++;
2052 }
2053
2054 /*
2055  * Handler for the various dummynet socket options
2056  */
2057 static int
2058 ip_dn_ctl(struct sockopt *sopt)
2059 {
2060         void *p = NULL;
2061         int error, l;
2062
2063         error = priv_check(sopt->sopt_td, PRIV_NETINET_DUMMYNET);
2064         if (error)
2065                 return (error);
2066
2067         /* Disallow sets in really-really secure mode. */
2068         if (sopt->sopt_dir == SOPT_SET) {
2069                 error =  securelevel_ge(sopt->sopt_td->td_ucred, 3);
2070                 if (error)
2071                         return (error);
2072         }
2073
2074         switch (sopt->sopt_name) {
2075         default :
2076                 D("dummynet: unknown option %d", sopt->sopt_name);
2077                 error = EINVAL;
2078                 break;
2079
2080         case IP_DUMMYNET_FLUSH:
2081         case IP_DUMMYNET_CONFIGURE:
2082         case IP_DUMMYNET_DEL:   /* remove a pipe or queue */
2083         case IP_DUMMYNET_GET:
2084                 D("dummynet: compat option %d", sopt->sopt_name);
2085                 error = ip_dummynet_compat(sopt);
2086                 break;
2087
2088         case IP_DUMMYNET3 :
2089                 if (sopt->sopt_dir == SOPT_GET) {
2090                         error = dummynet_get(sopt, NULL);
2091                         break;
2092                 }
2093                 l = sopt->sopt_valsize;
2094                 if (l < sizeof(struct dn_id) || l > 12000) {
2095                         D("argument len %d invalid", l);
2096                         break;
2097                 }
2098                 p = malloc(l, M_TEMP, M_WAITOK); // XXX can it fail ?
2099                 error = sooptcopyin(sopt, p, l, l);
2100                 if (error)
2101                         break ;
2102                 error = do_config(p, l);
2103                 break;
2104         }
2105
2106         if (p != NULL)
2107                 free(p, M_TEMP);
2108
2109         return error ;
2110 }
2111
2112
2113 static void
2114 ip_dn_init(void)
2115 {
2116         static int init_done = 0;
2117
2118         if (init_done)
2119                 return;
2120         init_done = 1;
2121         if (bootverbose)
2122                 printf("DUMMYNET with IPv6 initialized (100131)\n");
2123
2124         /* Set defaults here. MSVC does not accept initializers,
2125          * and this is also useful for vimages
2126          */
2127         /* queue limits */
2128         dn_cfg.slot_limit = 100; /* Foot shooting limit for queues. */
2129         dn_cfg.byte_limit = 1024 * 1024;
2130         dn_cfg.expire = 1;
2131
2132         /* RED parameters */
2133         dn_cfg.red_lookup_depth = 256;  /* default lookup table depth */
2134         dn_cfg.red_avg_pkt_size = 512;  /* default medium packet size */
2135         dn_cfg.red_max_pkt_size = 1500; /* default max packet size */
2136
2137         /* hash tables */
2138         dn_cfg.max_hash_size = 1024;    /* max in the hash tables */
2139         dn_cfg.hash_size = 64;          /* default hash size */
2140
2141         /* create hash tables for schedulers and flowsets.
2142          * In both we search by key and by pointer.
2143          */
2144         dn_cfg.schedhash = dn_ht_init(NULL, dn_cfg.hash_size,
2145                 offsetof(struct dn_schk, schk_next),
2146                 schk_hash, schk_match, schk_new);
2147         dn_cfg.fshash = dn_ht_init(NULL, dn_cfg.hash_size,
2148                 offsetof(struct dn_fsk, fsk_next),
2149                 fsk_hash, fsk_match, fsk_new);
2150
2151         /* bucket index to drain object */
2152         dn_cfg.drain_fs = 0;
2153         dn_cfg.drain_sch = 0;
2154
2155         heap_init(&dn_cfg.evheap, 16, offsetof(struct dn_id, id));
2156         SLIST_INIT(&dn_cfg.fsu);
2157         SLIST_INIT(&dn_cfg.schedlist);
2158
2159         DN_LOCK_INIT();
2160         ip_dn_ctl_ptr = ip_dn_ctl;
2161         ip_dn_io_ptr = dummynet_io;
2162
2163         TASK_INIT(&dn_task, 0, dummynet_task, NULL);
2164         dn_tq = taskqueue_create_fast("dummynet", M_NOWAIT,
2165             taskqueue_thread_enqueue, &dn_tq);
2166         taskqueue_start_threads(&dn_tq, 1, PI_NET, "dummynet");
2167
2168         callout_init(&dn_timeout, CALLOUT_MPSAFE);
2169         callout_reset(&dn_timeout, 1, dummynet, NULL);
2170
2171         /* Initialize curr_time adjustment mechanics. */
2172         getmicrouptime(&dn_cfg.prev_t);
2173 }
2174
2175 #ifdef KLD_MODULE
2176 static void
2177 ip_dn_destroy(void)
2178 {
2179         callout_drain(&dn_timeout);
2180
2181         DN_BH_WLOCK();
2182         ip_dn_ctl_ptr = NULL;
2183         ip_dn_io_ptr = NULL;
2184
2185         dummynet_flush();
2186         DN_BH_WUNLOCK();
2187         taskqueue_drain(dn_tq, &dn_task);
2188         taskqueue_free(dn_tq);
2189
2190         dn_ht_free(dn_cfg.schedhash, 0);
2191         dn_ht_free(dn_cfg.fshash, 0);
2192         heap_free(&dn_cfg.evheap);
2193
2194         DN_LOCK_DESTROY();
2195 }
2196 #endif /* KLD_MODULE */
2197
2198 static int
2199 dummynet_modevent(module_t mod, int type, void *data)
2200 {
2201
2202         if (type == MOD_LOAD) {
2203                 if (ip_dn_io_ptr) {
2204                         printf("DUMMYNET already loaded\n");
2205                         return EEXIST ;
2206                 }
2207                 ip_dn_init();
2208                 return 0;
2209         } else if (type == MOD_UNLOAD) {
2210 #if !defined(KLD_MODULE)
2211                 printf("dummynet statically compiled, cannot unload\n");
2212                 return EINVAL ;
2213 #else
2214                 ip_dn_destroy();
2215                 return 0;
2216 #endif
2217         } else
2218                 return EOPNOTSUPP;
2219 }
2220
2221 /* modevent helpers for the modules */
2222 static int
2223 load_dn_sched(struct dn_alg *d)
2224 {
2225         struct dn_alg *s;
2226
2227         if (d == NULL)
2228                 return 1; /* error */
2229         ip_dn_init();   /* just in case, we need the lock */
2230
2231         /* Check that mandatory funcs exists */
2232         if (d->enqueue == NULL || d->dequeue == NULL) {
2233                 D("missing enqueue or dequeue for %s", d->name);
2234                 return 1;
2235         }
2236
2237         /* Search if scheduler already exists */
2238         DN_BH_WLOCK();
2239         SLIST_FOREACH(s, &dn_cfg.schedlist, next) {
2240                 if (strcmp(s->name, d->name) == 0) {
2241                         D("%s already loaded", d->name);
2242                         break; /* scheduler already exists */
2243                 }
2244         }
2245         if (s == NULL)
2246                 SLIST_INSERT_HEAD(&dn_cfg.schedlist, d, next);
2247         DN_BH_WUNLOCK();
2248         D("dn_sched %s %sloaded", d->name, s ? "not ":"");
2249         return s ? 1 : 0;
2250 }
2251
2252 static int
2253 unload_dn_sched(struct dn_alg *s)
2254 {
2255         struct dn_alg *tmp, *r;
2256         int err = EINVAL;
2257
2258         D("called for %s", s->name);
2259
2260         DN_BH_WLOCK();
2261         SLIST_FOREACH_SAFE(r, &dn_cfg.schedlist, next, tmp) {
2262                 if (strcmp(s->name, r->name) != 0)
2263                         continue;
2264                 D("ref_count = %d", r->ref_count);
2265                 err = (r->ref_count != 0) ? EBUSY : 0;
2266                 if (err == 0)
2267                         SLIST_REMOVE(&dn_cfg.schedlist, r, dn_alg, next);
2268                 break;
2269         }
2270         DN_BH_WUNLOCK();
2271         D("dn_sched %s %sunloaded", s->name, err ? "not ":"");
2272         return err;
2273 }
2274
2275 int
2276 dn_sched_modevent(module_t mod, int cmd, void *arg)
2277 {
2278         struct dn_alg *sch = arg;
2279
2280         if (cmd == MOD_LOAD)
2281                 return load_dn_sched(sch);
2282         else if (cmd == MOD_UNLOAD)
2283                 return unload_dn_sched(sch);
2284         else
2285                 return EINVAL;
2286 }
2287
2288 static moduledata_t dummynet_mod = {
2289         "dummynet", dummynet_modevent, NULL
2290 };
2291
2292 DECLARE_MODULE(dummynet, dummynet_mod,
2293         SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY-1);
2294 MODULE_DEPEND(dummynet, ipfw, 2, 2, 2);
2295 MODULE_VERSION(dummynet, 1);
2296 /* end of file */