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