clocksource: make CLOCKSOURCE_OF_DECLARE type safe
[cascardo/linux.git] / net / sched / sch_qfq.c
1 /*
2  * net/sched/sch_qfq.c         Quick Fair Queueing Plus Scheduler.
3  *
4  * Copyright (c) 2009 Fabio Checconi, Luigi Rizzo, and Paolo Valente.
5  * Copyright (c) 2012 Paolo Valente.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * version 2 as published by the Free Software Foundation.
10  */
11
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/bitops.h>
15 #include <linux/errno.h>
16 #include <linux/netdevice.h>
17 #include <linux/pkt_sched.h>
18 #include <net/sch_generic.h>
19 #include <net/pkt_sched.h>
20 #include <net/pkt_cls.h>
21
22
23 /*  Quick Fair Queueing Plus
24     ========================
25
26     Sources:
27
28     [1] Paolo Valente,
29     "Reducing the Execution Time of Fair-Queueing Schedulers."
30     http://algo.ing.unimo.it/people/paolo/agg-sched/agg-sched.pdf
31
32     Sources for QFQ:
33
34     [2] Fabio Checconi, Luigi Rizzo, and Paolo Valente: "QFQ: Efficient
35     Packet Scheduling with Tight Bandwidth Distribution Guarantees."
36
37     See also:
38     http://retis.sssup.it/~fabio/linux/qfq/
39  */
40
41 /*
42
43   QFQ+ divides classes into aggregates of at most MAX_AGG_CLASSES
44   classes. Each aggregate is timestamped with a virtual start time S
45   and a virtual finish time F, and scheduled according to its
46   timestamps. S and F are computed as a function of a system virtual
47   time function V. The classes within each aggregate are instead
48   scheduled with DRR.
49
50   To speed up operations, QFQ+ divides also aggregates into a limited
51   number of groups. Which group a class belongs to depends on the
52   ratio between the maximum packet length for the class and the weight
53   of the class. Groups have their own S and F. In the end, QFQ+
54   schedules groups, then aggregates within groups, then classes within
55   aggregates. See [1] and [2] for a full description.
56
57   Virtual time computations.
58
59   S, F and V are all computed in fixed point arithmetic with
60   FRAC_BITS decimal bits.
61
62   QFQ_MAX_INDEX is the maximum index allowed for a group. We need
63         one bit per index.
64   QFQ_MAX_WSHIFT is the maximum power of two supported as a weight.
65
66   The layout of the bits is as below:
67
68                    [ MTU_SHIFT ][      FRAC_BITS    ]
69                    [ MAX_INDEX    ][ MIN_SLOT_SHIFT ]
70                                  ^.__grp->index = 0
71                                  *.__grp->slot_shift
72
73   where MIN_SLOT_SHIFT is derived by difference from the others.
74
75   The max group index corresponds to Lmax/w_min, where
76   Lmax=1<<MTU_SHIFT, w_min = 1 .
77   From this, and knowing how many groups (MAX_INDEX) we want,
78   we can derive the shift corresponding to each group.
79
80   Because we often need to compute
81         F = S + len/w_i  and V = V + len/wsum
82   instead of storing w_i store the value
83         inv_w = (1<<FRAC_BITS)/w_i
84   so we can do F = S + len * inv_w * wsum.
85   We use W_TOT in the formulas so we can easily move between
86   static and adaptive weight sum.
87
88   The per-scheduler-instance data contain all the data structures
89   for the scheduler: bitmaps and bucket lists.
90
91  */
92
93 /*
94  * Maximum number of consecutive slots occupied by backlogged classes
95  * inside a group.
96  */
97 #define QFQ_MAX_SLOTS   32
98
99 /*
100  * Shifts used for aggregate<->group mapping.  We allow class weights that are
101  * in the range [1, 2^MAX_WSHIFT], and we try to map each aggregate i to the
102  * group with the smallest index that can support the L_i / r_i configured
103  * for the classes in the aggregate.
104  *
105  * grp->index is the index of the group; and grp->slot_shift
106  * is the shift for the corresponding (scaled) sigma_i.
107  */
108 #define QFQ_MAX_INDEX           24
109 #define QFQ_MAX_WSHIFT          10
110
111 #define QFQ_MAX_WEIGHT          (1<<QFQ_MAX_WSHIFT) /* see qfq_slot_insert */
112 #define QFQ_MAX_WSUM            (64*QFQ_MAX_WEIGHT)
113
114 #define FRAC_BITS               30      /* fixed point arithmetic */
115 #define ONE_FP                  (1UL << FRAC_BITS)
116 #define IWSUM                   (ONE_FP/QFQ_MAX_WSUM)
117
118 #define QFQ_MTU_SHIFT           16      /* to support TSO/GSO */
119 #define QFQ_MIN_LMAX            512     /* see qfq_slot_insert */
120
121 #define QFQ_MAX_AGG_CLASSES     8 /* max num classes per aggregate allowed */
122
123 /*
124  * Possible group states.  These values are used as indexes for the bitmaps
125  * array of struct qfq_queue.
126  */
127 enum qfq_state { ER, IR, EB, IB, QFQ_MAX_STATE };
128
129 struct qfq_group;
130
131 struct qfq_aggregate;
132
133 struct qfq_class {
134         struct Qdisc_class_common common;
135
136         unsigned int refcnt;
137         unsigned int filter_cnt;
138
139         struct gnet_stats_basic_packed bstats;
140         struct gnet_stats_queue qstats;
141         struct gnet_stats_rate_est rate_est;
142         struct Qdisc *qdisc;
143         struct list_head alist;         /* Link for active-classes list. */
144         struct qfq_aggregate *agg;      /* Parent aggregate. */
145         int deficit;                    /* DRR deficit counter. */
146 };
147
148 struct qfq_aggregate {
149         struct hlist_node next; /* Link for the slot list. */
150         u64 S, F;               /* flow timestamps (exact) */
151
152         /* group we belong to. In principle we would need the index,
153          * which is log_2(lmax/weight), but we never reference it
154          * directly, only the group.
155          */
156         struct qfq_group *grp;
157
158         /* these are copied from the flowset. */
159         u32     class_weight; /* Weight of each class in this aggregate. */
160         /* Max pkt size for the classes in this aggregate, DRR quantum. */
161         int     lmax;
162
163         u32     inv_w;      /* ONE_FP/(sum of weights of classes in aggr.). */
164         u32     budgetmax;  /* Max budget for this aggregate. */
165         u32     initial_budget, budget;     /* Initial and current budget. */
166
167         int               num_classes;  /* Number of classes in this aggr. */
168         struct list_head  active;       /* DRR queue of active classes. */
169
170         struct hlist_node nonfull_next; /* See nonfull_aggs in qfq_sched. */
171 };
172
173 struct qfq_group {
174         u64 S, F;                       /* group timestamps (approx). */
175         unsigned int slot_shift;        /* Slot shift. */
176         unsigned int index;             /* Group index. */
177         unsigned int front;             /* Index of the front slot. */
178         unsigned long full_slots;       /* non-empty slots */
179
180         /* Array of RR lists of active aggregates. */
181         struct hlist_head slots[QFQ_MAX_SLOTS];
182 };
183
184 struct qfq_sched {
185         struct tcf_proto *filter_list;
186         struct Qdisc_class_hash clhash;
187
188         u64                     oldV, V;        /* Precise virtual times. */
189         struct qfq_aggregate    *in_serv_agg;   /* Aggregate being served. */
190         u32                     num_active_agg; /* Num. of active aggregates */
191         u32                     wsum;           /* weight sum */
192
193         unsigned long bitmaps[QFQ_MAX_STATE];       /* Group bitmaps. */
194         struct qfq_group groups[QFQ_MAX_INDEX + 1]; /* The groups. */
195         u32 min_slot_shift;     /* Index of the group-0 bit in the bitmaps. */
196
197         u32 max_agg_classes;            /* Max number of classes per aggr. */
198         struct hlist_head nonfull_aggs; /* Aggs with room for more classes. */
199 };
200
201 /*
202  * Possible reasons why the timestamps of an aggregate are updated
203  * enqueue: the aggregate switches from idle to active and must scheduled
204  *          for service
205  * requeue: the aggregate finishes its budget, so it stops being served and
206  *          must be rescheduled for service
207  */
208 enum update_reason {enqueue, requeue};
209
210 static struct qfq_class *qfq_find_class(struct Qdisc *sch, u32 classid)
211 {
212         struct qfq_sched *q = qdisc_priv(sch);
213         struct Qdisc_class_common *clc;
214
215         clc = qdisc_class_find(&q->clhash, classid);
216         if (clc == NULL)
217                 return NULL;
218         return container_of(clc, struct qfq_class, common);
219 }
220
221 static void qfq_purge_queue(struct qfq_class *cl)
222 {
223         unsigned int len = cl->qdisc->q.qlen;
224
225         qdisc_reset(cl->qdisc);
226         qdisc_tree_decrease_qlen(cl->qdisc, len);
227 }
228
229 static const struct nla_policy qfq_policy[TCA_QFQ_MAX + 1] = {
230         [TCA_QFQ_WEIGHT] = { .type = NLA_U32 },
231         [TCA_QFQ_LMAX] = { .type = NLA_U32 },
232 };
233
234 /*
235  * Calculate a flow index, given its weight and maximum packet length.
236  * index = log_2(maxlen/weight) but we need to apply the scaling.
237  * This is used only once at flow creation.
238  */
239 static int qfq_calc_index(u32 inv_w, unsigned int maxlen, u32 min_slot_shift)
240 {
241         u64 slot_size = (u64)maxlen * inv_w;
242         unsigned long size_map;
243         int index = 0;
244
245         size_map = slot_size >> min_slot_shift;
246         if (!size_map)
247                 goto out;
248
249         index = __fls(size_map) + 1;    /* basically a log_2 */
250         index -= !(slot_size - (1ULL << (index + min_slot_shift - 1)));
251
252         if (index < 0)
253                 index = 0;
254 out:
255         pr_debug("qfq calc_index: W = %lu, L = %u, I = %d\n",
256                  (unsigned long) ONE_FP/inv_w, maxlen, index);
257
258         return index;
259 }
260
261 static void qfq_deactivate_agg(struct qfq_sched *, struct qfq_aggregate *);
262 static void qfq_activate_agg(struct qfq_sched *, struct qfq_aggregate *,
263                              enum update_reason);
264
265 static void qfq_init_agg(struct qfq_sched *q, struct qfq_aggregate *agg,
266                          u32 lmax, u32 weight)
267 {
268         INIT_LIST_HEAD(&agg->active);
269         hlist_add_head(&agg->nonfull_next, &q->nonfull_aggs);
270
271         agg->lmax = lmax;
272         agg->class_weight = weight;
273 }
274
275 static struct qfq_aggregate *qfq_find_agg(struct qfq_sched *q,
276                                           u32 lmax, u32 weight)
277 {
278         struct qfq_aggregate *agg;
279
280         hlist_for_each_entry(agg, &q->nonfull_aggs, nonfull_next)
281                 if (agg->lmax == lmax && agg->class_weight == weight)
282                         return agg;
283
284         return NULL;
285 }
286
287
288 /* Update aggregate as a function of the new number of classes. */
289 static void qfq_update_agg(struct qfq_sched *q, struct qfq_aggregate *agg,
290                            int new_num_classes)
291 {
292         u32 new_agg_weight;
293
294         if (new_num_classes == q->max_agg_classes)
295                 hlist_del_init(&agg->nonfull_next);
296
297         if (agg->num_classes > new_num_classes &&
298             new_num_classes == q->max_agg_classes - 1) /* agg no more full */
299                 hlist_add_head(&agg->nonfull_next, &q->nonfull_aggs);
300
301         agg->budgetmax = new_num_classes * agg->lmax;
302         new_agg_weight = agg->class_weight * new_num_classes;
303         agg->inv_w = ONE_FP/new_agg_weight;
304
305         if (agg->grp == NULL) {
306                 int i = qfq_calc_index(agg->inv_w, agg->budgetmax,
307                                        q->min_slot_shift);
308                 agg->grp = &q->groups[i];
309         }
310
311         q->wsum +=
312                 (int) agg->class_weight * (new_num_classes - agg->num_classes);
313
314         agg->num_classes = new_num_classes;
315 }
316
317 /* Add class to aggregate. */
318 static void qfq_add_to_agg(struct qfq_sched *q,
319                            struct qfq_aggregate *agg,
320                            struct qfq_class *cl)
321 {
322         cl->agg = agg;
323
324         qfq_update_agg(q, agg, agg->num_classes+1);
325         if (cl->qdisc->q.qlen > 0) { /* adding an active class */
326                 list_add_tail(&cl->alist, &agg->active);
327                 if (list_first_entry(&agg->active, struct qfq_class, alist) ==
328                     cl && q->in_serv_agg != agg) /* agg was inactive */
329                         qfq_activate_agg(q, agg, enqueue); /* schedule agg */
330         }
331 }
332
333 static struct qfq_aggregate *qfq_choose_next_agg(struct qfq_sched *);
334
335 static void qfq_destroy_agg(struct qfq_sched *q, struct qfq_aggregate *agg)
336 {
337         if (!hlist_unhashed(&agg->nonfull_next))
338                 hlist_del_init(&agg->nonfull_next);
339         if (q->in_serv_agg == agg)
340                 q->in_serv_agg = qfq_choose_next_agg(q);
341         kfree(agg);
342 }
343
344 /* Deschedule class from within its parent aggregate. */
345 static void qfq_deactivate_class(struct qfq_sched *q, struct qfq_class *cl)
346 {
347         struct qfq_aggregate *agg = cl->agg;
348
349
350         list_del(&cl->alist); /* remove from RR queue of the aggregate */
351         if (list_empty(&agg->active)) /* agg is now inactive */
352                 qfq_deactivate_agg(q, agg);
353 }
354
355 /* Remove class from its parent aggregate. */
356 static void qfq_rm_from_agg(struct qfq_sched *q, struct qfq_class *cl)
357 {
358         struct qfq_aggregate *agg = cl->agg;
359
360         cl->agg = NULL;
361         if (agg->num_classes == 1) { /* agg being emptied, destroy it */
362                 qfq_destroy_agg(q, agg);
363                 return;
364         }
365         qfq_update_agg(q, agg, agg->num_classes-1);
366 }
367
368 /* Deschedule class and remove it from its parent aggregate. */
369 static void qfq_deact_rm_from_agg(struct qfq_sched *q, struct qfq_class *cl)
370 {
371         if (cl->qdisc->q.qlen > 0) /* class is active */
372                 qfq_deactivate_class(q, cl);
373
374         qfq_rm_from_agg(q, cl);
375 }
376
377 /* Move class to a new aggregate, matching the new class weight and/or lmax */
378 static int qfq_change_agg(struct Qdisc *sch, struct qfq_class *cl, u32 weight,
379                            u32 lmax)
380 {
381         struct qfq_sched *q = qdisc_priv(sch);
382         struct qfq_aggregate *new_agg = qfq_find_agg(q, lmax, weight);
383
384         if (new_agg == NULL) { /* create new aggregate */
385                 new_agg = kzalloc(sizeof(*new_agg), GFP_ATOMIC);
386                 if (new_agg == NULL)
387                         return -ENOBUFS;
388                 qfq_init_agg(q, new_agg, lmax, weight);
389         }
390         qfq_deact_rm_from_agg(q, cl);
391         qfq_add_to_agg(q, new_agg, cl);
392
393         return 0;
394 }
395
396 static int qfq_change_class(struct Qdisc *sch, u32 classid, u32 parentid,
397                             struct nlattr **tca, unsigned long *arg)
398 {
399         struct qfq_sched *q = qdisc_priv(sch);
400         struct qfq_class *cl = (struct qfq_class *)*arg;
401         bool existing = false;
402         struct nlattr *tb[TCA_QFQ_MAX + 1];
403         struct qfq_aggregate *new_agg = NULL;
404         u32 weight, lmax, inv_w;
405         int err;
406         int delta_w;
407
408         if (tca[TCA_OPTIONS] == NULL) {
409                 pr_notice("qfq: no options\n");
410                 return -EINVAL;
411         }
412
413         err = nla_parse_nested(tb, TCA_QFQ_MAX, tca[TCA_OPTIONS], qfq_policy);
414         if (err < 0)
415                 return err;
416
417         if (tb[TCA_QFQ_WEIGHT]) {
418                 weight = nla_get_u32(tb[TCA_QFQ_WEIGHT]);
419                 if (!weight || weight > (1UL << QFQ_MAX_WSHIFT)) {
420                         pr_notice("qfq: invalid weight %u\n", weight);
421                         return -EINVAL;
422                 }
423         } else
424                 weight = 1;
425
426         if (tb[TCA_QFQ_LMAX]) {
427                 lmax = nla_get_u32(tb[TCA_QFQ_LMAX]);
428                 if (lmax < QFQ_MIN_LMAX || lmax > (1UL << QFQ_MTU_SHIFT)) {
429                         pr_notice("qfq: invalid max length %u\n", lmax);
430                         return -EINVAL;
431                 }
432         } else
433                 lmax = psched_mtu(qdisc_dev(sch));
434
435         inv_w = ONE_FP / weight;
436         weight = ONE_FP / inv_w;
437
438         if (cl != NULL &&
439             lmax == cl->agg->lmax &&
440             weight == cl->agg->class_weight)
441                 return 0; /* nothing to change */
442
443         delta_w = weight - (cl ? cl->agg->class_weight : 0);
444
445         if (q->wsum + delta_w > QFQ_MAX_WSUM) {
446                 pr_notice("qfq: total weight out of range (%d + %u)\n",
447                           delta_w, q->wsum);
448                 return -EINVAL;
449         }
450
451         if (cl != NULL) { /* modify existing class */
452                 if (tca[TCA_RATE]) {
453                         err = gen_replace_estimator(&cl->bstats, &cl->rate_est,
454                                                     qdisc_root_sleeping_lock(sch),
455                                                     tca[TCA_RATE]);
456                         if (err)
457                                 return err;
458                 }
459                 existing = true;
460                 goto set_change_agg;
461         }
462
463         /* create and init new class */
464         cl = kzalloc(sizeof(struct qfq_class), GFP_KERNEL);
465         if (cl == NULL)
466                 return -ENOBUFS;
467
468         cl->refcnt = 1;
469         cl->common.classid = classid;
470         cl->deficit = lmax;
471
472         cl->qdisc = qdisc_create_dflt(sch->dev_queue,
473                                       &pfifo_qdisc_ops, classid);
474         if (cl->qdisc == NULL)
475                 cl->qdisc = &noop_qdisc;
476
477         if (tca[TCA_RATE]) {
478                 err = gen_new_estimator(&cl->bstats, &cl->rate_est,
479                                         qdisc_root_sleeping_lock(sch),
480                                         tca[TCA_RATE]);
481                 if (err)
482                         goto destroy_class;
483         }
484
485         sch_tree_lock(sch);
486         qdisc_class_hash_insert(&q->clhash, &cl->common);
487         sch_tree_unlock(sch);
488
489         qdisc_class_hash_grow(sch, &q->clhash);
490
491 set_change_agg:
492         sch_tree_lock(sch);
493         new_agg = qfq_find_agg(q, lmax, weight);
494         if (new_agg == NULL) { /* create new aggregate */
495                 sch_tree_unlock(sch);
496                 new_agg = kzalloc(sizeof(*new_agg), GFP_KERNEL);
497                 if (new_agg == NULL) {
498                         err = -ENOBUFS;
499                         gen_kill_estimator(&cl->bstats, &cl->rate_est);
500                         goto destroy_class;
501                 }
502                 sch_tree_lock(sch);
503                 qfq_init_agg(q, new_agg, lmax, weight);
504         }
505         if (existing)
506                 qfq_deact_rm_from_agg(q, cl);
507         qfq_add_to_agg(q, new_agg, cl);
508         sch_tree_unlock(sch);
509
510         *arg = (unsigned long)cl;
511         return 0;
512
513 destroy_class:
514         qdisc_destroy(cl->qdisc);
515         kfree(cl);
516         return err;
517 }
518
519 static void qfq_destroy_class(struct Qdisc *sch, struct qfq_class *cl)
520 {
521         struct qfq_sched *q = qdisc_priv(sch);
522
523         qfq_rm_from_agg(q, cl);
524         gen_kill_estimator(&cl->bstats, &cl->rate_est);
525         qdisc_destroy(cl->qdisc);
526         kfree(cl);
527 }
528
529 static int qfq_delete_class(struct Qdisc *sch, unsigned long arg)
530 {
531         struct qfq_sched *q = qdisc_priv(sch);
532         struct qfq_class *cl = (struct qfq_class *)arg;
533
534         if (cl->filter_cnt > 0)
535                 return -EBUSY;
536
537         sch_tree_lock(sch);
538
539         qfq_purge_queue(cl);
540         qdisc_class_hash_remove(&q->clhash, &cl->common);
541
542         BUG_ON(--cl->refcnt == 0);
543         /*
544          * This shouldn't happen: we "hold" one cops->get() when called
545          * from tc_ctl_tclass; the destroy method is done from cops->put().
546          */
547
548         sch_tree_unlock(sch);
549         return 0;
550 }
551
552 static unsigned long qfq_get_class(struct Qdisc *sch, u32 classid)
553 {
554         struct qfq_class *cl = qfq_find_class(sch, classid);
555
556         if (cl != NULL)
557                 cl->refcnt++;
558
559         return (unsigned long)cl;
560 }
561
562 static void qfq_put_class(struct Qdisc *sch, unsigned long arg)
563 {
564         struct qfq_class *cl = (struct qfq_class *)arg;
565
566         if (--cl->refcnt == 0)
567                 qfq_destroy_class(sch, cl);
568 }
569
570 static struct tcf_proto **qfq_tcf_chain(struct Qdisc *sch, unsigned long cl)
571 {
572         struct qfq_sched *q = qdisc_priv(sch);
573
574         if (cl)
575                 return NULL;
576
577         return &q->filter_list;
578 }
579
580 static unsigned long qfq_bind_tcf(struct Qdisc *sch, unsigned long parent,
581                                   u32 classid)
582 {
583         struct qfq_class *cl = qfq_find_class(sch, classid);
584
585         if (cl != NULL)
586                 cl->filter_cnt++;
587
588         return (unsigned long)cl;
589 }
590
591 static void qfq_unbind_tcf(struct Qdisc *sch, unsigned long arg)
592 {
593         struct qfq_class *cl = (struct qfq_class *)arg;
594
595         cl->filter_cnt--;
596 }
597
598 static int qfq_graft_class(struct Qdisc *sch, unsigned long arg,
599                            struct Qdisc *new, struct Qdisc **old)
600 {
601         struct qfq_class *cl = (struct qfq_class *)arg;
602
603         if (new == NULL) {
604                 new = qdisc_create_dflt(sch->dev_queue,
605                                         &pfifo_qdisc_ops, cl->common.classid);
606                 if (new == NULL)
607                         new = &noop_qdisc;
608         }
609
610         sch_tree_lock(sch);
611         qfq_purge_queue(cl);
612         *old = cl->qdisc;
613         cl->qdisc = new;
614         sch_tree_unlock(sch);
615         return 0;
616 }
617
618 static struct Qdisc *qfq_class_leaf(struct Qdisc *sch, unsigned long arg)
619 {
620         struct qfq_class *cl = (struct qfq_class *)arg;
621
622         return cl->qdisc;
623 }
624
625 static int qfq_dump_class(struct Qdisc *sch, unsigned long arg,
626                           struct sk_buff *skb, struct tcmsg *tcm)
627 {
628         struct qfq_class *cl = (struct qfq_class *)arg;
629         struct nlattr *nest;
630
631         tcm->tcm_parent = TC_H_ROOT;
632         tcm->tcm_handle = cl->common.classid;
633         tcm->tcm_info   = cl->qdisc->handle;
634
635         nest = nla_nest_start(skb, TCA_OPTIONS);
636         if (nest == NULL)
637                 goto nla_put_failure;
638         if (nla_put_u32(skb, TCA_QFQ_WEIGHT, cl->agg->class_weight) ||
639             nla_put_u32(skb, TCA_QFQ_LMAX, cl->agg->lmax))
640                 goto nla_put_failure;
641         return nla_nest_end(skb, nest);
642
643 nla_put_failure:
644         nla_nest_cancel(skb, nest);
645         return -EMSGSIZE;
646 }
647
648 static int qfq_dump_class_stats(struct Qdisc *sch, unsigned long arg,
649                                 struct gnet_dump *d)
650 {
651         struct qfq_class *cl = (struct qfq_class *)arg;
652         struct tc_qfq_stats xstats;
653
654         memset(&xstats, 0, sizeof(xstats));
655         cl->qdisc->qstats.qlen = cl->qdisc->q.qlen;
656
657         xstats.weight = cl->agg->class_weight;
658         xstats.lmax = cl->agg->lmax;
659
660         if (gnet_stats_copy_basic(d, &cl->bstats) < 0 ||
661             gnet_stats_copy_rate_est(d, &cl->bstats, &cl->rate_est) < 0 ||
662             gnet_stats_copy_queue(d, &cl->qdisc->qstats) < 0)
663                 return -1;
664
665         return gnet_stats_copy_app(d, &xstats, sizeof(xstats));
666 }
667
668 static void qfq_walk(struct Qdisc *sch, struct qdisc_walker *arg)
669 {
670         struct qfq_sched *q = qdisc_priv(sch);
671         struct qfq_class *cl;
672         unsigned int i;
673
674         if (arg->stop)
675                 return;
676
677         for (i = 0; i < q->clhash.hashsize; i++) {
678                 hlist_for_each_entry(cl, &q->clhash.hash[i], common.hnode) {
679                         if (arg->count < arg->skip) {
680                                 arg->count++;
681                                 continue;
682                         }
683                         if (arg->fn(sch, (unsigned long)cl, arg) < 0) {
684                                 arg->stop = 1;
685                                 return;
686                         }
687                         arg->count++;
688                 }
689         }
690 }
691
692 static struct qfq_class *qfq_classify(struct sk_buff *skb, struct Qdisc *sch,
693                                       int *qerr)
694 {
695         struct qfq_sched *q = qdisc_priv(sch);
696         struct qfq_class *cl;
697         struct tcf_result res;
698         int result;
699
700         if (TC_H_MAJ(skb->priority ^ sch->handle) == 0) {
701                 pr_debug("qfq_classify: found %d\n", skb->priority);
702                 cl = qfq_find_class(sch, skb->priority);
703                 if (cl != NULL)
704                         return cl;
705         }
706
707         *qerr = NET_XMIT_SUCCESS | __NET_XMIT_BYPASS;
708         result = tc_classify(skb, q->filter_list, &res);
709         if (result >= 0) {
710 #ifdef CONFIG_NET_CLS_ACT
711                 switch (result) {
712                 case TC_ACT_QUEUED:
713                 case TC_ACT_STOLEN:
714                         *qerr = NET_XMIT_SUCCESS | __NET_XMIT_STOLEN;
715                 case TC_ACT_SHOT:
716                         return NULL;
717                 }
718 #endif
719                 cl = (struct qfq_class *)res.class;
720                 if (cl == NULL)
721                         cl = qfq_find_class(sch, res.classid);
722                 return cl;
723         }
724
725         return NULL;
726 }
727
728 /* Generic comparison function, handling wraparound. */
729 static inline int qfq_gt(u64 a, u64 b)
730 {
731         return (s64)(a - b) > 0;
732 }
733
734 /* Round a precise timestamp to its slotted value. */
735 static inline u64 qfq_round_down(u64 ts, unsigned int shift)
736 {
737         return ts & ~((1ULL << shift) - 1);
738 }
739
740 /* return the pointer to the group with lowest index in the bitmap */
741 static inline struct qfq_group *qfq_ffs(struct qfq_sched *q,
742                                         unsigned long bitmap)
743 {
744         int index = __ffs(bitmap);
745         return &q->groups[index];
746 }
747 /* Calculate a mask to mimic what would be ffs_from(). */
748 static inline unsigned long mask_from(unsigned long bitmap, int from)
749 {
750         return bitmap & ~((1UL << from) - 1);
751 }
752
753 /*
754  * The state computation relies on ER=0, IR=1, EB=2, IB=3
755  * First compute eligibility comparing grp->S, q->V,
756  * then check if someone is blocking us and possibly add EB
757  */
758 static int qfq_calc_state(struct qfq_sched *q, const struct qfq_group *grp)
759 {
760         /* if S > V we are not eligible */
761         unsigned int state = qfq_gt(grp->S, q->V);
762         unsigned long mask = mask_from(q->bitmaps[ER], grp->index);
763         struct qfq_group *next;
764
765         if (mask) {
766                 next = qfq_ffs(q, mask);
767                 if (qfq_gt(grp->F, next->F))
768                         state |= EB;
769         }
770
771         return state;
772 }
773
774
775 /*
776  * In principle
777  *      q->bitmaps[dst] |= q->bitmaps[src] & mask;
778  *      q->bitmaps[src] &= ~mask;
779  * but we should make sure that src != dst
780  */
781 static inline void qfq_move_groups(struct qfq_sched *q, unsigned long mask,
782                                    int src, int dst)
783 {
784         q->bitmaps[dst] |= q->bitmaps[src] & mask;
785         q->bitmaps[src] &= ~mask;
786 }
787
788 static void qfq_unblock_groups(struct qfq_sched *q, int index, u64 old_F)
789 {
790         unsigned long mask = mask_from(q->bitmaps[ER], index + 1);
791         struct qfq_group *next;
792
793         if (mask) {
794                 next = qfq_ffs(q, mask);
795                 if (!qfq_gt(next->F, old_F))
796                         return;
797         }
798
799         mask = (1UL << index) - 1;
800         qfq_move_groups(q, mask, EB, ER);
801         qfq_move_groups(q, mask, IB, IR);
802 }
803
804 /*
805  * perhaps
806  *
807         old_V ^= q->V;
808         old_V >>= q->min_slot_shift;
809         if (old_V) {
810                 ...
811         }
812  *
813  */
814 static void qfq_make_eligible(struct qfq_sched *q)
815 {
816         unsigned long vslot = q->V >> q->min_slot_shift;
817         unsigned long old_vslot = q->oldV >> q->min_slot_shift;
818
819         if (vslot != old_vslot) {
820                 unsigned long mask = (1UL << fls(vslot ^ old_vslot)) - 1;
821                 qfq_move_groups(q, mask, IR, ER);
822                 qfq_move_groups(q, mask, IB, EB);
823         }
824 }
825
826
827 /*
828  * The index of the slot in which the aggregate is to be inserted must
829  * not be higher than QFQ_MAX_SLOTS-2. There is a '-2' and not a '-1'
830  * because the start time of the group may be moved backward by one
831  * slot after the aggregate has been inserted, and this would cause
832  * non-empty slots to be right-shifted by one position.
833  *
834  * If the weight and lmax (max_pkt_size) of the classes do not change,
835  * then QFQ+ does meet the above contraint according to the current
836  * values of its parameters. In fact, if the weight and lmax of the
837  * classes do not change, then, from the theory, QFQ+ guarantees that
838  * the slot index is never higher than
839  * 2 + QFQ_MAX_AGG_CLASSES * ((1<<QFQ_MTU_SHIFT)/QFQ_MIN_LMAX) *
840  * (QFQ_MAX_WEIGHT/QFQ_MAX_WSUM) = 2 + 8 * 128 * (1 / 64) = 18
841  *
842  * When the weight of a class is increased or the lmax of the class is
843  * decreased, a new aggregate with smaller slot size than the original
844  * parent aggregate of the class may happen to be activated. The
845  * activation of this aggregate should be properly delayed to when the
846  * service of the class has finished in the ideal system tracked by
847  * QFQ+. If the activation of the aggregate is not delayed to this
848  * reference time instant, then this aggregate may be unjustly served
849  * before other aggregates waiting for service. This may cause the
850  * above bound to the slot index to be violated for some of these
851  * unlucky aggregates.
852  *
853  * Instead of delaying the activation of the new aggregate, which is
854  * quite complex, the following inaccurate but simple solution is used:
855  * if the slot index is higher than QFQ_MAX_SLOTS-2, then the
856  * timestamps of the aggregate are shifted backward so as to let the
857  * slot index become equal to QFQ_MAX_SLOTS-2.
858  */
859 static void qfq_slot_insert(struct qfq_group *grp, struct qfq_aggregate *agg,
860                             u64 roundedS)
861 {
862         u64 slot = (roundedS - grp->S) >> grp->slot_shift;
863         unsigned int i; /* slot index in the bucket list */
864
865         if (unlikely(slot > QFQ_MAX_SLOTS - 2)) {
866                 u64 deltaS = roundedS - grp->S -
867                         ((u64)(QFQ_MAX_SLOTS - 2)<<grp->slot_shift);
868                 agg->S -= deltaS;
869                 agg->F -= deltaS;
870                 slot = QFQ_MAX_SLOTS - 2;
871         }
872
873         i = (grp->front + slot) % QFQ_MAX_SLOTS;
874
875         hlist_add_head(&agg->next, &grp->slots[i]);
876         __set_bit(slot, &grp->full_slots);
877 }
878
879 /* Maybe introduce hlist_first_entry?? */
880 static struct qfq_aggregate *qfq_slot_head(struct qfq_group *grp)
881 {
882         return hlist_entry(grp->slots[grp->front].first,
883                            struct qfq_aggregate, next);
884 }
885
886 /*
887  * remove the entry from the slot
888  */
889 static void qfq_front_slot_remove(struct qfq_group *grp)
890 {
891         struct qfq_aggregate *agg = qfq_slot_head(grp);
892
893         BUG_ON(!agg);
894         hlist_del(&agg->next);
895         if (hlist_empty(&grp->slots[grp->front]))
896                 __clear_bit(0, &grp->full_slots);
897 }
898
899 /*
900  * Returns the first aggregate in the first non-empty bucket of the
901  * group. As a side effect, adjusts the bucket list so the first
902  * non-empty bucket is at position 0 in full_slots.
903  */
904 static struct qfq_aggregate *qfq_slot_scan(struct qfq_group *grp)
905 {
906         unsigned int i;
907
908         pr_debug("qfq slot_scan: grp %u full %#lx\n",
909                  grp->index, grp->full_slots);
910
911         if (grp->full_slots == 0)
912                 return NULL;
913
914         i = __ffs(grp->full_slots);  /* zero based */
915         if (i > 0) {
916                 grp->front = (grp->front + i) % QFQ_MAX_SLOTS;
917                 grp->full_slots >>= i;
918         }
919
920         return qfq_slot_head(grp);
921 }
922
923 /*
924  * adjust the bucket list. When the start time of a group decreases,
925  * we move the index down (modulo QFQ_MAX_SLOTS) so we don't need to
926  * move the objects. The mask of occupied slots must be shifted
927  * because we use ffs() to find the first non-empty slot.
928  * This covers decreases in the group's start time, but what about
929  * increases of the start time ?
930  * Here too we should make sure that i is less than 32
931  */
932 static void qfq_slot_rotate(struct qfq_group *grp, u64 roundedS)
933 {
934         unsigned int i = (grp->S - roundedS) >> grp->slot_shift;
935
936         grp->full_slots <<= i;
937         grp->front = (grp->front - i) % QFQ_MAX_SLOTS;
938 }
939
940 static void qfq_update_eligible(struct qfq_sched *q)
941 {
942         struct qfq_group *grp;
943         unsigned long ineligible;
944
945         ineligible = q->bitmaps[IR] | q->bitmaps[IB];
946         if (ineligible) {
947                 if (!q->bitmaps[ER]) {
948                         grp = qfq_ffs(q, ineligible);
949                         if (qfq_gt(grp->S, q->V))
950                                 q->V = grp->S;
951                 }
952                 qfq_make_eligible(q);
953         }
954 }
955
956 /* Dequeue head packet of the head class in the DRR queue of the aggregate. */
957 static void agg_dequeue(struct qfq_aggregate *agg,
958                         struct qfq_class *cl, unsigned int len)
959 {
960         qdisc_dequeue_peeked(cl->qdisc);
961
962         cl->deficit -= (int) len;
963
964         if (cl->qdisc->q.qlen == 0) /* no more packets, remove from list */
965                 list_del(&cl->alist);
966         else if (cl->deficit < qdisc_pkt_len(cl->qdisc->ops->peek(cl->qdisc))) {
967                 cl->deficit += agg->lmax;
968                 list_move_tail(&cl->alist, &agg->active);
969         }
970 }
971
972 static inline struct sk_buff *qfq_peek_skb(struct qfq_aggregate *agg,
973                                            struct qfq_class **cl,
974                                            unsigned int *len)
975 {
976         struct sk_buff *skb;
977
978         *cl = list_first_entry(&agg->active, struct qfq_class, alist);
979         skb = (*cl)->qdisc->ops->peek((*cl)->qdisc);
980         if (skb == NULL)
981                 WARN_ONCE(1, "qfq_dequeue: non-workconserving leaf\n");
982         else
983                 *len = qdisc_pkt_len(skb);
984
985         return skb;
986 }
987
988 /* Update F according to the actual service received by the aggregate. */
989 static inline void charge_actual_service(struct qfq_aggregate *agg)
990 {
991         /* compute the service received by the aggregate */
992         u32 service_received = agg->initial_budget - agg->budget;
993
994         agg->F = agg->S + (u64)service_received * agg->inv_w;
995 }
996
997 static struct sk_buff *qfq_dequeue(struct Qdisc *sch)
998 {
999         struct qfq_sched *q = qdisc_priv(sch);
1000         struct qfq_aggregate *in_serv_agg = q->in_serv_agg;
1001         struct qfq_class *cl;
1002         struct sk_buff *skb = NULL;
1003         /* next-packet len, 0 means no more active classes in in-service agg */
1004         unsigned int len = 0;
1005
1006         if (in_serv_agg == NULL)
1007                 return NULL;
1008
1009         if (!list_empty(&in_serv_agg->active))
1010                 skb = qfq_peek_skb(in_serv_agg, &cl, &len);
1011
1012         /*
1013          * If there are no active classes in the in-service aggregate,
1014          * or if the aggregate has not enough budget to serve its next
1015          * class, then choose the next aggregate to serve.
1016          */
1017         if (len == 0 || in_serv_agg->budget < len) {
1018                 charge_actual_service(in_serv_agg);
1019
1020                 /* recharge the budget of the aggregate */
1021                 in_serv_agg->initial_budget = in_serv_agg->budget =
1022                         in_serv_agg->budgetmax;
1023
1024                 if (!list_empty(&in_serv_agg->active))
1025                         /*
1026                          * Still active: reschedule for
1027                          * service. Possible optimization: if no other
1028                          * aggregate is active, then there is no point
1029                          * in rescheduling this aggregate, and we can
1030                          * just keep it as the in-service one. This
1031                          * should be however a corner case, and to
1032                          * handle it, we would need to maintain an
1033                          * extra num_active_aggs field.
1034                         */
1035                         qfq_activate_agg(q, in_serv_agg, requeue);
1036                 else if (sch->q.qlen == 0) { /* no aggregate to serve */
1037                         q->in_serv_agg = NULL;
1038                         return NULL;
1039                 }
1040
1041                 /*
1042                  * If we get here, there are other aggregates queued:
1043                  * choose the new aggregate to serve.
1044                  */
1045                 in_serv_agg = q->in_serv_agg = qfq_choose_next_agg(q);
1046                 skb = qfq_peek_skb(in_serv_agg, &cl, &len);
1047         }
1048         if (!skb)
1049                 return NULL;
1050
1051         sch->q.qlen--;
1052         qdisc_bstats_update(sch, skb);
1053
1054         agg_dequeue(in_serv_agg, cl, len);
1055         in_serv_agg->budget -= len;
1056         q->V += (u64)len * IWSUM;
1057         pr_debug("qfq dequeue: len %u F %lld now %lld\n",
1058                  len, (unsigned long long) in_serv_agg->F,
1059                  (unsigned long long) q->V);
1060
1061         return skb;
1062 }
1063
1064 static struct qfq_aggregate *qfq_choose_next_agg(struct qfq_sched *q)
1065 {
1066         struct qfq_group *grp;
1067         struct qfq_aggregate *agg, *new_front_agg;
1068         u64 old_F;
1069
1070         qfq_update_eligible(q);
1071         q->oldV = q->V;
1072
1073         if (!q->bitmaps[ER])
1074                 return NULL;
1075
1076         grp = qfq_ffs(q, q->bitmaps[ER]);
1077         old_F = grp->F;
1078
1079         agg = qfq_slot_head(grp);
1080
1081         /* agg starts to be served, remove it from schedule */
1082         qfq_front_slot_remove(grp);
1083
1084         new_front_agg = qfq_slot_scan(grp);
1085
1086         if (new_front_agg == NULL) /* group is now inactive, remove from ER */
1087                 __clear_bit(grp->index, &q->bitmaps[ER]);
1088         else {
1089                 u64 roundedS = qfq_round_down(new_front_agg->S,
1090                                               grp->slot_shift);
1091                 unsigned int s;
1092
1093                 if (grp->S == roundedS)
1094                         return agg;
1095                 grp->S = roundedS;
1096                 grp->F = roundedS + (2ULL << grp->slot_shift);
1097                 __clear_bit(grp->index, &q->bitmaps[ER]);
1098                 s = qfq_calc_state(q, grp);
1099                 __set_bit(grp->index, &q->bitmaps[s]);
1100         }
1101
1102         qfq_unblock_groups(q, grp->index, old_F);
1103
1104         return agg;
1105 }
1106
1107 /*
1108  * Assign a reasonable start time for a new aggregate in group i.
1109  * Admissible values for \hat(F) are multiples of \sigma_i
1110  * no greater than V+\sigma_i . Larger values mean that
1111  * we had a wraparound so we consider the timestamp to be stale.
1112  *
1113  * If F is not stale and F >= V then we set S = F.
1114  * Otherwise we should assign S = V, but this may violate
1115  * the ordering in EB (see [2]). So, if we have groups in ER,
1116  * set S to the F_j of the first group j which would be blocking us.
1117  * We are guaranteed not to move S backward because
1118  * otherwise our group i would still be blocked.
1119  */
1120 static void qfq_update_start(struct qfq_sched *q, struct qfq_aggregate *agg)
1121 {
1122         unsigned long mask;
1123         u64 limit, roundedF;
1124         int slot_shift = agg->grp->slot_shift;
1125
1126         roundedF = qfq_round_down(agg->F, slot_shift);
1127         limit = qfq_round_down(q->V, slot_shift) + (1ULL << slot_shift);
1128
1129         if (!qfq_gt(agg->F, q->V) || qfq_gt(roundedF, limit)) {
1130                 /* timestamp was stale */
1131                 mask = mask_from(q->bitmaps[ER], agg->grp->index);
1132                 if (mask) {
1133                         struct qfq_group *next = qfq_ffs(q, mask);
1134                         if (qfq_gt(roundedF, next->F)) {
1135                                 if (qfq_gt(limit, next->F))
1136                                         agg->S = next->F;
1137                                 else /* preserve timestamp correctness */
1138                                         agg->S = limit;
1139                                 return;
1140                         }
1141                 }
1142                 agg->S = q->V;
1143         } else  /* timestamp is not stale */
1144                 agg->S = agg->F;
1145 }
1146
1147 /*
1148  * Update the timestamps of agg before scheduling/rescheduling it for
1149  * service.  In particular, assign to agg->F its maximum possible
1150  * value, i.e., the virtual finish time with which the aggregate
1151  * should be labeled if it used all its budget once in service.
1152  */
1153 static inline void
1154 qfq_update_agg_ts(struct qfq_sched *q,
1155                     struct qfq_aggregate *agg, enum update_reason reason)
1156 {
1157         if (reason != requeue)
1158                 qfq_update_start(q, agg);
1159         else /* just charge agg for the service received */
1160                 agg->S = agg->F;
1161
1162         agg->F = agg->S + (u64)agg->budgetmax * agg->inv_w;
1163 }
1164
1165 static void qfq_schedule_agg(struct qfq_sched *, struct qfq_aggregate *);
1166
1167 static int qfq_enqueue(struct sk_buff *skb, struct Qdisc *sch)
1168 {
1169         struct qfq_sched *q = qdisc_priv(sch);
1170         struct qfq_class *cl;
1171         struct qfq_aggregate *agg;
1172         int err = 0;
1173
1174         cl = qfq_classify(skb, sch, &err);
1175         if (cl == NULL) {
1176                 if (err & __NET_XMIT_BYPASS)
1177                         sch->qstats.drops++;
1178                 kfree_skb(skb);
1179                 return err;
1180         }
1181         pr_debug("qfq_enqueue: cl = %x\n", cl->common.classid);
1182
1183         if (unlikely(cl->agg->lmax < qdisc_pkt_len(skb))) {
1184                 pr_debug("qfq: increasing maxpkt from %u to %u for class %u",
1185                          cl->agg->lmax, qdisc_pkt_len(skb), cl->common.classid);
1186                 err = qfq_change_agg(sch, cl, cl->agg->class_weight,
1187                                      qdisc_pkt_len(skb));
1188                 if (err)
1189                         return err;
1190         }
1191
1192         err = qdisc_enqueue(skb, cl->qdisc);
1193         if (unlikely(err != NET_XMIT_SUCCESS)) {
1194                 pr_debug("qfq_enqueue: enqueue failed %d\n", err);
1195                 if (net_xmit_drop_count(err)) {
1196                         cl->qstats.drops++;
1197                         sch->qstats.drops++;
1198                 }
1199                 return err;
1200         }
1201
1202         bstats_update(&cl->bstats, skb);
1203         ++sch->q.qlen;
1204
1205         agg = cl->agg;
1206         /* if the queue was not empty, then done here */
1207         if (cl->qdisc->q.qlen != 1) {
1208                 if (unlikely(skb == cl->qdisc->ops->peek(cl->qdisc)) &&
1209                     list_first_entry(&agg->active, struct qfq_class, alist)
1210                     == cl && cl->deficit < qdisc_pkt_len(skb))
1211                         list_move_tail(&cl->alist, &agg->active);
1212
1213                 return err;
1214         }
1215
1216         /* schedule class for service within the aggregate */
1217         cl->deficit = agg->lmax;
1218         list_add_tail(&cl->alist, &agg->active);
1219
1220         if (list_first_entry(&agg->active, struct qfq_class, alist) != cl)
1221                 return err; /* aggregate was not empty, nothing else to do */
1222
1223         /* recharge budget */
1224         agg->initial_budget = agg->budget = agg->budgetmax;
1225
1226         qfq_update_agg_ts(q, agg, enqueue);
1227         if (q->in_serv_agg == NULL)
1228                 q->in_serv_agg = agg;
1229         else if (agg != q->in_serv_agg)
1230                 qfq_schedule_agg(q, agg);
1231
1232         return err;
1233 }
1234
1235 /*
1236  * Schedule aggregate according to its timestamps.
1237  */
1238 static void qfq_schedule_agg(struct qfq_sched *q, struct qfq_aggregate *agg)
1239 {
1240         struct qfq_group *grp = agg->grp;
1241         u64 roundedS;
1242         int s;
1243
1244         roundedS = qfq_round_down(agg->S, grp->slot_shift);
1245
1246         /*
1247          * Insert agg in the correct bucket.
1248          * If agg->S >= grp->S we don't need to adjust the
1249          * bucket list and simply go to the insertion phase.
1250          * Otherwise grp->S is decreasing, we must make room
1251          * in the bucket list, and also recompute the group state.
1252          * Finally, if there were no flows in this group and nobody
1253          * was in ER make sure to adjust V.
1254          */
1255         if (grp->full_slots) {
1256                 if (!qfq_gt(grp->S, agg->S))
1257                         goto skip_update;
1258
1259                 /* create a slot for this agg->S */
1260                 qfq_slot_rotate(grp, roundedS);
1261                 /* group was surely ineligible, remove */
1262                 __clear_bit(grp->index, &q->bitmaps[IR]);
1263                 __clear_bit(grp->index, &q->bitmaps[IB]);
1264         } else if (!q->bitmaps[ER] && qfq_gt(roundedS, q->V))
1265                 q->V = roundedS;
1266
1267         grp->S = roundedS;
1268         grp->F = roundedS + (2ULL << grp->slot_shift);
1269         s = qfq_calc_state(q, grp);
1270         __set_bit(grp->index, &q->bitmaps[s]);
1271
1272         pr_debug("qfq enqueue: new state %d %#lx S %lld F %lld V %lld\n",
1273                  s, q->bitmaps[s],
1274                  (unsigned long long) agg->S,
1275                  (unsigned long long) agg->F,
1276                  (unsigned long long) q->V);
1277
1278 skip_update:
1279         qfq_slot_insert(grp, agg, roundedS);
1280 }
1281
1282
1283 /* Update agg ts and schedule agg for service */
1284 static void qfq_activate_agg(struct qfq_sched *q, struct qfq_aggregate *agg,
1285                              enum update_reason reason)
1286 {
1287         qfq_update_agg_ts(q, agg, reason);
1288         qfq_schedule_agg(q, agg);
1289 }
1290
1291 static void qfq_slot_remove(struct qfq_sched *q, struct qfq_group *grp,
1292                             struct qfq_aggregate *agg)
1293 {
1294         unsigned int i, offset;
1295         u64 roundedS;
1296
1297         roundedS = qfq_round_down(agg->S, grp->slot_shift);
1298         offset = (roundedS - grp->S) >> grp->slot_shift;
1299
1300         i = (grp->front + offset) % QFQ_MAX_SLOTS;
1301
1302         hlist_del(&agg->next);
1303         if (hlist_empty(&grp->slots[i]))
1304                 __clear_bit(offset, &grp->full_slots);
1305 }
1306
1307 /*
1308  * Called to forcibly deschedule an aggregate.  If the aggregate is
1309  * not in the front bucket, or if the latter has other aggregates in
1310  * the front bucket, we can simply remove the aggregate with no other
1311  * side effects.
1312  * Otherwise we must propagate the event up.
1313  */
1314 static void qfq_deactivate_agg(struct qfq_sched *q, struct qfq_aggregate *agg)
1315 {
1316         struct qfq_group *grp = agg->grp;
1317         unsigned long mask;
1318         u64 roundedS;
1319         int s;
1320
1321         if (agg == q->in_serv_agg) {
1322                 charge_actual_service(agg);
1323                 q->in_serv_agg = qfq_choose_next_agg(q);
1324                 return;
1325         }
1326
1327         agg->F = agg->S;
1328         qfq_slot_remove(q, grp, agg);
1329
1330         if (!grp->full_slots) {
1331                 __clear_bit(grp->index, &q->bitmaps[IR]);
1332                 __clear_bit(grp->index, &q->bitmaps[EB]);
1333                 __clear_bit(grp->index, &q->bitmaps[IB]);
1334
1335                 if (test_bit(grp->index, &q->bitmaps[ER]) &&
1336                     !(q->bitmaps[ER] & ~((1UL << grp->index) - 1))) {
1337                         mask = q->bitmaps[ER] & ((1UL << grp->index) - 1);
1338                         if (mask)
1339                                 mask = ~((1UL << __fls(mask)) - 1);
1340                         else
1341                                 mask = ~0UL;
1342                         qfq_move_groups(q, mask, EB, ER);
1343                         qfq_move_groups(q, mask, IB, IR);
1344                 }
1345                 __clear_bit(grp->index, &q->bitmaps[ER]);
1346         } else if (hlist_empty(&grp->slots[grp->front])) {
1347                 agg = qfq_slot_scan(grp);
1348                 roundedS = qfq_round_down(agg->S, grp->slot_shift);
1349                 if (grp->S != roundedS) {
1350                         __clear_bit(grp->index, &q->bitmaps[ER]);
1351                         __clear_bit(grp->index, &q->bitmaps[IR]);
1352                         __clear_bit(grp->index, &q->bitmaps[EB]);
1353                         __clear_bit(grp->index, &q->bitmaps[IB]);
1354                         grp->S = roundedS;
1355                         grp->F = roundedS + (2ULL << grp->slot_shift);
1356                         s = qfq_calc_state(q, grp);
1357                         __set_bit(grp->index, &q->bitmaps[s]);
1358                 }
1359         }
1360
1361         qfq_update_eligible(q);
1362 }
1363
1364 static void qfq_qlen_notify(struct Qdisc *sch, unsigned long arg)
1365 {
1366         struct qfq_sched *q = qdisc_priv(sch);
1367         struct qfq_class *cl = (struct qfq_class *)arg;
1368
1369         if (cl->qdisc->q.qlen == 0)
1370                 qfq_deactivate_class(q, cl);
1371 }
1372
1373 static unsigned int qfq_drop_from_slot(struct qfq_sched *q,
1374                                        struct hlist_head *slot)
1375 {
1376         struct qfq_aggregate *agg;
1377         struct qfq_class *cl;
1378         unsigned int len;
1379
1380         hlist_for_each_entry(agg, slot, next) {
1381                 list_for_each_entry(cl, &agg->active, alist) {
1382
1383                         if (!cl->qdisc->ops->drop)
1384                                 continue;
1385
1386                         len = cl->qdisc->ops->drop(cl->qdisc);
1387                         if (len > 0) {
1388                                 if (cl->qdisc->q.qlen == 0)
1389                                         qfq_deactivate_class(q, cl);
1390
1391                                 return len;
1392                         }
1393                 }
1394         }
1395         return 0;
1396 }
1397
1398 static unsigned int qfq_drop(struct Qdisc *sch)
1399 {
1400         struct qfq_sched *q = qdisc_priv(sch);
1401         struct qfq_group *grp;
1402         unsigned int i, j, len;
1403
1404         for (i = 0; i <= QFQ_MAX_INDEX; i++) {
1405                 grp = &q->groups[i];
1406                 for (j = 0; j < QFQ_MAX_SLOTS; j++) {
1407                         len = qfq_drop_from_slot(q, &grp->slots[j]);
1408                         if (len > 0) {
1409                                 sch->q.qlen--;
1410                                 return len;
1411                         }
1412                 }
1413
1414         }
1415
1416         return 0;
1417 }
1418
1419 static int qfq_init_qdisc(struct Qdisc *sch, struct nlattr *opt)
1420 {
1421         struct qfq_sched *q = qdisc_priv(sch);
1422         struct qfq_group *grp;
1423         int i, j, err;
1424         u32 max_cl_shift, maxbudg_shift, max_classes;
1425
1426         err = qdisc_class_hash_init(&q->clhash);
1427         if (err < 0)
1428                 return err;
1429
1430         if (qdisc_dev(sch)->tx_queue_len + 1 > QFQ_MAX_AGG_CLASSES)
1431                 max_classes = QFQ_MAX_AGG_CLASSES;
1432         else
1433                 max_classes = qdisc_dev(sch)->tx_queue_len + 1;
1434         /* max_cl_shift = floor(log_2(max_classes)) */
1435         max_cl_shift = __fls(max_classes);
1436         q->max_agg_classes = 1<<max_cl_shift;
1437
1438         /* maxbudg_shift = log2(max_len * max_classes_per_agg) */
1439         maxbudg_shift = QFQ_MTU_SHIFT + max_cl_shift;
1440         q->min_slot_shift = FRAC_BITS + maxbudg_shift - QFQ_MAX_INDEX;
1441
1442         for (i = 0; i <= QFQ_MAX_INDEX; i++) {
1443                 grp = &q->groups[i];
1444                 grp->index = i;
1445                 grp->slot_shift = q->min_slot_shift + i;
1446                 for (j = 0; j < QFQ_MAX_SLOTS; j++)
1447                         INIT_HLIST_HEAD(&grp->slots[j]);
1448         }
1449
1450         INIT_HLIST_HEAD(&q->nonfull_aggs);
1451
1452         return 0;
1453 }
1454
1455 static void qfq_reset_qdisc(struct Qdisc *sch)
1456 {
1457         struct qfq_sched *q = qdisc_priv(sch);
1458         struct qfq_class *cl;
1459         unsigned int i;
1460
1461         for (i = 0; i < q->clhash.hashsize; i++) {
1462                 hlist_for_each_entry(cl, &q->clhash.hash[i], common.hnode) {
1463                         if (cl->qdisc->q.qlen > 0)
1464                                 qfq_deactivate_class(q, cl);
1465
1466                         qdisc_reset(cl->qdisc);
1467                 }
1468         }
1469         sch->q.qlen = 0;
1470 }
1471
1472 static void qfq_destroy_qdisc(struct Qdisc *sch)
1473 {
1474         struct qfq_sched *q = qdisc_priv(sch);
1475         struct qfq_class *cl;
1476         struct hlist_node *next;
1477         unsigned int i;
1478
1479         tcf_destroy_chain(&q->filter_list);
1480
1481         for (i = 0; i < q->clhash.hashsize; i++) {
1482                 hlist_for_each_entry_safe(cl, next, &q->clhash.hash[i],
1483                                           common.hnode) {
1484                         qfq_destroy_class(sch, cl);
1485                 }
1486         }
1487         qdisc_class_hash_destroy(&q->clhash);
1488 }
1489
1490 static const struct Qdisc_class_ops qfq_class_ops = {
1491         .change         = qfq_change_class,
1492         .delete         = qfq_delete_class,
1493         .get            = qfq_get_class,
1494         .put            = qfq_put_class,
1495         .tcf_chain      = qfq_tcf_chain,
1496         .bind_tcf       = qfq_bind_tcf,
1497         .unbind_tcf     = qfq_unbind_tcf,
1498         .graft          = qfq_graft_class,
1499         .leaf           = qfq_class_leaf,
1500         .qlen_notify    = qfq_qlen_notify,
1501         .dump           = qfq_dump_class,
1502         .dump_stats     = qfq_dump_class_stats,
1503         .walk           = qfq_walk,
1504 };
1505
1506 static struct Qdisc_ops qfq_qdisc_ops __read_mostly = {
1507         .cl_ops         = &qfq_class_ops,
1508         .id             = "qfq",
1509         .priv_size      = sizeof(struct qfq_sched),
1510         .enqueue        = qfq_enqueue,
1511         .dequeue        = qfq_dequeue,
1512         .peek           = qdisc_peek_dequeued,
1513         .drop           = qfq_drop,
1514         .init           = qfq_init_qdisc,
1515         .reset          = qfq_reset_qdisc,
1516         .destroy        = qfq_destroy_qdisc,
1517         .owner          = THIS_MODULE,
1518 };
1519
1520 static int __init qfq_init(void)
1521 {
1522         return register_qdisc(&qfq_qdisc_ops);
1523 }
1524
1525 static void __exit qfq_exit(void)
1526 {
1527         unregister_qdisc(&qfq_qdisc_ops);
1528 }
1529
1530 module_init(qfq_init);
1531 module_exit(qfq_exit);
1532 MODULE_LICENSE("GPL");