OSDN Git Service

Merge tag 'kbuild-fixes-v5.6-3' of git://git.kernel.org/pub/scm/linux/kernel/git...
[tomoyo/tomoyo-test1.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                         skb = NULL;
569                         continue;
570                 }
571
572                 len = qdisc_pkt_len(skb);
573                 guard = ktime_add_ns(taprio_get_time(q),
574                                      length_to_duration(q, len));
575
576                 /* In the case that there's no gate entry, there's no
577                  * guard band ...
578                  */
579                 if (gate_mask != TAPRIO_ALL_GATES_OPEN &&
580                     ktime_after(guard, entry->close_time)) {
581                         skb = NULL;
582                         continue;
583                 }
584
585                 /* ... and no budget. */
586                 if (gate_mask != TAPRIO_ALL_GATES_OPEN &&
587                     atomic_sub_return(len, &entry->budget) < 0) {
588                         skb = NULL;
589                         continue;
590                 }
591
592                 skb = child->ops->dequeue(child);
593                 if (unlikely(!skb))
594                         goto done;
595
596 skb_found:
597                 qdisc_bstats_update(sch, skb);
598                 qdisc_qstats_backlog_dec(sch, skb);
599                 sch->q.qlen--;
600
601                 goto done;
602         }
603
604 done:
605         rcu_read_unlock();
606
607         return skb;
608 }
609
610 static struct sk_buff *taprio_dequeue_offload(struct Qdisc *sch)
611 {
612         struct taprio_sched *q = qdisc_priv(sch);
613         struct net_device *dev = qdisc_dev(sch);
614         struct sk_buff *skb;
615         int i;
616
617         for (i = 0; i < dev->num_tx_queues; i++) {
618                 struct Qdisc *child = q->qdiscs[i];
619
620                 if (unlikely(!child))
621                         continue;
622
623                 skb = child->ops->dequeue(child);
624                 if (unlikely(!skb))
625                         continue;
626
627                 qdisc_bstats_update(sch, skb);
628                 qdisc_qstats_backlog_dec(sch, skb);
629                 sch->q.qlen--;
630
631                 return skb;
632         }
633
634         return NULL;
635 }
636
637 static struct sk_buff *taprio_dequeue(struct Qdisc *sch)
638 {
639         struct taprio_sched *q = qdisc_priv(sch);
640
641         return q->dequeue(sch);
642 }
643
644 static bool should_restart_cycle(const struct sched_gate_list *oper,
645                                  const struct sched_entry *entry)
646 {
647         if (list_is_last(&entry->list, &oper->entries))
648                 return true;
649
650         if (ktime_compare(entry->close_time, oper->cycle_close_time) == 0)
651                 return true;
652
653         return false;
654 }
655
656 static bool should_change_schedules(const struct sched_gate_list *admin,
657                                     const struct sched_gate_list *oper,
658                                     ktime_t close_time)
659 {
660         ktime_t next_base_time, extension_time;
661
662         if (!admin)
663                 return false;
664
665         next_base_time = sched_base_time(admin);
666
667         /* This is the simple case, the close_time would fall after
668          * the next schedule base_time.
669          */
670         if (ktime_compare(next_base_time, close_time) <= 0)
671                 return true;
672
673         /* This is the cycle_time_extension case, if the close_time
674          * plus the amount that can be extended would fall after the
675          * next schedule base_time, we can extend the current schedule
676          * for that amount.
677          */
678         extension_time = ktime_add_ns(close_time, oper->cycle_time_extension);
679
680         /* FIXME: the IEEE 802.1Q-2018 Specification isn't clear about
681          * how precisely the extension should be made. So after
682          * conformance testing, this logic may change.
683          */
684         if (ktime_compare(next_base_time, extension_time) <= 0)
685                 return true;
686
687         return false;
688 }
689
690 static enum hrtimer_restart advance_sched(struct hrtimer *timer)
691 {
692         struct taprio_sched *q = container_of(timer, struct taprio_sched,
693                                               advance_timer);
694         struct sched_gate_list *oper, *admin;
695         struct sched_entry *entry, *next;
696         struct Qdisc *sch = q->root;
697         ktime_t close_time;
698
699         spin_lock(&q->current_entry_lock);
700         entry = rcu_dereference_protected(q->current_entry,
701                                           lockdep_is_held(&q->current_entry_lock));
702         oper = rcu_dereference_protected(q->oper_sched,
703                                          lockdep_is_held(&q->current_entry_lock));
704         admin = rcu_dereference_protected(q->admin_sched,
705                                           lockdep_is_held(&q->current_entry_lock));
706
707         if (!oper)
708                 switch_schedules(q, &admin, &oper);
709
710         /* This can happen in two cases: 1. this is the very first run
711          * of this function (i.e. we weren't running any schedule
712          * previously); 2. The previous schedule just ended. The first
713          * entry of all schedules are pre-calculated during the
714          * schedule initialization.
715          */
716         if (unlikely(!entry || entry->close_time == oper->base_time)) {
717                 next = list_first_entry(&oper->entries, struct sched_entry,
718                                         list);
719                 close_time = next->close_time;
720                 goto first_run;
721         }
722
723         if (should_restart_cycle(oper, entry)) {
724                 next = list_first_entry(&oper->entries, struct sched_entry,
725                                         list);
726                 oper->cycle_close_time = ktime_add_ns(oper->cycle_close_time,
727                                                       oper->cycle_time);
728         } else {
729                 next = list_next_entry(entry, list);
730         }
731
732         close_time = ktime_add_ns(entry->close_time, next->interval);
733         close_time = min_t(ktime_t, close_time, oper->cycle_close_time);
734
735         if (should_change_schedules(admin, oper, close_time)) {
736                 /* Set things so the next time this runs, the new
737                  * schedule runs.
738                  */
739                 close_time = sched_base_time(admin);
740                 switch_schedules(q, &admin, &oper);
741         }
742
743         next->close_time = close_time;
744         taprio_set_budget(q, next);
745
746 first_run:
747         rcu_assign_pointer(q->current_entry, next);
748         spin_unlock(&q->current_entry_lock);
749
750         hrtimer_set_expires(&q->advance_timer, close_time);
751
752         rcu_read_lock();
753         __netif_schedule(sch);
754         rcu_read_unlock();
755
756         return HRTIMER_RESTART;
757 }
758
759 static const struct nla_policy entry_policy[TCA_TAPRIO_SCHED_ENTRY_MAX + 1] = {
760         [TCA_TAPRIO_SCHED_ENTRY_INDEX]     = { .type = NLA_U32 },
761         [TCA_TAPRIO_SCHED_ENTRY_CMD]       = { .type = NLA_U8 },
762         [TCA_TAPRIO_SCHED_ENTRY_GATE_MASK] = { .type = NLA_U32 },
763         [TCA_TAPRIO_SCHED_ENTRY_INTERVAL]  = { .type = NLA_U32 },
764 };
765
766 static const struct nla_policy taprio_policy[TCA_TAPRIO_ATTR_MAX + 1] = {
767         [TCA_TAPRIO_ATTR_PRIOMAP]              = {
768                 .len = sizeof(struct tc_mqprio_qopt)
769         },
770         [TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST]           = { .type = NLA_NESTED },
771         [TCA_TAPRIO_ATTR_SCHED_BASE_TIME]            = { .type = NLA_S64 },
772         [TCA_TAPRIO_ATTR_SCHED_SINGLE_ENTRY]         = { .type = NLA_NESTED },
773         [TCA_TAPRIO_ATTR_SCHED_CLOCKID]              = { .type = NLA_S32 },
774         [TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME]           = { .type = NLA_S64 },
775         [TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION] = { .type = NLA_S64 },
776         [TCA_TAPRIO_ATTR_FLAGS]                      = { .type = NLA_U32 },
777         [TCA_TAPRIO_ATTR_TXTIME_DELAY]               = { .type = NLA_U32 },
778 };
779
780 static int fill_sched_entry(struct nlattr **tb, struct sched_entry *entry,
781                             struct netlink_ext_ack *extack)
782 {
783         u32 interval = 0;
784
785         if (tb[TCA_TAPRIO_SCHED_ENTRY_CMD])
786                 entry->command = nla_get_u8(
787                         tb[TCA_TAPRIO_SCHED_ENTRY_CMD]);
788
789         if (tb[TCA_TAPRIO_SCHED_ENTRY_GATE_MASK])
790                 entry->gate_mask = nla_get_u32(
791                         tb[TCA_TAPRIO_SCHED_ENTRY_GATE_MASK]);
792
793         if (tb[TCA_TAPRIO_SCHED_ENTRY_INTERVAL])
794                 interval = nla_get_u32(
795                         tb[TCA_TAPRIO_SCHED_ENTRY_INTERVAL]);
796
797         if (interval == 0) {
798                 NL_SET_ERR_MSG(extack, "Invalid interval for schedule entry");
799                 return -EINVAL;
800         }
801
802         entry->interval = interval;
803
804         return 0;
805 }
806
807 static int parse_sched_entry(struct nlattr *n, struct sched_entry *entry,
808                              int index, struct netlink_ext_ack *extack)
809 {
810         struct nlattr *tb[TCA_TAPRIO_SCHED_ENTRY_MAX + 1] = { };
811         int err;
812
813         err = nla_parse_nested_deprecated(tb, TCA_TAPRIO_SCHED_ENTRY_MAX, n,
814                                           entry_policy, NULL);
815         if (err < 0) {
816                 NL_SET_ERR_MSG(extack, "Could not parse nested entry");
817                 return -EINVAL;
818         }
819
820         entry->index = index;
821
822         return fill_sched_entry(tb, entry, extack);
823 }
824
825 static int parse_sched_list(struct nlattr *list,
826                             struct sched_gate_list *sched,
827                             struct netlink_ext_ack *extack)
828 {
829         struct nlattr *n;
830         int err, rem;
831         int i = 0;
832
833         if (!list)
834                 return -EINVAL;
835
836         nla_for_each_nested(n, list, rem) {
837                 struct sched_entry *entry;
838
839                 if (nla_type(n) != TCA_TAPRIO_SCHED_ENTRY) {
840                         NL_SET_ERR_MSG(extack, "Attribute is not of type 'entry'");
841                         continue;
842                 }
843
844                 entry = kzalloc(sizeof(*entry), GFP_KERNEL);
845                 if (!entry) {
846                         NL_SET_ERR_MSG(extack, "Not enough memory for entry");
847                         return -ENOMEM;
848                 }
849
850                 err = parse_sched_entry(n, entry, i, extack);
851                 if (err < 0) {
852                         kfree(entry);
853                         return err;
854                 }
855
856                 list_add_tail(&entry->list, &sched->entries);
857                 i++;
858         }
859
860         sched->num_entries = i;
861
862         return i;
863 }
864
865 static int parse_taprio_schedule(struct nlattr **tb,
866                                  struct sched_gate_list *new,
867                                  struct netlink_ext_ack *extack)
868 {
869         int err = 0;
870
871         if (tb[TCA_TAPRIO_ATTR_SCHED_SINGLE_ENTRY]) {
872                 NL_SET_ERR_MSG(extack, "Adding a single entry is not supported");
873                 return -ENOTSUPP;
874         }
875
876         if (tb[TCA_TAPRIO_ATTR_SCHED_BASE_TIME])
877                 new->base_time = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_BASE_TIME]);
878
879         if (tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION])
880                 new->cycle_time_extension = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION]);
881
882         if (tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME])
883                 new->cycle_time = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME]);
884
885         if (tb[TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST])
886                 err = parse_sched_list(
887                         tb[TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST], new, extack);
888         if (err < 0)
889                 return err;
890
891         if (!new->cycle_time) {
892                 struct sched_entry *entry;
893                 ktime_t cycle = 0;
894
895                 list_for_each_entry(entry, &new->entries, list)
896                         cycle = ktime_add_ns(cycle, entry->interval);
897                 new->cycle_time = cycle;
898         }
899
900         return 0;
901 }
902
903 static int taprio_parse_mqprio_opt(struct net_device *dev,
904                                    struct tc_mqprio_qopt *qopt,
905                                    struct netlink_ext_ack *extack,
906                                    u32 taprio_flags)
907 {
908         int i, j;
909
910         if (!qopt && !dev->num_tc) {
911                 NL_SET_ERR_MSG(extack, "'mqprio' configuration is necessary");
912                 return -EINVAL;
913         }
914
915         /* If num_tc is already set, it means that the user already
916          * configured the mqprio part
917          */
918         if (dev->num_tc)
919                 return 0;
920
921         /* Verify num_tc is not out of max range */
922         if (qopt->num_tc > TC_MAX_QUEUE) {
923                 NL_SET_ERR_MSG(extack, "Number of traffic classes is outside valid range");
924                 return -EINVAL;
925         }
926
927         /* taprio imposes that traffic classes map 1:n to tx queues */
928         if (qopt->num_tc > dev->num_tx_queues) {
929                 NL_SET_ERR_MSG(extack, "Number of traffic classes is greater than number of HW queues");
930                 return -EINVAL;
931         }
932
933         /* Verify priority mapping uses valid tcs */
934         for (i = 0; i <= TC_BITMASK; i++) {
935                 if (qopt->prio_tc_map[i] >= qopt->num_tc) {
936                         NL_SET_ERR_MSG(extack, "Invalid traffic class in priority to traffic class mapping");
937                         return -EINVAL;
938                 }
939         }
940
941         for (i = 0; i < qopt->num_tc; i++) {
942                 unsigned int last = qopt->offset[i] + qopt->count[i];
943
944                 /* Verify the queue count is in tx range being equal to the
945                  * real_num_tx_queues indicates the last queue is in use.
946                  */
947                 if (qopt->offset[i] >= dev->num_tx_queues ||
948                     !qopt->count[i] ||
949                     last > dev->real_num_tx_queues) {
950                         NL_SET_ERR_MSG(extack, "Invalid queue in traffic class to queue mapping");
951                         return -EINVAL;
952                 }
953
954                 if (TXTIME_ASSIST_IS_ENABLED(taprio_flags))
955                         continue;
956
957                 /* Verify that the offset and counts do not overlap */
958                 for (j = i + 1; j < qopt->num_tc; j++) {
959                         if (last > qopt->offset[j]) {
960                                 NL_SET_ERR_MSG(extack, "Detected overlap in the traffic class to queue mapping");
961                                 return -EINVAL;
962                         }
963                 }
964         }
965
966         return 0;
967 }
968
969 static int taprio_get_start_time(struct Qdisc *sch,
970                                  struct sched_gate_list *sched,
971                                  ktime_t *start)
972 {
973         struct taprio_sched *q = qdisc_priv(sch);
974         ktime_t now, base, cycle;
975         s64 n;
976
977         base = sched_base_time(sched);
978         now = taprio_get_time(q);
979
980         if (ktime_after(base, now)) {
981                 *start = base;
982                 return 0;
983         }
984
985         cycle = sched->cycle_time;
986
987         /* The qdisc is expected to have at least one sched_entry.  Moreover,
988          * any entry must have 'interval' > 0. Thus if the cycle time is zero,
989          * something went really wrong. In that case, we should warn about this
990          * inconsistent state and return error.
991          */
992         if (WARN_ON(!cycle))
993                 return -EFAULT;
994
995         /* Schedule the start time for the beginning of the next
996          * cycle.
997          */
998         n = div64_s64(ktime_sub_ns(now, base), cycle);
999         *start = ktime_add_ns(base, (n + 1) * cycle);
1000         return 0;
1001 }
1002
1003 static void setup_first_close_time(struct taprio_sched *q,
1004                                    struct sched_gate_list *sched, ktime_t base)
1005 {
1006         struct sched_entry *first;
1007         ktime_t cycle;
1008
1009         first = list_first_entry(&sched->entries,
1010                                  struct sched_entry, list);
1011
1012         cycle = sched->cycle_time;
1013
1014         /* FIXME: find a better place to do this */
1015         sched->cycle_close_time = ktime_add_ns(base, cycle);
1016
1017         first->close_time = ktime_add_ns(base, first->interval);
1018         taprio_set_budget(q, first);
1019         rcu_assign_pointer(q->current_entry, NULL);
1020 }
1021
1022 static void taprio_start_sched(struct Qdisc *sch,
1023                                ktime_t start, struct sched_gate_list *new)
1024 {
1025         struct taprio_sched *q = qdisc_priv(sch);
1026         ktime_t expires;
1027
1028         if (FULL_OFFLOAD_IS_ENABLED(q->flags))
1029                 return;
1030
1031         expires = hrtimer_get_expires(&q->advance_timer);
1032         if (expires == 0)
1033                 expires = KTIME_MAX;
1034
1035         /* If the new schedule starts before the next expiration, we
1036          * reprogram it to the earliest one, so we change the admin
1037          * schedule to the operational one at the right time.
1038          */
1039         start = min_t(ktime_t, start, expires);
1040
1041         hrtimer_start(&q->advance_timer, start, HRTIMER_MODE_ABS);
1042 }
1043
1044 static void taprio_set_picos_per_byte(struct net_device *dev,
1045                                       struct taprio_sched *q)
1046 {
1047         struct ethtool_link_ksettings ecmd;
1048         int speed = SPEED_10;
1049         int picos_per_byte;
1050         int err;
1051
1052         err = __ethtool_get_link_ksettings(dev, &ecmd);
1053         if (err < 0)
1054                 goto skip;
1055
1056         if (ecmd.base.speed && ecmd.base.speed != SPEED_UNKNOWN)
1057                 speed = ecmd.base.speed;
1058
1059 skip:
1060         picos_per_byte = (USEC_PER_SEC * 8) / speed;
1061
1062         atomic64_set(&q->picos_per_byte, picos_per_byte);
1063         netdev_dbg(dev, "taprio: set %s's picos_per_byte to: %lld, linkspeed: %d\n",
1064                    dev->name, (long long)atomic64_read(&q->picos_per_byte),
1065                    ecmd.base.speed);
1066 }
1067
1068 static int taprio_dev_notifier(struct notifier_block *nb, unsigned long event,
1069                                void *ptr)
1070 {
1071         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1072         struct net_device *qdev;
1073         struct taprio_sched *q;
1074         bool found = false;
1075
1076         ASSERT_RTNL();
1077
1078         if (event != NETDEV_UP && event != NETDEV_CHANGE)
1079                 return NOTIFY_DONE;
1080
1081         spin_lock(&taprio_list_lock);
1082         list_for_each_entry(q, &taprio_list, taprio_list) {
1083                 qdev = qdisc_dev(q->root);
1084                 if (qdev == dev) {
1085                         found = true;
1086                         break;
1087                 }
1088         }
1089         spin_unlock(&taprio_list_lock);
1090
1091         if (found)
1092                 taprio_set_picos_per_byte(dev, q);
1093
1094         return NOTIFY_DONE;
1095 }
1096
1097 static void setup_txtime(struct taprio_sched *q,
1098                          struct sched_gate_list *sched, ktime_t base)
1099 {
1100         struct sched_entry *entry;
1101         u32 interval = 0;
1102
1103         list_for_each_entry(entry, &sched->entries, list) {
1104                 entry->next_txtime = ktime_add_ns(base, interval);
1105                 interval += entry->interval;
1106         }
1107 }
1108
1109 static struct tc_taprio_qopt_offload *taprio_offload_alloc(int num_entries)
1110 {
1111         size_t size = sizeof(struct tc_taprio_sched_entry) * num_entries +
1112                       sizeof(struct __tc_taprio_qopt_offload);
1113         struct __tc_taprio_qopt_offload *__offload;
1114
1115         __offload = kzalloc(size, GFP_KERNEL);
1116         if (!__offload)
1117                 return NULL;
1118
1119         refcount_set(&__offload->users, 1);
1120
1121         return &__offload->offload;
1122 }
1123
1124 struct tc_taprio_qopt_offload *taprio_offload_get(struct tc_taprio_qopt_offload
1125                                                   *offload)
1126 {
1127         struct __tc_taprio_qopt_offload *__offload;
1128
1129         __offload = container_of(offload, struct __tc_taprio_qopt_offload,
1130                                  offload);
1131
1132         refcount_inc(&__offload->users);
1133
1134         return offload;
1135 }
1136 EXPORT_SYMBOL_GPL(taprio_offload_get);
1137
1138 void taprio_offload_free(struct tc_taprio_qopt_offload *offload)
1139 {
1140         struct __tc_taprio_qopt_offload *__offload;
1141
1142         __offload = container_of(offload, struct __tc_taprio_qopt_offload,
1143                                  offload);
1144
1145         if (!refcount_dec_and_test(&__offload->users))
1146                 return;
1147
1148         kfree(__offload);
1149 }
1150 EXPORT_SYMBOL_GPL(taprio_offload_free);
1151
1152 /* The function will only serve to keep the pointers to the "oper" and "admin"
1153  * schedules valid in relation to their base times, so when calling dump() the
1154  * users looks at the right schedules.
1155  * When using full offload, the admin configuration is promoted to oper at the
1156  * base_time in the PHC time domain.  But because the system time is not
1157  * necessarily in sync with that, we can't just trigger a hrtimer to call
1158  * switch_schedules at the right hardware time.
1159  * At the moment we call this by hand right away from taprio, but in the future
1160  * it will be useful to create a mechanism for drivers to notify taprio of the
1161  * offload state (PENDING, ACTIVE, INACTIVE) so it can be visible in dump().
1162  * This is left as TODO.
1163  */
1164 static void taprio_offload_config_changed(struct taprio_sched *q)
1165 {
1166         struct sched_gate_list *oper, *admin;
1167
1168         spin_lock(&q->current_entry_lock);
1169
1170         oper = rcu_dereference_protected(q->oper_sched,
1171                                          lockdep_is_held(&q->current_entry_lock));
1172         admin = rcu_dereference_protected(q->admin_sched,
1173                                           lockdep_is_held(&q->current_entry_lock));
1174
1175         switch_schedules(q, &admin, &oper);
1176
1177         spin_unlock(&q->current_entry_lock);
1178 }
1179
1180 static void taprio_sched_to_offload(struct taprio_sched *q,
1181                                     struct sched_gate_list *sched,
1182                                     const struct tc_mqprio_qopt *mqprio,
1183                                     struct tc_taprio_qopt_offload *offload)
1184 {
1185         struct sched_entry *entry;
1186         int i = 0;
1187
1188         offload->base_time = sched->base_time;
1189         offload->cycle_time = sched->cycle_time;
1190         offload->cycle_time_extension = sched->cycle_time_extension;
1191
1192         list_for_each_entry(entry, &sched->entries, list) {
1193                 struct tc_taprio_sched_entry *e = &offload->entries[i];
1194
1195                 e->command = entry->command;
1196                 e->interval = entry->interval;
1197                 e->gate_mask = entry->gate_mask;
1198                 i++;
1199         }
1200
1201         offload->num_entries = i;
1202 }
1203
1204 static int taprio_enable_offload(struct net_device *dev,
1205                                  struct tc_mqprio_qopt *mqprio,
1206                                  struct taprio_sched *q,
1207                                  struct sched_gate_list *sched,
1208                                  struct netlink_ext_ack *extack)
1209 {
1210         const struct net_device_ops *ops = dev->netdev_ops;
1211         struct tc_taprio_qopt_offload *offload;
1212         int err = 0;
1213
1214         if (!ops->ndo_setup_tc) {
1215                 NL_SET_ERR_MSG(extack,
1216                                "Device does not support taprio offload");
1217                 return -EOPNOTSUPP;
1218         }
1219
1220         offload = taprio_offload_alloc(sched->num_entries);
1221         if (!offload) {
1222                 NL_SET_ERR_MSG(extack,
1223                                "Not enough memory for enabling offload mode");
1224                 return -ENOMEM;
1225         }
1226         offload->enable = 1;
1227         taprio_sched_to_offload(q, sched, mqprio, offload);
1228
1229         err = ops->ndo_setup_tc(dev, TC_SETUP_QDISC_TAPRIO, offload);
1230         if (err < 0) {
1231                 NL_SET_ERR_MSG(extack,
1232                                "Device failed to setup taprio offload");
1233                 goto done;
1234         }
1235
1236 done:
1237         taprio_offload_free(offload);
1238
1239         return err;
1240 }
1241
1242 static int taprio_disable_offload(struct net_device *dev,
1243                                   struct taprio_sched *q,
1244                                   struct netlink_ext_ack *extack)
1245 {
1246         const struct net_device_ops *ops = dev->netdev_ops;
1247         struct tc_taprio_qopt_offload *offload;
1248         int err;
1249
1250         if (!FULL_OFFLOAD_IS_ENABLED(q->flags))
1251                 return 0;
1252
1253         if (!ops->ndo_setup_tc)
1254                 return -EOPNOTSUPP;
1255
1256         offload = taprio_offload_alloc(0);
1257         if (!offload) {
1258                 NL_SET_ERR_MSG(extack,
1259                                "Not enough memory to disable offload mode");
1260                 return -ENOMEM;
1261         }
1262         offload->enable = 0;
1263
1264         err = ops->ndo_setup_tc(dev, TC_SETUP_QDISC_TAPRIO, offload);
1265         if (err < 0) {
1266                 NL_SET_ERR_MSG(extack,
1267                                "Device failed to disable offload");
1268                 goto out;
1269         }
1270
1271 out:
1272         taprio_offload_free(offload);
1273
1274         return err;
1275 }
1276
1277 /* If full offload is enabled, the only possible clockid is the net device's
1278  * PHC. For that reason, specifying a clockid through netlink is incorrect.
1279  * For txtime-assist, it is implicitly assumed that the device's PHC is kept
1280  * in sync with the specified clockid via a user space daemon such as phc2sys.
1281  * For both software taprio and txtime-assist, the clockid is used for the
1282  * hrtimer that advances the schedule and hence mandatory.
1283  */
1284 static int taprio_parse_clockid(struct Qdisc *sch, struct nlattr **tb,
1285                                 struct netlink_ext_ack *extack)
1286 {
1287         struct taprio_sched *q = qdisc_priv(sch);
1288         struct net_device *dev = qdisc_dev(sch);
1289         int err = -EINVAL;
1290
1291         if (FULL_OFFLOAD_IS_ENABLED(q->flags)) {
1292                 const struct ethtool_ops *ops = dev->ethtool_ops;
1293                 struct ethtool_ts_info info = {
1294                         .cmd = ETHTOOL_GET_TS_INFO,
1295                         .phc_index = -1,
1296                 };
1297
1298                 if (tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]) {
1299                         NL_SET_ERR_MSG(extack,
1300                                        "The 'clockid' cannot be specified for full offload");
1301                         goto out;
1302                 }
1303
1304                 if (ops && ops->get_ts_info)
1305                         err = ops->get_ts_info(dev, &info);
1306
1307                 if (err || info.phc_index < 0) {
1308                         NL_SET_ERR_MSG(extack,
1309                                        "Device does not have a PTP clock");
1310                         err = -ENOTSUPP;
1311                         goto out;
1312                 }
1313         } else if (tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]) {
1314                 int clockid = nla_get_s32(tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]);
1315
1316                 /* We only support static clockids and we don't allow
1317                  * for it to be modified after the first init.
1318                  */
1319                 if (clockid < 0 ||
1320                     (q->clockid != -1 && q->clockid != clockid)) {
1321                         NL_SET_ERR_MSG(extack,
1322                                        "Changing the 'clockid' of a running schedule is not supported");
1323                         err = -ENOTSUPP;
1324                         goto out;
1325                 }
1326
1327                 switch (clockid) {
1328                 case CLOCK_REALTIME:
1329                         q->tk_offset = TK_OFFS_REAL;
1330                         break;
1331                 case CLOCK_MONOTONIC:
1332                         q->tk_offset = TK_OFFS_MAX;
1333                         break;
1334                 case CLOCK_BOOTTIME:
1335                         q->tk_offset = TK_OFFS_BOOT;
1336                         break;
1337                 case CLOCK_TAI:
1338                         q->tk_offset = TK_OFFS_TAI;
1339                         break;
1340                 default:
1341                         NL_SET_ERR_MSG(extack, "Invalid 'clockid'");
1342                         err = -EINVAL;
1343                         goto out;
1344                 }
1345
1346                 q->clockid = clockid;
1347         } else {
1348                 NL_SET_ERR_MSG(extack, "Specifying a 'clockid' is mandatory");
1349                 goto out;
1350         }
1351
1352         /* Everything went ok, return success. */
1353         err = 0;
1354
1355 out:
1356         return err;
1357 }
1358
1359 static int taprio_mqprio_cmp(const struct net_device *dev,
1360                              const struct tc_mqprio_qopt *mqprio)
1361 {
1362         int i;
1363
1364         if (!mqprio || mqprio->num_tc != dev->num_tc)
1365                 return -1;
1366
1367         for (i = 0; i < mqprio->num_tc; i++)
1368                 if (dev->tc_to_txq[i].count != mqprio->count[i] ||
1369                     dev->tc_to_txq[i].offset != mqprio->offset[i])
1370                         return -1;
1371
1372         for (i = 0; i <= TC_BITMASK; i++)
1373                 if (dev->prio_tc_map[i] != mqprio->prio_tc_map[i])
1374                         return -1;
1375
1376         return 0;
1377 }
1378
1379 /* The semantics of the 'flags' argument in relation to 'change()'
1380  * requests, are interpreted following two rules (which are applied in
1381  * this order): (1) an omitted 'flags' argument is interpreted as
1382  * zero; (2) the 'flags' of a "running" taprio instance cannot be
1383  * changed.
1384  */
1385 static int taprio_new_flags(const struct nlattr *attr, u32 old,
1386                             struct netlink_ext_ack *extack)
1387 {
1388         u32 new = 0;
1389
1390         if (attr)
1391                 new = nla_get_u32(attr);
1392
1393         if (old != TAPRIO_FLAGS_INVALID && old != new) {
1394                 NL_SET_ERR_MSG_MOD(extack, "Changing 'flags' of a running schedule is not supported");
1395                 return -EOPNOTSUPP;
1396         }
1397
1398         if (!taprio_flags_valid(new)) {
1399                 NL_SET_ERR_MSG_MOD(extack, "Specified 'flags' are not valid");
1400                 return -EINVAL;
1401         }
1402
1403         return new;
1404 }
1405
1406 static int taprio_change(struct Qdisc *sch, struct nlattr *opt,
1407                          struct netlink_ext_ack *extack)
1408 {
1409         struct nlattr *tb[TCA_TAPRIO_ATTR_MAX + 1] = { };
1410         struct sched_gate_list *oper, *admin, *new_admin;
1411         struct taprio_sched *q = qdisc_priv(sch);
1412         struct net_device *dev = qdisc_dev(sch);
1413         struct tc_mqprio_qopt *mqprio = NULL;
1414         unsigned long flags;
1415         ktime_t start;
1416         int i, err;
1417
1418         err = nla_parse_nested_deprecated(tb, TCA_TAPRIO_ATTR_MAX, opt,
1419                                           taprio_policy, extack);
1420         if (err < 0)
1421                 return err;
1422
1423         if (tb[TCA_TAPRIO_ATTR_PRIOMAP])
1424                 mqprio = nla_data(tb[TCA_TAPRIO_ATTR_PRIOMAP]);
1425
1426         err = taprio_new_flags(tb[TCA_TAPRIO_ATTR_FLAGS],
1427                                q->flags, extack);
1428         if (err < 0)
1429                 return err;
1430
1431         q->flags = err;
1432
1433         err = taprio_parse_mqprio_opt(dev, mqprio, extack, q->flags);
1434         if (err < 0)
1435                 return err;
1436
1437         new_admin = kzalloc(sizeof(*new_admin), GFP_KERNEL);
1438         if (!new_admin) {
1439                 NL_SET_ERR_MSG(extack, "Not enough memory for a new schedule");
1440                 return -ENOMEM;
1441         }
1442         INIT_LIST_HEAD(&new_admin->entries);
1443
1444         rcu_read_lock();
1445         oper = rcu_dereference(q->oper_sched);
1446         admin = rcu_dereference(q->admin_sched);
1447         rcu_read_unlock();
1448
1449         /* no changes - no new mqprio settings */
1450         if (!taprio_mqprio_cmp(dev, mqprio))
1451                 mqprio = NULL;
1452
1453         if (mqprio && (oper || admin)) {
1454                 NL_SET_ERR_MSG(extack, "Changing the traffic mapping of a running schedule is not supported");
1455                 err = -ENOTSUPP;
1456                 goto free_sched;
1457         }
1458
1459         err = parse_taprio_schedule(tb, new_admin, extack);
1460         if (err < 0)
1461                 goto free_sched;
1462
1463         if (new_admin->num_entries == 0) {
1464                 NL_SET_ERR_MSG(extack, "There should be at least one entry in the schedule");
1465                 err = -EINVAL;
1466                 goto free_sched;
1467         }
1468
1469         err = taprio_parse_clockid(sch, tb, extack);
1470         if (err < 0)
1471                 goto free_sched;
1472
1473         taprio_set_picos_per_byte(dev, q);
1474
1475         if (mqprio) {
1476                 netdev_set_num_tc(dev, mqprio->num_tc);
1477                 for (i = 0; i < mqprio->num_tc; i++)
1478                         netdev_set_tc_queue(dev, i,
1479                                             mqprio->count[i],
1480                                             mqprio->offset[i]);
1481
1482                 /* Always use supplied priority mappings */
1483                 for (i = 0; i <= TC_BITMASK; i++)
1484                         netdev_set_prio_tc_map(dev, i,
1485                                                mqprio->prio_tc_map[i]);
1486         }
1487
1488         if (FULL_OFFLOAD_IS_ENABLED(q->flags))
1489                 err = taprio_enable_offload(dev, mqprio, q, new_admin, extack);
1490         else
1491                 err = taprio_disable_offload(dev, q, extack);
1492         if (err)
1493                 goto free_sched;
1494
1495         /* Protects against enqueue()/dequeue() */
1496         spin_lock_bh(qdisc_lock(sch));
1497
1498         if (tb[TCA_TAPRIO_ATTR_TXTIME_DELAY]) {
1499                 if (!TXTIME_ASSIST_IS_ENABLED(q->flags)) {
1500                         NL_SET_ERR_MSG_MOD(extack, "txtime-delay can only be set when txtime-assist mode is enabled");
1501                         err = -EINVAL;
1502                         goto unlock;
1503                 }
1504
1505                 q->txtime_delay = nla_get_u32(tb[TCA_TAPRIO_ATTR_TXTIME_DELAY]);
1506         }
1507
1508         if (!TXTIME_ASSIST_IS_ENABLED(q->flags) &&
1509             !FULL_OFFLOAD_IS_ENABLED(q->flags) &&
1510             !hrtimer_active(&q->advance_timer)) {
1511                 hrtimer_init(&q->advance_timer, q->clockid, HRTIMER_MODE_ABS);
1512                 q->advance_timer.function = advance_sched;
1513         }
1514
1515         if (FULL_OFFLOAD_IS_ENABLED(q->flags)) {
1516                 q->dequeue = taprio_dequeue_offload;
1517                 q->peek = taprio_peek_offload;
1518         } else {
1519                 /* Be sure to always keep the function pointers
1520                  * in a consistent state.
1521                  */
1522                 q->dequeue = taprio_dequeue_soft;
1523                 q->peek = taprio_peek_soft;
1524         }
1525
1526         err = taprio_get_start_time(sch, new_admin, &start);
1527         if (err < 0) {
1528                 NL_SET_ERR_MSG(extack, "Internal error: failed get start time");
1529                 goto unlock;
1530         }
1531
1532         setup_txtime(q, new_admin, start);
1533
1534         if (TXTIME_ASSIST_IS_ENABLED(q->flags)) {
1535                 if (!oper) {
1536                         rcu_assign_pointer(q->oper_sched, new_admin);
1537                         err = 0;
1538                         new_admin = NULL;
1539                         goto unlock;
1540                 }
1541
1542                 rcu_assign_pointer(q->admin_sched, new_admin);
1543                 if (admin)
1544                         call_rcu(&admin->rcu, taprio_free_sched_cb);
1545         } else {
1546                 setup_first_close_time(q, new_admin, start);
1547
1548                 /* Protects against advance_sched() */
1549                 spin_lock_irqsave(&q->current_entry_lock, flags);
1550
1551                 taprio_start_sched(sch, start, new_admin);
1552
1553                 rcu_assign_pointer(q->admin_sched, new_admin);
1554                 if (admin)
1555                         call_rcu(&admin->rcu, taprio_free_sched_cb);
1556
1557                 spin_unlock_irqrestore(&q->current_entry_lock, flags);
1558
1559                 if (FULL_OFFLOAD_IS_ENABLED(q->flags))
1560                         taprio_offload_config_changed(q);
1561         }
1562
1563         new_admin = NULL;
1564         err = 0;
1565
1566 unlock:
1567         spin_unlock_bh(qdisc_lock(sch));
1568
1569 free_sched:
1570         if (new_admin)
1571                 call_rcu(&new_admin->rcu, taprio_free_sched_cb);
1572
1573         return err;
1574 }
1575
1576 static void taprio_destroy(struct Qdisc *sch)
1577 {
1578         struct taprio_sched *q = qdisc_priv(sch);
1579         struct net_device *dev = qdisc_dev(sch);
1580         unsigned int i;
1581
1582         spin_lock(&taprio_list_lock);
1583         list_del(&q->taprio_list);
1584         spin_unlock(&taprio_list_lock);
1585
1586         hrtimer_cancel(&q->advance_timer);
1587
1588         taprio_disable_offload(dev, q, NULL);
1589
1590         if (q->qdiscs) {
1591                 for (i = 0; i < dev->num_tx_queues && q->qdiscs[i]; i++)
1592                         qdisc_put(q->qdiscs[i]);
1593
1594                 kfree(q->qdiscs);
1595         }
1596         q->qdiscs = NULL;
1597
1598         netdev_reset_tc(dev);
1599
1600         if (q->oper_sched)
1601                 call_rcu(&q->oper_sched->rcu, taprio_free_sched_cb);
1602
1603         if (q->admin_sched)
1604                 call_rcu(&q->admin_sched->rcu, taprio_free_sched_cb);
1605 }
1606
1607 static int taprio_init(struct Qdisc *sch, struct nlattr *opt,
1608                        struct netlink_ext_ack *extack)
1609 {
1610         struct taprio_sched *q = qdisc_priv(sch);
1611         struct net_device *dev = qdisc_dev(sch);
1612         int i;
1613
1614         spin_lock_init(&q->current_entry_lock);
1615
1616         hrtimer_init(&q->advance_timer, CLOCK_TAI, HRTIMER_MODE_ABS);
1617         q->advance_timer.function = advance_sched;
1618
1619         q->dequeue = taprio_dequeue_soft;
1620         q->peek = taprio_peek_soft;
1621
1622         q->root = sch;
1623
1624         /* We only support static clockids. Use an invalid value as default
1625          * and get the valid one on taprio_change().
1626          */
1627         q->clockid = -1;
1628         q->flags = TAPRIO_FLAGS_INVALID;
1629
1630         spin_lock(&taprio_list_lock);
1631         list_add(&q->taprio_list, &taprio_list);
1632         spin_unlock(&taprio_list_lock);
1633
1634         if (sch->parent != TC_H_ROOT)
1635                 return -EOPNOTSUPP;
1636
1637         if (!netif_is_multiqueue(dev))
1638                 return -EOPNOTSUPP;
1639
1640         /* pre-allocate qdisc, attachment can't fail */
1641         q->qdiscs = kcalloc(dev->num_tx_queues,
1642                             sizeof(q->qdiscs[0]),
1643                             GFP_KERNEL);
1644
1645         if (!q->qdiscs)
1646                 return -ENOMEM;
1647
1648         if (!opt)
1649                 return -EINVAL;
1650
1651         for (i = 0; i < dev->num_tx_queues; i++) {
1652                 struct netdev_queue *dev_queue;
1653                 struct Qdisc *qdisc;
1654
1655                 dev_queue = netdev_get_tx_queue(dev, i);
1656                 qdisc = qdisc_create_dflt(dev_queue,
1657                                           &pfifo_qdisc_ops,
1658                                           TC_H_MAKE(TC_H_MAJ(sch->handle),
1659                                                     TC_H_MIN(i + 1)),
1660                                           extack);
1661                 if (!qdisc)
1662                         return -ENOMEM;
1663
1664                 if (i < dev->real_num_tx_queues)
1665                         qdisc_hash_add(qdisc, false);
1666
1667                 q->qdiscs[i] = qdisc;
1668         }
1669
1670         return taprio_change(sch, opt, extack);
1671 }
1672
1673 static struct netdev_queue *taprio_queue_get(struct Qdisc *sch,
1674                                              unsigned long cl)
1675 {
1676         struct net_device *dev = qdisc_dev(sch);
1677         unsigned long ntx = cl - 1;
1678
1679         if (ntx >= dev->num_tx_queues)
1680                 return NULL;
1681
1682         return netdev_get_tx_queue(dev, ntx);
1683 }
1684
1685 static int taprio_graft(struct Qdisc *sch, unsigned long cl,
1686                         struct Qdisc *new, struct Qdisc **old,
1687                         struct netlink_ext_ack *extack)
1688 {
1689         struct taprio_sched *q = qdisc_priv(sch);
1690         struct net_device *dev = qdisc_dev(sch);
1691         struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
1692
1693         if (!dev_queue)
1694                 return -EINVAL;
1695
1696         if (dev->flags & IFF_UP)
1697                 dev_deactivate(dev);
1698
1699         *old = q->qdiscs[cl - 1];
1700         q->qdiscs[cl - 1] = new;
1701
1702         if (new)
1703                 new->flags |= TCQ_F_ONETXQUEUE | TCQ_F_NOPARENT;
1704
1705         if (dev->flags & IFF_UP)
1706                 dev_activate(dev);
1707
1708         return 0;
1709 }
1710
1711 static int dump_entry(struct sk_buff *msg,
1712                       const struct sched_entry *entry)
1713 {
1714         struct nlattr *item;
1715
1716         item = nla_nest_start_noflag(msg, TCA_TAPRIO_SCHED_ENTRY);
1717         if (!item)
1718                 return -ENOSPC;
1719
1720         if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_INDEX, entry->index))
1721                 goto nla_put_failure;
1722
1723         if (nla_put_u8(msg, TCA_TAPRIO_SCHED_ENTRY_CMD, entry->command))
1724                 goto nla_put_failure;
1725
1726         if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_GATE_MASK,
1727                         entry->gate_mask))
1728                 goto nla_put_failure;
1729
1730         if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_INTERVAL,
1731                         entry->interval))
1732                 goto nla_put_failure;
1733
1734         return nla_nest_end(msg, item);
1735
1736 nla_put_failure:
1737         nla_nest_cancel(msg, item);
1738         return -1;
1739 }
1740
1741 static int dump_schedule(struct sk_buff *msg,
1742                          const struct sched_gate_list *root)
1743 {
1744         struct nlattr *entry_list;
1745         struct sched_entry *entry;
1746
1747         if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_BASE_TIME,
1748                         root->base_time, TCA_TAPRIO_PAD))
1749                 return -1;
1750
1751         if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME,
1752                         root->cycle_time, TCA_TAPRIO_PAD))
1753                 return -1;
1754
1755         if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION,
1756                         root->cycle_time_extension, TCA_TAPRIO_PAD))
1757                 return -1;
1758
1759         entry_list = nla_nest_start_noflag(msg,
1760                                            TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST);
1761         if (!entry_list)
1762                 goto error_nest;
1763
1764         list_for_each_entry(entry, &root->entries, list) {
1765                 if (dump_entry(msg, entry) < 0)
1766                         goto error_nest;
1767         }
1768
1769         nla_nest_end(msg, entry_list);
1770         return 0;
1771
1772 error_nest:
1773         nla_nest_cancel(msg, entry_list);
1774         return -1;
1775 }
1776
1777 static int taprio_dump(struct Qdisc *sch, struct sk_buff *skb)
1778 {
1779         struct taprio_sched *q = qdisc_priv(sch);
1780         struct net_device *dev = qdisc_dev(sch);
1781         struct sched_gate_list *oper, *admin;
1782         struct tc_mqprio_qopt opt = { 0 };
1783         struct nlattr *nest, *sched_nest;
1784         unsigned int i;
1785
1786         rcu_read_lock();
1787         oper = rcu_dereference(q->oper_sched);
1788         admin = rcu_dereference(q->admin_sched);
1789
1790         opt.num_tc = netdev_get_num_tc(dev);
1791         memcpy(opt.prio_tc_map, dev->prio_tc_map, sizeof(opt.prio_tc_map));
1792
1793         for (i = 0; i < netdev_get_num_tc(dev); i++) {
1794                 opt.count[i] = dev->tc_to_txq[i].count;
1795                 opt.offset[i] = dev->tc_to_txq[i].offset;
1796         }
1797
1798         nest = nla_nest_start_noflag(skb, TCA_OPTIONS);
1799         if (!nest)
1800                 goto start_error;
1801
1802         if (nla_put(skb, TCA_TAPRIO_ATTR_PRIOMAP, sizeof(opt), &opt))
1803                 goto options_error;
1804
1805         if (!FULL_OFFLOAD_IS_ENABLED(q->flags) &&
1806             nla_put_s32(skb, TCA_TAPRIO_ATTR_SCHED_CLOCKID, q->clockid))
1807                 goto options_error;
1808
1809         if (q->flags && nla_put_u32(skb, TCA_TAPRIO_ATTR_FLAGS, q->flags))
1810                 goto options_error;
1811
1812         if (q->txtime_delay &&
1813             nla_put_u32(skb, TCA_TAPRIO_ATTR_TXTIME_DELAY, q->txtime_delay))
1814                 goto options_error;
1815
1816         if (oper && dump_schedule(skb, oper))
1817                 goto options_error;
1818
1819         if (!admin)
1820                 goto done;
1821
1822         sched_nest = nla_nest_start_noflag(skb, TCA_TAPRIO_ATTR_ADMIN_SCHED);
1823         if (!sched_nest)
1824                 goto options_error;
1825
1826         if (dump_schedule(skb, admin))
1827                 goto admin_error;
1828
1829         nla_nest_end(skb, sched_nest);
1830
1831 done:
1832         rcu_read_unlock();
1833
1834         return nla_nest_end(skb, nest);
1835
1836 admin_error:
1837         nla_nest_cancel(skb, sched_nest);
1838
1839 options_error:
1840         nla_nest_cancel(skb, nest);
1841
1842 start_error:
1843         rcu_read_unlock();
1844         return -ENOSPC;
1845 }
1846
1847 static struct Qdisc *taprio_leaf(struct Qdisc *sch, unsigned long cl)
1848 {
1849         struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
1850
1851         if (!dev_queue)
1852                 return NULL;
1853
1854         return dev_queue->qdisc_sleeping;
1855 }
1856
1857 static unsigned long taprio_find(struct Qdisc *sch, u32 classid)
1858 {
1859         unsigned int ntx = TC_H_MIN(classid);
1860
1861         if (!taprio_queue_get(sch, ntx))
1862                 return 0;
1863         return ntx;
1864 }
1865
1866 static int taprio_dump_class(struct Qdisc *sch, unsigned long cl,
1867                              struct sk_buff *skb, struct tcmsg *tcm)
1868 {
1869         struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
1870
1871         tcm->tcm_parent = TC_H_ROOT;
1872         tcm->tcm_handle |= TC_H_MIN(cl);
1873         tcm->tcm_info = dev_queue->qdisc_sleeping->handle;
1874
1875         return 0;
1876 }
1877
1878 static int taprio_dump_class_stats(struct Qdisc *sch, unsigned long cl,
1879                                    struct gnet_dump *d)
1880         __releases(d->lock)
1881         __acquires(d->lock)
1882 {
1883         struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
1884
1885         sch = dev_queue->qdisc_sleeping;
1886         if (gnet_stats_copy_basic(&sch->running, d, NULL, &sch->bstats) < 0 ||
1887             qdisc_qstats_copy(d, sch) < 0)
1888                 return -1;
1889         return 0;
1890 }
1891
1892 static void taprio_walk(struct Qdisc *sch, struct qdisc_walker *arg)
1893 {
1894         struct net_device *dev = qdisc_dev(sch);
1895         unsigned long ntx;
1896
1897         if (arg->stop)
1898                 return;
1899
1900         arg->count = arg->skip;
1901         for (ntx = arg->skip; ntx < dev->num_tx_queues; ntx++) {
1902                 if (arg->fn(sch, ntx + 1, arg) < 0) {
1903                         arg->stop = 1;
1904                         break;
1905                 }
1906                 arg->count++;
1907         }
1908 }
1909
1910 static struct netdev_queue *taprio_select_queue(struct Qdisc *sch,
1911                                                 struct tcmsg *tcm)
1912 {
1913         return taprio_queue_get(sch, TC_H_MIN(tcm->tcm_parent));
1914 }
1915
1916 static const struct Qdisc_class_ops taprio_class_ops = {
1917         .graft          = taprio_graft,
1918         .leaf           = taprio_leaf,
1919         .find           = taprio_find,
1920         .walk           = taprio_walk,
1921         .dump           = taprio_dump_class,
1922         .dump_stats     = taprio_dump_class_stats,
1923         .select_queue   = taprio_select_queue,
1924 };
1925
1926 static struct Qdisc_ops taprio_qdisc_ops __read_mostly = {
1927         .cl_ops         = &taprio_class_ops,
1928         .id             = "taprio",
1929         .priv_size      = sizeof(struct taprio_sched),
1930         .init           = taprio_init,
1931         .change         = taprio_change,
1932         .destroy        = taprio_destroy,
1933         .peek           = taprio_peek,
1934         .dequeue        = taprio_dequeue,
1935         .enqueue        = taprio_enqueue,
1936         .dump           = taprio_dump,
1937         .owner          = THIS_MODULE,
1938 };
1939
1940 static struct notifier_block taprio_device_notifier = {
1941         .notifier_call = taprio_dev_notifier,
1942 };
1943
1944 static int __init taprio_module_init(void)
1945 {
1946         int err = register_netdevice_notifier(&taprio_device_notifier);
1947
1948         if (err)
1949                 return err;
1950
1951         return register_qdisc(&taprio_qdisc_ops);
1952 }
1953
1954 static void __exit taprio_module_exit(void)
1955 {
1956         unregister_qdisc(&taprio_qdisc_ops);
1957         unregister_netdevice_notifier(&taprio_device_notifier);
1958 }
1959
1960 module_init(taprio_module_init);
1961 module_exit(taprio_module_exit);
1962 MODULE_LICENSE("GPL");