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