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