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