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