if: Multiple TX queue support step 1 of many; introduce ifaltq subqueue
[dragonfly.git] / sys / net / altq / altq_fairq.c
1 /*
2  * Copyright (c) 2008 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * $DragonFly: src/sys/net/altq/altq_fairq.c,v 1.2 2008/05/14 11:59:23 sephe Exp $
35  */
36 /*
37  * Matt: I gutted altq_priq.c and used it as a skeleton on which to build
38  * fairq.  The fairq algorithm is completely different then priq, of course,
39  * but because I used priq's skeleton I believe I should include priq's
40  * copyright.
41  *
42  * Copyright (C) 2000-2003
43  *      Sony Computer Science Laboratories Inc.  All rights reserved.
44  *
45  * Redistribution and use in source and binary forms, with or without
46  * modification, are permitted provided that the following conditions
47  * are met:
48  * 1. Redistributions of source code must retain the above copyright
49  *    notice, this list of conditions and the following disclaimer.
50  * 2. Redistributions in binary form must reproduce the above copyright
51  *    notice, this list of conditions and the following disclaimer in the
52  *    documentation and/or other materials provided with the distribution.
53  *
54  * THIS SOFTWARE IS PROVIDED BY SONY CSL AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL SONY CSL OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  */
66
67 /*
68  * FAIRQ - take traffic classified by keep state (hashed into
69  *         pf->state_hash) and bucketize it.  Fairly extract
70  *         the first packet from each bucket in a round-robin fashion.
71  *
72  * TODO - better overall qlimit support (right now it is per-bucket).
73  *      - NOTE: red etc is per bucket, not overall.
74  *      - better service curve support.
75  *
76  * EXAMPLE:
77  *
78  *  altq on em0 fairq bandwidth 650Kb queue { std, bulk }
79  *  queue std  priority 3 bandwidth 200Kb \
80  *      fairq (buckets 64, default, hogs 1Kb) qlimit 50
81  *  queue bulk priority 2 bandwidth 100Kb \
82  *      fairq (buckets 64, hogs 1Kb) qlimit 50
83  *
84  *      NOTE: When the aggregate bandwidth is less than the link bandwidth
85  *            any remaining bandwidth is dynamically assigned using the
86  *            existing bandwidth specs as weightings.
87  *
88  *  pass out on em0 from any to any keep state queue std
89  *  pass out on em0 inet proto tcp ..... port ... keep state queue bulk
90  */
91 #include "opt_altq.h"
92 #include "opt_inet.h"
93 #include "opt_inet6.h"
94
95 #ifdef ALTQ_FAIRQ  /* fairq is enabled in the kernel conf */
96
97 #include <sys/param.h>
98 #include <sys/malloc.h>
99 #include <sys/mbuf.h>
100 #include <sys/socket.h>
101 #include <sys/sockio.h>
102 #include <sys/systm.h>
103 #include <sys/proc.h>
104 #include <sys/errno.h>
105 #include <sys/kernel.h>
106 #include <sys/queue.h>
107 #include <sys/thread.h>
108
109 #include <net/if.h>
110 #include <net/ifq_var.h>
111 #include <netinet/in.h>
112
113 #include <net/pf/pfvar.h>
114 #include <net/altq/altq.h>
115 #include <net/altq/altq_fairq.h>
116
117 #include <sys/thread2.h>
118
119 #define FAIRQ_SUBQ_INDEX        ALTQ_SUBQ_INDEX_DEFAULT
120 #define FAIRQ_LOCK(ifq) \
121     ALTQ_SQ_LOCK(&(ifq)->altq_subq[FAIRQ_SUBQ_INDEX])
122 #define FAIRQ_UNLOCK(ifq) \
123     ALTQ_SQ_UNLOCK(&(ifq)->altq_subq[FAIRQ_SUBQ_INDEX])
124
125 /*
126  * function prototypes
127  */
128 static int      fairq_clear_interface(struct fairq_if *);
129 static int      fairq_request(struct ifaltq_subque *, int, void *);
130 static void     fairq_purge(struct fairq_if *);
131 static struct fairq_class *fairq_class_create(struct fairq_if *, int,
132                                         int, u_int, struct fairq_opts *, int);
133 static int      fairq_class_destroy(struct fairq_class *);
134 static int      fairq_enqueue(struct ifaltq_subque *, struct mbuf *,
135                                         struct altq_pktattr *);
136 static struct mbuf *fairq_dequeue(struct ifaltq_subque *, struct mbuf *, int);
137
138 static int      fairq_addq(struct fairq_class *, struct mbuf *, int hash);
139 static struct mbuf *fairq_getq(struct fairq_class *, uint64_t);
140 static struct mbuf *fairq_pollq(struct fairq_class *, uint64_t, int *);
141 static fairq_bucket_t *fairq_selectq(struct fairq_class *, int);
142 static void     fairq_purgeq(struct fairq_class *);
143
144 static void     get_class_stats(struct fairq_classstats *,
145                                         struct fairq_class *);
146 static struct fairq_class *clh_to_clp(struct fairq_if *, uint32_t);
147
148 int
149 fairq_pfattach(struct pf_altq *a, struct ifaltq *ifq)
150 {
151         return altq_attach(ifq, ALTQT_FAIRQ, a->altq_disc,
152                            fairq_enqueue, fairq_dequeue,
153                            fairq_request, NULL, NULL);
154 }
155
156 int
157 fairq_add_altq(struct pf_altq *a)
158 {
159         struct fairq_if *pif;
160         struct ifnet *ifp;
161
162         if ((ifp = ifunit(a->ifname)) == NULL)
163                 return (EINVAL);
164         if (!ifq_is_ready(&ifp->if_snd))
165                 return (ENODEV);
166
167         pif = kmalloc(sizeof(*pif), M_ALTQ, M_WAITOK | M_ZERO);
168         pif->pif_bandwidth = a->ifbandwidth;
169         pif->pif_maxpri = -1;
170         pif->pif_ifq = &ifp->if_snd;
171         ifq_purge_all(&ifp->if_snd);
172
173         /* keep the state in pf_altq */
174         a->altq_disc = pif;
175
176         return (0);
177 }
178
179 int
180 fairq_remove_altq(struct pf_altq *a)
181 {
182         struct fairq_if *pif;
183
184         if ((pif = a->altq_disc) == NULL)
185                 return (EINVAL);
186         a->altq_disc = NULL;
187
188         fairq_clear_interface(pif);
189
190         kfree(pif, M_ALTQ);
191         return (0);
192 }
193
194 static int
195 fairq_add_queue_locked(struct pf_altq *a, struct fairq_if *pif)
196 {
197         struct fairq_class *cl;
198
199         KKASSERT(a->priority < FAIRQ_MAXPRI);
200         KKASSERT(a->qid != 0);
201
202         if (pif->pif_classes[a->priority] != NULL)
203                 return (EBUSY);
204         if (clh_to_clp(pif, a->qid) != NULL)
205                 return (EBUSY);
206
207         cl = fairq_class_create(pif, a->priority, a->qlimit, a->bandwidth,
208                                &a->pq_u.fairq_opts, a->qid);
209         if (cl == NULL)
210                 return (ENOMEM);
211
212         return (0);
213 }
214
215 int
216 fairq_add_queue(struct pf_altq *a)
217 {
218         struct fairq_if *pif;
219         struct ifaltq *ifq;
220         int error;
221
222         /* check parameters */
223         if (a->priority >= FAIRQ_MAXPRI)
224                 return (EINVAL);
225         if (a->qid == 0)
226                 return (EINVAL);
227
228         /* XXX not MP safe */
229         if ((pif = a->altq_disc) == NULL)
230                 return (EINVAL);
231         ifq = pif->pif_ifq;
232
233         FAIRQ_LOCK(ifq);
234         error = fairq_add_queue_locked(a, pif);
235         FAIRQ_UNLOCK(ifq);
236
237         return error;
238 }
239
240 static int
241 fairq_remove_queue_locked(struct pf_altq *a, struct fairq_if *pif)
242 {
243         struct fairq_class *cl;
244
245         if ((cl = clh_to_clp(pif, a->qid)) == NULL)
246                 return (EINVAL);
247
248         return (fairq_class_destroy(cl));
249 }
250
251 int
252 fairq_remove_queue(struct pf_altq *a)
253 {
254         struct fairq_if *pif;
255         struct ifaltq *ifq;
256         int error;
257
258         /* XXX not MP safe */
259         if ((pif = a->altq_disc) == NULL)
260                 return (EINVAL);
261         ifq = pif->pif_ifq;
262
263         FAIRQ_LOCK(ifq);
264         error = fairq_remove_queue_locked(a, pif);
265         FAIRQ_UNLOCK(ifq);
266
267         return error;
268 }
269
270 int
271 fairq_getqstats(struct pf_altq *a, void *ubuf, int *nbytes)
272 {
273         struct fairq_if *pif;
274         struct fairq_class *cl;
275         struct fairq_classstats stats;
276         struct ifaltq *ifq;
277         int error = 0;
278
279         if (*nbytes < sizeof(stats))
280                 return (EINVAL);
281
282         /* XXX not MP safe */
283         if ((pif = altq_lookup(a->ifname, ALTQT_FAIRQ)) == NULL)
284                 return (EBADF);
285         ifq = pif->pif_ifq;
286
287         FAIRQ_LOCK(ifq);
288
289         if ((cl = clh_to_clp(pif, a->qid)) == NULL) {
290                 FAIRQ_UNLOCK(ifq);
291                 return (EINVAL);
292         }
293
294         get_class_stats(&stats, cl);
295
296         FAIRQ_UNLOCK(ifq);
297
298         if ((error = copyout((caddr_t)&stats, ubuf, sizeof(stats))) != 0)
299                 return (error);
300         *nbytes = sizeof(stats);
301         return (0);
302 }
303
304 /*
305  * bring the interface back to the initial state by discarding
306  * all the filters and classes.
307  */
308 static int
309 fairq_clear_interface(struct fairq_if *pif)
310 {
311         struct fairq_class *cl;
312         int pri;
313
314         /* clear out the classes */
315         for (pri = 0; pri <= pif->pif_maxpri; pri++) {
316                 if ((cl = pif->pif_classes[pri]) != NULL)
317                         fairq_class_destroy(cl);
318         }
319
320         return (0);
321 }
322
323 static int
324 fairq_request(struct ifaltq_subque *ifsq, int req, void *arg)
325 {
326         struct ifaltq *ifq = ifsq->ifsq_altq;
327         struct fairq_if *pif = (struct fairq_if *)ifq->altq_disc;
328
329         crit_enter();
330         switch (req) {
331         case ALTRQ_PURGE:
332                 if (ifsq_get_index(ifsq) == FAIRQ_SUBQ_INDEX) {
333                         fairq_purge(pif);
334                 } else {
335                         /*
336                          * Race happened, the unrelated subqueue was
337                          * picked during the packet scheduler transition.
338                          */
339                         ifsq_classic_request(ifsq, ALTRQ_PURGE, NULL);
340                 }
341                 break;
342         }
343         crit_exit();
344         return (0);
345 }
346
347 /* discard all the queued packets on the interface */
348 static void
349 fairq_purge(struct fairq_if *pif)
350 {
351         struct fairq_class *cl;
352         int pri;
353
354         for (pri = 0; pri <= pif->pif_maxpri; pri++) {
355                 if ((cl = pif->pif_classes[pri]) != NULL && cl->cl_head)
356                         fairq_purgeq(cl);
357         }
358         if (ifq_is_enabled(pif->pif_ifq))
359                 pif->pif_ifq->altq_subq[FAIRQ_SUBQ_INDEX].ifq_len = 0;
360 }
361
362 static struct fairq_class *
363 fairq_class_create(struct fairq_if *pif, int pri, int qlimit,
364                    u_int bandwidth, struct fairq_opts *opts, int qid)
365 {
366         struct fairq_class *cl;
367         int flags = opts->flags;
368         u_int nbuckets = opts->nbuckets;
369         int i;
370
371 #ifndef ALTQ_RED
372         if (flags & FARF_RED) {
373 #ifdef ALTQ_DEBUG
374                 kprintf("fairq_class_create: RED not configured for FAIRQ!\n");
375 #endif
376                 return (NULL);
377         }
378 #endif
379         if (nbuckets == 0)
380                 nbuckets = 256;
381         if (nbuckets > FAIRQ_MAX_BUCKETS)
382                 nbuckets = FAIRQ_MAX_BUCKETS;
383         /* enforce power-of-2 size */
384         while ((nbuckets ^ (nbuckets - 1)) != ((nbuckets << 1) - 1))
385                 ++nbuckets;
386
387         if ((cl = pif->pif_classes[pri]) != NULL) {
388                 /* modify the class instead of creating a new one */
389                 crit_enter();
390                 if (cl->cl_head)
391                         fairq_purgeq(cl);
392                 crit_exit();
393 #ifdef ALTQ_RIO
394                 if (cl->cl_qtype == Q_RIO)
395                         rio_destroy((rio_t *)cl->cl_red);
396 #endif
397 #ifdef ALTQ_RED
398                 if (cl->cl_qtype == Q_RED)
399                         red_destroy(cl->cl_red);
400 #endif
401         } else {
402                 cl = kmalloc(sizeof(*cl), M_ALTQ, M_WAITOK | M_ZERO);
403                 cl->cl_nbuckets = nbuckets;
404                 cl->cl_nbucket_mask = nbuckets - 1;
405
406                 cl->cl_buckets = kmalloc(sizeof(*cl->cl_buckets) *
407                                          cl->cl_nbuckets,
408                                          M_ALTQ, M_WAITOK | M_ZERO);
409                 cl->cl_head = NULL;
410         }
411
412         pif->pif_classes[pri] = cl;
413         if (flags & FARF_DEFAULTCLASS)
414                 pif->pif_default = cl;
415         if (qlimit == 0)
416                 qlimit = 50;  /* use default */
417         cl->cl_qlimit = qlimit;
418         for (i = 0; i < cl->cl_nbuckets; ++i) {
419                 qlimit(&cl->cl_buckets[i].queue) = qlimit;
420         }
421         cl->cl_bandwidth = bandwidth / 8;       /* cvt to bytes per second */
422         cl->cl_qtype = Q_DROPTAIL;
423         cl->cl_flags = flags & FARF_USERFLAGS;
424         cl->cl_pri = pri;
425         if (pri > pif->pif_maxpri)
426                 pif->pif_maxpri = pri;
427         cl->cl_pif = pif;
428         cl->cl_handle = qid;
429         cl->cl_hogs_m1 = opts->hogs_m1 / 8;
430         cl->cl_lssc_m1 = opts->lssc_m1 / 8;     /* NOT YET USED */
431         cl->cl_bw_current = 0;
432
433 #ifdef ALTQ_RED
434         if (flags & (FARF_RED|FARF_RIO)) {
435                 int red_flags, red_pkttime;
436
437                 red_flags = 0;
438                 if (flags & FARF_ECN)
439                         red_flags |= REDF_ECN;
440 #ifdef ALTQ_RIO
441                 if (flags & FARF_CLEARDSCP)
442                         red_flags |= RIOF_CLEARDSCP;
443 #endif
444                 if (pif->pif_bandwidth < 8)
445                         red_pkttime = 1000 * 1000 * 1000; /* 1 sec */
446                 else
447                         red_pkttime = (int64_t)pif->pif_ifq->altq_ifp->if_mtu
448                           * 1000 * 1000 * 1000 / (pif->pif_bandwidth / 8);
449 #ifdef ALTQ_RIO
450                 if (flags & FARF_RIO) {
451                         cl->cl_red = (red_t *)rio_alloc(0, NULL,
452                                                 red_flags, red_pkttime);
453                         if (cl->cl_red != NULL)
454                                 cl->cl_qtype = Q_RIO;
455                 } else
456 #endif
457                 if (flags & FARF_RED) {
458                         cl->cl_red = red_alloc(0, 0,
459                             cl->cl_qlimit * 10/100,
460                             cl->cl_qlimit * 30/100,
461                             red_flags, red_pkttime);
462                         if (cl->cl_red != NULL)
463                                 cl->cl_qtype = Q_RED;
464                 }
465         }
466 #endif /* ALTQ_RED */
467
468         return (cl);
469 }
470
471 static int
472 fairq_class_destroy(struct fairq_class *cl)
473 {
474         struct fairq_if *pif;
475         int pri;
476
477         crit_enter();
478
479         if (cl->cl_head)
480                 fairq_purgeq(cl);
481
482         pif = cl->cl_pif;
483         pif->pif_classes[cl->cl_pri] = NULL;
484         if (pif->pif_poll_cache == cl)
485                 pif->pif_poll_cache = NULL;
486         if (pif->pif_maxpri == cl->cl_pri) {
487                 for (pri = cl->cl_pri; pri >= 0; pri--)
488                         if (pif->pif_classes[pri] != NULL) {
489                                 pif->pif_maxpri = pri;
490                                 break;
491                         }
492                 if (pri < 0)
493                         pif->pif_maxpri = -1;
494         }
495         crit_exit();
496
497         if (cl->cl_red != NULL) {
498 #ifdef ALTQ_RIO
499                 if (cl->cl_qtype == Q_RIO)
500                         rio_destroy((rio_t *)cl->cl_red);
501 #endif
502 #ifdef ALTQ_RED
503                 if (cl->cl_qtype == Q_RED)
504                         red_destroy(cl->cl_red);
505 #endif
506         }
507         kfree(cl->cl_buckets, M_ALTQ);
508         cl->cl_head = NULL;     /* sanity */
509         cl->cl_polled = NULL;   /* sanity */
510         cl->cl_buckets = NULL;  /* sanity */
511         kfree(cl, M_ALTQ);
512
513         return (0);
514 }
515
516 /*
517  * fairq_enqueue is an enqueue function to be registered to
518  * (*altq_enqueue) in struct ifaltq.
519  */
520 static int
521 fairq_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m,
522     struct altq_pktattr *pktattr)
523 {
524         struct ifaltq *ifq = ifsq->ifsq_altq;
525         struct fairq_if *pif = (struct fairq_if *)ifq->altq_disc;
526         struct fairq_class *cl;
527         int error;
528         int len;
529         int hash;
530
531         if (ifsq_get_index(ifsq) != FAIRQ_SUBQ_INDEX) {
532                 /*
533                  * Race happened, the unrelated subqueue was
534                  * picked during the packet scheduler transition.
535                  */
536                 ifsq_classic_request(ifsq, ALTRQ_PURGE, NULL);
537                 m_freem(m);
538                 return ENOBUFS;
539         }
540
541         crit_enter();
542
543         /* grab class set by classifier */
544         if ((m->m_flags & M_PKTHDR) == 0) {
545                 /* should not happen */
546                 if_printf(ifq->altq_ifp, "altq: packet does not have pkthdr\n");
547                 m_freem(m);
548                 error = ENOBUFS;
549                 goto done;
550         }
551
552         if (m->m_pkthdr.fw_flags & PF_MBUF_STRUCTURE) {
553                 cl = clh_to_clp(pif, m->m_pkthdr.pf.qid);
554                 if (m->m_pkthdr.pf.flags & PF_TAG_STATE_HASHED)
555                         hash = (int)m->m_pkthdr.pf.state_hash;
556                 else
557                         hash = 0;
558         } else {
559                 cl = NULL;
560                 hash = 0;
561         }
562         if (cl == NULL) {
563                 cl = pif->pif_default;
564                 if (cl == NULL) {
565                         m_freem(m);
566                         error = ENOBUFS;
567                         goto done;
568                 }
569         }
570         cl->cl_flags |= FARF_HAS_PACKETS;
571         cl->cl_pktattr = NULL;
572         len = m_pktlen(m);
573         if (fairq_addq(cl, m, hash) != 0) {
574                 /* drop occurred.  mbuf was freed in fairq_addq. */
575                 PKTCNTR_ADD(&cl->cl_dropcnt, len);
576                 error = ENOBUFS;
577                 goto done;
578         }
579         ifsq->ifq_len++;
580         error = 0;
581 done:
582         crit_exit();
583         return (error);
584 }
585
586 /*
587  * fairq_dequeue is a dequeue function to be registered to
588  * (*altq_dequeue) in struct ifaltq.
589  *
590  * note: ALTDQ_POLL returns the next packet without removing the packet
591  *      from the queue.  ALTDQ_REMOVE is a normal dequeue operation.
592  *      ALTDQ_REMOVE must return the same packet if called immediately
593  *      after ALTDQ_POLL.
594  */
595 static struct mbuf *
596 fairq_dequeue(struct ifaltq_subque *ifsq, struct mbuf *mpolled, int op)
597 {
598         struct ifaltq *ifq = ifsq->ifsq_altq;
599         struct fairq_if *pif = (struct fairq_if *)ifq->altq_disc;
600         struct fairq_class *cl;
601         struct fairq_class *best_cl;
602         struct mbuf *best_m;
603         struct mbuf *m;
604         uint64_t cur_time = read_machclk();
605         u_int best_scale;
606         u_int scale;
607         int pri;
608         int hit_limit;
609
610         if (ifsq_get_index(ifsq) != FAIRQ_SUBQ_INDEX) {
611                 /*
612                  * Race happened, the unrelated subqueue was
613                  * picked during the packet scheduler transition.
614                  */
615                 ifsq_classic_request(ifsq, ALTRQ_PURGE, NULL);
616                 return NULL;
617         }
618
619         if (ifsq_is_empty(ifsq)) {
620                 /* no packet in the queue */
621                 KKASSERT(mpolled == NULL);
622                 return (NULL);
623         }
624
625         crit_enter();
626         if (pif->pif_poll_cache && op == ALTDQ_REMOVE) {
627                 best_cl = pif->pif_poll_cache;
628                 m = fairq_getq(best_cl, cur_time);
629                 pif->pif_poll_cache = NULL;
630                 if (m) {
631                         ifsq->ifq_len--;
632                         PKTCNTR_ADD(&best_cl->cl_xmitcnt, m_pktlen(m));
633                 }
634         } else {
635                 best_cl = NULL;
636                 best_m = NULL;
637                 best_scale = 0xFFFFFFFFU;
638
639                 for (pri = pif->pif_maxpri;  pri >= 0; pri--) {
640                         if ((cl = pif->pif_classes[pri]) == NULL)
641                                 continue;
642                         if ((cl->cl_flags & FARF_HAS_PACKETS) == 0)
643                                 continue;
644                         m = fairq_pollq(cl, cur_time, &hit_limit);
645                         if (m == NULL) {
646                                 cl->cl_flags &= ~FARF_HAS_PACKETS;
647                                 continue;
648                         }
649
650                         /*
651                          * We can halt the search immediately if the queue
652                          * did not hit its bandwidth limit.
653                          */
654                         if (hit_limit == 0) {
655                                 best_cl = cl;
656                                 best_m = m;
657                                 break;
658                         }
659
660                         /*
661                          * Otherwise calculate the scale factor and select
662                          * the queue with the lowest scale factor.  This
663                          * apportions any unused bandwidth weighted by
664                          * the relative bandwidth specification.
665                          */
666                         scale = cl->cl_bw_current * 100 / cl->cl_bandwidth;
667                         if (scale < best_scale) {
668                                 best_cl = cl;
669                                 best_m = m;
670                                 best_scale = scale;
671                         }
672                 }
673
674                 if (op == ALTDQ_POLL) {
675                         pif->pif_poll_cache = best_cl;
676                         m = best_m;
677                 } else if (best_cl) {
678                         m = fairq_getq(best_cl, cur_time);
679                         KKASSERT(best_m == m);
680                         ifsq->ifq_len--;
681                         PKTCNTR_ADD(&best_cl->cl_xmitcnt, m_pktlen(m));
682                 } else {
683                         m = NULL;
684                 }
685         }
686         crit_exit();
687         KKASSERT(mpolled == NULL || mpolled == m);
688         return (m);
689 }
690
691 static int
692 fairq_addq(struct fairq_class *cl, struct mbuf *m, int hash)
693 {
694         fairq_bucket_t *b;
695         u_int hindex;
696         uint64_t bw;
697
698         /*
699          * If the packet doesn't have any keep state put it on the end of
700          * our queue.  XXX this can result in out of order delivery.
701          */
702         if (hash == 0) {
703                 if (cl->cl_head)
704                         b = cl->cl_head->prev;
705                 else
706                         b = &cl->cl_buckets[0];
707         } else {
708                 hindex = hash & cl->cl_nbucket_mask;
709                 b = &cl->cl_buckets[hindex];
710         }
711
712         /*
713          * Add the bucket to the end of the circular list of active buckets.
714          *
715          * As a special case we add the bucket to the beginning of the list
716          * instead of the end if it was not previously on the list and if
717          * its traffic is less then the hog level.
718          */
719         if (b->in_use == 0) {
720                 b->in_use = 1;
721                 if (cl->cl_head == NULL) {
722                         cl->cl_head = b;
723                         b->next = b;
724                         b->prev = b;
725                 } else {
726                         b->next = cl->cl_head;
727                         b->prev = cl->cl_head->prev;
728                         b->prev->next = b;
729                         b->next->prev = b;
730
731                         if (b->bw_delta && cl->cl_hogs_m1) {
732                                 bw = b->bw_bytes * machclk_freq / b->bw_delta;
733                                 if (bw < cl->cl_hogs_m1)
734                                         cl->cl_head = b;
735                         }
736                 }
737         }
738
739 #ifdef ALTQ_RIO
740         if (cl->cl_qtype == Q_RIO)
741                 return rio_addq((rio_t *)cl->cl_red, &b->queue, m, cl->cl_pktattr);
742 #endif
743 #ifdef ALTQ_RED
744         if (cl->cl_qtype == Q_RED)
745                 return red_addq(cl->cl_red, &b->queue, m, cl->cl_pktattr);
746 #endif
747         if (qlen(&b->queue) >= qlimit(&b->queue)) {
748                 m_freem(m);
749                 return (-1);
750         }
751
752         if (cl->cl_flags & FARF_CLEARDSCP)
753                 write_dsfield(m, cl->cl_pktattr, 0);
754
755         _addq(&b->queue, m);
756
757         return (0);
758 }
759
760 static struct mbuf *
761 fairq_getq(struct fairq_class *cl, uint64_t cur_time)
762 {
763         fairq_bucket_t *b;
764         struct mbuf *m;
765
766         b = fairq_selectq(cl, 0);
767         if (b == NULL)
768                 m = NULL;
769 #ifdef ALTQ_RIO
770         else if (cl->cl_qtype == Q_RIO)
771                 m = rio_getq((rio_t *)cl->cl_red, &b->queue);
772 #endif
773 #ifdef ALTQ_RED
774         else if (cl->cl_qtype == Q_RED)
775                 m = red_getq(cl->cl_red, &b->queue);
776 #endif
777         else
778                 m = _getq(&b->queue);
779
780         /*
781          * Calculate the BW change
782          */
783         if (m != NULL) {
784                 uint64_t delta;
785
786                 /*
787                  * Per-class bandwidth calculation
788                  */
789                 delta = (cur_time - cl->cl_last_time);
790                 if (delta > machclk_freq * 8)
791                         delta = machclk_freq * 8;
792                 cl->cl_bw_delta += delta;
793                 cl->cl_bw_bytes += m->m_pkthdr.len;
794                 cl->cl_last_time = cur_time;
795                 if (cl->cl_bw_delta > machclk_freq) {
796                         cl->cl_bw_delta -= cl->cl_bw_delta >> 2;
797                         cl->cl_bw_bytes -= cl->cl_bw_bytes >> 2;
798                 }
799
800                 /*
801                  * Per-bucket bandwidth calculation
802                  */
803                 delta = (cur_time - b->last_time);
804                 if (delta > machclk_freq * 8)
805                         delta = machclk_freq * 8;
806                 b->bw_delta += delta;
807                 b->bw_bytes += m->m_pkthdr.len;
808                 b->last_time = cur_time;
809                 if (b->bw_delta > machclk_freq) {
810                         b->bw_delta -= b->bw_delta >> 2;
811                         b->bw_bytes -= b->bw_bytes >> 2;
812                 }
813         }
814         return(m);
815 }
816
817 /*
818  * Figure out what the next packet would be if there were no limits.  If
819  * this class hits its bandwidth limit *hit_limit is set to no-zero, otherwise
820  * it is set to 0.  A non-NULL mbuf is returned either way.
821  */
822 static struct mbuf *
823 fairq_pollq(struct fairq_class *cl, uint64_t cur_time, int *hit_limit)
824 {
825         fairq_bucket_t *b;
826         struct mbuf *m;
827         uint64_t delta;
828         uint64_t bw;
829
830         *hit_limit = 0;
831         b = fairq_selectq(cl, 1);
832         if (b == NULL)
833                 return(NULL);
834         m = qhead(&b->queue);
835
836         /*
837          * Did this packet exceed the class bandwidth?  Calculate the
838          * bandwidth component of the packet.
839          *
840          * - Calculate bytes per second
841          */
842         delta = cur_time - cl->cl_last_time;
843         if (delta > machclk_freq * 8)
844                 delta = machclk_freq * 8;
845         cl->cl_bw_delta += delta;
846         cl->cl_last_time = cur_time;
847         if (cl->cl_bw_delta) {
848                 bw = cl->cl_bw_bytes * machclk_freq / cl->cl_bw_delta;
849
850                 if (bw > cl->cl_bandwidth)
851                         *hit_limit = 1;
852                 cl->cl_bw_current = bw;
853 #if 0
854                 kprintf("BW %6lld relative to %6u %d queue %p\n",
855                         bw, cl->cl_bandwidth, *hit_limit, b);
856 #endif
857         }
858         return(m);
859 }
860
861 /*
862  * Locate the next queue we want to pull a packet out of.  This code
863  * is also responsible for removing empty buckets from the circular list.
864  */
865 static
866 fairq_bucket_t *
867 fairq_selectq(struct fairq_class *cl, int ispoll)
868 {
869         fairq_bucket_t *b;
870         uint64_t bw;
871
872         if (ispoll == 0 && cl->cl_polled) {
873                 b = cl->cl_polled;
874                 cl->cl_polled = NULL;
875                 return(b);
876         }
877
878         while ((b = cl->cl_head) != NULL) {
879                 /*
880                  * Remove empty queues from consideration
881                  */
882                 if (qempty(&b->queue)) {
883                         b->in_use = 0;
884                         cl->cl_head = b->next;
885                         if (cl->cl_head == b) {
886                                 cl->cl_head = NULL;
887                         } else {
888                                 b->next->prev = b->prev;
889                                 b->prev->next = b->next;
890                         }
891                         continue;
892                 }
893
894                 /*
895                  * Advance the round robin.  Queues with bandwidths less
896                  * then the hog bandwidth are allowed to burst.
897                  */
898                 if (cl->cl_hogs_m1 == 0) {
899                         cl->cl_head = b->next;
900                 } else if (b->bw_delta) {
901                         bw = b->bw_bytes * machclk_freq / b->bw_delta;
902                         if (bw >= cl->cl_hogs_m1) {
903                                 cl->cl_head = b->next;
904                         }
905                         /*
906                          * XXX TODO - 
907                          */
908                 }
909
910                 /*
911                  * Return bucket b.
912                  */
913                 break;
914         }
915         if (ispoll)
916                 cl->cl_polled = b;
917         return(b);
918 }
919
920 static void
921 fairq_purgeq(struct fairq_class *cl)
922 {
923         fairq_bucket_t *b;
924         struct mbuf *m;
925
926         while ((b = fairq_selectq(cl, 0)) != NULL) {
927                 while ((m = _getq(&b->queue)) != NULL) {
928                         PKTCNTR_ADD(&cl->cl_dropcnt, m_pktlen(m));
929                         m_freem(m);
930                 }
931                 KKASSERT(qlen(&b->queue) == 0);
932         }
933 }
934
935 static void
936 get_class_stats(struct fairq_classstats *sp, struct fairq_class *cl)
937 {
938         fairq_bucket_t *b;
939
940         sp->class_handle = cl->cl_handle;
941         sp->qlimit = cl->cl_qlimit;
942         sp->xmit_cnt = cl->cl_xmitcnt;
943         sp->drop_cnt = cl->cl_dropcnt;
944         sp->qtype = cl->cl_qtype;
945         sp->qlength = 0;
946
947         if (cl->cl_head) {
948                 b = cl->cl_head;
949                 do {
950                         sp->qlength += qlen(&b->queue);
951                         b = b->next;
952                 } while (b != cl->cl_head);
953         }
954
955 #ifdef ALTQ_RED
956         if (cl->cl_qtype == Q_RED)
957                 red_getstats(cl->cl_red, &sp->red[0]);
958 #endif
959 #ifdef ALTQ_RIO
960         if (cl->cl_qtype == Q_RIO)
961                 rio_getstats((rio_t *)cl->cl_red, &sp->red[0]);
962 #endif
963 }
964
965 /* convert a class handle to the corresponding class pointer */
966 static struct fairq_class *
967 clh_to_clp(struct fairq_if *pif, uint32_t chandle)
968 {
969         struct fairq_class *cl;
970         int idx;
971
972         if (chandle == 0)
973                 return (NULL);
974
975         for (idx = pif->pif_maxpri; idx >= 0; idx--)
976                 if ((cl = pif->pif_classes[idx]) != NULL &&
977                     cl->cl_handle == chandle)
978                         return (cl);
979
980         return (NULL);
981 }
982
983 #endif /* ALTQ_FAIRQ */