taprio: Fix still allowing changing the flags during runtime
[linux-2.6-microblaze.git] / net / sched / sch_taprio.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 /* net/sched/sch_taprio.c        Time Aware Priority Scheduler
4  *
5  * Authors:     Vinicius Costa Gomes <vinicius.gomes@intel.com>
6  *
7  */
8
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/kernel.h>
12 #include <linux/string.h>
13 #include <linux/list.h>
14 #include <linux/errno.h>
15 #include <linux/skbuff.h>
16 #include <linux/math64.h>
17 #include <linux/module.h>
18 #include <linux/spinlock.h>
19 #include <linux/rcupdate.h>
20 #include <net/netlink.h>
21 #include <net/pkt_sched.h>
22 #include <net/pkt_cls.h>
23 #include <net/sch_generic.h>
24 #include <net/sock.h>
25 #include <net/tcp.h>
26
27 static LIST_HEAD(taprio_list);
28 static DEFINE_SPINLOCK(taprio_list_lock);
29
30 #define TAPRIO_ALL_GATES_OPEN -1
31
32 #define TXTIME_ASSIST_IS_ENABLED(flags) ((flags) & TCA_TAPRIO_ATTR_FLAG_TXTIME_ASSIST)
33 #define FULL_OFFLOAD_IS_ENABLED(flags) ((flags) & TCA_TAPRIO_ATTR_FLAG_FULL_OFFLOAD)
34 #define TAPRIO_FLAGS_INVALID U32_MAX
35
36 struct sched_entry {
37         struct list_head list;
38
39         /* The instant that this entry "closes" and the next one
40          * should open, the qdisc will make some effort so that no
41          * packet leaves after this time.
42          */
43         ktime_t close_time;
44         ktime_t next_txtime;
45         atomic_t budget;
46         int index;
47         u32 gate_mask;
48         u32 interval;
49         u8 command;
50 };
51
52 struct sched_gate_list {
53         struct rcu_head rcu;
54         struct list_head entries;
55         size_t num_entries;
56         ktime_t cycle_close_time;
57         s64 cycle_time;
58         s64 cycle_time_extension;
59         s64 base_time;
60 };
61
62 struct taprio_sched {
63         struct Qdisc **qdiscs;
64         struct Qdisc *root;
65         u32 flags;
66         enum tk_offsets tk_offset;
67         int clockid;
68         atomic64_t picos_per_byte; /* Using picoseconds because for 10Gbps+
69                                     * speeds it's sub-nanoseconds per byte
70                                     */
71
72         /* Protects the update side of the RCU protected current_entry */
73         spinlock_t current_entry_lock;
74         struct sched_entry __rcu *current_entry;
75         struct sched_gate_list __rcu *oper_sched;
76         struct sched_gate_list __rcu *admin_sched;
77         struct hrtimer advance_timer;
78         struct list_head taprio_list;
79         struct sk_buff *(*dequeue)(struct Qdisc *sch);
80         struct sk_buff *(*peek)(struct Qdisc *sch);
81         u32 txtime_delay;
82 };
83
84 struct __tc_taprio_qopt_offload {
85         refcount_t users;
86         struct tc_taprio_qopt_offload offload;
87 };
88
89 static ktime_t sched_base_time(const struct sched_gate_list *sched)
90 {
91         if (!sched)
92                 return KTIME_MAX;
93
94         return ns_to_ktime(sched->base_time);
95 }
96
97 static ktime_t taprio_get_time(struct taprio_sched *q)
98 {
99         ktime_t mono = ktime_get();
100
101         switch (q->tk_offset) {
102         case TK_OFFS_MAX:
103                 return mono;
104         default:
105                 return ktime_mono_to_any(mono, q->tk_offset);
106         }
107
108         return KTIME_MAX;
109 }
110
111 static void taprio_free_sched_cb(struct rcu_head *head)
112 {
113         struct sched_gate_list *sched = container_of(head, struct sched_gate_list, rcu);
114         struct sched_entry *entry, *n;
115
116         if (!sched)
117                 return;
118
119         list_for_each_entry_safe(entry, n, &sched->entries, list) {
120                 list_del(&entry->list);
121                 kfree(entry);
122         }
123
124         kfree(sched);
125 }
126
127 static void switch_schedules(struct taprio_sched *q,
128                              struct sched_gate_list **admin,
129                              struct sched_gate_list **oper)
130 {
131         rcu_assign_pointer(q->oper_sched, *admin);
132         rcu_assign_pointer(q->admin_sched, NULL);
133
134         if (*oper)
135                 call_rcu(&(*oper)->rcu, taprio_free_sched_cb);
136
137         *oper = *admin;
138         *admin = NULL;
139 }
140
141 /* Get how much time has been already elapsed in the current cycle. */
142 static s32 get_cycle_time_elapsed(struct sched_gate_list *sched, ktime_t time)
143 {
144         ktime_t time_since_sched_start;
145         s32 time_elapsed;
146
147         time_since_sched_start = ktime_sub(time, sched->base_time);
148         div_s64_rem(time_since_sched_start, sched->cycle_time, &time_elapsed);
149
150         return time_elapsed;
151 }
152
153 static ktime_t get_interval_end_time(struct sched_gate_list *sched,
154                                      struct sched_gate_list *admin,
155                                      struct sched_entry *entry,
156                                      ktime_t intv_start)
157 {
158         s32 cycle_elapsed = get_cycle_time_elapsed(sched, intv_start);
159         ktime_t intv_end, cycle_ext_end, cycle_end;
160
161         cycle_end = ktime_add_ns(intv_start, sched->cycle_time - cycle_elapsed);
162         intv_end = ktime_add_ns(intv_start, entry->interval);
163         cycle_ext_end = ktime_add(cycle_end, sched->cycle_time_extension);
164
165         if (ktime_before(intv_end, cycle_end))
166                 return intv_end;
167         else if (admin && admin != sched &&
168                  ktime_after(admin->base_time, cycle_end) &&
169                  ktime_before(admin->base_time, cycle_ext_end))
170                 return admin->base_time;
171         else
172                 return cycle_end;
173 }
174
175 static int length_to_duration(struct taprio_sched *q, int len)
176 {
177         return div_u64(len * atomic64_read(&q->picos_per_byte), 1000);
178 }
179
180 /* Returns the entry corresponding to next available interval. If
181  * validate_interval is set, it only validates whether the timestamp occurs
182  * when the gate corresponding to the skb's traffic class is open.
183  */
184 static struct sched_entry *find_entry_to_transmit(struct sk_buff *skb,
185                                                   struct Qdisc *sch,
186                                                   struct sched_gate_list *sched,
187                                                   struct sched_gate_list *admin,
188                                                   ktime_t time,
189                                                   ktime_t *interval_start,
190                                                   ktime_t *interval_end,
191                                                   bool validate_interval)
192 {
193         ktime_t curr_intv_start, curr_intv_end, cycle_end, packet_transmit_time;
194         ktime_t earliest_txtime = KTIME_MAX, txtime, cycle, transmit_end_time;
195         struct sched_entry *entry = NULL, *entry_found = NULL;
196         struct taprio_sched *q = qdisc_priv(sch);
197         struct net_device *dev = qdisc_dev(sch);
198         bool entry_available = false;
199         s32 cycle_elapsed;
200         int tc, n;
201
202         tc = netdev_get_prio_tc_map(dev, skb->priority);
203         packet_transmit_time = length_to_duration(q, qdisc_pkt_len(skb));
204
205         *interval_start = 0;
206         *interval_end = 0;
207
208         if (!sched)
209                 return NULL;
210
211         cycle = sched->cycle_time;
212         cycle_elapsed = get_cycle_time_elapsed(sched, time);
213         curr_intv_end = ktime_sub_ns(time, cycle_elapsed);
214         cycle_end = ktime_add_ns(curr_intv_end, cycle);
215
216         list_for_each_entry(entry, &sched->entries, list) {
217                 curr_intv_start = curr_intv_end;
218                 curr_intv_end = get_interval_end_time(sched, admin, entry,
219                                                       curr_intv_start);
220
221                 if (ktime_after(curr_intv_start, cycle_end))
222                         break;
223
224                 if (!(entry->gate_mask & BIT(tc)) ||
225                     packet_transmit_time > entry->interval)
226                         continue;
227
228                 txtime = entry->next_txtime;
229
230                 if (ktime_before(txtime, time) || validate_interval) {
231                         transmit_end_time = ktime_add_ns(time, packet_transmit_time);
232                         if ((ktime_before(curr_intv_start, time) &&
233                              ktime_before(transmit_end_time, curr_intv_end)) ||
234                             (ktime_after(curr_intv_start, time) && !validate_interval)) {
235                                 entry_found = entry;
236                                 *interval_start = curr_intv_start;
237                                 *interval_end = curr_intv_end;
238                                 break;
239                         } else if (!entry_available && !validate_interval) {
240                                 /* Here, we are just trying to find out the
241                                  * first available interval in the next cycle.
242                                  */
243                                 entry_available = 1;
244                                 entry_found = entry;
245                                 *interval_start = ktime_add_ns(curr_intv_start, cycle);
246                                 *interval_end = ktime_add_ns(curr_intv_end, cycle);
247                         }
248                 } else if (ktime_before(txtime, earliest_txtime) &&
249                            !entry_available) {
250                         earliest_txtime = txtime;
251                         entry_found = entry;
252                         n = div_s64(ktime_sub(txtime, curr_intv_start), cycle);
253                         *interval_start = ktime_add(curr_intv_start, n * cycle);
254                         *interval_end = ktime_add(curr_intv_end, n * cycle);
255                 }
256         }
257
258         return entry_found;
259 }
260
261 static bool is_valid_interval(struct sk_buff *skb, struct Qdisc *sch)
262 {
263         struct taprio_sched *q = qdisc_priv(sch);
264         struct sched_gate_list *sched, *admin;
265         ktime_t interval_start, interval_end;
266         struct sched_entry *entry;
267
268         rcu_read_lock();
269         sched = rcu_dereference(q->oper_sched);
270         admin = rcu_dereference(q->admin_sched);
271
272         entry = find_entry_to_transmit(skb, sch, sched, admin, skb->tstamp,
273                                        &interval_start, &interval_end, true);
274         rcu_read_unlock();
275
276         return entry;
277 }
278
279 static bool taprio_flags_valid(u32 flags)
280 {
281         /* Make sure no other flag bits are set. */
282         if (flags & ~(TCA_TAPRIO_ATTR_FLAG_TXTIME_ASSIST |
283                       TCA_TAPRIO_ATTR_FLAG_FULL_OFFLOAD))
284                 return false;
285         /* txtime-assist and full offload are mutually exclusive */
286         if ((flags & TCA_TAPRIO_ATTR_FLAG_TXTIME_ASSIST) &&
287             (flags & TCA_TAPRIO_ATTR_FLAG_FULL_OFFLOAD))
288                 return false;
289         return true;
290 }
291
292 /* This returns the tstamp value set by TCP in terms of the set clock. */
293 static ktime_t get_tcp_tstamp(struct taprio_sched *q, struct sk_buff *skb)
294 {
295         unsigned int offset = skb_network_offset(skb);
296         const struct ipv6hdr *ipv6h;
297         const struct iphdr *iph;
298         struct ipv6hdr _ipv6h;
299
300         ipv6h = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
301         if (!ipv6h)
302                 return 0;
303
304         if (ipv6h->version == 4) {
305                 iph = (struct iphdr *)ipv6h;
306                 offset += iph->ihl * 4;
307
308                 /* special-case 6in4 tunnelling, as that is a common way to get
309                  * v6 connectivity in the home
310                  */
311                 if (iph->protocol == IPPROTO_IPV6) {
312                         ipv6h = skb_header_pointer(skb, offset,
313                                                    sizeof(_ipv6h), &_ipv6h);
314
315                         if (!ipv6h || ipv6h->nexthdr != IPPROTO_TCP)
316                                 return 0;
317                 } else if (iph->protocol != IPPROTO_TCP) {
318                         return 0;
319                 }
320         } else if (ipv6h->version == 6 && ipv6h->nexthdr != IPPROTO_TCP) {
321                 return 0;
322         }
323
324         return ktime_mono_to_any(skb->skb_mstamp_ns, q->tk_offset);
325 }
326
327 /* There are a few scenarios where we will have to modify the txtime from
328  * what is read from next_txtime in sched_entry. They are:
329  * 1. If txtime is in the past,
330  *    a. The gate for the traffic class is currently open and packet can be
331  *       transmitted before it closes, schedule the packet right away.
332  *    b. If the gate corresponding to the traffic class is going to open later
333  *       in the cycle, set the txtime of packet to the interval start.
334  * 2. If txtime is in the future, there are packets corresponding to the
335  *    current traffic class waiting to be transmitted. So, the following
336  *    possibilities exist:
337  *    a. We can transmit the packet before the window containing the txtime
338  *       closes.
339  *    b. The window might close before the transmission can be completed
340  *       successfully. So, schedule the packet in the next open window.
341  */
342 static long get_packet_txtime(struct sk_buff *skb, struct Qdisc *sch)
343 {
344         ktime_t transmit_end_time, interval_end, interval_start, tcp_tstamp;
345         struct taprio_sched *q = qdisc_priv(sch);
346         struct sched_gate_list *sched, *admin;
347         ktime_t minimum_time, now, txtime;
348         int len, packet_transmit_time;
349         struct sched_entry *entry;
350         bool sched_changed;
351
352         now = taprio_get_time(q);
353         minimum_time = ktime_add_ns(now, q->txtime_delay);
354
355         tcp_tstamp = get_tcp_tstamp(q, skb);
356         minimum_time = max_t(ktime_t, minimum_time, tcp_tstamp);
357
358         rcu_read_lock();
359         admin = rcu_dereference(q->admin_sched);
360         sched = rcu_dereference(q->oper_sched);
361         if (admin && ktime_after(minimum_time, admin->base_time))
362                 switch_schedules(q, &admin, &sched);
363
364         /* Until the schedule starts, all the queues are open */
365         if (!sched || ktime_before(minimum_time, sched->base_time)) {
366                 txtime = minimum_time;
367                 goto done;
368         }
369
370         len = qdisc_pkt_len(skb);
371         packet_transmit_time = length_to_duration(q, len);
372
373         do {
374                 sched_changed = 0;
375
376                 entry = find_entry_to_transmit(skb, sch, sched, admin,
377                                                minimum_time,
378                                                &interval_start, &interval_end,
379                                                false);
380                 if (!entry) {
381                         txtime = 0;
382                         goto done;
383                 }
384
385                 txtime = entry->next_txtime;
386                 txtime = max_t(ktime_t, txtime, minimum_time);
387                 txtime = max_t(ktime_t, txtime, interval_start);
388
389                 if (admin && admin != sched &&
390                     ktime_after(txtime, admin->base_time)) {
391                         sched = admin;
392                         sched_changed = 1;
393                         continue;
394                 }
395
396                 transmit_end_time = ktime_add(txtime, packet_transmit_time);
397                 minimum_time = transmit_end_time;
398
399                 /* Update the txtime of current entry to the next time it's
400                  * interval starts.
401                  */
402                 if (ktime_after(transmit_end_time, interval_end))
403                         entry->next_txtime = ktime_add(interval_start, sched->cycle_time);
404         } while (sched_changed || ktime_after(transmit_end_time, interval_end));
405
406         entry->next_txtime = transmit_end_time;
407
408 done:
409         rcu_read_unlock();
410         return txtime;
411 }
412
413 static int taprio_enqueue(struct sk_buff *skb, struct Qdisc *sch,
414                           struct sk_buff **to_free)
415 {
416         struct taprio_sched *q = qdisc_priv(sch);
417         struct Qdisc *child;
418         int queue;
419
420         queue = skb_get_queue_mapping(skb);
421
422         child = q->qdiscs[queue];
423         if (unlikely(!child))
424                 return qdisc_drop(skb, sch, to_free);
425
426         if (skb->sk && sock_flag(skb->sk, SOCK_TXTIME)) {
427                 if (!is_valid_interval(skb, sch))
428                         return qdisc_drop(skb, sch, to_free);
429         } else if (TXTIME_ASSIST_IS_ENABLED(q->flags)) {
430                 skb->tstamp = get_packet_txtime(skb, sch);
431                 if (!skb->tstamp)
432                         return qdisc_drop(skb, sch, to_free);
433         }
434
435         qdisc_qstats_backlog_inc(sch, skb);
436         sch->q.qlen++;
437
438         return qdisc_enqueue(skb, child, to_free);
439 }
440
441 static struct sk_buff *taprio_peek_soft(struct Qdisc *sch)
442 {
443         struct taprio_sched *q = qdisc_priv(sch);
444         struct net_device *dev = qdisc_dev(sch);
445         struct sched_entry *entry;
446         struct sk_buff *skb;
447         u32 gate_mask;
448         int i;
449
450         rcu_read_lock();
451         entry = rcu_dereference(q->current_entry);
452         gate_mask = entry ? entry->gate_mask : TAPRIO_ALL_GATES_OPEN;
453         rcu_read_unlock();
454
455         if (!gate_mask)
456                 return NULL;
457
458         for (i = 0; i < dev->num_tx_queues; i++) {
459                 struct Qdisc *child = q->qdiscs[i];
460                 int prio;
461                 u8 tc;
462
463                 if (unlikely(!child))
464                         continue;
465
466                 skb = child->ops->peek(child);
467                 if (!skb)
468                         continue;
469
470                 if (TXTIME_ASSIST_IS_ENABLED(q->flags))
471                         return skb;
472
473                 prio = skb->priority;
474                 tc = netdev_get_prio_tc_map(dev, prio);
475
476                 if (!(gate_mask & BIT(tc)))
477                         continue;
478
479                 return skb;
480         }
481
482         return NULL;
483 }
484
485 static struct sk_buff *taprio_peek_offload(struct Qdisc *sch)
486 {
487         struct taprio_sched *q = qdisc_priv(sch);
488         struct net_device *dev = qdisc_dev(sch);
489         struct sk_buff *skb;
490         int i;
491
492         for (i = 0; i < dev->num_tx_queues; i++) {
493                 struct Qdisc *child = q->qdiscs[i];
494
495                 if (unlikely(!child))
496                         continue;
497
498                 skb = child->ops->peek(child);
499                 if (!skb)
500                         continue;
501
502                 return skb;
503         }
504
505         return NULL;
506 }
507
508 static struct sk_buff *taprio_peek(struct Qdisc *sch)
509 {
510         struct taprio_sched *q = qdisc_priv(sch);
511
512         return q->peek(sch);
513 }
514
515 static void taprio_set_budget(struct taprio_sched *q, struct sched_entry *entry)
516 {
517         atomic_set(&entry->budget,
518                    div64_u64((u64)entry->interval * 1000,
519                              atomic64_read(&q->picos_per_byte)));
520 }
521
522 static struct sk_buff *taprio_dequeue_soft(struct Qdisc *sch)
523 {
524         struct taprio_sched *q = qdisc_priv(sch);
525         struct net_device *dev = qdisc_dev(sch);
526         struct sk_buff *skb = NULL;
527         struct sched_entry *entry;
528         u32 gate_mask;
529         int i;
530
531         rcu_read_lock();
532         entry = rcu_dereference(q->current_entry);
533         /* if there's no entry, it means that the schedule didn't
534          * start yet, so force all gates to be open, this is in
535          * accordance to IEEE 802.1Qbv-2015 Section 8.6.9.4.5
536          * "AdminGateSates"
537          */
538         gate_mask = entry ? entry->gate_mask : TAPRIO_ALL_GATES_OPEN;
539
540         if (!gate_mask)
541                 goto done;
542
543         for (i = 0; i < dev->num_tx_queues; i++) {
544                 struct Qdisc *child = q->qdiscs[i];
545                 ktime_t guard;
546                 int prio;
547                 int len;
548                 u8 tc;
549
550                 if (unlikely(!child))
551                         continue;
552
553                 if (TXTIME_ASSIST_IS_ENABLED(q->flags)) {
554                         skb = child->ops->dequeue(child);
555                         if (!skb)
556                                 continue;
557                         goto skb_found;
558                 }
559
560                 skb = child->ops->peek(child);
561                 if (!skb)
562                         continue;
563
564                 prio = skb->priority;
565                 tc = netdev_get_prio_tc_map(dev, prio);
566
567                 if (!(gate_mask & BIT(tc)))
568                         continue;
569
570                 len = qdisc_pkt_len(skb);
571                 guard = ktime_add_ns(taprio_get_time(q),
572                                      length_to_duration(q, len));
573
574                 /* In the case that there's no gate entry, there's no
575                  * guard band ...
576                  */
577                 if (gate_mask != TAPRIO_ALL_GATES_OPEN &&
578                     ktime_after(guard, entry->close_time))
579                         continue;
580
581                 /* ... and no budget. */
582                 if (gate_mask != TAPRIO_ALL_GATES_OPEN &&
583                     atomic_sub_return(len, &entry->budget) < 0)
584                         continue;
585
586                 skb = child->ops->dequeue(child);
587                 if (unlikely(!skb))
588                         goto done;
589
590 skb_found:
591                 qdisc_bstats_update(sch, skb);
592                 qdisc_qstats_backlog_dec(sch, skb);
593                 sch->q.qlen--;
594
595                 goto done;
596         }
597
598 done:
599         rcu_read_unlock();
600
601         return skb;
602 }
603
604 static struct sk_buff *taprio_dequeue_offload(struct Qdisc *sch)
605 {
606         struct taprio_sched *q = qdisc_priv(sch);
607         struct net_device *dev = qdisc_dev(sch);
608         struct sk_buff *skb;
609         int i;
610
611         for (i = 0; i < dev->num_tx_queues; i++) {
612                 struct Qdisc *child = q->qdiscs[i];
613
614                 if (unlikely(!child))
615                         continue;
616
617                 skb = child->ops->dequeue(child);
618                 if (unlikely(!skb))
619                         continue;
620
621                 qdisc_bstats_update(sch, skb);
622                 qdisc_qstats_backlog_dec(sch, skb);
623                 sch->q.qlen--;
624
625                 return skb;
626         }
627
628         return NULL;
629 }
630
631 static struct sk_buff *taprio_dequeue(struct Qdisc *sch)
632 {
633         struct taprio_sched *q = qdisc_priv(sch);
634
635         return q->dequeue(sch);
636 }
637
638 static bool should_restart_cycle(const struct sched_gate_list *oper,
639                                  const struct sched_entry *entry)
640 {
641         if (list_is_last(&entry->list, &oper->entries))
642                 return true;
643
644         if (ktime_compare(entry->close_time, oper->cycle_close_time) == 0)
645                 return true;
646
647         return false;
648 }
649
650 static bool should_change_schedules(const struct sched_gate_list *admin,
651                                     const struct sched_gate_list *oper,
652                                     ktime_t close_time)
653 {
654         ktime_t next_base_time, extension_time;
655
656         if (!admin)
657                 return false;
658
659         next_base_time = sched_base_time(admin);
660
661         /* This is the simple case, the close_time would fall after
662          * the next schedule base_time.
663          */
664         if (ktime_compare(next_base_time, close_time) <= 0)
665                 return true;
666
667         /* This is the cycle_time_extension case, if the close_time
668          * plus the amount that can be extended would fall after the
669          * next schedule base_time, we can extend the current schedule
670          * for that amount.
671          */
672         extension_time = ktime_add_ns(close_time, oper->cycle_time_extension);
673
674         /* FIXME: the IEEE 802.1Q-2018 Specification isn't clear about
675          * how precisely the extension should be made. So after
676          * conformance testing, this logic may change.
677          */
678         if (ktime_compare(next_base_time, extension_time) <= 0)
679                 return true;
680
681         return false;
682 }
683
684 static enum hrtimer_restart advance_sched(struct hrtimer *timer)
685 {
686         struct taprio_sched *q = container_of(timer, struct taprio_sched,
687                                               advance_timer);
688         struct sched_gate_list *oper, *admin;
689         struct sched_entry *entry, *next;
690         struct Qdisc *sch = q->root;
691         ktime_t close_time;
692
693         spin_lock(&q->current_entry_lock);
694         entry = rcu_dereference_protected(q->current_entry,
695                                           lockdep_is_held(&q->current_entry_lock));
696         oper = rcu_dereference_protected(q->oper_sched,
697                                          lockdep_is_held(&q->current_entry_lock));
698         admin = rcu_dereference_protected(q->admin_sched,
699                                           lockdep_is_held(&q->current_entry_lock));
700
701         if (!oper)
702                 switch_schedules(q, &admin, &oper);
703
704         /* This can happen in two cases: 1. this is the very first run
705          * of this function (i.e. we weren't running any schedule
706          * previously); 2. The previous schedule just ended. The first
707          * entry of all schedules are pre-calculated during the
708          * schedule initialization.
709          */
710         if (unlikely(!entry || entry->close_time == oper->base_time)) {
711                 next = list_first_entry(&oper->entries, struct sched_entry,
712                                         list);
713                 close_time = next->close_time;
714                 goto first_run;
715         }
716
717         if (should_restart_cycle(oper, entry)) {
718                 next = list_first_entry(&oper->entries, struct sched_entry,
719                                         list);
720                 oper->cycle_close_time = ktime_add_ns(oper->cycle_close_time,
721                                                       oper->cycle_time);
722         } else {
723                 next = list_next_entry(entry, list);
724         }
725
726         close_time = ktime_add_ns(entry->close_time, next->interval);
727         close_time = min_t(ktime_t, close_time, oper->cycle_close_time);
728
729         if (should_change_schedules(admin, oper, close_time)) {
730                 /* Set things so the next time this runs, the new
731                  * schedule runs.
732                  */
733                 close_time = sched_base_time(admin);
734                 switch_schedules(q, &admin, &oper);
735         }
736
737         next->close_time = close_time;
738         taprio_set_budget(q, next);
739
740 first_run:
741         rcu_assign_pointer(q->current_entry, next);
742         spin_unlock(&q->current_entry_lock);
743
744         hrtimer_set_expires(&q->advance_timer, close_time);
745
746         rcu_read_lock();
747         __netif_schedule(sch);
748         rcu_read_unlock();
749
750         return HRTIMER_RESTART;
751 }
752
753 static const struct nla_policy entry_policy[TCA_TAPRIO_SCHED_ENTRY_MAX + 1] = {
754         [TCA_TAPRIO_SCHED_ENTRY_INDEX]     = { .type = NLA_U32 },
755         [TCA_TAPRIO_SCHED_ENTRY_CMD]       = { .type = NLA_U8 },
756         [TCA_TAPRIO_SCHED_ENTRY_GATE_MASK] = { .type = NLA_U32 },
757         [TCA_TAPRIO_SCHED_ENTRY_INTERVAL]  = { .type = NLA_U32 },
758 };
759
760 static const struct nla_policy taprio_policy[TCA_TAPRIO_ATTR_MAX + 1] = {
761         [TCA_TAPRIO_ATTR_PRIOMAP]              = {
762                 .len = sizeof(struct tc_mqprio_qopt)
763         },
764         [TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST]           = { .type = NLA_NESTED },
765         [TCA_TAPRIO_ATTR_SCHED_BASE_TIME]            = { .type = NLA_S64 },
766         [TCA_TAPRIO_ATTR_SCHED_SINGLE_ENTRY]         = { .type = NLA_NESTED },
767         [TCA_TAPRIO_ATTR_SCHED_CLOCKID]              = { .type = NLA_S32 },
768         [TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME]           = { .type = NLA_S64 },
769         [TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION] = { .type = NLA_S64 },
770 };
771
772 static int fill_sched_entry(struct nlattr **tb, struct sched_entry *entry,
773                             struct netlink_ext_ack *extack)
774 {
775         u32 interval = 0;
776
777         if (tb[TCA_TAPRIO_SCHED_ENTRY_CMD])
778                 entry->command = nla_get_u8(
779                         tb[TCA_TAPRIO_SCHED_ENTRY_CMD]);
780
781         if (tb[TCA_TAPRIO_SCHED_ENTRY_GATE_MASK])
782                 entry->gate_mask = nla_get_u32(
783                         tb[TCA_TAPRIO_SCHED_ENTRY_GATE_MASK]);
784
785         if (tb[TCA_TAPRIO_SCHED_ENTRY_INTERVAL])
786                 interval = nla_get_u32(
787                         tb[TCA_TAPRIO_SCHED_ENTRY_INTERVAL]);
788
789         if (interval == 0) {
790                 NL_SET_ERR_MSG(extack, "Invalid interval for schedule entry");
791                 return -EINVAL;
792         }
793
794         entry->interval = interval;
795
796         return 0;
797 }
798
799 static int parse_sched_entry(struct nlattr *n, struct sched_entry *entry,
800                              int index, struct netlink_ext_ack *extack)
801 {
802         struct nlattr *tb[TCA_TAPRIO_SCHED_ENTRY_MAX + 1] = { };
803         int err;
804
805         err = nla_parse_nested_deprecated(tb, TCA_TAPRIO_SCHED_ENTRY_MAX, n,
806                                           entry_policy, NULL);
807         if (err < 0) {
808                 NL_SET_ERR_MSG(extack, "Could not parse nested entry");
809                 return -EINVAL;
810         }
811
812         entry->index = index;
813
814         return fill_sched_entry(tb, entry, extack);
815 }
816
817 static int parse_sched_list(struct nlattr *list,
818                             struct sched_gate_list *sched,
819                             struct netlink_ext_ack *extack)
820 {
821         struct nlattr *n;
822         int err, rem;
823         int i = 0;
824
825         if (!list)
826                 return -EINVAL;
827
828         nla_for_each_nested(n, list, rem) {
829                 struct sched_entry *entry;
830
831                 if (nla_type(n) != TCA_TAPRIO_SCHED_ENTRY) {
832                         NL_SET_ERR_MSG(extack, "Attribute is not of type 'entry'");
833                         continue;
834                 }
835
836                 entry = kzalloc(sizeof(*entry), GFP_KERNEL);
837                 if (!entry) {
838                         NL_SET_ERR_MSG(extack, "Not enough memory for entry");
839                         return -ENOMEM;
840                 }
841
842                 err = parse_sched_entry(n, entry, i, extack);
843                 if (err < 0) {
844                         kfree(entry);
845                         return err;
846                 }
847
848                 list_add_tail(&entry->list, &sched->entries);
849                 i++;
850         }
851
852         sched->num_entries = i;
853
854         return i;
855 }
856
857 static int parse_taprio_schedule(struct nlattr **tb,
858                                  struct sched_gate_list *new,
859                                  struct netlink_ext_ack *extack)
860 {
861         int err = 0;
862
863         if (tb[TCA_TAPRIO_ATTR_SCHED_SINGLE_ENTRY]) {
864                 NL_SET_ERR_MSG(extack, "Adding a single entry is not supported");
865                 return -ENOTSUPP;
866         }
867
868         if (tb[TCA_TAPRIO_ATTR_SCHED_BASE_TIME])
869                 new->base_time = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_BASE_TIME]);
870
871         if (tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION])
872                 new->cycle_time_extension = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION]);
873
874         if (tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME])
875                 new->cycle_time = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME]);
876
877         if (tb[TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST])
878                 err = parse_sched_list(
879                         tb[TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST], new, extack);
880         if (err < 0)
881                 return err;
882
883         if (!new->cycle_time) {
884                 struct sched_entry *entry;
885                 ktime_t cycle = 0;
886
887                 list_for_each_entry(entry, &new->entries, list)
888                         cycle = ktime_add_ns(cycle, entry->interval);
889                 new->cycle_time = cycle;
890         }
891
892         return 0;
893 }
894
895 static int taprio_parse_mqprio_opt(struct net_device *dev,
896                                    struct tc_mqprio_qopt *qopt,
897                                    struct netlink_ext_ack *extack,
898                                    u32 taprio_flags)
899 {
900         int i, j;
901
902         if (!qopt && !dev->num_tc) {
903                 NL_SET_ERR_MSG(extack, "'mqprio' configuration is necessary");
904                 return -EINVAL;
905         }
906
907         /* If num_tc is already set, it means that the user already
908          * configured the mqprio part
909          */
910         if (dev->num_tc)
911                 return 0;
912
913         /* Verify num_tc is not out of max range */
914         if (qopt->num_tc > TC_MAX_QUEUE) {
915                 NL_SET_ERR_MSG(extack, "Number of traffic classes is outside valid range");
916                 return -EINVAL;
917         }
918
919         /* taprio imposes that traffic classes map 1:n to tx queues */
920         if (qopt->num_tc > dev->num_tx_queues) {
921                 NL_SET_ERR_MSG(extack, "Number of traffic classes is greater than number of HW queues");
922                 return -EINVAL;
923         }
924
925         /* Verify priority mapping uses valid tcs */
926         for (i = 0; i <= TC_BITMASK; i++) {
927                 if (qopt->prio_tc_map[i] >= qopt->num_tc) {
928                         NL_SET_ERR_MSG(extack, "Invalid traffic class in priority to traffic class mapping");
929                         return -EINVAL;
930                 }
931         }
932
933         for (i = 0; i < qopt->num_tc; i++) {
934                 unsigned int last = qopt->offset[i] + qopt->count[i];
935
936                 /* Verify the queue count is in tx range being equal to the
937                  * real_num_tx_queues indicates the last queue is in use.
938                  */
939                 if (qopt->offset[i] >= dev->num_tx_queues ||
940                     !qopt->count[i] ||
941                     last > dev->real_num_tx_queues) {
942                         NL_SET_ERR_MSG(extack, "Invalid queue in traffic class to queue mapping");
943                         return -EINVAL;
944                 }
945
946                 if (TXTIME_ASSIST_IS_ENABLED(taprio_flags))
947                         continue;
948
949                 /* Verify that the offset and counts do not overlap */
950                 for (j = i + 1; j < qopt->num_tc; j++) {
951                         if (last > qopt->offset[j]) {
952                                 NL_SET_ERR_MSG(extack, "Detected overlap in the traffic class to queue mapping");
953                                 return -EINVAL;
954                         }
955                 }
956         }
957
958         return 0;
959 }
960
961 static int taprio_get_start_time(struct Qdisc *sch,
962                                  struct sched_gate_list *sched,
963                                  ktime_t *start)
964 {
965         struct taprio_sched *q = qdisc_priv(sch);
966         ktime_t now, base, cycle;
967         s64 n;
968
969         base = sched_base_time(sched);
970         now = taprio_get_time(q);
971
972         if (ktime_after(base, now)) {
973                 *start = base;
974                 return 0;
975         }
976
977         cycle = sched->cycle_time;
978
979         /* The qdisc is expected to have at least one sched_entry.  Moreover,
980          * any entry must have 'interval' > 0. Thus if the cycle time is zero,
981          * something went really wrong. In that case, we should warn about this
982          * inconsistent state and return error.
983          */
984         if (WARN_ON(!cycle))
985                 return -EFAULT;
986
987         /* Schedule the start time for the beginning of the next
988          * cycle.
989          */
990         n = div64_s64(ktime_sub_ns(now, base), cycle);
991         *start = ktime_add_ns(base, (n + 1) * cycle);
992         return 0;
993 }
994
995 static void setup_first_close_time(struct taprio_sched *q,
996                                    struct sched_gate_list *sched, ktime_t base)
997 {
998         struct sched_entry *first;
999         ktime_t cycle;
1000
1001         first = list_first_entry(&sched->entries,
1002                                  struct sched_entry, list);
1003
1004         cycle = sched->cycle_time;
1005
1006         /* FIXME: find a better place to do this */
1007         sched->cycle_close_time = ktime_add_ns(base, cycle);
1008
1009         first->close_time = ktime_add_ns(base, first->interval);
1010         taprio_set_budget(q, first);
1011         rcu_assign_pointer(q->current_entry, NULL);
1012 }
1013
1014 static void taprio_start_sched(struct Qdisc *sch,
1015                                ktime_t start, struct sched_gate_list *new)
1016 {
1017         struct taprio_sched *q = qdisc_priv(sch);
1018         ktime_t expires;
1019
1020         if (FULL_OFFLOAD_IS_ENABLED(q->flags))
1021                 return;
1022
1023         expires = hrtimer_get_expires(&q->advance_timer);
1024         if (expires == 0)
1025                 expires = KTIME_MAX;
1026
1027         /* If the new schedule starts before the next expiration, we
1028          * reprogram it to the earliest one, so we change the admin
1029          * schedule to the operational one at the right time.
1030          */
1031         start = min_t(ktime_t, start, expires);
1032
1033         hrtimer_start(&q->advance_timer, start, HRTIMER_MODE_ABS);
1034 }
1035
1036 static void taprio_set_picos_per_byte(struct net_device *dev,
1037                                       struct taprio_sched *q)
1038 {
1039         struct ethtool_link_ksettings ecmd;
1040         int speed = SPEED_10;
1041         int picos_per_byte;
1042         int err;
1043
1044         err = __ethtool_get_link_ksettings(dev, &ecmd);
1045         if (err < 0)
1046                 goto skip;
1047
1048         if (ecmd.base.speed && ecmd.base.speed != SPEED_UNKNOWN)
1049                 speed = ecmd.base.speed;
1050
1051 skip:
1052         picos_per_byte = (USEC_PER_SEC * 8) / speed;
1053
1054         atomic64_set(&q->picos_per_byte, picos_per_byte);
1055         netdev_dbg(dev, "taprio: set %s's picos_per_byte to: %lld, linkspeed: %d\n",
1056                    dev->name, (long long)atomic64_read(&q->picos_per_byte),
1057                    ecmd.base.speed);
1058 }
1059
1060 static int taprio_dev_notifier(struct notifier_block *nb, unsigned long event,
1061                                void *ptr)
1062 {
1063         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1064         struct net_device *qdev;
1065         struct taprio_sched *q;
1066         bool found = false;
1067
1068         ASSERT_RTNL();
1069
1070         if (event != NETDEV_UP && event != NETDEV_CHANGE)
1071                 return NOTIFY_DONE;
1072
1073         spin_lock(&taprio_list_lock);
1074         list_for_each_entry(q, &taprio_list, taprio_list) {
1075                 qdev = qdisc_dev(q->root);
1076                 if (qdev == dev) {
1077                         found = true;
1078                         break;
1079                 }
1080         }
1081         spin_unlock(&taprio_list_lock);
1082
1083         if (found)
1084                 taprio_set_picos_per_byte(dev, q);
1085
1086         return NOTIFY_DONE;
1087 }
1088
1089 static void setup_txtime(struct taprio_sched *q,
1090                          struct sched_gate_list *sched, ktime_t base)
1091 {
1092         struct sched_entry *entry;
1093         u32 interval = 0;
1094
1095         list_for_each_entry(entry, &sched->entries, list) {
1096                 entry->next_txtime = ktime_add_ns(base, interval);
1097                 interval += entry->interval;
1098         }
1099 }
1100
1101 static struct tc_taprio_qopt_offload *taprio_offload_alloc(int num_entries)
1102 {
1103         size_t size = sizeof(struct tc_taprio_sched_entry) * num_entries +
1104                       sizeof(struct __tc_taprio_qopt_offload);
1105         struct __tc_taprio_qopt_offload *__offload;
1106
1107         __offload = kzalloc(size, GFP_KERNEL);
1108         if (!__offload)
1109                 return NULL;
1110
1111         refcount_set(&__offload->users, 1);
1112
1113         return &__offload->offload;
1114 }
1115
1116 struct tc_taprio_qopt_offload *taprio_offload_get(struct tc_taprio_qopt_offload
1117                                                   *offload)
1118 {
1119         struct __tc_taprio_qopt_offload *__offload;
1120
1121         __offload = container_of(offload, struct __tc_taprio_qopt_offload,
1122                                  offload);
1123
1124         refcount_inc(&__offload->users);
1125
1126         return offload;
1127 }
1128 EXPORT_SYMBOL_GPL(taprio_offload_get);
1129
1130 void taprio_offload_free(struct tc_taprio_qopt_offload *offload)
1131 {
1132         struct __tc_taprio_qopt_offload *__offload;
1133
1134         __offload = container_of(offload, struct __tc_taprio_qopt_offload,
1135                                  offload);
1136
1137         if (!refcount_dec_and_test(&__offload->users))
1138                 return;
1139
1140         kfree(__offload);
1141 }
1142 EXPORT_SYMBOL_GPL(taprio_offload_free);
1143
1144 /* The function will only serve to keep the pointers to the "oper" and "admin"
1145  * schedules valid in relation to their base times, so when calling dump() the
1146  * users looks at the right schedules.
1147  * When using full offload, the admin configuration is promoted to oper at the
1148  * base_time in the PHC time domain.  But because the system time is not
1149  * necessarily in sync with that, we can't just trigger a hrtimer to call
1150  * switch_schedules at the right hardware time.
1151  * At the moment we call this by hand right away from taprio, but in the future
1152  * it will be useful to create a mechanism for drivers to notify taprio of the
1153  * offload state (PENDING, ACTIVE, INACTIVE) so it can be visible in dump().
1154  * This is left as TODO.
1155  */
1156 static void taprio_offload_config_changed(struct taprio_sched *q)
1157 {
1158         struct sched_gate_list *oper, *admin;
1159
1160         spin_lock(&q->current_entry_lock);
1161
1162         oper = rcu_dereference_protected(q->oper_sched,
1163                                          lockdep_is_held(&q->current_entry_lock));
1164         admin = rcu_dereference_protected(q->admin_sched,
1165                                           lockdep_is_held(&q->current_entry_lock));
1166
1167         switch_schedules(q, &admin, &oper);
1168
1169         spin_unlock(&q->current_entry_lock);
1170 }
1171
1172 static void taprio_sched_to_offload(struct taprio_sched *q,
1173                                     struct sched_gate_list *sched,
1174                                     const struct tc_mqprio_qopt *mqprio,
1175                                     struct tc_taprio_qopt_offload *offload)
1176 {
1177         struct sched_entry *entry;
1178         int i = 0;
1179
1180         offload->base_time = sched->base_time;
1181         offload->cycle_time = sched->cycle_time;
1182         offload->cycle_time_extension = sched->cycle_time_extension;
1183
1184         list_for_each_entry(entry, &sched->entries, list) {
1185                 struct tc_taprio_sched_entry *e = &offload->entries[i];
1186
1187                 e->command = entry->command;
1188                 e->interval = entry->interval;
1189                 e->gate_mask = entry->gate_mask;
1190                 i++;
1191         }
1192
1193         offload->num_entries = i;
1194 }
1195
1196 static int taprio_enable_offload(struct net_device *dev,
1197                                  struct tc_mqprio_qopt *mqprio,
1198                                  struct taprio_sched *q,
1199                                  struct sched_gate_list *sched,
1200                                  struct netlink_ext_ack *extack)
1201 {
1202         const struct net_device_ops *ops = dev->netdev_ops;
1203         struct tc_taprio_qopt_offload *offload;
1204         int err = 0;
1205
1206         if (!ops->ndo_setup_tc) {
1207                 NL_SET_ERR_MSG(extack,
1208                                "Device does not support taprio offload");
1209                 return -EOPNOTSUPP;
1210         }
1211
1212         offload = taprio_offload_alloc(sched->num_entries);
1213         if (!offload) {
1214                 NL_SET_ERR_MSG(extack,
1215                                "Not enough memory for enabling offload mode");
1216                 return -ENOMEM;
1217         }
1218         offload->enable = 1;
1219         taprio_sched_to_offload(q, sched, mqprio, offload);
1220
1221         err = ops->ndo_setup_tc(dev, TC_SETUP_QDISC_TAPRIO, offload);
1222         if (err < 0) {
1223                 NL_SET_ERR_MSG(extack,
1224                                "Device failed to setup taprio offload");
1225                 goto done;
1226         }
1227
1228 done:
1229         taprio_offload_free(offload);
1230
1231         return err;
1232 }
1233
1234 static int taprio_disable_offload(struct net_device *dev,
1235                                   struct taprio_sched *q,
1236                                   struct netlink_ext_ack *extack)
1237 {
1238         const struct net_device_ops *ops = dev->netdev_ops;
1239         struct tc_taprio_qopt_offload *offload;
1240         int err;
1241
1242         if (!FULL_OFFLOAD_IS_ENABLED(q->flags))
1243                 return 0;
1244
1245         if (!ops->ndo_setup_tc)
1246                 return -EOPNOTSUPP;
1247
1248         offload = taprio_offload_alloc(0);
1249         if (!offload) {
1250                 NL_SET_ERR_MSG(extack,
1251                                "Not enough memory to disable offload mode");
1252                 return -ENOMEM;
1253         }
1254         offload->enable = 0;
1255
1256         err = ops->ndo_setup_tc(dev, TC_SETUP_QDISC_TAPRIO, offload);
1257         if (err < 0) {
1258                 NL_SET_ERR_MSG(extack,
1259                                "Device failed to disable offload");
1260                 goto out;
1261         }
1262
1263 out:
1264         taprio_offload_free(offload);
1265
1266         return err;
1267 }
1268
1269 /* If full offload is enabled, the only possible clockid is the net device's
1270  * PHC. For that reason, specifying a clockid through netlink is incorrect.
1271  * For txtime-assist, it is implicitly assumed that the device's PHC is kept
1272  * in sync with the specified clockid via a user space daemon such as phc2sys.
1273  * For both software taprio and txtime-assist, the clockid is used for the
1274  * hrtimer that advances the schedule and hence mandatory.
1275  */
1276 static int taprio_parse_clockid(struct Qdisc *sch, struct nlattr **tb,
1277                                 struct netlink_ext_ack *extack)
1278 {
1279         struct taprio_sched *q = qdisc_priv(sch);
1280         struct net_device *dev = qdisc_dev(sch);
1281         int err = -EINVAL;
1282
1283         if (FULL_OFFLOAD_IS_ENABLED(q->flags)) {
1284                 const struct ethtool_ops *ops = dev->ethtool_ops;
1285                 struct ethtool_ts_info info = {
1286                         .cmd = ETHTOOL_GET_TS_INFO,
1287                         .phc_index = -1,
1288                 };
1289
1290                 if (tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]) {
1291                         NL_SET_ERR_MSG(extack,
1292                                        "The 'clockid' cannot be specified for full offload");
1293                         goto out;
1294                 }
1295
1296                 if (ops && ops->get_ts_info)
1297                         err = ops->get_ts_info(dev, &info);
1298
1299                 if (err || info.phc_index < 0) {
1300                         NL_SET_ERR_MSG(extack,
1301                                        "Device does not have a PTP clock");
1302                         err = -ENOTSUPP;
1303                         goto out;
1304                 }
1305         } else if (tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]) {
1306                 int clockid = nla_get_s32(tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]);
1307
1308                 /* We only support static clockids and we don't allow
1309                  * for it to be modified after the first init.
1310                  */
1311                 if (clockid < 0 ||
1312                     (q->clockid != -1 && q->clockid != clockid)) {
1313                         NL_SET_ERR_MSG(extack,
1314                                        "Changing the 'clockid' of a running schedule is not supported");
1315                         err = -ENOTSUPP;
1316                         goto out;
1317                 }
1318
1319                 switch (clockid) {
1320                 case CLOCK_REALTIME:
1321                         q->tk_offset = TK_OFFS_REAL;
1322                         break;
1323                 case CLOCK_MONOTONIC:
1324                         q->tk_offset = TK_OFFS_MAX;
1325                         break;
1326                 case CLOCK_BOOTTIME:
1327                         q->tk_offset = TK_OFFS_BOOT;
1328                         break;
1329                 case CLOCK_TAI:
1330                         q->tk_offset = TK_OFFS_TAI;
1331                         break;
1332                 default:
1333                         NL_SET_ERR_MSG(extack, "Invalid 'clockid'");
1334                         err = -EINVAL;
1335                         goto out;
1336                 }
1337
1338                 q->clockid = clockid;
1339         } else {
1340                 NL_SET_ERR_MSG(extack, "Specifying a 'clockid' is mandatory");
1341                 goto out;
1342         }
1343
1344         /* Everything went ok, return success. */
1345         err = 0;
1346
1347 out:
1348         return err;
1349 }
1350
1351 static int taprio_mqprio_cmp(const struct net_device *dev,
1352                              const struct tc_mqprio_qopt *mqprio)
1353 {
1354         int i;
1355
1356         if (!mqprio || mqprio->num_tc != dev->num_tc)
1357                 return -1;
1358
1359         for (i = 0; i < mqprio->num_tc; i++)
1360                 if (dev->tc_to_txq[i].count != mqprio->count[i] ||
1361                     dev->tc_to_txq[i].offset != mqprio->offset[i])
1362                         return -1;
1363
1364         for (i = 0; i <= TC_BITMASK; i++)
1365                 if (dev->prio_tc_map[i] != mqprio->prio_tc_map[i])
1366                         return -1;
1367
1368         return 0;
1369 }
1370
1371 /* The semantics of the 'flags' argument in relation to 'change()'
1372  * requests, are interpreted following two rules (which are applied in
1373  * this order): (1) an omitted 'flags' argument is interpreted as
1374  * zero; (2) the 'flags' of a "running" taprio instance cannot be
1375  * changed.
1376  */
1377 static int taprio_new_flags(const struct nlattr *attr, u32 old,
1378                             struct netlink_ext_ack *extack)
1379 {
1380         u32 new = 0;
1381
1382         if (attr)
1383                 new = nla_get_u32(attr);
1384
1385         if (old != TAPRIO_FLAGS_INVALID && old != new) {
1386                 NL_SET_ERR_MSG_MOD(extack, "Changing 'flags' of a running schedule is not supported");
1387                 return -EOPNOTSUPP;
1388         }
1389
1390         if (!taprio_flags_valid(new)) {
1391                 NL_SET_ERR_MSG_MOD(extack, "Specified 'flags' are not valid");
1392                 return -EINVAL;
1393         }
1394
1395         return new;
1396 }
1397
1398 static int taprio_change(struct Qdisc *sch, struct nlattr *opt,
1399                          struct netlink_ext_ack *extack)
1400 {
1401         struct nlattr *tb[TCA_TAPRIO_ATTR_MAX + 1] = { };
1402         struct sched_gate_list *oper, *admin, *new_admin;
1403         struct taprio_sched *q = qdisc_priv(sch);
1404         struct net_device *dev = qdisc_dev(sch);
1405         struct tc_mqprio_qopt *mqprio = NULL;
1406         unsigned long flags;
1407         ktime_t start;
1408         int i, err;
1409
1410         err = nla_parse_nested_deprecated(tb, TCA_TAPRIO_ATTR_MAX, opt,
1411                                           taprio_policy, extack);
1412         if (err < 0)
1413                 return err;
1414
1415         if (tb[TCA_TAPRIO_ATTR_PRIOMAP])
1416                 mqprio = nla_data(tb[TCA_TAPRIO_ATTR_PRIOMAP]);
1417
1418         err = taprio_new_flags(tb[TCA_TAPRIO_ATTR_FLAGS],
1419                                q->flags, extack);
1420         if (err < 0)
1421                 return err;
1422
1423         q->flags = err;
1424
1425         err = taprio_parse_mqprio_opt(dev, mqprio, extack, q->flags);
1426         if (err < 0)
1427                 return err;
1428
1429         new_admin = kzalloc(sizeof(*new_admin), GFP_KERNEL);
1430         if (!new_admin) {
1431                 NL_SET_ERR_MSG(extack, "Not enough memory for a new schedule");
1432                 return -ENOMEM;
1433         }
1434         INIT_LIST_HEAD(&new_admin->entries);
1435
1436         rcu_read_lock();
1437         oper = rcu_dereference(q->oper_sched);
1438         admin = rcu_dereference(q->admin_sched);
1439         rcu_read_unlock();
1440
1441         /* no changes - no new mqprio settings */
1442         if (!taprio_mqprio_cmp(dev, mqprio))
1443                 mqprio = NULL;
1444
1445         if (mqprio && (oper || admin)) {
1446                 NL_SET_ERR_MSG(extack, "Changing the traffic mapping of a running schedule is not supported");
1447                 err = -ENOTSUPP;
1448                 goto free_sched;
1449         }
1450
1451         err = parse_taprio_schedule(tb, new_admin, extack);
1452         if (err < 0)
1453                 goto free_sched;
1454
1455         if (new_admin->num_entries == 0) {
1456                 NL_SET_ERR_MSG(extack, "There should be at least one entry in the schedule");
1457                 err = -EINVAL;
1458                 goto free_sched;
1459         }
1460
1461         err = taprio_parse_clockid(sch, tb, extack);
1462         if (err < 0)
1463                 goto free_sched;
1464
1465         taprio_set_picos_per_byte(dev, q);
1466
1467         if (mqprio) {
1468                 netdev_set_num_tc(dev, mqprio->num_tc);
1469                 for (i = 0; i < mqprio->num_tc; i++)
1470                         netdev_set_tc_queue(dev, i,
1471                                             mqprio->count[i],
1472                                             mqprio->offset[i]);
1473
1474                 /* Always use supplied priority mappings */
1475                 for (i = 0; i <= TC_BITMASK; i++)
1476                         netdev_set_prio_tc_map(dev, i,
1477                                                mqprio->prio_tc_map[i]);
1478         }
1479
1480         if (FULL_OFFLOAD_IS_ENABLED(q->flags))
1481                 err = taprio_enable_offload(dev, mqprio, q, new_admin, extack);
1482         else
1483                 err = taprio_disable_offload(dev, q, extack);
1484         if (err)
1485                 goto free_sched;
1486
1487         /* Protects against enqueue()/dequeue() */
1488         spin_lock_bh(qdisc_lock(sch));
1489
1490         if (tb[TCA_TAPRIO_ATTR_TXTIME_DELAY]) {
1491                 if (!TXTIME_ASSIST_IS_ENABLED(q->flags)) {
1492                         NL_SET_ERR_MSG_MOD(extack, "txtime-delay can only be set when txtime-assist mode is enabled");
1493                         err = -EINVAL;
1494                         goto unlock;
1495                 }
1496
1497                 q->txtime_delay = nla_get_u32(tb[TCA_TAPRIO_ATTR_TXTIME_DELAY]);
1498         }
1499
1500         if (!TXTIME_ASSIST_IS_ENABLED(q->flags) &&
1501             !FULL_OFFLOAD_IS_ENABLED(q->flags) &&
1502             !hrtimer_active(&q->advance_timer)) {
1503                 hrtimer_init(&q->advance_timer, q->clockid, HRTIMER_MODE_ABS);
1504                 q->advance_timer.function = advance_sched;
1505         }
1506
1507         if (FULL_OFFLOAD_IS_ENABLED(q->flags)) {
1508                 q->dequeue = taprio_dequeue_offload;
1509                 q->peek = taprio_peek_offload;
1510         } else {
1511                 /* Be sure to always keep the function pointers
1512                  * in a consistent state.
1513                  */
1514                 q->dequeue = taprio_dequeue_soft;
1515                 q->peek = taprio_peek_soft;
1516         }
1517
1518         err = taprio_get_start_time(sch, new_admin, &start);
1519         if (err < 0) {
1520                 NL_SET_ERR_MSG(extack, "Internal error: failed get start time");
1521                 goto unlock;
1522         }
1523
1524         if (TXTIME_ASSIST_IS_ENABLED(q->flags)) {
1525                 setup_txtime(q, new_admin, start);
1526
1527                 if (!oper) {
1528                         rcu_assign_pointer(q->oper_sched, new_admin);
1529                         err = 0;
1530                         new_admin = NULL;
1531                         goto unlock;
1532                 }
1533
1534                 rcu_assign_pointer(q->admin_sched, new_admin);
1535                 if (admin)
1536                         call_rcu(&admin->rcu, taprio_free_sched_cb);
1537         } else {
1538                 setup_first_close_time(q, new_admin, start);
1539
1540                 /* Protects against advance_sched() */
1541                 spin_lock_irqsave(&q->current_entry_lock, flags);
1542
1543                 taprio_start_sched(sch, start, new_admin);
1544
1545                 rcu_assign_pointer(q->admin_sched, new_admin);
1546                 if (admin)
1547                         call_rcu(&admin->rcu, taprio_free_sched_cb);
1548
1549                 spin_unlock_irqrestore(&q->current_entry_lock, flags);
1550
1551                 if (FULL_OFFLOAD_IS_ENABLED(q->flags))
1552                         taprio_offload_config_changed(q);
1553         }
1554
1555         new_admin = NULL;
1556         err = 0;
1557
1558 unlock:
1559         spin_unlock_bh(qdisc_lock(sch));
1560
1561 free_sched:
1562         if (new_admin)
1563                 call_rcu(&new_admin->rcu, taprio_free_sched_cb);
1564
1565         return err;
1566 }
1567
1568 static void taprio_destroy(struct Qdisc *sch)
1569 {
1570         struct taprio_sched *q = qdisc_priv(sch);
1571         struct net_device *dev = qdisc_dev(sch);
1572         unsigned int i;
1573
1574         spin_lock(&taprio_list_lock);
1575         list_del(&q->taprio_list);
1576         spin_unlock(&taprio_list_lock);
1577
1578         hrtimer_cancel(&q->advance_timer);
1579
1580         taprio_disable_offload(dev, q, NULL);
1581
1582         if (q->qdiscs) {
1583                 for (i = 0; i < dev->num_tx_queues && q->qdiscs[i]; i++)
1584                         qdisc_put(q->qdiscs[i]);
1585
1586                 kfree(q->qdiscs);
1587         }
1588         q->qdiscs = NULL;
1589
1590         netdev_set_num_tc(dev, 0);
1591
1592         if (q->oper_sched)
1593                 call_rcu(&q->oper_sched->rcu, taprio_free_sched_cb);
1594
1595         if (q->admin_sched)
1596                 call_rcu(&q->admin_sched->rcu, taprio_free_sched_cb);
1597 }
1598
1599 static int taprio_init(struct Qdisc *sch, struct nlattr *opt,
1600                        struct netlink_ext_ack *extack)
1601 {
1602         struct taprio_sched *q = qdisc_priv(sch);
1603         struct net_device *dev = qdisc_dev(sch);
1604         int i;
1605
1606         spin_lock_init(&q->current_entry_lock);
1607
1608         hrtimer_init(&q->advance_timer, CLOCK_TAI, HRTIMER_MODE_ABS);
1609         q->advance_timer.function = advance_sched;
1610
1611         q->dequeue = taprio_dequeue_soft;
1612         q->peek = taprio_peek_soft;
1613
1614         q->root = sch;
1615
1616         /* We only support static clockids. Use an invalid value as default
1617          * and get the valid one on taprio_change().
1618          */
1619         q->clockid = -1;
1620         q->flags = TAPRIO_FLAGS_INVALID;
1621
1622         spin_lock(&taprio_list_lock);
1623         list_add(&q->taprio_list, &taprio_list);
1624         spin_unlock(&taprio_list_lock);
1625
1626         if (sch->parent != TC_H_ROOT)
1627                 return -EOPNOTSUPP;
1628
1629         if (!netif_is_multiqueue(dev))
1630                 return -EOPNOTSUPP;
1631
1632         /* pre-allocate qdisc, attachment can't fail */
1633         q->qdiscs = kcalloc(dev->num_tx_queues,
1634                             sizeof(q->qdiscs[0]),
1635                             GFP_KERNEL);
1636
1637         if (!q->qdiscs)
1638                 return -ENOMEM;
1639
1640         if (!opt)
1641                 return -EINVAL;
1642
1643         for (i = 0; i < dev->num_tx_queues; i++) {
1644                 struct netdev_queue *dev_queue;
1645                 struct Qdisc *qdisc;
1646
1647                 dev_queue = netdev_get_tx_queue(dev, i);
1648                 qdisc = qdisc_create_dflt(dev_queue,
1649                                           &pfifo_qdisc_ops,
1650                                           TC_H_MAKE(TC_H_MAJ(sch->handle),
1651                                                     TC_H_MIN(i + 1)),
1652                                           extack);
1653                 if (!qdisc)
1654                         return -ENOMEM;
1655
1656                 if (i < dev->real_num_tx_queues)
1657                         qdisc_hash_add(qdisc, false);
1658
1659                 q->qdiscs[i] = qdisc;
1660         }
1661
1662         return taprio_change(sch, opt, extack);
1663 }
1664
1665 static struct netdev_queue *taprio_queue_get(struct Qdisc *sch,
1666                                              unsigned long cl)
1667 {
1668         struct net_device *dev = qdisc_dev(sch);
1669         unsigned long ntx = cl - 1;
1670
1671         if (ntx >= dev->num_tx_queues)
1672                 return NULL;
1673
1674         return netdev_get_tx_queue(dev, ntx);
1675 }
1676
1677 static int taprio_graft(struct Qdisc *sch, unsigned long cl,
1678                         struct Qdisc *new, struct Qdisc **old,
1679                         struct netlink_ext_ack *extack)
1680 {
1681         struct taprio_sched *q = qdisc_priv(sch);
1682         struct net_device *dev = qdisc_dev(sch);
1683         struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
1684
1685         if (!dev_queue)
1686                 return -EINVAL;
1687
1688         if (dev->flags & IFF_UP)
1689                 dev_deactivate(dev);
1690
1691         *old = q->qdiscs[cl - 1];
1692         q->qdiscs[cl - 1] = new;
1693
1694         if (new)
1695                 new->flags |= TCQ_F_ONETXQUEUE | TCQ_F_NOPARENT;
1696
1697         if (dev->flags & IFF_UP)
1698                 dev_activate(dev);
1699
1700         return 0;
1701 }
1702
1703 static int dump_entry(struct sk_buff *msg,
1704                       const struct sched_entry *entry)
1705 {
1706         struct nlattr *item;
1707
1708         item = nla_nest_start_noflag(msg, TCA_TAPRIO_SCHED_ENTRY);
1709         if (!item)
1710                 return -ENOSPC;
1711
1712         if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_INDEX, entry->index))
1713                 goto nla_put_failure;
1714
1715         if (nla_put_u8(msg, TCA_TAPRIO_SCHED_ENTRY_CMD, entry->command))
1716                 goto nla_put_failure;
1717
1718         if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_GATE_MASK,
1719                         entry->gate_mask))
1720                 goto nla_put_failure;
1721
1722         if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_INTERVAL,
1723                         entry->interval))
1724                 goto nla_put_failure;
1725
1726         return nla_nest_end(msg, item);
1727
1728 nla_put_failure:
1729         nla_nest_cancel(msg, item);
1730         return -1;
1731 }
1732
1733 static int dump_schedule(struct sk_buff *msg,
1734                          const struct sched_gate_list *root)
1735 {
1736         struct nlattr *entry_list;
1737         struct sched_entry *entry;
1738
1739         if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_BASE_TIME,
1740                         root->base_time, TCA_TAPRIO_PAD))
1741                 return -1;
1742
1743         if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME,
1744                         root->cycle_time, TCA_TAPRIO_PAD))
1745                 return -1;
1746
1747         if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION,
1748                         root->cycle_time_extension, TCA_TAPRIO_PAD))
1749                 return -1;
1750
1751         entry_list = nla_nest_start_noflag(msg,
1752                                            TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST);
1753         if (!entry_list)
1754                 goto error_nest;
1755
1756         list_for_each_entry(entry, &root->entries, list) {
1757                 if (dump_entry(msg, entry) < 0)
1758                         goto error_nest;
1759         }
1760
1761         nla_nest_end(msg, entry_list);
1762         return 0;
1763
1764 error_nest:
1765         nla_nest_cancel(msg, entry_list);
1766         return -1;
1767 }
1768
1769 static int taprio_dump(struct Qdisc *sch, struct sk_buff *skb)
1770 {
1771         struct taprio_sched *q = qdisc_priv(sch);
1772         struct net_device *dev = qdisc_dev(sch);
1773         struct sched_gate_list *oper, *admin;
1774         struct tc_mqprio_qopt opt = { 0 };
1775         struct nlattr *nest, *sched_nest;
1776         unsigned int i;
1777
1778         rcu_read_lock();
1779         oper = rcu_dereference(q->oper_sched);
1780         admin = rcu_dereference(q->admin_sched);
1781
1782         opt.num_tc = netdev_get_num_tc(dev);
1783         memcpy(opt.prio_tc_map, dev->prio_tc_map, sizeof(opt.prio_tc_map));
1784
1785         for (i = 0; i < netdev_get_num_tc(dev); i++) {
1786                 opt.count[i] = dev->tc_to_txq[i].count;
1787                 opt.offset[i] = dev->tc_to_txq[i].offset;
1788         }
1789
1790         nest = nla_nest_start_noflag(skb, TCA_OPTIONS);
1791         if (!nest)
1792                 goto start_error;
1793
1794         if (nla_put(skb, TCA_TAPRIO_ATTR_PRIOMAP, sizeof(opt), &opt))
1795                 goto options_error;
1796
1797         if (!FULL_OFFLOAD_IS_ENABLED(q->flags) &&
1798             nla_put_s32(skb, TCA_TAPRIO_ATTR_SCHED_CLOCKID, q->clockid))
1799                 goto options_error;
1800
1801         if (q->flags && nla_put_u32(skb, TCA_TAPRIO_ATTR_FLAGS, q->flags))
1802                 goto options_error;
1803
1804         if (q->txtime_delay &&
1805             nla_put_u32(skb, TCA_TAPRIO_ATTR_TXTIME_DELAY, q->txtime_delay))
1806                 goto options_error;
1807
1808         if (oper && dump_schedule(skb, oper))
1809                 goto options_error;
1810
1811         if (!admin)
1812                 goto done;
1813
1814         sched_nest = nla_nest_start_noflag(skb, TCA_TAPRIO_ATTR_ADMIN_SCHED);
1815         if (!sched_nest)
1816                 goto options_error;
1817
1818         if (dump_schedule(skb, admin))
1819                 goto admin_error;
1820
1821         nla_nest_end(skb, sched_nest);
1822
1823 done:
1824         rcu_read_unlock();
1825
1826         return nla_nest_end(skb, nest);
1827
1828 admin_error:
1829         nla_nest_cancel(skb, sched_nest);
1830
1831 options_error:
1832         nla_nest_cancel(skb, nest);
1833
1834 start_error:
1835         rcu_read_unlock();
1836         return -ENOSPC;
1837 }
1838
1839 static struct Qdisc *taprio_leaf(struct Qdisc *sch, unsigned long cl)
1840 {
1841         struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
1842
1843         if (!dev_queue)
1844                 return NULL;
1845
1846         return dev_queue->qdisc_sleeping;
1847 }
1848
1849 static unsigned long taprio_find(struct Qdisc *sch, u32 classid)
1850 {
1851         unsigned int ntx = TC_H_MIN(classid);
1852
1853         if (!taprio_queue_get(sch, ntx))
1854                 return 0;
1855         return ntx;
1856 }
1857
1858 static int taprio_dump_class(struct Qdisc *sch, unsigned long cl,
1859                              struct sk_buff *skb, struct tcmsg *tcm)
1860 {
1861         struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
1862
1863         tcm->tcm_parent = TC_H_ROOT;
1864         tcm->tcm_handle |= TC_H_MIN(cl);
1865         tcm->tcm_info = dev_queue->qdisc_sleeping->handle;
1866
1867         return 0;
1868 }
1869
1870 static int taprio_dump_class_stats(struct Qdisc *sch, unsigned long cl,
1871                                    struct gnet_dump *d)
1872         __releases(d->lock)
1873         __acquires(d->lock)
1874 {
1875         struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
1876
1877         sch = dev_queue->qdisc_sleeping;
1878         if (gnet_stats_copy_basic(&sch->running, d, NULL, &sch->bstats) < 0 ||
1879             qdisc_qstats_copy(d, sch) < 0)
1880                 return -1;
1881         return 0;
1882 }
1883
1884 static void taprio_walk(struct Qdisc *sch, struct qdisc_walker *arg)
1885 {
1886         struct net_device *dev = qdisc_dev(sch);
1887         unsigned long ntx;
1888
1889         if (arg->stop)
1890                 return;
1891
1892         arg->count = arg->skip;
1893         for (ntx = arg->skip; ntx < dev->num_tx_queues; ntx++) {
1894                 if (arg->fn(sch, ntx + 1, arg) < 0) {
1895                         arg->stop = 1;
1896                         break;
1897                 }
1898                 arg->count++;
1899         }
1900 }
1901
1902 static struct netdev_queue *taprio_select_queue(struct Qdisc *sch,
1903                                                 struct tcmsg *tcm)
1904 {
1905         return taprio_queue_get(sch, TC_H_MIN(tcm->tcm_parent));
1906 }
1907
1908 static const struct Qdisc_class_ops taprio_class_ops = {
1909         .graft          = taprio_graft,
1910         .leaf           = taprio_leaf,
1911         .find           = taprio_find,
1912         .walk           = taprio_walk,
1913         .dump           = taprio_dump_class,
1914         .dump_stats     = taprio_dump_class_stats,
1915         .select_queue   = taprio_select_queue,
1916 };
1917
1918 static struct Qdisc_ops taprio_qdisc_ops __read_mostly = {
1919         .cl_ops         = &taprio_class_ops,
1920         .id             = "taprio",
1921         .priv_size      = sizeof(struct taprio_sched),
1922         .init           = taprio_init,
1923         .change         = taprio_change,
1924         .destroy        = taprio_destroy,
1925         .peek           = taprio_peek,
1926         .dequeue        = taprio_dequeue,
1927         .enqueue        = taprio_enqueue,
1928         .dump           = taprio_dump,
1929         .owner          = THIS_MODULE,
1930 };
1931
1932 static struct notifier_block taprio_device_notifier = {
1933         .notifier_call = taprio_dev_notifier,
1934 };
1935
1936 static int __init taprio_module_init(void)
1937 {
1938         int err = register_netdevice_notifier(&taprio_device_notifier);
1939
1940         if (err)
1941                 return err;
1942
1943         return register_qdisc(&taprio_qdisc_ops);
1944 }
1945
1946 static void __exit taprio_module_exit(void)
1947 {
1948         unregister_qdisc(&taprio_qdisc_ops);
1949         unregister_netdevice_notifier(&taprio_device_notifier);
1950 }
1951
1952 module_init(taprio_module_init);
1953 module_exit(taprio_module_exit);
1954 MODULE_LICENSE("GPL");