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