xref: /linux/net/sched/sch_taprio.c (revision f19f2b308beb158d0e6f6eb806ced636e4ebf6ce)
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/ethtool_netlink.h>
11 #include <linux/types.h>
12 #include <linux/slab.h>
13 #include <linux/kernel.h>
14 #include <linux/string.h>
15 #include <linux/list.h>
16 #include <linux/errno.h>
17 #include <linux/skbuff.h>
18 #include <linux/math64.h>
19 #include <linux/module.h>
20 #include <linux/spinlock.h>
21 #include <linux/rcupdate.h>
22 #include <linux/time.h>
23 #include <net/gso.h>
24 #include <net/netlink.h>
25 #include <net/pkt_sched.h>
26 #include <net/pkt_cls.h>
27 #include <net/sch_generic.h>
28 #include <net/sock.h>
29 #include <net/tcp.h>
30 
31 #define TAPRIO_STAT_NOT_SET	(~0ULL)
32 
33 #include "sch_mqprio_lib.h"
34 
35 static LIST_HEAD(taprio_list);
36 static struct static_key_false taprio_have_broken_mqprio;
37 static struct static_key_false taprio_have_working_mqprio;
38 
39 #define TAPRIO_ALL_GATES_OPEN -1
40 
41 #define TXTIME_ASSIST_IS_ENABLED(flags) ((flags) & TCA_TAPRIO_ATTR_FLAG_TXTIME_ASSIST)
42 #define FULL_OFFLOAD_IS_ENABLED(flags) ((flags) & TCA_TAPRIO_ATTR_FLAG_FULL_OFFLOAD)
43 #define TAPRIO_SUPPORTED_FLAGS \
44 	(TCA_TAPRIO_ATTR_FLAG_TXTIME_ASSIST | TCA_TAPRIO_ATTR_FLAG_FULL_OFFLOAD)
45 #define TAPRIO_FLAGS_INVALID U32_MAX
46 /* Minimum value for picos_per_byte to ensure non-zero duration
47  * for minimum-sized Ethernet frames (ETH_ZLEN = 60).
48  * 60 * 17 > PSEC_PER_NSEC (1000)
49  */
50 #define TAPRIO_PICOS_PER_BYTE_MIN 17
51 
52 /* Each entry is a separate 368-byte sched_entry and, in full offload, is
53  * also composed into a per-entry offload array. The u16 nla_len admits
54  * roughly 5460 minimal 12-byte entries, pinning ~2 MiB; 1024 matches the
55  * SJA1105 schedule-table capacity (SJA1110 provides 4096) and the act_gate cap.
56  */
57 #define TAPRIO_ENTRIES_MAX	1024U
58 
59 struct sched_entry {
60 	/* Durations between this GCL entry and the GCL entry where the
61 	 * respective traffic class gate closes
62 	 */
63 	u64 gate_duration[TC_MAX_QUEUE];
64 	atomic_t budget[TC_MAX_QUEUE];
65 	/* The qdisc makes some effort so that no packet leaves
66 	 * after this time
67 	 */
68 	ktime_t gate_close_time[TC_MAX_QUEUE];
69 	struct list_head list;
70 	/* Used to calculate when to advance the schedule */
71 	ktime_t end_time;
72 	ktime_t next_txtime;
73 	int index;
74 	u32 gate_mask;
75 	u32 interval;
76 	u8 command;
77 };
78 
79 struct sched_gate_list {
80 	/* Longest non-zero contiguous gate durations per traffic class,
81 	 * or 0 if a traffic class gate never opens during the schedule.
82 	 */
83 	u64 max_open_gate_duration[TC_MAX_QUEUE];
84 	u32 max_frm_len[TC_MAX_QUEUE]; /* for the fast path */
85 	u32 max_sdu[TC_MAX_QUEUE]; /* for dump */
86 	struct rcu_head rcu;
87 	struct list_head entries;
88 	size_t num_entries;
89 	ktime_t cycle_end_time;
90 	s64 cycle_time;
91 	s64 cycle_time_extension;
92 	s64 base_time;
93 };
94 
95 struct taprio_sched {
96 	struct Qdisc **qdiscs;
97 	struct Qdisc *root;
98 	u32 flags;
99 	enum tk_offsets tk_offset;
100 	int clockid;
101 	bool offloaded;
102 	bool detected_mqprio;
103 	bool broken_mqprio;
104 	atomic64_t picos_per_byte; /* Using picoseconds because for 10Gbps+
105 				    * speeds it's sub-nanoseconds per byte
106 				    */
107 
108 	/* Protects the update side of the RCU protected current_entry */
109 	spinlock_t current_entry_lock;
110 	struct sched_entry __rcu *current_entry;
111 	struct sched_gate_list __rcu *oper_sched;
112 	struct sched_gate_list __rcu *admin_sched;
113 	struct hrtimer advance_timer;
114 	struct list_head taprio_list;
115 	int cur_txq[TC_MAX_QUEUE];
116 	u32 max_sdu[TC_MAX_QUEUE]; /* save info from the user */
117 	u32 fp[TC_QOPT_MAX_QUEUE]; /* only for dump and offloading */
118 	u32 txtime_delay;
119 };
120 
121 struct __tc_taprio_qopt_offload {
122 	refcount_t users;
123 	struct tc_taprio_qopt_offload offload;
124 };
125 
126 static void taprio_calculate_gate_durations(struct taprio_sched *q,
127 					    struct sched_gate_list *sched)
128 {
129 	struct net_device *dev = qdisc_dev(q->root);
130 	int num_tc = netdev_get_num_tc(dev);
131 	struct sched_entry *entry, *cur;
132 	int tc;
133 
134 	list_for_each_entry(entry, &sched->entries, list) {
135 		u32 gates_still_open = entry->gate_mask;
136 
137 		/* For each traffic class, calculate each open gate duration,
138 		 * starting at this schedule entry and ending at the schedule
139 		 * entry containing a gate close event for that TC.
140 		 */
141 		cur = entry;
142 
143 		do {
144 			if (!gates_still_open)
145 				break;
146 
147 			for (tc = 0; tc < num_tc; tc++) {
148 				if (!(gates_still_open & BIT(tc)))
149 					continue;
150 
151 				if (cur->gate_mask & BIT(tc))
152 					entry->gate_duration[tc] += cur->interval;
153 				else
154 					gates_still_open &= ~BIT(tc);
155 			}
156 
157 			cur = list_next_entry_circular(cur, &sched->entries, list);
158 		} while (cur != entry);
159 
160 		/* Keep track of the maximum gate duration for each traffic
161 		 * class, taking care to not confuse a traffic class which is
162 		 * temporarily closed with one that is always closed.
163 		 */
164 		for (tc = 0; tc < num_tc; tc++)
165 			if (entry->gate_duration[tc] &&
166 			    sched->max_open_gate_duration[tc] < entry->gate_duration[tc])
167 				sched->max_open_gate_duration[tc] = entry->gate_duration[tc];
168 	}
169 }
170 
171 static bool taprio_entry_allows_tx(ktime_t skb_end_time,
172 				   struct sched_entry *entry, int tc)
173 {
174 	return ktime_before(skb_end_time, entry->gate_close_time[tc]);
175 }
176 
177 static ktime_t sched_base_time(const struct sched_gate_list *sched)
178 {
179 	if (!sched)
180 		return KTIME_MAX;
181 
182 	return ns_to_ktime(sched->base_time);
183 }
184 
185 static ktime_t taprio_mono_to_any(const struct taprio_sched *q, ktime_t mono)
186 {
187 	/* This pairs with WRITE_ONCE() in taprio_parse_clockid() */
188 	enum tk_offsets tk_offset = READ_ONCE(q->tk_offset);
189 
190 	switch (tk_offset) {
191 	case TK_OFFS_MAX:
192 		return mono;
193 	default:
194 		return ktime_mono_to_any(mono, tk_offset);
195 	}
196 }
197 
198 static ktime_t taprio_get_time(const struct taprio_sched *q)
199 {
200 	return taprio_mono_to_any(q, ktime_get());
201 }
202 
203 static void taprio_free_sched_cb(struct rcu_head *head)
204 {
205 	struct sched_gate_list *sched = container_of(head, struct sched_gate_list, rcu);
206 	struct sched_entry *entry, *n;
207 
208 	list_for_each_entry_safe(entry, n, &sched->entries, list) {
209 		list_del(&entry->list);
210 		kfree(entry);
211 	}
212 
213 	kfree(sched);
214 }
215 
216 static void switch_schedules(struct taprio_sched *q,
217 			     struct sched_gate_list **admin,
218 			     struct sched_gate_list **oper)
219 {
220 	rcu_assign_pointer(q->oper_sched, *admin);
221 	rcu_assign_pointer(q->admin_sched, NULL);
222 
223 	if (*oper)
224 		call_rcu(&(*oper)->rcu, taprio_free_sched_cb);
225 
226 	*oper = *admin;
227 	*admin = NULL;
228 }
229 
230 /* Get how much time has been already elapsed in the current cycle. */
231 static s32 get_cycle_time_elapsed(struct sched_gate_list *sched, ktime_t time)
232 {
233 	ktime_t time_since_sched_start;
234 	s32 time_elapsed;
235 
236 	time_since_sched_start = ktime_sub(time, sched->base_time);
237 	div_s64_rem(time_since_sched_start, sched->cycle_time, &time_elapsed);
238 
239 	return time_elapsed;
240 }
241 
242 static ktime_t get_interval_end_time(struct sched_gate_list *sched,
243 				     struct sched_gate_list *admin,
244 				     struct sched_entry *entry,
245 				     ktime_t intv_start)
246 {
247 	s32 cycle_elapsed = get_cycle_time_elapsed(sched, intv_start);
248 	ktime_t intv_end, cycle_ext_end, cycle_end;
249 
250 	cycle_end = ktime_add_ns(intv_start, sched->cycle_time - cycle_elapsed);
251 	intv_end = ktime_add_ns(intv_start, entry->interval);
252 	cycle_ext_end = ktime_add(cycle_end, sched->cycle_time_extension);
253 
254 	if (ktime_before(intv_end, cycle_end))
255 		return intv_end;
256 	else if (admin && admin != sched &&
257 		 ktime_after(admin->base_time, cycle_end) &&
258 		 ktime_before(admin->base_time, cycle_ext_end))
259 		return admin->base_time;
260 	else
261 		return cycle_end;
262 }
263 
264 static int length_to_duration(struct taprio_sched *q, int len)
265 {
266 	return div_u64(len * atomic64_read(&q->picos_per_byte), PSEC_PER_NSEC);
267 }
268 
269 static int duration_to_length(struct taprio_sched *q, u64 duration)
270 {
271 	return div_u64(duration * PSEC_PER_NSEC, atomic64_read(&q->picos_per_byte));
272 }
273 
274 /* Sets sched->max_sdu[] and sched->max_frm_len[] to the minimum between the
275  * q->max_sdu[] requested by the user and the max_sdu dynamically determined by
276  * the maximum open gate durations at the given link speed.
277  */
278 static void taprio_update_queue_max_sdu(struct taprio_sched *q,
279 					struct sched_gate_list *sched,
280 					struct qdisc_size_table *stab)
281 {
282 	struct net_device *dev = qdisc_dev(q->root);
283 	int num_tc = netdev_get_num_tc(dev);
284 	u32 max_sdu_from_user;
285 	u32 max_sdu_dynamic;
286 	u32 max_sdu;
287 	int tc;
288 
289 	for (tc = 0; tc < num_tc; tc++) {
290 		max_sdu_from_user = q->max_sdu[tc] ?: U32_MAX;
291 
292 		/* TC gate never closes => keep the queueMaxSDU
293 		 * selected by the user
294 		 */
295 		if (sched->max_open_gate_duration[tc] == sched->cycle_time) {
296 			max_sdu_dynamic = U32_MAX;
297 		} else {
298 			u32 max_frm_len;
299 
300 			max_frm_len = duration_to_length(q, sched->max_open_gate_duration[tc]);
301 			/* Compensate for L1 overhead from size table,
302 			 * but don't let the frame size go negative
303 			 */
304 			if (stab) {
305 				max_frm_len -= stab->szopts.overhead;
306 				max_frm_len = max_t(int, max_frm_len,
307 						    dev->hard_header_len + 1);
308 			}
309 			max_sdu_dynamic = max_frm_len - dev->hard_header_len;
310 			if (max_sdu_dynamic > dev->max_mtu)
311 				max_sdu_dynamic = U32_MAX;
312 		}
313 
314 		max_sdu = min(max_sdu_dynamic, max_sdu_from_user);
315 
316 		if (max_sdu != U32_MAX) {
317 			sched->max_frm_len[tc] = max_sdu + dev->hard_header_len;
318 			WRITE_ONCE(sched->max_sdu[tc], max_sdu);
319 		} else {
320 			sched->max_frm_len[tc] = U32_MAX; /* never oversized */
321 			WRITE_ONCE(sched->max_sdu[tc], 0);
322 		}
323 	}
324 }
325 
326 /* Returns the entry corresponding to next available interval. If
327  * validate_interval is set, it only validates whether the timestamp occurs
328  * when the gate corresponding to the skb's traffic class is open.
329  */
330 static struct sched_entry *find_entry_to_transmit(struct sk_buff *skb,
331 						  struct Qdisc *sch,
332 						  struct sched_gate_list *sched,
333 						  struct sched_gate_list *admin,
334 						  ktime_t time,
335 						  ktime_t *interval_start,
336 						  ktime_t *interval_end,
337 						  bool validate_interval)
338 {
339 	ktime_t curr_intv_start, curr_intv_end, cycle_end, packet_transmit_time;
340 	ktime_t earliest_txtime = KTIME_MAX, txtime, cycle, transmit_end_time;
341 	struct sched_entry *entry = NULL, *entry_found = NULL;
342 	struct taprio_sched *q = qdisc_priv(sch);
343 	struct net_device *dev = qdisc_dev(sch);
344 	bool entry_available = false;
345 	s32 cycle_elapsed;
346 	int tc, n;
347 
348 	tc = netdev_get_prio_tc_map(dev, skb->priority);
349 	packet_transmit_time = length_to_duration(q, qdisc_pkt_len(skb));
350 
351 	*interval_start = 0;
352 	*interval_end = 0;
353 
354 	if (!sched)
355 		return NULL;
356 
357 	cycle = sched->cycle_time;
358 	cycle_elapsed = get_cycle_time_elapsed(sched, time);
359 	curr_intv_end = ktime_sub_ns(time, cycle_elapsed);
360 	cycle_end = ktime_add_ns(curr_intv_end, cycle);
361 
362 	list_for_each_entry(entry, &sched->entries, list) {
363 		curr_intv_start = curr_intv_end;
364 		curr_intv_end = get_interval_end_time(sched, admin, entry,
365 						      curr_intv_start);
366 
367 		if (ktime_after(curr_intv_start, cycle_end))
368 			break;
369 
370 		if (!(entry->gate_mask & BIT(tc)) ||
371 		    packet_transmit_time > entry->interval)
372 			continue;
373 
374 		txtime = entry->next_txtime;
375 
376 		if (ktime_before(txtime, time) || validate_interval) {
377 			transmit_end_time = ktime_add_ns(time, packet_transmit_time);
378 			if ((ktime_before(curr_intv_start, time) &&
379 			     ktime_before(transmit_end_time, curr_intv_end)) ||
380 			    (ktime_after(curr_intv_start, time) && !validate_interval)) {
381 				entry_found = entry;
382 				*interval_start = curr_intv_start;
383 				*interval_end = curr_intv_end;
384 				break;
385 			} else if (!entry_available && !validate_interval) {
386 				/* Here, we are just trying to find out the
387 				 * first available interval in the next cycle.
388 				 */
389 				entry_available = true;
390 				entry_found = entry;
391 				*interval_start = ktime_add_ns(curr_intv_start, cycle);
392 				*interval_end = ktime_add_ns(curr_intv_end, cycle);
393 			}
394 		} else if (ktime_before(txtime, earliest_txtime) &&
395 			   !entry_available) {
396 			earliest_txtime = txtime;
397 			entry_found = entry;
398 			n = div_s64(ktime_sub(txtime, curr_intv_start), cycle);
399 			*interval_start = ktime_add(curr_intv_start, n * cycle);
400 			*interval_end = ktime_add(curr_intv_end, n * cycle);
401 		}
402 	}
403 
404 	return entry_found;
405 }
406 
407 static bool is_valid_interval(struct sk_buff *skb, struct Qdisc *sch)
408 {
409 	struct taprio_sched *q = qdisc_priv(sch);
410 	struct sched_gate_list *sched, *admin;
411 	ktime_t interval_start, interval_end;
412 	struct sched_entry *entry;
413 
414 	rcu_read_lock();
415 	sched = rcu_dereference(q->oper_sched);
416 	admin = rcu_dereference(q->admin_sched);
417 
418 	entry = find_entry_to_transmit(skb, sch, sched, admin, skb->tstamp,
419 				       &interval_start, &interval_end, true);
420 	rcu_read_unlock();
421 
422 	return entry;
423 }
424 
425 /* This returns the tstamp value set by TCP in terms of the set clock. */
426 static ktime_t get_tcp_tstamp(struct taprio_sched *q, struct sk_buff *skb)
427 {
428 	unsigned int offset = skb_network_offset(skb);
429 	const struct ipv6hdr *ipv6h;
430 	const struct iphdr *iph;
431 	struct ipv6hdr _ipv6h;
432 
433 	ipv6h = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
434 	if (!ipv6h)
435 		return 0;
436 
437 	if (ipv6h->version == 4) {
438 		iph = (struct iphdr *)ipv6h;
439 		offset += iph->ihl * 4;
440 
441 		/* special-case 6in4 tunnelling, as that is a common way to get
442 		 * v6 connectivity in the home
443 		 */
444 		if (iph->protocol == IPPROTO_IPV6) {
445 			ipv6h = skb_header_pointer(skb, offset,
446 						   sizeof(_ipv6h), &_ipv6h);
447 
448 			if (!ipv6h || ipv6h->nexthdr != IPPROTO_TCP)
449 				return 0;
450 		} else if (iph->protocol != IPPROTO_TCP) {
451 			return 0;
452 		}
453 	} else if (ipv6h->version == 6 && ipv6h->nexthdr != IPPROTO_TCP) {
454 		return 0;
455 	}
456 
457 	return taprio_mono_to_any(q, skb->skb_mstamp_ns);
458 }
459 
460 /* There are a few scenarios where we will have to modify the txtime from
461  * what is read from next_txtime in sched_entry. They are:
462  * 1. If txtime is in the past,
463  *    a. The gate for the traffic class is currently open and packet can be
464  *       transmitted before it closes, schedule the packet right away.
465  *    b. If the gate corresponding to the traffic class is going to open later
466  *       in the cycle, set the txtime of packet to the interval start.
467  * 2. If txtime is in the future, there are packets corresponding to the
468  *    current traffic class waiting to be transmitted. So, the following
469  *    possibilities exist:
470  *    a. We can transmit the packet before the window containing the txtime
471  *       closes.
472  *    b. The window might close before the transmission can be completed
473  *       successfully. So, schedule the packet in the next open window.
474  */
475 static long get_packet_txtime(struct sk_buff *skb, struct Qdisc *sch)
476 {
477 	ktime_t transmit_end_time, interval_end, interval_start, tcp_tstamp;
478 	struct taprio_sched *q = qdisc_priv(sch);
479 	struct sched_gate_list *sched, *admin;
480 	ktime_t minimum_time, now, txtime;
481 	int len, packet_transmit_time;
482 	struct sched_entry *entry;
483 	bool sched_changed;
484 
485 	now = taprio_get_time(q);
486 	minimum_time = ktime_add_ns(now, q->txtime_delay);
487 
488 	tcp_tstamp = get_tcp_tstamp(q, skb);
489 	minimum_time = max_t(ktime_t, minimum_time, tcp_tstamp);
490 
491 	rcu_read_lock();
492 	admin = rcu_dereference(q->admin_sched);
493 	sched = rcu_dereference(q->oper_sched);
494 	if (admin && ktime_after(minimum_time, admin->base_time))
495 		switch_schedules(q, &admin, &sched);
496 
497 	/* Until the schedule starts, all the queues are open */
498 	if (!sched || ktime_before(minimum_time, sched->base_time)) {
499 		txtime = minimum_time;
500 		goto done;
501 	}
502 
503 	len = qdisc_pkt_len(skb);
504 	packet_transmit_time = length_to_duration(q, len);
505 
506 	do {
507 		sched_changed = false;
508 
509 		entry = find_entry_to_transmit(skb, sch, sched, admin,
510 					       minimum_time,
511 					       &interval_start, &interval_end,
512 					       false);
513 		if (!entry) {
514 			txtime = 0;
515 			goto done;
516 		}
517 
518 		txtime = entry->next_txtime;
519 		txtime = max_t(ktime_t, txtime, minimum_time);
520 		txtime = max_t(ktime_t, txtime, interval_start);
521 
522 		if (admin && admin != sched &&
523 		    ktime_after(txtime, admin->base_time)) {
524 			sched = admin;
525 			sched_changed = true;
526 			continue;
527 		}
528 
529 		transmit_end_time = ktime_add(txtime, packet_transmit_time);
530 		minimum_time = transmit_end_time;
531 
532 		/* Update the txtime of current entry to the next time it's
533 		 * interval starts.
534 		 */
535 		if (ktime_after(transmit_end_time, interval_end))
536 			entry->next_txtime = ktime_add(interval_start, sched->cycle_time);
537 	} while (sched_changed || ktime_after(transmit_end_time, interval_end));
538 
539 	entry->next_txtime = transmit_end_time;
540 
541 done:
542 	rcu_read_unlock();
543 	return txtime;
544 }
545 
546 /* Devices with full offload are expected to honor this in hardware */
547 static bool taprio_skb_exceeds_queue_max_sdu(struct Qdisc *sch,
548 					     struct sk_buff *skb)
549 {
550 	struct taprio_sched *q = qdisc_priv(sch);
551 	struct net_device *dev = qdisc_dev(sch);
552 	struct sched_gate_list *sched;
553 	int prio = skb->priority;
554 	bool exceeds = false;
555 	u8 tc;
556 
557 	tc = netdev_get_prio_tc_map(dev, prio);
558 
559 	rcu_read_lock();
560 	sched = rcu_dereference(q->oper_sched);
561 	if (sched && skb->len > sched->max_frm_len[tc])
562 		exceeds = true;
563 	rcu_read_unlock();
564 
565 	return exceeds;
566 }
567 
568 static int taprio_enqueue_one(struct sk_buff *skb, struct Qdisc *sch,
569 			      struct Qdisc *child, struct sk_buff **to_free)
570 {
571 	struct taprio_sched *q = qdisc_priv(sch);
572 
573 	/* sk_flags are only safe to use on full sockets. */
574 	if (skb->sk && sk_fullsock(skb->sk) && sock_flag(skb->sk, SOCK_TXTIME)) {
575 		if (!is_valid_interval(skb, sch))
576 			return qdisc_drop(skb, sch, to_free);
577 	} else if (TXTIME_ASSIST_IS_ENABLED(q->flags)) {
578 		skb->tstamp = get_packet_txtime(skb, sch);
579 		if (!skb->tstamp)
580 			return qdisc_drop(skb, sch, to_free);
581 	}
582 
583 	qdisc_qstats_backlog_inc(sch, skb);
584 	qdisc_qlen_inc(sch);
585 
586 	return qdisc_enqueue(skb, child, to_free);
587 }
588 
589 static int taprio_enqueue_segmented(struct sk_buff *skb, struct Qdisc *sch,
590 				    struct Qdisc *child,
591 				    struct sk_buff **to_free)
592 {
593 	unsigned int slen = 0, numsegs = 0, len = qdisc_pkt_len(skb);
594 	netdev_features_t features = netif_skb_features(skb);
595 	struct sk_buff *segs, *nskb;
596 	int ret;
597 
598 	segs = skb_gso_segment(skb, features & ~NETIF_F_GSO_MASK);
599 	if (IS_ERR_OR_NULL(segs))
600 		return qdisc_drop(skb, sch, to_free);
601 
602 	skb_list_walk_safe(segs, segs, nskb) {
603 		skb_mark_not_on_list(segs);
604 		qdisc_skb_cb(segs)->pkt_len = segs->len;
605 		qdisc_skb_cb(segs)->pkt_segs = 1;
606 		slen += segs->len;
607 
608 		/* FIXME: we should be segmenting to a smaller size
609 		 * rather than dropping these
610 		 */
611 		if (taprio_skb_exceeds_queue_max_sdu(sch, segs))
612 			ret = qdisc_drop(segs, sch, to_free);
613 		else
614 			ret = taprio_enqueue_one(segs, sch, child, to_free);
615 
616 		if (ret != NET_XMIT_SUCCESS) {
617 			if (net_xmit_drop_count(ret))
618 				qdisc_qstats_drop(sch);
619 		} else {
620 			numsegs++;
621 		}
622 	}
623 
624 	if (numsegs > 1)
625 		qdisc_tree_reduce_backlog(sch, 1 - numsegs, len - slen);
626 	consume_skb(skb);
627 
628 	return numsegs > 0 ? NET_XMIT_SUCCESS : NET_XMIT_DROP;
629 }
630 
631 /* Will not be called in the full offload case, since the TX queues are
632  * attached to the Qdisc created using qdisc_create_dflt()
633  */
634 static int taprio_enqueue(struct sk_buff *skb, struct Qdisc *sch,
635 			  struct sk_buff **to_free)
636 {
637 	struct taprio_sched *q = qdisc_priv(sch);
638 	struct Qdisc *child;
639 	int queue;
640 
641 	queue = skb_get_queue_mapping(skb);
642 	if (unlikely(queue >= qdisc_dev(sch)->real_num_tx_queues)) {
643 		/* A tc BPF program may have stored an out-of-range mapping. */
644 		queue = netdev_cap_txqueue(qdisc_dev(sch), queue);
645 		skb_set_queue_mapping(skb, queue);
646 	}
647 
648 	child = q->qdiscs[queue];
649 	if (unlikely(child == &noop_qdisc))
650 		return qdisc_drop(skb, sch, to_free);
651 
652 	if (taprio_skb_exceeds_queue_max_sdu(sch, skb)) {
653 		/* Large packets might not be transmitted when the transmission
654 		 * duration exceeds any configured interval. Therefore, segment
655 		 * the skb into smaller chunks. Drivers with full offload are
656 		 * expected to handle this in hardware.
657 		 */
658 		if (skb_is_gso(skb))
659 			return taprio_enqueue_segmented(skb, sch, child,
660 							to_free);
661 
662 		return qdisc_drop(skb, sch, to_free);
663 	}
664 
665 	return taprio_enqueue_one(skb, sch, child, to_free);
666 }
667 
668 static struct sk_buff *taprio_peek(struct Qdisc *sch)
669 {
670 	WARN_ONCE(1, "taprio only supports operating as root qdisc, peek() not implemented");
671 	return NULL;
672 }
673 
674 static void taprio_set_budgets(struct taprio_sched *q,
675 			       struct sched_gate_list *sched,
676 			       struct sched_entry *entry)
677 {
678 	struct net_device *dev = qdisc_dev(q->root);
679 	int num_tc = netdev_get_num_tc(dev);
680 	int tc, budget;
681 
682 	for (tc = 0; tc < num_tc; tc++) {
683 		/* Traffic classes which never close have infinite budget */
684 		if (entry->gate_duration[tc] == sched->cycle_time)
685 			budget = INT_MAX;
686 		else
687 			budget = div64_u64((u64)entry->gate_duration[tc] * PSEC_PER_NSEC,
688 					   atomic64_read(&q->picos_per_byte));
689 
690 		atomic_set(&entry->budget[tc], budget);
691 	}
692 }
693 
694 /* When an skb is sent, it consumes from the budget of all traffic classes */
695 static int taprio_update_budgets(struct sched_entry *entry, size_t len,
696 				 int tc_consumed, int num_tc)
697 {
698 	int tc, budget, new_budget = 0;
699 
700 	for (tc = 0; tc < num_tc; tc++) {
701 		budget = atomic_read(&entry->budget[tc]);
702 		/* Don't consume from infinite budget */
703 		if (budget == INT_MAX) {
704 			if (tc == tc_consumed)
705 				new_budget = budget;
706 			continue;
707 		}
708 
709 		if (tc == tc_consumed)
710 			new_budget = atomic_sub_return(len, &entry->budget[tc]);
711 		else
712 			atomic_sub(len, &entry->budget[tc]);
713 	}
714 
715 	return new_budget;
716 }
717 
718 static struct sk_buff *taprio_dequeue_from_txq(struct Qdisc *sch, int txq,
719 					       struct sched_entry *entry,
720 					       u32 gate_mask)
721 {
722 	struct taprio_sched *q = qdisc_priv(sch);
723 	struct net_device *dev = qdisc_dev(sch);
724 	struct Qdisc *child = q->qdiscs[txq];
725 	int num_tc = netdev_get_num_tc(dev);
726 	struct sk_buff *skb;
727 	ktime_t guard;
728 	int prio;
729 	int len;
730 	u8 tc;
731 
732 	if (unlikely(child == &noop_qdisc))
733 		return NULL;
734 
735 	if (TXTIME_ASSIST_IS_ENABLED(q->flags))
736 		goto skip_peek_checks;
737 
738 	skb = child->ops->peek(child);
739 	if (!skb)
740 		return NULL;
741 
742 	prio = skb->priority;
743 	tc = netdev_get_prio_tc_map(dev, prio);
744 
745 	if (!(gate_mask & BIT(tc)))
746 		return NULL;
747 
748 	len = qdisc_pkt_len(skb);
749 	guard = ktime_add_ns(taprio_get_time(q), length_to_duration(q, len));
750 
751 	/* In the case that there's no gate entry, there's no
752 	 * guard band ...
753 	 */
754 	if (gate_mask != TAPRIO_ALL_GATES_OPEN &&
755 	    !taprio_entry_allows_tx(guard, entry, tc))
756 		return NULL;
757 
758 	/* ... and no budget. */
759 	if (gate_mask != TAPRIO_ALL_GATES_OPEN &&
760 	    taprio_update_budgets(entry, len, tc, num_tc) < 0)
761 		return NULL;
762 
763 skip_peek_checks:
764 	skb = qdisc_dequeue_peeked(child);
765 	if (unlikely(!skb))
766 		return NULL;
767 
768 	qdisc_bstats_update(sch, skb);
769 	qdisc_qstats_backlog_dec(sch, skb);
770 	qdisc_qlen_dec(sch);
771 
772 	return skb;
773 }
774 
775 static void taprio_next_tc_txq(struct net_device *dev, int tc, int *txq)
776 {
777 	struct netdev_tc_txq res;
778 
779 	res.combined = READ_ONCE(dev->tc_to_txq[tc].combined);
780 
781 	(*txq)++;
782 	if (*txq == res.offset + res.count)
783 		*txq = res.offset;
784 }
785 
786 /* Prioritize higher traffic classes, and select among TXQs belonging to the
787  * same TC using round robin
788  */
789 static struct sk_buff *taprio_dequeue_tc_priority(struct Qdisc *sch,
790 						  struct sched_entry *entry,
791 						  u32 gate_mask)
792 {
793 	struct taprio_sched *q = qdisc_priv(sch);
794 	struct net_device *dev = qdisc_dev(sch);
795 	int num_tc = netdev_get_num_tc(dev);
796 	struct sk_buff *skb;
797 	int tc;
798 
799 	for (tc = num_tc - 1; tc >= 0; tc--) {
800 		int first_txq = q->cur_txq[tc];
801 
802 		if (!(gate_mask & BIT(tc)))
803 			continue;
804 
805 		do {
806 			skb = taprio_dequeue_from_txq(sch, q->cur_txq[tc],
807 						      entry, gate_mask);
808 
809 			taprio_next_tc_txq(dev, tc, &q->cur_txq[tc]);
810 
811 			if (q->cur_txq[tc] >= dev->num_tx_queues)
812 				q->cur_txq[tc] = first_txq;
813 
814 			if (skb)
815 				return skb;
816 		} while (q->cur_txq[tc] != first_txq);
817 	}
818 
819 	return NULL;
820 }
821 
822 /* Broken way of prioritizing smaller TXQ indices and ignoring the traffic
823  * class other than to determine whether the gate is open or not
824  */
825 static struct sk_buff *taprio_dequeue_txq_priority(struct Qdisc *sch,
826 						   struct sched_entry *entry,
827 						   u32 gate_mask)
828 {
829 	struct net_device *dev = qdisc_dev(sch);
830 	struct sk_buff *skb;
831 	int i;
832 
833 	for (i = 0; i < dev->num_tx_queues; i++) {
834 		skb = taprio_dequeue_from_txq(sch, i, entry, gate_mask);
835 		if (skb)
836 			return skb;
837 	}
838 
839 	return NULL;
840 }
841 
842 /* Will not be called in the full offload case, since the TX queues are
843  * attached to the Qdisc created using qdisc_create_dflt()
844  */
845 static struct sk_buff *taprio_dequeue(struct Qdisc *sch)
846 {
847 	struct taprio_sched *q = qdisc_priv(sch);
848 	struct sk_buff *skb = NULL;
849 	struct sched_entry *entry;
850 	u32 gate_mask;
851 
852 	rcu_read_lock();
853 	entry = rcu_dereference(q->current_entry);
854 	/* if there's no entry, it means that the schedule didn't
855 	 * start yet, so force all gates to be open, this is in
856 	 * accordance to IEEE 802.1Qbv-2015 Section 8.6.9.4.5
857 	 * "AdminGateStates"
858 	 */
859 	gate_mask = entry ? entry->gate_mask : TAPRIO_ALL_GATES_OPEN;
860 	if (!gate_mask)
861 		goto done;
862 
863 	if (static_branch_unlikely(&taprio_have_broken_mqprio) &&
864 	    !static_branch_likely(&taprio_have_working_mqprio)) {
865 		/* Single NIC kind which is broken */
866 		skb = taprio_dequeue_txq_priority(sch, entry, gate_mask);
867 	} else if (static_branch_likely(&taprio_have_working_mqprio) &&
868 		   !static_branch_unlikely(&taprio_have_broken_mqprio)) {
869 		/* Single NIC kind which prioritizes properly */
870 		skb = taprio_dequeue_tc_priority(sch, entry, gate_mask);
871 	} else {
872 		/* Mixed NIC kinds present in system, need dynamic testing */
873 		if (q->broken_mqprio)
874 			skb = taprio_dequeue_txq_priority(sch, entry, gate_mask);
875 		else
876 			skb = taprio_dequeue_tc_priority(sch, entry, gate_mask);
877 	}
878 
879 done:
880 	rcu_read_unlock();
881 
882 	return skb;
883 }
884 
885 static bool should_restart_cycle(const struct sched_gate_list *oper,
886 				 const struct sched_entry *entry)
887 {
888 	if (list_is_last(&entry->list, &oper->entries))
889 		return true;
890 
891 	if (ktime_compare(entry->end_time, oper->cycle_end_time) == 0)
892 		return true;
893 
894 	return false;
895 }
896 
897 static bool should_change_schedules(const struct sched_gate_list *admin,
898 				    const struct sched_gate_list *oper,
899 				    ktime_t end_time)
900 {
901 	ktime_t next_base_time, extension_time;
902 
903 	if (!admin)
904 		return false;
905 
906 	next_base_time = sched_base_time(admin);
907 
908 	/* This is the simple case, the end_time would fall after
909 	 * the next schedule base_time.
910 	 */
911 	if (ktime_compare(next_base_time, end_time) <= 0)
912 		return true;
913 
914 	/* This is the cycle_time_extension case, if the end_time
915 	 * plus the amount that can be extended would fall after the
916 	 * next schedule base_time, we can extend the current schedule
917 	 * for that amount.
918 	 */
919 	extension_time = ktime_add_ns(end_time, oper->cycle_time_extension);
920 
921 	/* FIXME: the IEEE 802.1Q-2018 Specification isn't clear about
922 	 * how precisely the extension should be made. So after
923 	 * conformance testing, this logic may change.
924 	 */
925 	if (ktime_compare(next_base_time, extension_time) <= 0)
926 		return true;
927 
928 	return false;
929 }
930 
931 static enum hrtimer_restart advance_sched(struct hrtimer *timer)
932 {
933 	struct taprio_sched *q = container_of(timer, struct taprio_sched,
934 					      advance_timer);
935 	struct net_device *dev = qdisc_dev(q->root);
936 	struct sched_gate_list *oper, *admin;
937 	int num_tc = netdev_get_num_tc(dev);
938 	struct sched_entry *entry, *next;
939 	struct Qdisc *sch = q->root;
940 	ktime_t end_time;
941 	int tc;
942 
943 	spin_lock(&q->current_entry_lock);
944 	entry = rcu_dereference_protected(q->current_entry,
945 					  lockdep_is_held(&q->current_entry_lock));
946 	oper = rcu_dereference_protected(q->oper_sched,
947 					 lockdep_is_held(&q->current_entry_lock));
948 	admin = rcu_dereference_protected(q->admin_sched,
949 					  lockdep_is_held(&q->current_entry_lock));
950 
951 	if (!oper)
952 		switch_schedules(q, &admin, &oper);
953 
954 	/* This can happen in two cases: 1. this is the very first run
955 	 * of this function (i.e. we weren't running any schedule
956 	 * previously); 2. The previous schedule just ended. The first
957 	 * entry of all schedules are pre-calculated during the
958 	 * schedule initialization.
959 	 */
960 	if (unlikely(!entry || entry->end_time == oper->base_time)) {
961 		next = list_first_entry(&oper->entries, struct sched_entry,
962 					list);
963 		end_time = next->end_time;
964 		goto first_run;
965 	}
966 
967 	if (should_restart_cycle(oper, entry)) {
968 		next = list_first_entry(&oper->entries, struct sched_entry,
969 					list);
970 		oper->cycle_end_time = ktime_add_ns(oper->cycle_end_time,
971 						    oper->cycle_time);
972 	} else {
973 		next = list_next_entry(entry, list);
974 	}
975 
976 	end_time = ktime_add_ns(entry->end_time, next->interval);
977 	end_time = min_t(ktime_t, end_time, oper->cycle_end_time);
978 
979 	for (tc = 0; tc < num_tc; tc++) {
980 		if (next->gate_duration[tc] == oper->cycle_time)
981 			next->gate_close_time[tc] = KTIME_MAX;
982 		else
983 			next->gate_close_time[tc] = ktime_add_ns(entry->end_time,
984 								 next->gate_duration[tc]);
985 	}
986 
987 	if (should_change_schedules(admin, oper, end_time)) {
988 		switch_schedules(q, &admin, &oper);
989 		/* After changing schedules, the next entry is the first one
990 		 * in the new schedule, with a pre-calculated end_time.
991 		 */
992 		next = list_first_entry(&oper->entries, struct sched_entry, list);
993 		end_time = next->end_time;
994 	}
995 
996 	next->end_time = end_time;
997 	taprio_set_budgets(q, oper, next);
998 
999 first_run:
1000 	rcu_assign_pointer(q->current_entry, next);
1001 	spin_unlock(&q->current_entry_lock);
1002 
1003 	hrtimer_set_expires(&q->advance_timer, end_time);
1004 
1005 	rcu_read_lock();
1006 	__netif_schedule(sch);
1007 	rcu_read_unlock();
1008 
1009 	return HRTIMER_RESTART;
1010 }
1011 
1012 static const struct nla_policy entry_policy[TCA_TAPRIO_SCHED_ENTRY_MAX + 1] = {
1013 	[TCA_TAPRIO_SCHED_ENTRY_INDEX]	   = { .type = NLA_U32 },
1014 	[TCA_TAPRIO_SCHED_ENTRY_CMD]	   = { .type = NLA_U8 },
1015 	[TCA_TAPRIO_SCHED_ENTRY_GATE_MASK] = { .type = NLA_U32 },
1016 	[TCA_TAPRIO_SCHED_ENTRY_INTERVAL]  = { .type = NLA_U32 },
1017 };
1018 
1019 static const struct nla_policy taprio_tc_policy[TCA_TAPRIO_TC_ENTRY_MAX + 1] = {
1020 	[TCA_TAPRIO_TC_ENTRY_INDEX]	   = NLA_POLICY_MAX(NLA_U32,
1021 							    TC_QOPT_MAX_QUEUE - 1),
1022 	[TCA_TAPRIO_TC_ENTRY_MAX_SDU]	   = { .type = NLA_U32 },
1023 	[TCA_TAPRIO_TC_ENTRY_FP]	   = NLA_POLICY_RANGE(NLA_U32,
1024 							      TC_FP_EXPRESS,
1025 							      TC_FP_PREEMPTIBLE),
1026 };
1027 
1028 static const struct netlink_range_validation_signed taprio_cycle_time_range = {
1029 	.min = 0,
1030 	.max = INT_MAX,
1031 };
1032 
1033 static const struct nla_policy taprio_policy[TCA_TAPRIO_ATTR_MAX + 1] = {
1034 	[TCA_TAPRIO_ATTR_PRIOMAP]	       = {
1035 		.len = sizeof(struct tc_mqprio_qopt)
1036 	},
1037 	[TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST]           = { .type = NLA_NESTED },
1038 	[TCA_TAPRIO_ATTR_SCHED_BASE_TIME]            = { .type = NLA_S64 },
1039 	[TCA_TAPRIO_ATTR_SCHED_SINGLE_ENTRY]         = { .type = NLA_NESTED },
1040 	[TCA_TAPRIO_ATTR_SCHED_CLOCKID]              = { .type = NLA_S32 },
1041 	[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME]           =
1042 		NLA_POLICY_FULL_RANGE_SIGNED(NLA_S64, &taprio_cycle_time_range),
1043 	[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION] = { .type = NLA_S64 },
1044 	[TCA_TAPRIO_ATTR_FLAGS]                      =
1045 		NLA_POLICY_MASK(NLA_U32, TAPRIO_SUPPORTED_FLAGS),
1046 	[TCA_TAPRIO_ATTR_TXTIME_DELAY]		     = { .type = NLA_U32 },
1047 	[TCA_TAPRIO_ATTR_TC_ENTRY]		     = { .type = NLA_NESTED },
1048 };
1049 
1050 static int fill_sched_entry(struct taprio_sched *q, struct nlattr **tb,
1051 			    struct sched_entry *entry,
1052 			    struct netlink_ext_ack *extack)
1053 {
1054 	int min_duration = length_to_duration(q, ETH_ZLEN);
1055 	u32 interval = 0;
1056 
1057 	if (tb[TCA_TAPRIO_SCHED_ENTRY_CMD])
1058 		entry->command = nla_get_u8(
1059 			tb[TCA_TAPRIO_SCHED_ENTRY_CMD]);
1060 
1061 	if (tb[TCA_TAPRIO_SCHED_ENTRY_GATE_MASK])
1062 		entry->gate_mask = nla_get_u32(
1063 			tb[TCA_TAPRIO_SCHED_ENTRY_GATE_MASK]);
1064 
1065 	if (tb[TCA_TAPRIO_SCHED_ENTRY_INTERVAL])
1066 		interval = nla_get_u32(
1067 			tb[TCA_TAPRIO_SCHED_ENTRY_INTERVAL]);
1068 
1069 	/* The interval should allow at least the minimum ethernet
1070 	 * frame to go out.
1071 	 */
1072 	if (interval < min_duration) {
1073 		NL_SET_ERR_MSG(extack, "Invalid interval for schedule entry");
1074 		return -EINVAL;
1075 	}
1076 
1077 	entry->interval = interval;
1078 
1079 	return 0;
1080 }
1081 
1082 static int parse_sched_entry(struct taprio_sched *q, struct nlattr *n,
1083 			     struct sched_entry *entry, int index,
1084 			     struct netlink_ext_ack *extack)
1085 {
1086 	struct nlattr *tb[TCA_TAPRIO_SCHED_ENTRY_MAX + 1] = { };
1087 	int err;
1088 
1089 	err = nla_parse_nested_deprecated(tb, TCA_TAPRIO_SCHED_ENTRY_MAX, n,
1090 					  entry_policy, NULL);
1091 	if (err < 0) {
1092 		NL_SET_ERR_MSG(extack, "Could not parse nested entry");
1093 		return -EINVAL;
1094 	}
1095 
1096 	entry->index = index;
1097 
1098 	return fill_sched_entry(q, tb, entry, extack);
1099 }
1100 
1101 static int parse_sched_list(struct taprio_sched *q, struct nlattr *list,
1102 			    struct sched_gate_list *sched,
1103 			    struct netlink_ext_ack *extack)
1104 {
1105 	struct nlattr *n;
1106 	int err, rem;
1107 	int i = 0;
1108 
1109 	if (!list)
1110 		return -EINVAL;
1111 
1112 	nla_for_each_nested(n, list, rem) {
1113 		struct sched_entry *entry;
1114 
1115 		if (nla_type(n) != TCA_TAPRIO_SCHED_ENTRY) {
1116 			NL_SET_ERR_MSG(extack, "Attribute is not of type 'entry'");
1117 			continue;
1118 		}
1119 
1120 		if (i >= TAPRIO_ENTRIES_MAX) {
1121 			NL_SET_ERR_MSG_FMT(extack,
1122 					   "Too many schedule entries, at most %u are supported",
1123 					   TAPRIO_ENTRIES_MAX);
1124 			return -E2BIG;
1125 		}
1126 
1127 		entry = kzalloc_obj(*entry);
1128 		if (!entry) {
1129 			NL_SET_ERR_MSG(extack, "Not enough memory for entry");
1130 			return -ENOMEM;
1131 		}
1132 
1133 		err = parse_sched_entry(q, n, entry, i, extack);
1134 		if (err < 0) {
1135 			kfree(entry);
1136 			return err;
1137 		}
1138 
1139 		list_add_tail(&entry->list, &sched->entries);
1140 		i++;
1141 	}
1142 
1143 	sched->num_entries = i;
1144 
1145 	return i;
1146 }
1147 
1148 static int parse_taprio_schedule(struct taprio_sched *q, struct nlattr **tb,
1149 				 struct sched_gate_list *new,
1150 				 struct netlink_ext_ack *extack)
1151 {
1152 	int err = 0;
1153 
1154 	if (tb[TCA_TAPRIO_ATTR_SCHED_SINGLE_ENTRY]) {
1155 		NL_SET_ERR_MSG(extack, "Adding a single entry is not supported");
1156 		return -ENOTSUPP;
1157 	}
1158 
1159 	if (tb[TCA_TAPRIO_ATTR_SCHED_BASE_TIME])
1160 		new->base_time = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_BASE_TIME]);
1161 
1162 	if (tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION])
1163 		new->cycle_time_extension = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION]);
1164 
1165 	if (tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME])
1166 		new->cycle_time = nla_get_s64(tb[TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME]);
1167 
1168 	if (tb[TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST])
1169 		err = parse_sched_list(q, tb[TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST],
1170 				       new, extack);
1171 	if (err < 0)
1172 		return err;
1173 
1174 	if (!new->cycle_time) {
1175 		struct sched_entry *entry;
1176 		ktime_t cycle = 0;
1177 
1178 		list_for_each_entry(entry, &new->entries, list)
1179 			cycle = ktime_add_ns(cycle, entry->interval);
1180 
1181 		if (cycle < 0 || cycle > INT_MAX) {
1182 			NL_SET_ERR_MSG(extack, "'cycle_time' is too big");
1183 			return -EINVAL;
1184 		}
1185 
1186 		new->cycle_time = cycle;
1187 	}
1188 
1189 	if (new->cycle_time < new->num_entries * length_to_duration(q, ETH_ZLEN)) {
1190 		NL_SET_ERR_MSG(extack, "'cycle_time' is too small");
1191 		return -EINVAL;
1192 	}
1193 
1194 	taprio_calculate_gate_durations(q, new);
1195 
1196 	return 0;
1197 }
1198 
1199 static int taprio_parse_mqprio_opt(struct net_device *dev,
1200 				   struct tc_mqprio_qopt *qopt,
1201 				   struct netlink_ext_ack *extack,
1202 				   u32 taprio_flags)
1203 {
1204 	bool allow_overlapping_txqs = TXTIME_ASSIST_IS_ENABLED(taprio_flags);
1205 
1206 	if (!qopt) {
1207 		if (!netdev_get_num_tc(dev)) {
1208 			NL_SET_ERR_MSG(extack, "'mqprio' configuration is necessary");
1209 			return -EINVAL;
1210 		}
1211 		return 0;
1212 	}
1213 
1214 	/* taprio imposes that traffic classes map 1:n to tx queues */
1215 	if (qopt->num_tc > dev->num_tx_queues) {
1216 		NL_SET_ERR_MSG(extack, "Number of traffic classes is greater than number of HW queues");
1217 		return -EINVAL;
1218 	}
1219 
1220 	/* For some reason, in txtime-assist mode, we allow TXQ ranges for
1221 	 * different TCs to overlap, and just validate the TXQ ranges.
1222 	 */
1223 	return mqprio_validate_qopt(dev, qopt, true, allow_overlapping_txqs,
1224 				    extack);
1225 }
1226 
1227 static int taprio_get_start_time(struct Qdisc *sch,
1228 				 struct sched_gate_list *sched,
1229 				 ktime_t *start)
1230 {
1231 	struct taprio_sched *q = qdisc_priv(sch);
1232 	ktime_t now, base, cycle;
1233 	s64 n;
1234 
1235 	base = sched_base_time(sched);
1236 	now = taprio_get_time(q);
1237 
1238 	if (ktime_after(base, now)) {
1239 		*start = base;
1240 		return 0;
1241 	}
1242 
1243 	cycle = sched->cycle_time;
1244 
1245 	/* The qdisc is expected to have at least one sched_entry.  Moreover,
1246 	 * any entry must have 'interval' > 0. Thus if the cycle time is zero,
1247 	 * something went really wrong. In that case, we should warn about this
1248 	 * inconsistent state and return error.
1249 	 */
1250 	if (WARN_ON(!cycle))
1251 		return -EFAULT;
1252 
1253 	/* Schedule the start time for the beginning of the next
1254 	 * cycle.
1255 	 */
1256 	n = div64_s64(ktime_sub_ns(now, base), cycle);
1257 	*start = ktime_add_ns(base, (n + 1) * cycle);
1258 	return 0;
1259 }
1260 
1261 static void setup_first_end_time(struct taprio_sched *q,
1262 				 struct sched_gate_list *sched, ktime_t base)
1263 {
1264 	struct net_device *dev = qdisc_dev(q->root);
1265 	int num_tc = netdev_get_num_tc(dev);
1266 	struct sched_entry *first;
1267 	ktime_t cycle;
1268 	int tc;
1269 
1270 	first = list_first_entry(&sched->entries,
1271 				 struct sched_entry, list);
1272 
1273 	cycle = sched->cycle_time;
1274 
1275 	/* FIXME: find a better place to do this */
1276 	sched->cycle_end_time = ktime_add_ns(base, cycle);
1277 
1278 	first->end_time = ktime_add_ns(base, first->interval);
1279 	taprio_set_budgets(q, sched, first);
1280 
1281 	for (tc = 0; tc < num_tc; tc++) {
1282 		if (first->gate_duration[tc] == sched->cycle_time)
1283 			first->gate_close_time[tc] = KTIME_MAX;
1284 		else
1285 			first->gate_close_time[tc] = ktime_add_ns(base, first->gate_duration[tc]);
1286 	}
1287 
1288 	rcu_assign_pointer(q->current_entry, NULL);
1289 }
1290 
1291 static void taprio_start_sched(struct Qdisc *sch,
1292 			       ktime_t start, struct sched_gate_list *new)
1293 {
1294 	struct taprio_sched *q = qdisc_priv(sch);
1295 	ktime_t expires;
1296 
1297 	if (FULL_OFFLOAD_IS_ENABLED(q->flags))
1298 		return;
1299 
1300 	expires = hrtimer_get_expires(&q->advance_timer);
1301 	if (expires == 0)
1302 		expires = KTIME_MAX;
1303 
1304 	/* If the new schedule starts before the next expiration, we
1305 	 * reprogram it to the earliest one, so we change the admin
1306 	 * schedule to the operational one at the right time.
1307 	 */
1308 	start = min_t(ktime_t, start, expires);
1309 
1310 	hrtimer_start(&q->advance_timer, start, HRTIMER_MODE_ABS);
1311 }
1312 
1313 static void taprio_set_picos_per_byte(struct net_device *dev,
1314 				      struct taprio_sched *q,
1315 				      struct netlink_ext_ack *extack)
1316 {
1317 	struct ethtool_link_ksettings ecmd;
1318 	int speed = SPEED_10;
1319 	int picos_per_byte;
1320 	int err;
1321 
1322 	err = netif_get_link_ksettings(dev, &ecmd);
1323 	if (err < 0)
1324 		goto skip;
1325 
1326 	if (ecmd.base.speed && ecmd.base.speed != SPEED_UNKNOWN)
1327 		speed = ecmd.base.speed;
1328 
1329 skip:
1330 	picos_per_byte = (USEC_PER_SEC * 8) / speed;
1331 	if (picos_per_byte < TAPRIO_PICOS_PER_BYTE_MIN) {
1332 		if (!extack)
1333 			pr_warn("Link speed %d is too high. Schedule may be inaccurate.\n",
1334 				speed);
1335 		NL_SET_ERR_MSG_FMT_MOD(extack,
1336 				       "Link speed %d is too high. Schedule may be inaccurate.",
1337 				       speed);
1338 		picos_per_byte = TAPRIO_PICOS_PER_BYTE_MIN;
1339 	}
1340 
1341 	atomic64_set(&q->picos_per_byte, picos_per_byte);
1342 	netdev_dbg(dev, "taprio: set %s's picos_per_byte to: %lld, linkspeed: %d\n",
1343 		   dev->name, (long long)atomic64_read(&q->picos_per_byte),
1344 		   speed);
1345 }
1346 
1347 static int taprio_dev_notifier(struct notifier_block *nb, unsigned long event,
1348 			       void *ptr)
1349 {
1350 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1351 	struct sched_gate_list *oper, *admin;
1352 	struct qdisc_size_table *stab;
1353 	struct taprio_sched *q;
1354 
1355 	ASSERT_RTNL();
1356 
1357 	if (event != NETDEV_UP && event != NETDEV_CHANGE)
1358 		return NOTIFY_DONE;
1359 
1360 	list_for_each_entry(q, &taprio_list, taprio_list) {
1361 		if (dev != qdisc_dev(q->root))
1362 			continue;
1363 
1364 		taprio_set_picos_per_byte(dev, q, NULL);
1365 
1366 		stab = rtnl_dereference(q->root->stab);
1367 
1368 		rcu_read_lock();
1369 		oper = rcu_dereference(q->oper_sched);
1370 		if (oper)
1371 			taprio_update_queue_max_sdu(q, oper, stab);
1372 
1373 		admin = rcu_dereference(q->admin_sched);
1374 		if (admin)
1375 			taprio_update_queue_max_sdu(q, admin, stab);
1376 		rcu_read_unlock();
1377 
1378 		break;
1379 	}
1380 
1381 	return NOTIFY_DONE;
1382 }
1383 
1384 static void setup_txtime(struct taprio_sched *q,
1385 			 struct sched_gate_list *sched, ktime_t base)
1386 {
1387 	struct sched_entry *entry;
1388 	u64 interval = 0;
1389 
1390 	list_for_each_entry(entry, &sched->entries, list) {
1391 		entry->next_txtime = ktime_add_ns(base, interval);
1392 		interval += entry->interval;
1393 	}
1394 }
1395 
1396 static struct tc_taprio_qopt_offload *taprio_offload_alloc(int num_entries)
1397 {
1398 	struct __tc_taprio_qopt_offload *__offload;
1399 
1400 	__offload = kzalloc_flex(*__offload, offload.entries, num_entries);
1401 	if (!__offload)
1402 		return NULL;
1403 
1404 	refcount_set(&__offload->users, 1);
1405 
1406 	return &__offload->offload;
1407 }
1408 
1409 struct tc_taprio_qopt_offload *taprio_offload_get(struct tc_taprio_qopt_offload
1410 						  *offload)
1411 {
1412 	struct __tc_taprio_qopt_offload *__offload;
1413 
1414 	__offload = container_of(offload, struct __tc_taprio_qopt_offload,
1415 				 offload);
1416 
1417 	refcount_inc(&__offload->users);
1418 
1419 	return offload;
1420 }
1421 EXPORT_SYMBOL_GPL(taprio_offload_get);
1422 
1423 void taprio_offload_free(struct tc_taprio_qopt_offload *offload)
1424 {
1425 	struct __tc_taprio_qopt_offload *__offload;
1426 
1427 	__offload = container_of(offload, struct __tc_taprio_qopt_offload,
1428 				 offload);
1429 
1430 	if (!refcount_dec_and_test(&__offload->users))
1431 		return;
1432 
1433 	kfree(__offload);
1434 }
1435 EXPORT_SYMBOL_GPL(taprio_offload_free);
1436 
1437 /* The function will only serve to keep the pointers to the "oper" and "admin"
1438  * schedules valid in relation to their base times, so when calling dump() the
1439  * users looks at the right schedules.
1440  * When using full offload, the admin configuration is promoted to oper at the
1441  * base_time in the PHC time domain.  But because the system time is not
1442  * necessarily in sync with that, we can't just trigger a hrtimer to call
1443  * switch_schedules at the right hardware time.
1444  * At the moment we call this by hand right away from taprio, but in the future
1445  * it will be useful to create a mechanism for drivers to notify taprio of the
1446  * offload state (PENDING, ACTIVE, INACTIVE) so it can be visible in dump().
1447  * This is left as TODO.
1448  */
1449 static void taprio_offload_config_changed(struct taprio_sched *q)
1450 {
1451 	struct sched_gate_list *oper, *admin;
1452 
1453 	oper = rtnl_dereference(q->oper_sched);
1454 	admin = rtnl_dereference(q->admin_sched);
1455 
1456 	switch_schedules(q, &admin, &oper);
1457 }
1458 
1459 static u32 tc_map_to_queue_mask(struct net_device *dev, u32 tc_mask)
1460 {
1461 	int num_tc = netdev_get_num_tc(dev);
1462 	u32 i, queue_mask = 0;
1463 
1464 	for (i = 0; i < num_tc; i++) {
1465 		struct netdev_tc_txq res;
1466 
1467 		if (!(tc_mask & BIT(i)))
1468 			continue;
1469 
1470 		res.combined = READ_ONCE(dev->tc_to_txq[i].combined);
1471 
1472 		queue_mask |= GENMASK(res.offset + res.count - 1, res.offset);
1473 	}
1474 
1475 	return queue_mask;
1476 }
1477 
1478 static void taprio_sched_to_offload(struct net_device *dev,
1479 				    struct sched_gate_list *sched,
1480 				    struct tc_taprio_qopt_offload *offload,
1481 				    const struct tc_taprio_caps *caps)
1482 {
1483 	struct sched_entry *entry;
1484 	int i = 0;
1485 
1486 	offload->base_time = sched->base_time;
1487 	offload->cycle_time = sched->cycle_time;
1488 	offload->cycle_time_extension = sched->cycle_time_extension;
1489 
1490 	list_for_each_entry(entry, &sched->entries, list) {
1491 		struct tc_taprio_sched_entry *e = &offload->entries[i];
1492 
1493 		e->command = entry->command;
1494 		e->interval = entry->interval;
1495 		if (caps->gate_mask_per_txq)
1496 			e->gate_mask = tc_map_to_queue_mask(dev,
1497 							    entry->gate_mask);
1498 		else
1499 			e->gate_mask = entry->gate_mask;
1500 
1501 		i++;
1502 	}
1503 
1504 	offload->num_entries = i;
1505 }
1506 
1507 static void taprio_detect_broken_mqprio(struct taprio_sched *q)
1508 {
1509 	struct net_device *dev = qdisc_dev(q->root);
1510 	struct tc_taprio_caps caps;
1511 
1512 	qdisc_offload_query_caps(dev, TC_SETUP_QDISC_TAPRIO,
1513 				 &caps, sizeof(caps));
1514 
1515 	q->broken_mqprio = caps.broken_mqprio;
1516 	if (q->broken_mqprio)
1517 		static_branch_inc(&taprio_have_broken_mqprio);
1518 	else
1519 		static_branch_inc(&taprio_have_working_mqprio);
1520 
1521 	q->detected_mqprio = true;
1522 }
1523 
1524 static void taprio_cleanup_broken_mqprio(struct taprio_sched *q)
1525 {
1526 	if (!q->detected_mqprio)
1527 		return;
1528 
1529 	if (q->broken_mqprio)
1530 		static_branch_dec(&taprio_have_broken_mqprio);
1531 	else
1532 		static_branch_dec(&taprio_have_working_mqprio);
1533 }
1534 
1535 static int taprio_enable_offload(struct net_device *dev,
1536 				 struct taprio_sched *q,
1537 				 struct sched_gate_list *sched,
1538 				 struct netlink_ext_ack *extack)
1539 {
1540 	const struct net_device_ops *ops = dev->netdev_ops;
1541 	struct tc_taprio_qopt_offload *offload;
1542 	struct tc_taprio_caps caps;
1543 	int tc, err = 0;
1544 
1545 	if (!ops->ndo_setup_tc) {
1546 		NL_SET_ERR_MSG(extack,
1547 			       "Device does not support taprio offload");
1548 		return -EOPNOTSUPP;
1549 	}
1550 
1551 	qdisc_offload_query_caps(dev, TC_SETUP_QDISC_TAPRIO,
1552 				 &caps, sizeof(caps));
1553 
1554 	if (!caps.supports_queue_max_sdu) {
1555 		for (tc = 0; tc < TC_MAX_QUEUE; tc++) {
1556 			if (q->max_sdu[tc]) {
1557 				NL_SET_ERR_MSG_MOD(extack,
1558 						   "Device does not handle queueMaxSDU");
1559 				return -EOPNOTSUPP;
1560 			}
1561 		}
1562 	}
1563 
1564 	offload = taprio_offload_alloc(sched->num_entries);
1565 	if (!offload) {
1566 		NL_SET_ERR_MSG(extack,
1567 			       "Not enough memory for enabling offload mode");
1568 		return -ENOMEM;
1569 	}
1570 	offload->cmd = TAPRIO_CMD_REPLACE;
1571 	offload->extack = extack;
1572 	mqprio_qopt_reconstruct(dev, &offload->mqprio.qopt);
1573 	offload->mqprio.extack = extack;
1574 	taprio_sched_to_offload(dev, sched, offload, &caps);
1575 	mqprio_fp_to_offload(q->fp, &offload->mqprio);
1576 
1577 	for (tc = 0; tc < TC_MAX_QUEUE; tc++)
1578 		offload->max_sdu[tc] = q->max_sdu[tc];
1579 
1580 	err = ops->ndo_setup_tc(dev, TC_SETUP_QDISC_TAPRIO, offload);
1581 	if (err < 0) {
1582 		NL_SET_ERR_MSG_WEAK(extack,
1583 				    "Device failed to setup taprio offload");
1584 		goto done;
1585 	}
1586 
1587 	q->offloaded = true;
1588 
1589 done:
1590 	/* The offload structure may linger around via a reference taken by the
1591 	 * device driver, so clear up the netlink extack pointer so that the
1592 	 * driver isn't tempted to dereference data which stopped being valid
1593 	 */
1594 	offload->extack = NULL;
1595 	offload->mqprio.extack = NULL;
1596 	taprio_offload_free(offload);
1597 
1598 	return err;
1599 }
1600 
1601 static int taprio_disable_offload(struct net_device *dev,
1602 				  struct taprio_sched *q,
1603 				  struct netlink_ext_ack *extack)
1604 {
1605 	const struct net_device_ops *ops = dev->netdev_ops;
1606 	struct tc_taprio_qopt_offload *offload;
1607 	int err;
1608 
1609 	if (!q->offloaded)
1610 		return 0;
1611 
1612 	offload = taprio_offload_alloc(0);
1613 	if (!offload) {
1614 		NL_SET_ERR_MSG(extack,
1615 			       "Not enough memory to disable offload mode");
1616 		return -ENOMEM;
1617 	}
1618 	offload->cmd = TAPRIO_CMD_DESTROY;
1619 
1620 	err = ops->ndo_setup_tc(dev, TC_SETUP_QDISC_TAPRIO, offload);
1621 	if (err < 0) {
1622 		NL_SET_ERR_MSG(extack,
1623 			       "Device failed to disable offload");
1624 		goto out;
1625 	}
1626 
1627 	q->offloaded = false;
1628 
1629 out:
1630 	taprio_offload_free(offload);
1631 
1632 	return err;
1633 }
1634 
1635 /* If full offload is enabled, the only possible clockid is the net device's
1636  * PHC. For that reason, specifying a clockid through netlink is incorrect.
1637  * For txtime-assist, it is implicitly assumed that the device's PHC is kept
1638  * in sync with the specified clockid via a user space daemon such as phc2sys.
1639  * For both software taprio and txtime-assist, the clockid is used for the
1640  * hrtimer that advances the schedule and hence mandatory.
1641  */
1642 static int taprio_parse_clockid(struct Qdisc *sch, struct nlattr **tb,
1643 				struct netlink_ext_ack *extack)
1644 {
1645 	struct taprio_sched *q = qdisc_priv(sch);
1646 	struct net_device *dev = qdisc_dev(sch);
1647 	int err = -EINVAL;
1648 
1649 	if (FULL_OFFLOAD_IS_ENABLED(q->flags)) {
1650 		const struct ethtool_ops *ops = dev->ethtool_ops;
1651 		struct kernel_ethtool_ts_info info = {
1652 			.cmd = ETHTOOL_GET_TS_INFO,
1653 			.phc_index = -1,
1654 		};
1655 
1656 		if (tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]) {
1657 			NL_SET_ERR_MSG(extack,
1658 				       "The 'clockid' cannot be specified for full offload");
1659 			goto out;
1660 		}
1661 
1662 		if (ops && ops->get_ts_info)
1663 			err = ops->get_ts_info(dev, &info);
1664 
1665 		if (err || info.phc_index < 0) {
1666 			NL_SET_ERR_MSG(extack,
1667 				       "Device does not have a PTP clock");
1668 			err = -ENOTSUPP;
1669 			goto out;
1670 		}
1671 	} else if (tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]) {
1672 		int clockid = nla_get_s32(tb[TCA_TAPRIO_ATTR_SCHED_CLOCKID]);
1673 		enum tk_offsets tk_offset;
1674 
1675 		/* We only support static clockids and we don't allow
1676 		 * for it to be modified after the first init.
1677 		 */
1678 		if (clockid < 0 ||
1679 		    (q->clockid != -1 && q->clockid != clockid)) {
1680 			NL_SET_ERR_MSG(extack,
1681 				       "Changing the 'clockid' of a running schedule is not supported");
1682 			err = -ENOTSUPP;
1683 			goto out;
1684 		}
1685 
1686 		switch (clockid) {
1687 		case CLOCK_REALTIME:
1688 			tk_offset = TK_OFFS_REAL;
1689 			break;
1690 		case CLOCK_MONOTONIC:
1691 			tk_offset = TK_OFFS_MAX;
1692 			break;
1693 		case CLOCK_BOOTTIME:
1694 			tk_offset = TK_OFFS_BOOT;
1695 			break;
1696 		case CLOCK_TAI:
1697 			tk_offset = TK_OFFS_TAI;
1698 			break;
1699 		default:
1700 			NL_SET_ERR_MSG(extack, "Invalid 'clockid'");
1701 			err = -EINVAL;
1702 			goto out;
1703 		}
1704 		/* This pairs with READ_ONCE() in taprio_mono_to_any */
1705 		WRITE_ONCE(q->tk_offset, tk_offset);
1706 
1707 		q->clockid = clockid;
1708 	} else {
1709 		NL_SET_ERR_MSG(extack, "Specifying a 'clockid' is mandatory");
1710 		goto out;
1711 	}
1712 
1713 	/* Everything went ok, return success. */
1714 	err = 0;
1715 
1716 out:
1717 	return err;
1718 }
1719 
1720 static int taprio_parse_tc_entry(struct Qdisc *sch,
1721 				 struct nlattr *opt,
1722 				 u32 max_sdu[TC_QOPT_MAX_QUEUE],
1723 				 u32 fp[TC_QOPT_MAX_QUEUE],
1724 				 unsigned long *seen_tcs,
1725 				 struct netlink_ext_ack *extack)
1726 {
1727 	struct nlattr *tb[TCA_TAPRIO_TC_ENTRY_MAX + 1] = { };
1728 	struct net_device *dev = qdisc_dev(sch);
1729 	int err, tc;
1730 	u32 val;
1731 
1732 	err = nla_parse_nested(tb, TCA_TAPRIO_TC_ENTRY_MAX, opt,
1733 			       taprio_tc_policy, extack);
1734 	if (err < 0)
1735 		return err;
1736 
1737 	if (NL_REQ_ATTR_CHECK(extack, opt, tb, TCA_TAPRIO_TC_ENTRY_INDEX)) {
1738 		NL_SET_ERR_MSG_MOD(extack, "TC entry index missing");
1739 		return -EINVAL;
1740 	}
1741 
1742 	tc = nla_get_u32(tb[TCA_TAPRIO_TC_ENTRY_INDEX]);
1743 	if (*seen_tcs & BIT(tc)) {
1744 		NL_SET_ERR_MSG_ATTR(extack, tb[TCA_TAPRIO_TC_ENTRY_INDEX],
1745 				    "Duplicate tc entry");
1746 		return -EINVAL;
1747 	}
1748 
1749 	*seen_tcs |= BIT(tc);
1750 
1751 	if (tb[TCA_TAPRIO_TC_ENTRY_MAX_SDU]) {
1752 		val = nla_get_u32(tb[TCA_TAPRIO_TC_ENTRY_MAX_SDU]);
1753 		if (val > dev->max_mtu) {
1754 			NL_SET_ERR_MSG_MOD(extack, "TC max SDU exceeds device max MTU");
1755 			return -ERANGE;
1756 		}
1757 
1758 		max_sdu[tc] = val;
1759 	}
1760 
1761 	if (tb[TCA_TAPRIO_TC_ENTRY_FP])
1762 		fp[tc] = nla_get_u32(tb[TCA_TAPRIO_TC_ENTRY_FP]);
1763 
1764 	return 0;
1765 }
1766 
1767 static int taprio_parse_tc_entries(struct Qdisc *sch,
1768 				   struct nlattr *opt,
1769 				   struct netlink_ext_ack *extack)
1770 {
1771 	struct taprio_sched *q = qdisc_priv(sch);
1772 	struct net_device *dev = qdisc_dev(sch);
1773 	u32 max_sdu[TC_QOPT_MAX_QUEUE];
1774 	bool have_preemption = false;
1775 	unsigned long seen_tcs = 0;
1776 	u32 fp[TC_QOPT_MAX_QUEUE];
1777 	struct nlattr *n;
1778 	int tc, rem;
1779 	int err = 0;
1780 
1781 	for (tc = 0; tc < TC_QOPT_MAX_QUEUE; tc++) {
1782 		max_sdu[tc] = q->max_sdu[tc];
1783 		fp[tc] = q->fp[tc];
1784 	}
1785 
1786 	nla_for_each_nested_type(n, TCA_TAPRIO_ATTR_TC_ENTRY, opt, rem) {
1787 		err = taprio_parse_tc_entry(sch, n, max_sdu, fp, &seen_tcs,
1788 					    extack);
1789 		if (err)
1790 			return err;
1791 	}
1792 
1793 	for (tc = 0; tc < TC_QOPT_MAX_QUEUE; tc++) {
1794 		WRITE_ONCE(q->max_sdu[tc], max_sdu[tc]);
1795 		WRITE_ONCE(q->fp[tc], fp[tc]);
1796 		if (fp[tc] != TC_FP_EXPRESS)
1797 			have_preemption = true;
1798 	}
1799 
1800 	if (have_preemption) {
1801 		if (!FULL_OFFLOAD_IS_ENABLED(q->flags)) {
1802 			NL_SET_ERR_MSG(extack,
1803 				       "Preemption only supported with full offload");
1804 			return -EOPNOTSUPP;
1805 		}
1806 
1807 		if (!ethtool_dev_mm_supported(dev)) {
1808 			NL_SET_ERR_MSG(extack,
1809 				       "Device does not support preemption");
1810 			return -EOPNOTSUPP;
1811 		}
1812 	}
1813 
1814 	return err;
1815 }
1816 
1817 static int taprio_mqprio_cmp(const struct net_device *dev,
1818 			     const struct tc_mqprio_qopt *mqprio)
1819 {
1820 	int i;
1821 
1822 	if (!mqprio || mqprio->num_tc != netdev_get_num_tc(dev))
1823 		return -1;
1824 
1825 	for (i = 0; i < mqprio->num_tc; i++) {
1826 		struct netdev_tc_txq res;
1827 
1828 		res.combined = READ_ONCE(dev->tc_to_txq[i].combined);
1829 		if (res.count != mqprio->count[i] ||
1830 		    res.offset != mqprio->offset[i])
1831 			return -1;
1832 	}
1833 
1834 	for (i = 0; i <= TC_BITMASK; i++)
1835 		if (netdev_get_prio_tc_map(dev, i) != mqprio->prio_tc_map[i])
1836 			return -1;
1837 
1838 	return 0;
1839 }
1840 
1841 static int taprio_change(struct Qdisc *sch, struct nlattr *opt,
1842 			 struct netlink_ext_ack *extack)
1843 {
1844 	struct qdisc_size_table *stab = rtnl_dereference(sch->stab);
1845 	struct nlattr *tb[TCA_TAPRIO_ATTR_MAX + 1] = { };
1846 	struct sched_gate_list *oper, *admin, *new_admin;
1847 	struct taprio_sched *q = qdisc_priv(sch);
1848 	struct net_device *dev = qdisc_dev(sch);
1849 	struct tc_mqprio_qopt *mqprio = NULL;
1850 	unsigned long flags;
1851 	u32 taprio_flags;
1852 	ktime_t start;
1853 	int i, err;
1854 
1855 	err = nla_parse_nested_deprecated(tb, TCA_TAPRIO_ATTR_MAX, opt,
1856 					  taprio_policy, extack);
1857 	if (err < 0)
1858 		return err;
1859 
1860 	if (tb[TCA_TAPRIO_ATTR_PRIOMAP])
1861 		mqprio = nla_data(tb[TCA_TAPRIO_ATTR_PRIOMAP]);
1862 
1863 	/* The semantics of the 'flags' argument in relation to 'change()'
1864 	 * requests, are interpreted following two rules (which are applied in
1865 	 * this order): (1) an omitted 'flags' argument is interpreted as
1866 	 * zero; (2) the 'flags' of a "running" taprio instance cannot be
1867 	 * changed.
1868 	 */
1869 	taprio_flags = nla_get_u32_default(tb[TCA_TAPRIO_ATTR_FLAGS], 0);
1870 
1871 	/* txtime-assist and full offload are mutually exclusive */
1872 	if ((taprio_flags & TCA_TAPRIO_ATTR_FLAG_TXTIME_ASSIST) &&
1873 	    (taprio_flags & TCA_TAPRIO_ATTR_FLAG_FULL_OFFLOAD)) {
1874 		NL_SET_ERR_MSG_ATTR(extack, tb[TCA_TAPRIO_ATTR_FLAGS],
1875 				    "TXTIME_ASSIST and FULL_OFFLOAD are mutually exclusive");
1876 		return -EINVAL;
1877 	}
1878 
1879 	if (q->flags != taprio_flags) {
1880 		if (q->flags != TAPRIO_FLAGS_INVALID) {
1881 			NL_SET_ERR_MSG_MOD(extack,
1882 					   "Changing 'flags' of a running schedule is not supported");
1883 			return -EOPNOTSUPP;
1884 		}
1885 		WRITE_ONCE(q->flags, taprio_flags);
1886 	}
1887 
1888 	/* Needed for length_to_duration() during netlink attribute parsing */
1889 	taprio_set_picos_per_byte(dev, q, extack);
1890 
1891 	err = taprio_parse_mqprio_opt(dev, mqprio, extack, q->flags);
1892 	if (err < 0)
1893 		return err;
1894 
1895 	err = taprio_parse_tc_entries(sch, opt, extack);
1896 	if (err)
1897 		return err;
1898 
1899 	new_admin = kzalloc_obj(*new_admin);
1900 	if (!new_admin) {
1901 		NL_SET_ERR_MSG(extack, "Not enough memory for a new schedule");
1902 		return -ENOMEM;
1903 	}
1904 	INIT_LIST_HEAD(&new_admin->entries);
1905 
1906 	oper = rtnl_dereference(q->oper_sched);
1907 	admin = rtnl_dereference(q->admin_sched);
1908 
1909 	/* no changes - no new mqprio settings */
1910 	if (!taprio_mqprio_cmp(dev, mqprio))
1911 		mqprio = NULL;
1912 
1913 	if (mqprio && (oper || admin)) {
1914 		NL_SET_ERR_MSG(extack, "Changing the traffic mapping of a running schedule is not supported");
1915 		err = -ENOTSUPP;
1916 		goto free_sched;
1917 	}
1918 
1919 	if (mqprio) {
1920 		err = netdev_set_num_tc(dev, mqprio->num_tc);
1921 		if (err)
1922 			goto free_sched;
1923 		for (i = 0; i < mqprio->num_tc; i++) {
1924 			netdev_set_tc_queue(dev, i,
1925 					    mqprio->count[i],
1926 					    mqprio->offset[i]);
1927 			q->cur_txq[i] = mqprio->offset[i];
1928 		}
1929 
1930 		/* Always use supplied priority mappings */
1931 		for (i = 0; i <= TC_BITMASK; i++)
1932 			netdev_set_prio_tc_map(dev, i,
1933 					       mqprio->prio_tc_map[i]);
1934 	}
1935 
1936 	err = parse_taprio_schedule(q, tb, new_admin, extack);
1937 	if (err < 0)
1938 		goto free_sched;
1939 
1940 	if (new_admin->num_entries == 0) {
1941 		NL_SET_ERR_MSG(extack, "There should be at least one entry in the schedule");
1942 		err = -EINVAL;
1943 		goto free_sched;
1944 	}
1945 
1946 	err = taprio_parse_clockid(sch, tb, extack);
1947 	if (err < 0)
1948 		goto free_sched;
1949 
1950 	taprio_update_queue_max_sdu(q, new_admin, stab);
1951 
1952 	if (FULL_OFFLOAD_IS_ENABLED(q->flags))
1953 		err = taprio_enable_offload(dev, q, new_admin, extack);
1954 	else
1955 		err = taprio_disable_offload(dev, q, extack);
1956 	if (err)
1957 		goto free_sched;
1958 
1959 	/* Protects against enqueue()/dequeue() */
1960 	spin_lock_bh(qdisc_lock(sch));
1961 
1962 	if (tb[TCA_TAPRIO_ATTR_TXTIME_DELAY]) {
1963 		if (!TXTIME_ASSIST_IS_ENABLED(q->flags)) {
1964 			NL_SET_ERR_MSG_MOD(extack, "txtime-delay can only be set when txtime-assist mode is enabled");
1965 			err = -EINVAL;
1966 			goto unlock;
1967 		}
1968 
1969 		WRITE_ONCE(q->txtime_delay,
1970 			   nla_get_u32(tb[TCA_TAPRIO_ATTR_TXTIME_DELAY]));
1971 	}
1972 
1973 	if (!TXTIME_ASSIST_IS_ENABLED(q->flags) &&
1974 	    !FULL_OFFLOAD_IS_ENABLED(q->flags) &&
1975 	    !hrtimer_active(&q->advance_timer)) {
1976 		hrtimer_setup(&q->advance_timer, advance_sched, q->clockid, HRTIMER_MODE_ABS);
1977 	}
1978 
1979 	err = taprio_get_start_time(sch, new_admin, &start);
1980 	if (err < 0) {
1981 		NL_SET_ERR_MSG(extack, "Internal error: failed get start time");
1982 		goto unlock;
1983 	}
1984 
1985 	setup_txtime(q, new_admin, start);
1986 
1987 	if (TXTIME_ASSIST_IS_ENABLED(q->flags)) {
1988 		if (!oper) {
1989 			rcu_assign_pointer(q->oper_sched, new_admin);
1990 			err = 0;
1991 			new_admin = NULL;
1992 			goto unlock;
1993 		}
1994 
1995 		/* Not going to race against advance_sched(), but still */
1996 		admin = rcu_replace_pointer(q->admin_sched, new_admin,
1997 					    lockdep_rtnl_is_held());
1998 		if (admin)
1999 			call_rcu(&admin->rcu, taprio_free_sched_cb);
2000 	} else {
2001 		setup_first_end_time(q, new_admin, start);
2002 
2003 		/* Protects against advance_sched() */
2004 		spin_lock_irqsave(&q->current_entry_lock, flags);
2005 
2006 		taprio_start_sched(sch, start, new_admin);
2007 
2008 		admin = rcu_replace_pointer(q->admin_sched, new_admin,
2009 					    lockdep_rtnl_is_held());
2010 		if (admin)
2011 			call_rcu(&admin->rcu, taprio_free_sched_cb);
2012 
2013 		spin_unlock_irqrestore(&q->current_entry_lock, flags);
2014 
2015 		if (FULL_OFFLOAD_IS_ENABLED(q->flags))
2016 			taprio_offload_config_changed(q);
2017 	}
2018 
2019 	new_admin = NULL;
2020 	err = 0;
2021 
2022 	if (!stab)
2023 		NL_SET_ERR_MSG_MOD(extack,
2024 				   "Size table not specified, frame length estimations may be inaccurate");
2025 
2026 unlock:
2027 	spin_unlock_bh(qdisc_lock(sch));
2028 
2029 free_sched:
2030 	if (new_admin)
2031 		call_rcu(&new_admin->rcu, taprio_free_sched_cb);
2032 
2033 	return err;
2034 }
2035 
2036 static void taprio_reset(struct Qdisc *sch)
2037 {
2038 	struct taprio_sched *q = qdisc_priv(sch);
2039 	struct net_device *dev = qdisc_dev(sch);
2040 	int i;
2041 
2042 	hrtimer_cancel(&q->advance_timer);
2043 
2044 	if (q->qdiscs) {
2045 		for (i = 0; i < dev->num_tx_queues; i++)
2046 			if (q->qdiscs[i])
2047 				qdisc_reset(q->qdiscs[i]);
2048 	}
2049 }
2050 
2051 static void taprio_destroy(struct Qdisc *sch)
2052 {
2053 	struct taprio_sched *q = qdisc_priv(sch);
2054 	struct net_device *dev = qdisc_dev(sch);
2055 	struct sched_gate_list *oper, *admin;
2056 	unsigned int i;
2057 
2058 	list_del(&q->taprio_list);
2059 
2060 	/* Note that taprio_reset() might not be called if an error
2061 	 * happens in qdisc_create(), after taprio_init() has been called.
2062 	 */
2063 	hrtimer_cancel(&q->advance_timer);
2064 	qdisc_synchronize(sch);
2065 
2066 	taprio_disable_offload(dev, q, NULL);
2067 
2068 	if (q->qdiscs) {
2069 		for (i = 0; i < dev->num_tx_queues; i++)
2070 			qdisc_put(q->qdiscs[i]);
2071 
2072 		kfree(q->qdiscs);
2073 	}
2074 	q->qdiscs = NULL;
2075 
2076 	netdev_reset_tc(dev);
2077 
2078 	oper = rtnl_dereference(q->oper_sched);
2079 	admin = rtnl_dereference(q->admin_sched);
2080 
2081 	if (oper)
2082 		call_rcu(&oper->rcu, taprio_free_sched_cb);
2083 
2084 	if (admin)
2085 		call_rcu(&admin->rcu, taprio_free_sched_cb);
2086 
2087 	taprio_cleanup_broken_mqprio(q);
2088 }
2089 
2090 static int taprio_init(struct Qdisc *sch, struct nlattr *opt,
2091 		       struct netlink_ext_ack *extack)
2092 {
2093 	struct taprio_sched *q = qdisc_priv(sch);
2094 	struct net_device *dev = qdisc_dev(sch);
2095 	int i, tc;
2096 
2097 	spin_lock_init(&q->current_entry_lock);
2098 
2099 	hrtimer_setup(&q->advance_timer, advance_sched, CLOCK_TAI, HRTIMER_MODE_ABS);
2100 
2101 	q->root = sch;
2102 
2103 	/* We only support static clockids. Use an invalid value as default
2104 	 * and get the valid one on taprio_change().
2105 	 */
2106 	q->clockid = -1;
2107 	q->flags = TAPRIO_FLAGS_INVALID;
2108 
2109 	list_add(&q->taprio_list, &taprio_list);
2110 
2111 	if (sch->parent != TC_H_ROOT) {
2112 		NL_SET_ERR_MSG_MOD(extack, "Can only be attached as root qdisc");
2113 		return -EOPNOTSUPP;
2114 	}
2115 
2116 	if (!netif_is_multiqueue(dev)) {
2117 		NL_SET_ERR_MSG_MOD(extack, "Multi-queue device is required");
2118 		return -EOPNOTSUPP;
2119 	}
2120 
2121 	q->qdiscs = kzalloc_objs(q->qdiscs[0], dev->num_tx_queues);
2122 	if (!q->qdiscs)
2123 		return -ENOMEM;
2124 
2125 	if (!opt)
2126 		return -EINVAL;
2127 
2128 	for (i = 0; i < dev->num_tx_queues; i++) {
2129 		struct netdev_queue *dev_queue;
2130 		struct Qdisc *qdisc;
2131 
2132 		dev_queue = netdev_get_tx_queue(dev, i);
2133 		qdisc = qdisc_create_dflt(dev_queue,
2134 					  &pfifo_qdisc_ops,
2135 					  TC_H_MAKE(TC_H_MAJ(sch->handle),
2136 						    TC_H_MIN(i + 1)),
2137 					  extack);
2138 		if (!qdisc)
2139 			return -ENOMEM;
2140 
2141 		if (i < dev->real_num_tx_queues)
2142 			qdisc_hash_add(qdisc, false);
2143 
2144 		q->qdiscs[i] = qdisc;
2145 	}
2146 
2147 	for (tc = 0; tc < TC_QOPT_MAX_QUEUE; tc++)
2148 		q->fp[tc] = TC_FP_EXPRESS;
2149 
2150 	taprio_detect_broken_mqprio(q);
2151 
2152 	return taprio_change(sch, opt, extack);
2153 }
2154 
2155 static void taprio_attach(struct Qdisc *sch)
2156 {
2157 	struct taprio_sched *q = qdisc_priv(sch);
2158 	struct net_device *dev = qdisc_dev(sch);
2159 	unsigned int ntx;
2160 
2161 	/* Attach underlying qdisc */
2162 	for (ntx = 0; ntx < dev->num_tx_queues; ntx++) {
2163 		struct netdev_queue *dev_queue = netdev_get_tx_queue(dev, ntx);
2164 		struct Qdisc *old, *dev_queue_qdisc;
2165 
2166 		if (FULL_OFFLOAD_IS_ENABLED(q->flags)) {
2167 			struct Qdisc *qdisc = q->qdiscs[ntx];
2168 
2169 			/* In offload mode, the root taprio qdisc is bypassed
2170 			 * and the netdev TX queues see the children directly
2171 			 */
2172 			qdisc->flags |= TCQ_F_ONETXQUEUE | TCQ_F_NOPARENT;
2173 			dev_queue_qdisc = qdisc;
2174 		} else {
2175 			/* In software mode, attach the root taprio qdisc
2176 			 * to all netdev TX queues, so that dev_qdisc_enqueue()
2177 			 * goes through taprio_enqueue().
2178 			 */
2179 			dev_queue_qdisc = sch;
2180 		}
2181 		old = dev_graft_qdisc(dev_queue, dev_queue_qdisc);
2182 		/* The qdisc's refcount requires to be elevated once
2183 		 * for each netdev TX queue it is grafted onto
2184 		 */
2185 		qdisc_refcount_inc(dev_queue_qdisc);
2186 		if (old)
2187 			qdisc_put(old);
2188 	}
2189 }
2190 
2191 static struct netdev_queue *taprio_queue_get(struct Qdisc *sch,
2192 					     unsigned long cl)
2193 {
2194 	struct net_device *dev = qdisc_dev(sch);
2195 	unsigned long ntx = cl - 1;
2196 
2197 	if (ntx >= dev->num_tx_queues)
2198 		return NULL;
2199 
2200 	return netdev_get_tx_queue(dev, ntx);
2201 }
2202 
2203 static int taprio_graft(struct Qdisc *sch, unsigned long cl,
2204 			struct Qdisc *new, struct Qdisc **old,
2205 			struct netlink_ext_ack *extack)
2206 {
2207 	struct taprio_sched *q = qdisc_priv(sch);
2208 	struct net_device *dev = qdisc_dev(sch);
2209 	struct netdev_queue *dev_queue = taprio_queue_get(sch, cl);
2210 
2211 	if (!dev_queue)
2212 		return -EINVAL;
2213 
2214 	if (!new)
2215 		new = &noop_qdisc;
2216 
2217 	if (dev->flags & IFF_UP)
2218 		dev_deactivate(dev, false);
2219 
2220 	/* In offload mode, the child Qdisc is directly attached to the netdev
2221 	 * TX queue, and thus, we need to keep its refcount elevated in order
2222 	 * to counteract qdisc_graft()'s call to qdisc_put() once per TX queue.
2223 	 * However, save the reference to the new qdisc in the private array in
2224 	 * both software and offload cases, to have an up-to-date reference to
2225 	 * our children.
2226 	 */
2227 	*old = q->qdiscs[cl - 1];
2228 	if (FULL_OFFLOAD_IS_ENABLED(q->flags)) {
2229 		WARN_ON_ONCE(dev_graft_qdisc(dev_queue, new) != *old);
2230 		if (new != &noop_qdisc)
2231 			qdisc_refcount_inc(new);
2232 		if (*old && *old != &noop_qdisc)
2233 			qdisc_put(*old);
2234 	}
2235 
2236 	q->qdiscs[cl - 1] = new;
2237 	if (new != &noop_qdisc)
2238 		new->flags |= TCQ_F_ONETXQUEUE | TCQ_F_NOPARENT;
2239 
2240 	if (dev->flags & IFF_UP)
2241 		dev_activate(dev);
2242 
2243 	return 0;
2244 }
2245 
2246 static int dump_entry(struct sk_buff *msg,
2247 		      const struct sched_entry *entry)
2248 {
2249 	struct nlattr *item;
2250 
2251 	item = nla_nest_start_noflag(msg, TCA_TAPRIO_SCHED_ENTRY);
2252 	if (!item)
2253 		return -ENOSPC;
2254 
2255 	if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_INDEX, entry->index))
2256 		goto nla_put_failure;
2257 
2258 	if (nla_put_u8(msg, TCA_TAPRIO_SCHED_ENTRY_CMD, entry->command))
2259 		goto nla_put_failure;
2260 
2261 	if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_GATE_MASK,
2262 			entry->gate_mask))
2263 		goto nla_put_failure;
2264 
2265 	if (nla_put_u32(msg, TCA_TAPRIO_SCHED_ENTRY_INTERVAL,
2266 			entry->interval))
2267 		goto nla_put_failure;
2268 
2269 	return nla_nest_end(msg, item);
2270 
2271 nla_put_failure:
2272 	nla_nest_cancel(msg, item);
2273 	return -1;
2274 }
2275 
2276 static int dump_schedule(struct sk_buff *msg,
2277 			 const struct sched_gate_list *root)
2278 {
2279 	struct nlattr *entry_list;
2280 	struct sched_entry *entry;
2281 
2282 	if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_BASE_TIME,
2283 			root->base_time, TCA_TAPRIO_PAD))
2284 		return -1;
2285 
2286 	if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME,
2287 			root->cycle_time, TCA_TAPRIO_PAD))
2288 		return -1;
2289 
2290 	if (nla_put_s64(msg, TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION,
2291 			root->cycle_time_extension, TCA_TAPRIO_PAD))
2292 		return -1;
2293 
2294 	entry_list = nla_nest_start_noflag(msg,
2295 					   TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST);
2296 	if (!entry_list)
2297 		goto error_nest;
2298 
2299 	list_for_each_entry(entry, &root->entries, list) {
2300 		if (dump_entry(msg, entry) < 0)
2301 			goto error_nest;
2302 	}
2303 
2304 	nla_nest_end(msg, entry_list);
2305 	return 0;
2306 
2307 error_nest:
2308 	nla_nest_cancel(msg, entry_list);
2309 	return -1;
2310 }
2311 
2312 static int taprio_dump_tc_entries(struct sk_buff *skb,
2313 				  const struct taprio_sched *q,
2314 				  const struct sched_gate_list *sched)
2315 {
2316 	struct nlattr *n;
2317 	int tc;
2318 
2319 	for (tc = 0; tc < TC_MAX_QUEUE; tc++) {
2320 		n = nla_nest_start(skb, TCA_TAPRIO_ATTR_TC_ENTRY);
2321 		if (!n)
2322 			return -EMSGSIZE;
2323 
2324 		if (nla_put_u32(skb, TCA_TAPRIO_TC_ENTRY_INDEX, tc))
2325 			goto nla_put_failure;
2326 
2327 		if (nla_put_u32(skb, TCA_TAPRIO_TC_ENTRY_MAX_SDU,
2328 				READ_ONCE(sched->max_sdu[tc])))
2329 			goto nla_put_failure;
2330 
2331 		if (nla_put_u32(skb, TCA_TAPRIO_TC_ENTRY_FP,
2332 				READ_ONCE(q->fp[tc])))
2333 			goto nla_put_failure;
2334 
2335 		nla_nest_end(skb, n);
2336 	}
2337 
2338 	return 0;
2339 
2340 nla_put_failure:
2341 	nla_nest_cancel(skb, n);
2342 	return -EMSGSIZE;
2343 }
2344 
2345 static int taprio_put_stat(struct sk_buff *skb, u64 val, u16 attrtype)
2346 {
2347 	if (val == TAPRIO_STAT_NOT_SET)
2348 		return 0;
2349 	if (nla_put_u64_64bit(skb, attrtype, val, TCA_TAPRIO_OFFLOAD_STATS_PAD))
2350 		return -EMSGSIZE;
2351 	return 0;
2352 }
2353 
2354 static int taprio_dump_xstats(struct Qdisc *sch, struct gnet_dump *d,
2355 			      struct tc_taprio_qopt_offload *offload,
2356 			      struct tc_taprio_qopt_stats *stats)
2357 {
2358 	struct net_device *dev = qdisc_dev(sch);
2359 	const struct net_device_ops *ops;
2360 	struct sk_buff *skb = d->skb;
2361 	struct nlattr *xstats;
2362 	int err;
2363 
2364 	ops = qdisc_dev(sch)->netdev_ops;
2365 
2366 	/* FIXME I could use qdisc_offload_dump_helper(), but that messes
2367 	 * with sch->flags depending on whether the device reports taprio
2368 	 * stats, and I'm not sure whether that's a good idea, considering
2369 	 * that stats are optional to the offload itself
2370 	 */
2371 	if (!ops->ndo_setup_tc)
2372 		return 0;
2373 
2374 	memset(stats, 0xff, sizeof(*stats));
2375 
2376 	err = ops->ndo_setup_tc(dev, TC_SETUP_QDISC_TAPRIO, offload);
2377 	if (err == -EOPNOTSUPP)
2378 		return 0;
2379 	if (err)
2380 		return err;
2381 
2382 	xstats = nla_nest_start(skb, TCA_STATS_APP);
2383 	if (!xstats)
2384 		goto err;
2385 
2386 	if (taprio_put_stat(skb, stats->window_drops,
2387 			    TCA_TAPRIO_OFFLOAD_STATS_WINDOW_DROPS) ||
2388 	    taprio_put_stat(skb, stats->tx_overruns,
2389 			    TCA_TAPRIO_OFFLOAD_STATS_TX_OVERRUNS))
2390 		goto err_cancel;
2391 
2392 	nla_nest_end(skb, xstats);
2393 
2394 	return 0;
2395 
2396 err_cancel:
2397 	nla_nest_cancel(skb, xstats);
2398 err:
2399 	return -EMSGSIZE;
2400 }
2401 
2402 static int taprio_dump_stats(struct Qdisc *sch, struct gnet_dump *d)
2403 {
2404 	struct tc_taprio_qopt_offload offload = {
2405 		.cmd = TAPRIO_CMD_STATS,
2406 	};
2407 
2408 	return taprio_dump_xstats(sch, d, &offload, &offload.stats);
2409 }
2410 
2411 static int taprio_dump(struct Qdisc *sch, struct sk_buff *skb)
2412 {
2413 	struct taprio_sched *q = qdisc_priv(sch);
2414 	struct net_device *dev = qdisc_dev(sch);
2415 	struct sched_gate_list *oper, *admin;
2416 	struct tc_mqprio_qopt opt = { 0 };
2417 	struct nlattr *nest, *sched_nest;
2418 	u32 txtime_delay;
2419 
2420 	mqprio_qopt_reconstruct(dev, &opt);
2421 
2422 	nest = nla_nest_start_noflag(skb, TCA_OPTIONS);
2423 	if (!nest)
2424 		goto start_error;
2425 
2426 	if (nla_put(skb, TCA_TAPRIO_ATTR_PRIOMAP, sizeof(opt), &opt))
2427 		goto options_error;
2428 
2429 	if (!FULL_OFFLOAD_IS_ENABLED(q->flags) &&
2430 	    nla_put_s32(skb, TCA_TAPRIO_ATTR_SCHED_CLOCKID, q->clockid))
2431 		goto options_error;
2432 
2433 	if (q->flags && nla_put_u32(skb, TCA_TAPRIO_ATTR_FLAGS, q->flags))
2434 		goto options_error;
2435 
2436 	txtime_delay = READ_ONCE(q->txtime_delay);
2437 	if (txtime_delay &&
2438 	    nla_put_u32(skb, TCA_TAPRIO_ATTR_TXTIME_DELAY, txtime_delay))
2439 		goto options_error;
2440 
2441 	rcu_read_lock();
2442 
2443 	oper = rcu_dereference(q->oper_sched);
2444 	admin = rcu_dereference(q->admin_sched);
2445 
2446 	if (oper && taprio_dump_tc_entries(skb, q, oper))
2447 		goto options_error_rcu;
2448 
2449 	if (oper && dump_schedule(skb, oper))
2450 		goto options_error_rcu;
2451 
2452 	if (!admin)
2453 		goto done;
2454 
2455 	sched_nest = nla_nest_start_noflag(skb, TCA_TAPRIO_ATTR_ADMIN_SCHED);
2456 	if (!sched_nest)
2457 		goto options_error_rcu;
2458 
2459 	if (dump_schedule(skb, admin))
2460 		goto admin_error;
2461 
2462 	nla_nest_end(skb, sched_nest);
2463 
2464 done:
2465 	rcu_read_unlock();
2466 	return nla_nest_end(skb, nest);
2467 
2468 admin_error:
2469 	nla_nest_cancel(skb, sched_nest);
2470 
2471 options_error_rcu:
2472 	rcu_read_unlock();
2473 
2474 options_error:
2475 	nla_nest_cancel(skb, nest);
2476 
2477 start_error:
2478 	return -ENOSPC;
2479 }
2480 
2481 static struct Qdisc *taprio_leaf(struct Qdisc *sch, unsigned long cl)
2482 {
2483 	struct taprio_sched *q = qdisc_priv(sch);
2484 	struct net_device *dev = qdisc_dev(sch);
2485 	unsigned int ntx = cl - 1;
2486 
2487 	if (ntx >= dev->num_tx_queues)
2488 		return NULL;
2489 
2490 	return q->qdiscs[ntx];
2491 }
2492 
2493 static unsigned long taprio_find(struct Qdisc *sch, u32 classid)
2494 {
2495 	unsigned int ntx = TC_H_MIN(classid);
2496 
2497 	if (!taprio_queue_get(sch, ntx))
2498 		return 0;
2499 	return ntx;
2500 }
2501 
2502 static int taprio_dump_class(struct Qdisc *sch, unsigned long cl,
2503 			     struct sk_buff *skb, struct tcmsg *tcm)
2504 {
2505 	struct Qdisc *child = taprio_leaf(sch, cl);
2506 
2507 	tcm->tcm_parent = TC_H_ROOT;
2508 	tcm->tcm_handle |= TC_H_MIN(cl);
2509 	tcm->tcm_info = child->handle;
2510 
2511 	return 0;
2512 }
2513 
2514 static int taprio_dump_class_stats(struct Qdisc *sch, unsigned long cl,
2515 				   struct gnet_dump *d)
2516 	__releases(d->lock)
2517 	__acquires(d->lock)
2518 {
2519 	struct Qdisc *child = taprio_leaf(sch, cl);
2520 	struct tc_taprio_qopt_offload offload = {
2521 		.cmd = TAPRIO_CMD_QUEUE_STATS,
2522 		.queue_stats = {
2523 			.queue = cl - 1,
2524 		},
2525 	};
2526 
2527 	if (gnet_stats_copy_basic(d, NULL, &child->bstats, true) < 0 ||
2528 	    qdisc_qstats_copy(d, child) < 0)
2529 		return -1;
2530 
2531 	return taprio_dump_xstats(sch, d, &offload, &offload.queue_stats.stats);
2532 }
2533 
2534 static void taprio_walk(struct Qdisc *sch, struct qdisc_walker *arg)
2535 {
2536 	struct net_device *dev = qdisc_dev(sch);
2537 	unsigned long ntx;
2538 
2539 	if (arg->stop)
2540 		return;
2541 
2542 	arg->count = arg->skip;
2543 	for (ntx = arg->skip; ntx < dev->num_tx_queues; ntx++) {
2544 		if (!tc_qdisc_stats_dump(sch, ntx + 1, arg))
2545 			break;
2546 	}
2547 }
2548 
2549 static struct netdev_queue *taprio_select_queue(struct Qdisc *sch,
2550 						struct tcmsg *tcm)
2551 {
2552 	return taprio_queue_get(sch, TC_H_MIN(tcm->tcm_parent));
2553 }
2554 
2555 static const struct Qdisc_class_ops taprio_class_ops = {
2556 	.graft		= taprio_graft,
2557 	.leaf		= taprio_leaf,
2558 	.find		= taprio_find,
2559 	.walk		= taprio_walk,
2560 	.dump		= taprio_dump_class,
2561 	.dump_stats	= taprio_dump_class_stats,
2562 	.select_queue	= taprio_select_queue,
2563 };
2564 
2565 static struct Qdisc_ops taprio_qdisc_ops __read_mostly = {
2566 	.cl_ops		= &taprio_class_ops,
2567 	.id		= "taprio",
2568 	.priv_size	= sizeof(struct taprio_sched),
2569 	.init		= taprio_init,
2570 	.change		= taprio_change,
2571 	.destroy	= taprio_destroy,
2572 	.reset		= taprio_reset,
2573 	.attach		= taprio_attach,
2574 	.peek		= taprio_peek,
2575 	.dequeue	= taprio_dequeue,
2576 	.enqueue	= taprio_enqueue,
2577 	.dump		= taprio_dump,
2578 	.dump_stats	= taprio_dump_stats,
2579 	.owner		= THIS_MODULE,
2580 };
2581 MODULE_ALIAS_NET_SCH("taprio");
2582 
2583 static struct notifier_block taprio_device_notifier = {
2584 	.notifier_call = taprio_dev_notifier,
2585 };
2586 
2587 static int __init taprio_module_init(void)
2588 {
2589 	int err = register_netdevice_notifier(&taprio_device_notifier);
2590 
2591 	if (err)
2592 		return err;
2593 
2594 	err = register_qdisc(&taprio_qdisc_ops);
2595 	if (err)
2596 		unregister_netdevice_notifier(&taprio_device_notifier);
2597 
2598 	return err;
2599 }
2600 
2601 static void __exit taprio_module_exit(void)
2602 {
2603 	unregister_qdisc(&taprio_qdisc_ops);
2604 	unregister_netdevice_notifier(&taprio_device_notifier);
2605 }
2606 
2607 module_init(taprio_module_init);
2608 module_exit(taprio_module_exit);
2609 MODULE_LICENSE("GPL");
2610 MODULE_DESCRIPTION("Time Aware Priority qdisc");
2611