xref: /openbmc/linux/net/core/drop_monitor.c (revision 359745d7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Monitoring code for network dropped packet alerts
4  *
5  * Copyright (C) 2009 Neil Horman <nhorman@tuxdriver.com>
6  */
7 
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 
10 #include <linux/netdevice.h>
11 #include <linux/etherdevice.h>
12 #include <linux/string.h>
13 #include <linux/if_arp.h>
14 #include <linux/inetdevice.h>
15 #include <linux/inet.h>
16 #include <linux/interrupt.h>
17 #include <linux/netpoll.h>
18 #include <linux/sched.h>
19 #include <linux/delay.h>
20 #include <linux/types.h>
21 #include <linux/workqueue.h>
22 #include <linux/netlink.h>
23 #include <linux/net_dropmon.h>
24 #include <linux/percpu.h>
25 #include <linux/timer.h>
26 #include <linux/bitops.h>
27 #include <linux/slab.h>
28 #include <linux/module.h>
29 #include <net/genetlink.h>
30 #include <net/netevent.h>
31 #include <net/flow_offload.h>
32 #include <net/devlink.h>
33 
34 #include <trace/events/skb.h>
35 #include <trace/events/napi.h>
36 #include <trace/events/devlink.h>
37 
38 #include <asm/unaligned.h>
39 
40 #define TRACE_ON 1
41 #define TRACE_OFF 0
42 
43 /*
44  * Globals, our netlink socket pointer
45  * and the work handle that will send up
46  * netlink alerts
47  */
48 static int trace_state = TRACE_OFF;
49 static bool monitor_hw;
50 
51 /* net_dm_mutex
52  *
53  * An overall lock guarding every operation coming from userspace.
54  * It also guards the global 'hw_stats_list' list.
55  */
56 static DEFINE_MUTEX(net_dm_mutex);
57 
58 struct net_dm_stats {
59 	u64 dropped;
60 	struct u64_stats_sync syncp;
61 };
62 
63 #define NET_DM_MAX_HW_TRAP_NAME_LEN 40
64 
65 struct net_dm_hw_entry {
66 	char trap_name[NET_DM_MAX_HW_TRAP_NAME_LEN];
67 	u32 count;
68 };
69 
70 struct net_dm_hw_entries {
71 	u32 num_entries;
72 	struct net_dm_hw_entry entries[];
73 };
74 
75 struct per_cpu_dm_data {
76 	spinlock_t		lock;	/* Protects 'skb', 'hw_entries' and
77 					 * 'send_timer'
78 					 */
79 	union {
80 		struct sk_buff			*skb;
81 		struct net_dm_hw_entries	*hw_entries;
82 	};
83 	struct sk_buff_head	drop_queue;
84 	struct work_struct	dm_alert_work;
85 	struct timer_list	send_timer;
86 	struct net_dm_stats	stats;
87 };
88 
89 struct dm_hw_stat_delta {
90 	struct net_device *dev;
91 	unsigned long last_rx;
92 	struct list_head list;
93 	struct rcu_head rcu;
94 	unsigned long last_drop_val;
95 };
96 
97 static struct genl_family net_drop_monitor_family;
98 
99 static DEFINE_PER_CPU(struct per_cpu_dm_data, dm_cpu_data);
100 static DEFINE_PER_CPU(struct per_cpu_dm_data, dm_hw_cpu_data);
101 
102 static int dm_hit_limit = 64;
103 static int dm_delay = 1;
104 static unsigned long dm_hw_check_delta = 2*HZ;
105 static LIST_HEAD(hw_stats_list);
106 
107 static enum net_dm_alert_mode net_dm_alert_mode = NET_DM_ALERT_MODE_SUMMARY;
108 static u32 net_dm_trunc_len;
109 static u32 net_dm_queue_len = 1000;
110 
111 struct net_dm_alert_ops {
112 	void (*kfree_skb_probe)(void *ignore, struct sk_buff *skb,
113 				void *location,
114 				enum skb_drop_reason reason);
115 	void (*napi_poll_probe)(void *ignore, struct napi_struct *napi,
116 				int work, int budget);
117 	void (*work_item_func)(struct work_struct *work);
118 	void (*hw_work_item_func)(struct work_struct *work);
119 	void (*hw_trap_probe)(void *ignore, const struct devlink *devlink,
120 			      struct sk_buff *skb,
121 			      const struct devlink_trap_metadata *metadata);
122 };
123 
124 struct net_dm_skb_cb {
125 	union {
126 		struct devlink_trap_metadata *hw_metadata;
127 		void *pc;
128 	};
129 };
130 
131 #define NET_DM_SKB_CB(__skb) ((struct net_dm_skb_cb *)&((__skb)->cb[0]))
132 
133 static struct sk_buff *reset_per_cpu_data(struct per_cpu_dm_data *data)
134 {
135 	size_t al;
136 	struct net_dm_alert_msg *msg;
137 	struct nlattr *nla;
138 	struct sk_buff *skb;
139 	unsigned long flags;
140 	void *msg_header;
141 
142 	al = sizeof(struct net_dm_alert_msg);
143 	al += dm_hit_limit * sizeof(struct net_dm_drop_point);
144 	al += sizeof(struct nlattr);
145 
146 	skb = genlmsg_new(al, GFP_KERNEL);
147 
148 	if (!skb)
149 		goto err;
150 
151 	msg_header = genlmsg_put(skb, 0, 0, &net_drop_monitor_family,
152 				 0, NET_DM_CMD_ALERT);
153 	if (!msg_header) {
154 		nlmsg_free(skb);
155 		skb = NULL;
156 		goto err;
157 	}
158 	nla = nla_reserve(skb, NLA_UNSPEC,
159 			  sizeof(struct net_dm_alert_msg));
160 	if (!nla) {
161 		nlmsg_free(skb);
162 		skb = NULL;
163 		goto err;
164 	}
165 	msg = nla_data(nla);
166 	memset(msg, 0, al);
167 	goto out;
168 
169 err:
170 	mod_timer(&data->send_timer, jiffies + HZ / 10);
171 out:
172 	spin_lock_irqsave(&data->lock, flags);
173 	swap(data->skb, skb);
174 	spin_unlock_irqrestore(&data->lock, flags);
175 
176 	if (skb) {
177 		struct nlmsghdr *nlh = (struct nlmsghdr *)skb->data;
178 		struct genlmsghdr *gnlh = (struct genlmsghdr *)nlmsg_data(nlh);
179 
180 		genlmsg_end(skb, genlmsg_data(gnlh));
181 	}
182 
183 	return skb;
184 }
185 
186 static const struct genl_multicast_group dropmon_mcgrps[] = {
187 	{ .name = "events", },
188 };
189 
190 static void send_dm_alert(struct work_struct *work)
191 {
192 	struct sk_buff *skb;
193 	struct per_cpu_dm_data *data;
194 
195 	data = container_of(work, struct per_cpu_dm_data, dm_alert_work);
196 
197 	skb = reset_per_cpu_data(data);
198 
199 	if (skb)
200 		genlmsg_multicast(&net_drop_monitor_family, skb, 0,
201 				  0, GFP_KERNEL);
202 }
203 
204 /*
205  * This is the timer function to delay the sending of an alert
206  * in the event that more drops will arrive during the
207  * hysteresis period.
208  */
209 static void sched_send_work(struct timer_list *t)
210 {
211 	struct per_cpu_dm_data *data = from_timer(data, t, send_timer);
212 
213 	schedule_work(&data->dm_alert_work);
214 }
215 
216 static void trace_drop_common(struct sk_buff *skb, void *location)
217 {
218 	struct net_dm_alert_msg *msg;
219 	struct net_dm_drop_point *point;
220 	struct nlmsghdr *nlh;
221 	struct nlattr *nla;
222 	int i;
223 	struct sk_buff *dskb;
224 	struct per_cpu_dm_data *data;
225 	unsigned long flags;
226 
227 	local_irq_save(flags);
228 	data = this_cpu_ptr(&dm_cpu_data);
229 	spin_lock(&data->lock);
230 	dskb = data->skb;
231 
232 	if (!dskb)
233 		goto out;
234 
235 	nlh = (struct nlmsghdr *)dskb->data;
236 	nla = genlmsg_data(nlmsg_data(nlh));
237 	msg = nla_data(nla);
238 	point = msg->points;
239 	for (i = 0; i < msg->entries; i++) {
240 		if (!memcmp(&location, &point->pc, sizeof(void *))) {
241 			point->count++;
242 			goto out;
243 		}
244 		point++;
245 	}
246 	if (msg->entries == dm_hit_limit)
247 		goto out;
248 	/*
249 	 * We need to create a new entry
250 	 */
251 	__nla_reserve_nohdr(dskb, sizeof(struct net_dm_drop_point));
252 	nla->nla_len += NLA_ALIGN(sizeof(struct net_dm_drop_point));
253 	memcpy(point->pc, &location, sizeof(void *));
254 	point->count = 1;
255 	msg->entries++;
256 
257 	if (!timer_pending(&data->send_timer)) {
258 		data->send_timer.expires = jiffies + dm_delay * HZ;
259 		add_timer(&data->send_timer);
260 	}
261 
262 out:
263 	spin_unlock_irqrestore(&data->lock, flags);
264 }
265 
266 static void trace_kfree_skb_hit(void *ignore, struct sk_buff *skb,
267 				void *location,
268 				enum skb_drop_reason reason)
269 {
270 	trace_drop_common(skb, location);
271 }
272 
273 static void trace_napi_poll_hit(void *ignore, struct napi_struct *napi,
274 				int work, int budget)
275 {
276 	struct dm_hw_stat_delta *new_stat;
277 
278 	/*
279 	 * Don't check napi structures with no associated device
280 	 */
281 	if (!napi->dev)
282 		return;
283 
284 	rcu_read_lock();
285 	list_for_each_entry_rcu(new_stat, &hw_stats_list, list) {
286 		/*
287 		 * only add a note to our monitor buffer if:
288 		 * 1) this is the dev we received on
289 		 * 2) its after the last_rx delta
290 		 * 3) our rx_dropped count has gone up
291 		 */
292 		if ((new_stat->dev == napi->dev)  &&
293 		    (time_after(jiffies, new_stat->last_rx + dm_hw_check_delta)) &&
294 		    (napi->dev->stats.rx_dropped != new_stat->last_drop_val)) {
295 			trace_drop_common(NULL, NULL);
296 			new_stat->last_drop_val = napi->dev->stats.rx_dropped;
297 			new_stat->last_rx = jiffies;
298 			break;
299 		}
300 	}
301 	rcu_read_unlock();
302 }
303 
304 static struct net_dm_hw_entries *
305 net_dm_hw_reset_per_cpu_data(struct per_cpu_dm_data *hw_data)
306 {
307 	struct net_dm_hw_entries *hw_entries;
308 	unsigned long flags;
309 
310 	hw_entries = kzalloc(struct_size(hw_entries, entries, dm_hit_limit),
311 			     GFP_KERNEL);
312 	if (!hw_entries) {
313 		/* If the memory allocation failed, we try to perform another
314 		 * allocation in 1/10 second. Otherwise, the probe function
315 		 * will constantly bail out.
316 		 */
317 		mod_timer(&hw_data->send_timer, jiffies + HZ / 10);
318 	}
319 
320 	spin_lock_irqsave(&hw_data->lock, flags);
321 	swap(hw_data->hw_entries, hw_entries);
322 	spin_unlock_irqrestore(&hw_data->lock, flags);
323 
324 	return hw_entries;
325 }
326 
327 static int net_dm_hw_entry_put(struct sk_buff *msg,
328 			       const struct net_dm_hw_entry *hw_entry)
329 {
330 	struct nlattr *attr;
331 
332 	attr = nla_nest_start(msg, NET_DM_ATTR_HW_ENTRY);
333 	if (!attr)
334 		return -EMSGSIZE;
335 
336 	if (nla_put_string(msg, NET_DM_ATTR_HW_TRAP_NAME, hw_entry->trap_name))
337 		goto nla_put_failure;
338 
339 	if (nla_put_u32(msg, NET_DM_ATTR_HW_TRAP_COUNT, hw_entry->count))
340 		goto nla_put_failure;
341 
342 	nla_nest_end(msg, attr);
343 
344 	return 0;
345 
346 nla_put_failure:
347 	nla_nest_cancel(msg, attr);
348 	return -EMSGSIZE;
349 }
350 
351 static int net_dm_hw_entries_put(struct sk_buff *msg,
352 				 const struct net_dm_hw_entries *hw_entries)
353 {
354 	struct nlattr *attr;
355 	int i;
356 
357 	attr = nla_nest_start(msg, NET_DM_ATTR_HW_ENTRIES);
358 	if (!attr)
359 		return -EMSGSIZE;
360 
361 	for (i = 0; i < hw_entries->num_entries; i++) {
362 		int rc;
363 
364 		rc = net_dm_hw_entry_put(msg, &hw_entries->entries[i]);
365 		if (rc)
366 			goto nla_put_failure;
367 	}
368 
369 	nla_nest_end(msg, attr);
370 
371 	return 0;
372 
373 nla_put_failure:
374 	nla_nest_cancel(msg, attr);
375 	return -EMSGSIZE;
376 }
377 
378 static int
379 net_dm_hw_summary_report_fill(struct sk_buff *msg,
380 			      const struct net_dm_hw_entries *hw_entries)
381 {
382 	struct net_dm_alert_msg anc_hdr = { 0 };
383 	void *hdr;
384 	int rc;
385 
386 	hdr = genlmsg_put(msg, 0, 0, &net_drop_monitor_family, 0,
387 			  NET_DM_CMD_ALERT);
388 	if (!hdr)
389 		return -EMSGSIZE;
390 
391 	/* We need to put the ancillary header in order not to break user
392 	 * space.
393 	 */
394 	if (nla_put(msg, NLA_UNSPEC, sizeof(anc_hdr), &anc_hdr))
395 		goto nla_put_failure;
396 
397 	rc = net_dm_hw_entries_put(msg, hw_entries);
398 	if (rc)
399 		goto nla_put_failure;
400 
401 	genlmsg_end(msg, hdr);
402 
403 	return 0;
404 
405 nla_put_failure:
406 	genlmsg_cancel(msg, hdr);
407 	return -EMSGSIZE;
408 }
409 
410 static void net_dm_hw_summary_work(struct work_struct *work)
411 {
412 	struct net_dm_hw_entries *hw_entries;
413 	struct per_cpu_dm_data *hw_data;
414 	struct sk_buff *msg;
415 	int rc;
416 
417 	hw_data = container_of(work, struct per_cpu_dm_data, dm_alert_work);
418 
419 	hw_entries = net_dm_hw_reset_per_cpu_data(hw_data);
420 	if (!hw_entries)
421 		return;
422 
423 	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
424 	if (!msg)
425 		goto out;
426 
427 	rc = net_dm_hw_summary_report_fill(msg, hw_entries);
428 	if (rc) {
429 		nlmsg_free(msg);
430 		goto out;
431 	}
432 
433 	genlmsg_multicast(&net_drop_monitor_family, msg, 0, 0, GFP_KERNEL);
434 
435 out:
436 	kfree(hw_entries);
437 }
438 
439 static void
440 net_dm_hw_trap_summary_probe(void *ignore, const struct devlink *devlink,
441 			     struct sk_buff *skb,
442 			     const struct devlink_trap_metadata *metadata)
443 {
444 	struct net_dm_hw_entries *hw_entries;
445 	struct net_dm_hw_entry *hw_entry;
446 	struct per_cpu_dm_data *hw_data;
447 	unsigned long flags;
448 	int i;
449 
450 	if (metadata->trap_type == DEVLINK_TRAP_TYPE_CONTROL)
451 		return;
452 
453 	hw_data = this_cpu_ptr(&dm_hw_cpu_data);
454 	spin_lock_irqsave(&hw_data->lock, flags);
455 	hw_entries = hw_data->hw_entries;
456 
457 	if (!hw_entries)
458 		goto out;
459 
460 	for (i = 0; i < hw_entries->num_entries; i++) {
461 		hw_entry = &hw_entries->entries[i];
462 		if (!strncmp(hw_entry->trap_name, metadata->trap_name,
463 			     NET_DM_MAX_HW_TRAP_NAME_LEN - 1)) {
464 			hw_entry->count++;
465 			goto out;
466 		}
467 	}
468 	if (WARN_ON_ONCE(hw_entries->num_entries == dm_hit_limit))
469 		goto out;
470 
471 	hw_entry = &hw_entries->entries[hw_entries->num_entries];
472 	strlcpy(hw_entry->trap_name, metadata->trap_name,
473 		NET_DM_MAX_HW_TRAP_NAME_LEN - 1);
474 	hw_entry->count = 1;
475 	hw_entries->num_entries++;
476 
477 	if (!timer_pending(&hw_data->send_timer)) {
478 		hw_data->send_timer.expires = jiffies + dm_delay * HZ;
479 		add_timer(&hw_data->send_timer);
480 	}
481 
482 out:
483 	spin_unlock_irqrestore(&hw_data->lock, flags);
484 }
485 
486 static const struct net_dm_alert_ops net_dm_alert_summary_ops = {
487 	.kfree_skb_probe	= trace_kfree_skb_hit,
488 	.napi_poll_probe	= trace_napi_poll_hit,
489 	.work_item_func		= send_dm_alert,
490 	.hw_work_item_func	= net_dm_hw_summary_work,
491 	.hw_trap_probe		= net_dm_hw_trap_summary_probe,
492 };
493 
494 static void net_dm_packet_trace_kfree_skb_hit(void *ignore,
495 					      struct sk_buff *skb,
496 					      void *location,
497 					      enum skb_drop_reason reason)
498 {
499 	ktime_t tstamp = ktime_get_real();
500 	struct per_cpu_dm_data *data;
501 	struct sk_buff *nskb;
502 	unsigned long flags;
503 
504 	if (!skb_mac_header_was_set(skb))
505 		return;
506 
507 	nskb = skb_clone(skb, GFP_ATOMIC);
508 	if (!nskb)
509 		return;
510 
511 	NET_DM_SKB_CB(nskb)->pc = location;
512 	/* Override the timestamp because we care about the time when the
513 	 * packet was dropped.
514 	 */
515 	nskb->tstamp = tstamp;
516 
517 	data = this_cpu_ptr(&dm_cpu_data);
518 
519 	spin_lock_irqsave(&data->drop_queue.lock, flags);
520 	if (skb_queue_len(&data->drop_queue) < net_dm_queue_len)
521 		__skb_queue_tail(&data->drop_queue, nskb);
522 	else
523 		goto unlock_free;
524 	spin_unlock_irqrestore(&data->drop_queue.lock, flags);
525 
526 	schedule_work(&data->dm_alert_work);
527 
528 	return;
529 
530 unlock_free:
531 	spin_unlock_irqrestore(&data->drop_queue.lock, flags);
532 	u64_stats_update_begin(&data->stats.syncp);
533 	data->stats.dropped++;
534 	u64_stats_update_end(&data->stats.syncp);
535 	consume_skb(nskb);
536 }
537 
538 static void net_dm_packet_trace_napi_poll_hit(void *ignore,
539 					      struct napi_struct *napi,
540 					      int work, int budget)
541 {
542 }
543 
544 static size_t net_dm_in_port_size(void)
545 {
546 	       /* NET_DM_ATTR_IN_PORT nest */
547 	return nla_total_size(0) +
548 	       /* NET_DM_ATTR_PORT_NETDEV_IFINDEX */
549 	       nla_total_size(sizeof(u32)) +
550 	       /* NET_DM_ATTR_PORT_NETDEV_NAME */
551 	       nla_total_size(IFNAMSIZ + 1);
552 }
553 
554 #define NET_DM_MAX_SYMBOL_LEN 40
555 
556 static size_t net_dm_packet_report_size(size_t payload_len)
557 {
558 	size_t size;
559 
560 	size = nlmsg_msg_size(GENL_HDRLEN + net_drop_monitor_family.hdrsize);
561 
562 	return NLMSG_ALIGN(size) +
563 	       /* NET_DM_ATTR_ORIGIN */
564 	       nla_total_size(sizeof(u16)) +
565 	       /* NET_DM_ATTR_PC */
566 	       nla_total_size(sizeof(u64)) +
567 	       /* NET_DM_ATTR_SYMBOL */
568 	       nla_total_size(NET_DM_MAX_SYMBOL_LEN + 1) +
569 	       /* NET_DM_ATTR_IN_PORT */
570 	       net_dm_in_port_size() +
571 	       /* NET_DM_ATTR_TIMESTAMP */
572 	       nla_total_size(sizeof(u64)) +
573 	       /* NET_DM_ATTR_ORIG_LEN */
574 	       nla_total_size(sizeof(u32)) +
575 	       /* NET_DM_ATTR_PROTO */
576 	       nla_total_size(sizeof(u16)) +
577 	       /* NET_DM_ATTR_PAYLOAD */
578 	       nla_total_size(payload_len);
579 }
580 
581 static int net_dm_packet_report_in_port_put(struct sk_buff *msg, int ifindex,
582 					    const char *name)
583 {
584 	struct nlattr *attr;
585 
586 	attr = nla_nest_start(msg, NET_DM_ATTR_IN_PORT);
587 	if (!attr)
588 		return -EMSGSIZE;
589 
590 	if (ifindex &&
591 	    nla_put_u32(msg, NET_DM_ATTR_PORT_NETDEV_IFINDEX, ifindex))
592 		goto nla_put_failure;
593 
594 	if (name && nla_put_string(msg, NET_DM_ATTR_PORT_NETDEV_NAME, name))
595 		goto nla_put_failure;
596 
597 	nla_nest_end(msg, attr);
598 
599 	return 0;
600 
601 nla_put_failure:
602 	nla_nest_cancel(msg, attr);
603 	return -EMSGSIZE;
604 }
605 
606 static int net_dm_packet_report_fill(struct sk_buff *msg, struct sk_buff *skb,
607 				     size_t payload_len)
608 {
609 	u64 pc = (u64)(uintptr_t) NET_DM_SKB_CB(skb)->pc;
610 	char buf[NET_DM_MAX_SYMBOL_LEN];
611 	struct nlattr *attr;
612 	void *hdr;
613 	int rc;
614 
615 	hdr = genlmsg_put(msg, 0, 0, &net_drop_monitor_family, 0,
616 			  NET_DM_CMD_PACKET_ALERT);
617 	if (!hdr)
618 		return -EMSGSIZE;
619 
620 	if (nla_put_u16(msg, NET_DM_ATTR_ORIGIN, NET_DM_ORIGIN_SW))
621 		goto nla_put_failure;
622 
623 	if (nla_put_u64_64bit(msg, NET_DM_ATTR_PC, pc, NET_DM_ATTR_PAD))
624 		goto nla_put_failure;
625 
626 	snprintf(buf, sizeof(buf), "%pS", NET_DM_SKB_CB(skb)->pc);
627 	if (nla_put_string(msg, NET_DM_ATTR_SYMBOL, buf))
628 		goto nla_put_failure;
629 
630 	rc = net_dm_packet_report_in_port_put(msg, skb->skb_iif, NULL);
631 	if (rc)
632 		goto nla_put_failure;
633 
634 	if (nla_put_u64_64bit(msg, NET_DM_ATTR_TIMESTAMP,
635 			      ktime_to_ns(skb->tstamp), NET_DM_ATTR_PAD))
636 		goto nla_put_failure;
637 
638 	if (nla_put_u32(msg, NET_DM_ATTR_ORIG_LEN, skb->len))
639 		goto nla_put_failure;
640 
641 	if (!payload_len)
642 		goto out;
643 
644 	if (nla_put_u16(msg, NET_DM_ATTR_PROTO, be16_to_cpu(skb->protocol)))
645 		goto nla_put_failure;
646 
647 	attr = skb_put(msg, nla_total_size(payload_len));
648 	attr->nla_type = NET_DM_ATTR_PAYLOAD;
649 	attr->nla_len = nla_attr_size(payload_len);
650 	if (skb_copy_bits(skb, 0, nla_data(attr), payload_len))
651 		goto nla_put_failure;
652 
653 out:
654 	genlmsg_end(msg, hdr);
655 
656 	return 0;
657 
658 nla_put_failure:
659 	genlmsg_cancel(msg, hdr);
660 	return -EMSGSIZE;
661 }
662 
663 #define NET_DM_MAX_PACKET_SIZE (0xffff - NLA_HDRLEN - NLA_ALIGNTO)
664 
665 static void net_dm_packet_report(struct sk_buff *skb)
666 {
667 	struct sk_buff *msg;
668 	size_t payload_len;
669 	int rc;
670 
671 	/* Make sure we start copying the packet from the MAC header */
672 	if (skb->data > skb_mac_header(skb))
673 		skb_push(skb, skb->data - skb_mac_header(skb));
674 	else
675 		skb_pull(skb, skb_mac_header(skb) - skb->data);
676 
677 	/* Ensure packet fits inside a single netlink attribute */
678 	payload_len = min_t(size_t, skb->len, NET_DM_MAX_PACKET_SIZE);
679 	if (net_dm_trunc_len)
680 		payload_len = min_t(size_t, net_dm_trunc_len, payload_len);
681 
682 	msg = nlmsg_new(net_dm_packet_report_size(payload_len), GFP_KERNEL);
683 	if (!msg)
684 		goto out;
685 
686 	rc = net_dm_packet_report_fill(msg, skb, payload_len);
687 	if (rc) {
688 		nlmsg_free(msg);
689 		goto out;
690 	}
691 
692 	genlmsg_multicast(&net_drop_monitor_family, msg, 0, 0, GFP_KERNEL);
693 
694 out:
695 	consume_skb(skb);
696 }
697 
698 static void net_dm_packet_work(struct work_struct *work)
699 {
700 	struct per_cpu_dm_data *data;
701 	struct sk_buff_head list;
702 	struct sk_buff *skb;
703 	unsigned long flags;
704 
705 	data = container_of(work, struct per_cpu_dm_data, dm_alert_work);
706 
707 	__skb_queue_head_init(&list);
708 
709 	spin_lock_irqsave(&data->drop_queue.lock, flags);
710 	skb_queue_splice_tail_init(&data->drop_queue, &list);
711 	spin_unlock_irqrestore(&data->drop_queue.lock, flags);
712 
713 	while ((skb = __skb_dequeue(&list)))
714 		net_dm_packet_report(skb);
715 }
716 
717 static size_t
718 net_dm_flow_action_cookie_size(const struct devlink_trap_metadata *hw_metadata)
719 {
720 	return hw_metadata->fa_cookie ?
721 	       nla_total_size(hw_metadata->fa_cookie->cookie_len) : 0;
722 }
723 
724 static size_t
725 net_dm_hw_packet_report_size(size_t payload_len,
726 			     const struct devlink_trap_metadata *hw_metadata)
727 {
728 	size_t size;
729 
730 	size = nlmsg_msg_size(GENL_HDRLEN + net_drop_monitor_family.hdrsize);
731 
732 	return NLMSG_ALIGN(size) +
733 	       /* NET_DM_ATTR_ORIGIN */
734 	       nla_total_size(sizeof(u16)) +
735 	       /* NET_DM_ATTR_HW_TRAP_GROUP_NAME */
736 	       nla_total_size(strlen(hw_metadata->trap_group_name) + 1) +
737 	       /* NET_DM_ATTR_HW_TRAP_NAME */
738 	       nla_total_size(strlen(hw_metadata->trap_name) + 1) +
739 	       /* NET_DM_ATTR_IN_PORT */
740 	       net_dm_in_port_size() +
741 	       /* NET_DM_ATTR_FLOW_ACTION_COOKIE */
742 	       net_dm_flow_action_cookie_size(hw_metadata) +
743 	       /* NET_DM_ATTR_TIMESTAMP */
744 	       nla_total_size(sizeof(u64)) +
745 	       /* NET_DM_ATTR_ORIG_LEN */
746 	       nla_total_size(sizeof(u32)) +
747 	       /* NET_DM_ATTR_PROTO */
748 	       nla_total_size(sizeof(u16)) +
749 	       /* NET_DM_ATTR_PAYLOAD */
750 	       nla_total_size(payload_len);
751 }
752 
753 static int net_dm_hw_packet_report_fill(struct sk_buff *msg,
754 					struct sk_buff *skb, size_t payload_len)
755 {
756 	struct devlink_trap_metadata *hw_metadata;
757 	struct nlattr *attr;
758 	void *hdr;
759 
760 	hw_metadata = NET_DM_SKB_CB(skb)->hw_metadata;
761 
762 	hdr = genlmsg_put(msg, 0, 0, &net_drop_monitor_family, 0,
763 			  NET_DM_CMD_PACKET_ALERT);
764 	if (!hdr)
765 		return -EMSGSIZE;
766 
767 	if (nla_put_u16(msg, NET_DM_ATTR_ORIGIN, NET_DM_ORIGIN_HW))
768 		goto nla_put_failure;
769 
770 	if (nla_put_string(msg, NET_DM_ATTR_HW_TRAP_GROUP_NAME,
771 			   hw_metadata->trap_group_name))
772 		goto nla_put_failure;
773 
774 	if (nla_put_string(msg, NET_DM_ATTR_HW_TRAP_NAME,
775 			   hw_metadata->trap_name))
776 		goto nla_put_failure;
777 
778 	if (hw_metadata->input_dev) {
779 		struct net_device *dev = hw_metadata->input_dev;
780 		int rc;
781 
782 		rc = net_dm_packet_report_in_port_put(msg, dev->ifindex,
783 						      dev->name);
784 		if (rc)
785 			goto nla_put_failure;
786 	}
787 
788 	if (hw_metadata->fa_cookie &&
789 	    nla_put(msg, NET_DM_ATTR_FLOW_ACTION_COOKIE,
790 		    hw_metadata->fa_cookie->cookie_len,
791 		    hw_metadata->fa_cookie->cookie))
792 		goto nla_put_failure;
793 
794 	if (nla_put_u64_64bit(msg, NET_DM_ATTR_TIMESTAMP,
795 			      ktime_to_ns(skb->tstamp), NET_DM_ATTR_PAD))
796 		goto nla_put_failure;
797 
798 	if (nla_put_u32(msg, NET_DM_ATTR_ORIG_LEN, skb->len))
799 		goto nla_put_failure;
800 
801 	if (!payload_len)
802 		goto out;
803 
804 	if (nla_put_u16(msg, NET_DM_ATTR_PROTO, be16_to_cpu(skb->protocol)))
805 		goto nla_put_failure;
806 
807 	attr = skb_put(msg, nla_total_size(payload_len));
808 	attr->nla_type = NET_DM_ATTR_PAYLOAD;
809 	attr->nla_len = nla_attr_size(payload_len);
810 	if (skb_copy_bits(skb, 0, nla_data(attr), payload_len))
811 		goto nla_put_failure;
812 
813 out:
814 	genlmsg_end(msg, hdr);
815 
816 	return 0;
817 
818 nla_put_failure:
819 	genlmsg_cancel(msg, hdr);
820 	return -EMSGSIZE;
821 }
822 
823 static struct devlink_trap_metadata *
824 net_dm_hw_metadata_copy(const struct devlink_trap_metadata *metadata)
825 {
826 	const struct flow_action_cookie *fa_cookie;
827 	struct devlink_trap_metadata *hw_metadata;
828 	const char *trap_group_name;
829 	const char *trap_name;
830 
831 	hw_metadata = kzalloc(sizeof(*hw_metadata), GFP_ATOMIC);
832 	if (!hw_metadata)
833 		return NULL;
834 
835 	trap_group_name = kstrdup(metadata->trap_group_name, GFP_ATOMIC);
836 	if (!trap_group_name)
837 		goto free_hw_metadata;
838 	hw_metadata->trap_group_name = trap_group_name;
839 
840 	trap_name = kstrdup(metadata->trap_name, GFP_ATOMIC);
841 	if (!trap_name)
842 		goto free_trap_group;
843 	hw_metadata->trap_name = trap_name;
844 
845 	if (metadata->fa_cookie) {
846 		size_t cookie_size = sizeof(*fa_cookie) +
847 				     metadata->fa_cookie->cookie_len;
848 
849 		fa_cookie = kmemdup(metadata->fa_cookie, cookie_size,
850 				    GFP_ATOMIC);
851 		if (!fa_cookie)
852 			goto free_trap_name;
853 		hw_metadata->fa_cookie = fa_cookie;
854 	}
855 
856 	hw_metadata->input_dev = metadata->input_dev;
857 	dev_hold_track(hw_metadata->input_dev, &hw_metadata->dev_tracker, GFP_ATOMIC);
858 
859 	return hw_metadata;
860 
861 free_trap_name:
862 	kfree(trap_name);
863 free_trap_group:
864 	kfree(trap_group_name);
865 free_hw_metadata:
866 	kfree(hw_metadata);
867 	return NULL;
868 }
869 
870 static void
871 net_dm_hw_metadata_free(struct devlink_trap_metadata *hw_metadata)
872 {
873 	dev_put_track(hw_metadata->input_dev, &hw_metadata->dev_tracker);
874 	kfree(hw_metadata->fa_cookie);
875 	kfree(hw_metadata->trap_name);
876 	kfree(hw_metadata->trap_group_name);
877 	kfree(hw_metadata);
878 }
879 
880 static void net_dm_hw_packet_report(struct sk_buff *skb)
881 {
882 	struct devlink_trap_metadata *hw_metadata;
883 	struct sk_buff *msg;
884 	size_t payload_len;
885 	int rc;
886 
887 	if (skb->data > skb_mac_header(skb))
888 		skb_push(skb, skb->data - skb_mac_header(skb));
889 	else
890 		skb_pull(skb, skb_mac_header(skb) - skb->data);
891 
892 	payload_len = min_t(size_t, skb->len, NET_DM_MAX_PACKET_SIZE);
893 	if (net_dm_trunc_len)
894 		payload_len = min_t(size_t, net_dm_trunc_len, payload_len);
895 
896 	hw_metadata = NET_DM_SKB_CB(skb)->hw_metadata;
897 	msg = nlmsg_new(net_dm_hw_packet_report_size(payload_len, hw_metadata),
898 			GFP_KERNEL);
899 	if (!msg)
900 		goto out;
901 
902 	rc = net_dm_hw_packet_report_fill(msg, skb, payload_len);
903 	if (rc) {
904 		nlmsg_free(msg);
905 		goto out;
906 	}
907 
908 	genlmsg_multicast(&net_drop_monitor_family, msg, 0, 0, GFP_KERNEL);
909 
910 out:
911 	net_dm_hw_metadata_free(NET_DM_SKB_CB(skb)->hw_metadata);
912 	consume_skb(skb);
913 }
914 
915 static void net_dm_hw_packet_work(struct work_struct *work)
916 {
917 	struct per_cpu_dm_data *hw_data;
918 	struct sk_buff_head list;
919 	struct sk_buff *skb;
920 	unsigned long flags;
921 
922 	hw_data = container_of(work, struct per_cpu_dm_data, dm_alert_work);
923 
924 	__skb_queue_head_init(&list);
925 
926 	spin_lock_irqsave(&hw_data->drop_queue.lock, flags);
927 	skb_queue_splice_tail_init(&hw_data->drop_queue, &list);
928 	spin_unlock_irqrestore(&hw_data->drop_queue.lock, flags);
929 
930 	while ((skb = __skb_dequeue(&list)))
931 		net_dm_hw_packet_report(skb);
932 }
933 
934 static void
935 net_dm_hw_trap_packet_probe(void *ignore, const struct devlink *devlink,
936 			    struct sk_buff *skb,
937 			    const struct devlink_trap_metadata *metadata)
938 {
939 	struct devlink_trap_metadata *n_hw_metadata;
940 	ktime_t tstamp = ktime_get_real();
941 	struct per_cpu_dm_data *hw_data;
942 	struct sk_buff *nskb;
943 	unsigned long flags;
944 
945 	if (metadata->trap_type == DEVLINK_TRAP_TYPE_CONTROL)
946 		return;
947 
948 	if (!skb_mac_header_was_set(skb))
949 		return;
950 
951 	nskb = skb_clone(skb, GFP_ATOMIC);
952 	if (!nskb)
953 		return;
954 
955 	n_hw_metadata = net_dm_hw_metadata_copy(metadata);
956 	if (!n_hw_metadata)
957 		goto free;
958 
959 	NET_DM_SKB_CB(nskb)->hw_metadata = n_hw_metadata;
960 	nskb->tstamp = tstamp;
961 
962 	hw_data = this_cpu_ptr(&dm_hw_cpu_data);
963 
964 	spin_lock_irqsave(&hw_data->drop_queue.lock, flags);
965 	if (skb_queue_len(&hw_data->drop_queue) < net_dm_queue_len)
966 		__skb_queue_tail(&hw_data->drop_queue, nskb);
967 	else
968 		goto unlock_free;
969 	spin_unlock_irqrestore(&hw_data->drop_queue.lock, flags);
970 
971 	schedule_work(&hw_data->dm_alert_work);
972 
973 	return;
974 
975 unlock_free:
976 	spin_unlock_irqrestore(&hw_data->drop_queue.lock, flags);
977 	u64_stats_update_begin(&hw_data->stats.syncp);
978 	hw_data->stats.dropped++;
979 	u64_stats_update_end(&hw_data->stats.syncp);
980 	net_dm_hw_metadata_free(n_hw_metadata);
981 free:
982 	consume_skb(nskb);
983 }
984 
985 static const struct net_dm_alert_ops net_dm_alert_packet_ops = {
986 	.kfree_skb_probe	= net_dm_packet_trace_kfree_skb_hit,
987 	.napi_poll_probe	= net_dm_packet_trace_napi_poll_hit,
988 	.work_item_func		= net_dm_packet_work,
989 	.hw_work_item_func	= net_dm_hw_packet_work,
990 	.hw_trap_probe		= net_dm_hw_trap_packet_probe,
991 };
992 
993 static const struct net_dm_alert_ops *net_dm_alert_ops_arr[] = {
994 	[NET_DM_ALERT_MODE_SUMMARY]	= &net_dm_alert_summary_ops,
995 	[NET_DM_ALERT_MODE_PACKET]	= &net_dm_alert_packet_ops,
996 };
997 
998 #if IS_ENABLED(CONFIG_NET_DEVLINK)
999 static int net_dm_hw_probe_register(const struct net_dm_alert_ops *ops)
1000 {
1001 	return register_trace_devlink_trap_report(ops->hw_trap_probe, NULL);
1002 }
1003 
1004 static void net_dm_hw_probe_unregister(const struct net_dm_alert_ops *ops)
1005 {
1006 	unregister_trace_devlink_trap_report(ops->hw_trap_probe, NULL);
1007 	tracepoint_synchronize_unregister();
1008 }
1009 #else
1010 static int net_dm_hw_probe_register(const struct net_dm_alert_ops *ops)
1011 {
1012 	return -EOPNOTSUPP;
1013 }
1014 
1015 static void net_dm_hw_probe_unregister(const struct net_dm_alert_ops *ops)
1016 {
1017 }
1018 #endif
1019 
1020 static int net_dm_hw_monitor_start(struct netlink_ext_ack *extack)
1021 {
1022 	const struct net_dm_alert_ops *ops;
1023 	int cpu, rc;
1024 
1025 	if (monitor_hw) {
1026 		NL_SET_ERR_MSG_MOD(extack, "Hardware monitoring already enabled");
1027 		return -EAGAIN;
1028 	}
1029 
1030 	ops = net_dm_alert_ops_arr[net_dm_alert_mode];
1031 
1032 	if (!try_module_get(THIS_MODULE)) {
1033 		NL_SET_ERR_MSG_MOD(extack, "Failed to take reference on module");
1034 		return -ENODEV;
1035 	}
1036 
1037 	for_each_possible_cpu(cpu) {
1038 		struct per_cpu_dm_data *hw_data = &per_cpu(dm_hw_cpu_data, cpu);
1039 		struct net_dm_hw_entries *hw_entries;
1040 
1041 		INIT_WORK(&hw_data->dm_alert_work, ops->hw_work_item_func);
1042 		timer_setup(&hw_data->send_timer, sched_send_work, 0);
1043 		hw_entries = net_dm_hw_reset_per_cpu_data(hw_data);
1044 		kfree(hw_entries);
1045 	}
1046 
1047 	rc = net_dm_hw_probe_register(ops);
1048 	if (rc) {
1049 		NL_SET_ERR_MSG_MOD(extack, "Failed to connect probe to devlink_trap_probe() tracepoint");
1050 		goto err_module_put;
1051 	}
1052 
1053 	monitor_hw = true;
1054 
1055 	return 0;
1056 
1057 err_module_put:
1058 	for_each_possible_cpu(cpu) {
1059 		struct per_cpu_dm_data *hw_data = &per_cpu(dm_hw_cpu_data, cpu);
1060 		struct sk_buff *skb;
1061 
1062 		del_timer_sync(&hw_data->send_timer);
1063 		cancel_work_sync(&hw_data->dm_alert_work);
1064 		while ((skb = __skb_dequeue(&hw_data->drop_queue))) {
1065 			struct devlink_trap_metadata *hw_metadata;
1066 
1067 			hw_metadata = NET_DM_SKB_CB(skb)->hw_metadata;
1068 			net_dm_hw_metadata_free(hw_metadata);
1069 			consume_skb(skb);
1070 		}
1071 	}
1072 	module_put(THIS_MODULE);
1073 	return rc;
1074 }
1075 
1076 static void net_dm_hw_monitor_stop(struct netlink_ext_ack *extack)
1077 {
1078 	const struct net_dm_alert_ops *ops;
1079 	int cpu;
1080 
1081 	if (!monitor_hw) {
1082 		NL_SET_ERR_MSG_MOD(extack, "Hardware monitoring already disabled");
1083 		return;
1084 	}
1085 
1086 	ops = net_dm_alert_ops_arr[net_dm_alert_mode];
1087 
1088 	monitor_hw = false;
1089 
1090 	net_dm_hw_probe_unregister(ops);
1091 
1092 	for_each_possible_cpu(cpu) {
1093 		struct per_cpu_dm_data *hw_data = &per_cpu(dm_hw_cpu_data, cpu);
1094 		struct sk_buff *skb;
1095 
1096 		del_timer_sync(&hw_data->send_timer);
1097 		cancel_work_sync(&hw_data->dm_alert_work);
1098 		while ((skb = __skb_dequeue(&hw_data->drop_queue))) {
1099 			struct devlink_trap_metadata *hw_metadata;
1100 
1101 			hw_metadata = NET_DM_SKB_CB(skb)->hw_metadata;
1102 			net_dm_hw_metadata_free(hw_metadata);
1103 			consume_skb(skb);
1104 		}
1105 	}
1106 
1107 	module_put(THIS_MODULE);
1108 }
1109 
1110 static int net_dm_trace_on_set(struct netlink_ext_ack *extack)
1111 {
1112 	const struct net_dm_alert_ops *ops;
1113 	int cpu, rc;
1114 
1115 	ops = net_dm_alert_ops_arr[net_dm_alert_mode];
1116 
1117 	if (!try_module_get(THIS_MODULE)) {
1118 		NL_SET_ERR_MSG_MOD(extack, "Failed to take reference on module");
1119 		return -ENODEV;
1120 	}
1121 
1122 	for_each_possible_cpu(cpu) {
1123 		struct per_cpu_dm_data *data = &per_cpu(dm_cpu_data, cpu);
1124 		struct sk_buff *skb;
1125 
1126 		INIT_WORK(&data->dm_alert_work, ops->work_item_func);
1127 		timer_setup(&data->send_timer, sched_send_work, 0);
1128 		/* Allocate a new per-CPU skb for the summary alert message and
1129 		 * free the old one which might contain stale data from
1130 		 * previous tracing.
1131 		 */
1132 		skb = reset_per_cpu_data(data);
1133 		consume_skb(skb);
1134 	}
1135 
1136 	rc = register_trace_kfree_skb(ops->kfree_skb_probe, NULL);
1137 	if (rc) {
1138 		NL_SET_ERR_MSG_MOD(extack, "Failed to connect probe to kfree_skb() tracepoint");
1139 		goto err_module_put;
1140 	}
1141 
1142 	rc = register_trace_napi_poll(ops->napi_poll_probe, NULL);
1143 	if (rc) {
1144 		NL_SET_ERR_MSG_MOD(extack, "Failed to connect probe to napi_poll() tracepoint");
1145 		goto err_unregister_trace;
1146 	}
1147 
1148 	return 0;
1149 
1150 err_unregister_trace:
1151 	unregister_trace_kfree_skb(ops->kfree_skb_probe, NULL);
1152 err_module_put:
1153 	for_each_possible_cpu(cpu) {
1154 		struct per_cpu_dm_data *data = &per_cpu(dm_cpu_data, cpu);
1155 		struct sk_buff *skb;
1156 
1157 		del_timer_sync(&data->send_timer);
1158 		cancel_work_sync(&data->dm_alert_work);
1159 		while ((skb = __skb_dequeue(&data->drop_queue)))
1160 			consume_skb(skb);
1161 	}
1162 	module_put(THIS_MODULE);
1163 	return rc;
1164 }
1165 
1166 static void net_dm_trace_off_set(void)
1167 {
1168 	struct dm_hw_stat_delta *new_stat, *temp;
1169 	const struct net_dm_alert_ops *ops;
1170 	int cpu;
1171 
1172 	ops = net_dm_alert_ops_arr[net_dm_alert_mode];
1173 
1174 	unregister_trace_napi_poll(ops->napi_poll_probe, NULL);
1175 	unregister_trace_kfree_skb(ops->kfree_skb_probe, NULL);
1176 
1177 	tracepoint_synchronize_unregister();
1178 
1179 	/* Make sure we do not send notifications to user space after request
1180 	 * to stop tracing returns.
1181 	 */
1182 	for_each_possible_cpu(cpu) {
1183 		struct per_cpu_dm_data *data = &per_cpu(dm_cpu_data, cpu);
1184 		struct sk_buff *skb;
1185 
1186 		del_timer_sync(&data->send_timer);
1187 		cancel_work_sync(&data->dm_alert_work);
1188 		while ((skb = __skb_dequeue(&data->drop_queue)))
1189 			consume_skb(skb);
1190 	}
1191 
1192 	list_for_each_entry_safe(new_stat, temp, &hw_stats_list, list) {
1193 		if (new_stat->dev == NULL) {
1194 			list_del_rcu(&new_stat->list);
1195 			kfree_rcu(new_stat, rcu);
1196 		}
1197 	}
1198 
1199 	module_put(THIS_MODULE);
1200 }
1201 
1202 static int set_all_monitor_traces(int state, struct netlink_ext_ack *extack)
1203 {
1204 	int rc = 0;
1205 
1206 	if (state == trace_state) {
1207 		NL_SET_ERR_MSG_MOD(extack, "Trace state already set to requested state");
1208 		return -EAGAIN;
1209 	}
1210 
1211 	switch (state) {
1212 	case TRACE_ON:
1213 		rc = net_dm_trace_on_set(extack);
1214 		break;
1215 	case TRACE_OFF:
1216 		net_dm_trace_off_set();
1217 		break;
1218 	default:
1219 		rc = 1;
1220 		break;
1221 	}
1222 
1223 	if (!rc)
1224 		trace_state = state;
1225 	else
1226 		rc = -EINPROGRESS;
1227 
1228 	return rc;
1229 }
1230 
1231 static bool net_dm_is_monitoring(void)
1232 {
1233 	return trace_state == TRACE_ON || monitor_hw;
1234 }
1235 
1236 static int net_dm_alert_mode_get_from_info(struct genl_info *info,
1237 					   enum net_dm_alert_mode *p_alert_mode)
1238 {
1239 	u8 val;
1240 
1241 	val = nla_get_u8(info->attrs[NET_DM_ATTR_ALERT_MODE]);
1242 
1243 	switch (val) {
1244 	case NET_DM_ALERT_MODE_SUMMARY:
1245 	case NET_DM_ALERT_MODE_PACKET:
1246 		*p_alert_mode = val;
1247 		break;
1248 	default:
1249 		return -EINVAL;
1250 	}
1251 
1252 	return 0;
1253 }
1254 
1255 static int net_dm_alert_mode_set(struct genl_info *info)
1256 {
1257 	struct netlink_ext_ack *extack = info->extack;
1258 	enum net_dm_alert_mode alert_mode;
1259 	int rc;
1260 
1261 	if (!info->attrs[NET_DM_ATTR_ALERT_MODE])
1262 		return 0;
1263 
1264 	rc = net_dm_alert_mode_get_from_info(info, &alert_mode);
1265 	if (rc) {
1266 		NL_SET_ERR_MSG_MOD(extack, "Invalid alert mode");
1267 		return -EINVAL;
1268 	}
1269 
1270 	net_dm_alert_mode = alert_mode;
1271 
1272 	return 0;
1273 }
1274 
1275 static void net_dm_trunc_len_set(struct genl_info *info)
1276 {
1277 	if (!info->attrs[NET_DM_ATTR_TRUNC_LEN])
1278 		return;
1279 
1280 	net_dm_trunc_len = nla_get_u32(info->attrs[NET_DM_ATTR_TRUNC_LEN]);
1281 }
1282 
1283 static void net_dm_queue_len_set(struct genl_info *info)
1284 {
1285 	if (!info->attrs[NET_DM_ATTR_QUEUE_LEN])
1286 		return;
1287 
1288 	net_dm_queue_len = nla_get_u32(info->attrs[NET_DM_ATTR_QUEUE_LEN]);
1289 }
1290 
1291 static int net_dm_cmd_config(struct sk_buff *skb,
1292 			struct genl_info *info)
1293 {
1294 	struct netlink_ext_ack *extack = info->extack;
1295 	int rc;
1296 
1297 	if (net_dm_is_monitoring()) {
1298 		NL_SET_ERR_MSG_MOD(extack, "Cannot configure drop monitor during monitoring");
1299 		return -EBUSY;
1300 	}
1301 
1302 	rc = net_dm_alert_mode_set(info);
1303 	if (rc)
1304 		return rc;
1305 
1306 	net_dm_trunc_len_set(info);
1307 
1308 	net_dm_queue_len_set(info);
1309 
1310 	return 0;
1311 }
1312 
1313 static int net_dm_monitor_start(bool set_sw, bool set_hw,
1314 				struct netlink_ext_ack *extack)
1315 {
1316 	bool sw_set = false;
1317 	int rc;
1318 
1319 	if (set_sw) {
1320 		rc = set_all_monitor_traces(TRACE_ON, extack);
1321 		if (rc)
1322 			return rc;
1323 		sw_set = true;
1324 	}
1325 
1326 	if (set_hw) {
1327 		rc = net_dm_hw_monitor_start(extack);
1328 		if (rc)
1329 			goto err_monitor_hw;
1330 	}
1331 
1332 	return 0;
1333 
1334 err_monitor_hw:
1335 	if (sw_set)
1336 		set_all_monitor_traces(TRACE_OFF, extack);
1337 	return rc;
1338 }
1339 
1340 static void net_dm_monitor_stop(bool set_sw, bool set_hw,
1341 				struct netlink_ext_ack *extack)
1342 {
1343 	if (set_hw)
1344 		net_dm_hw_monitor_stop(extack);
1345 	if (set_sw)
1346 		set_all_monitor_traces(TRACE_OFF, extack);
1347 }
1348 
1349 static int net_dm_cmd_trace(struct sk_buff *skb,
1350 			struct genl_info *info)
1351 {
1352 	bool set_sw = !!info->attrs[NET_DM_ATTR_SW_DROPS];
1353 	bool set_hw = !!info->attrs[NET_DM_ATTR_HW_DROPS];
1354 	struct netlink_ext_ack *extack = info->extack;
1355 
1356 	/* To maintain backward compatibility, we start / stop monitoring of
1357 	 * software drops if no flag is specified.
1358 	 */
1359 	if (!set_sw && !set_hw)
1360 		set_sw = true;
1361 
1362 	switch (info->genlhdr->cmd) {
1363 	case NET_DM_CMD_START:
1364 		return net_dm_monitor_start(set_sw, set_hw, extack);
1365 	case NET_DM_CMD_STOP:
1366 		net_dm_monitor_stop(set_sw, set_hw, extack);
1367 		return 0;
1368 	}
1369 
1370 	return -EOPNOTSUPP;
1371 }
1372 
1373 static int net_dm_config_fill(struct sk_buff *msg, struct genl_info *info)
1374 {
1375 	void *hdr;
1376 
1377 	hdr = genlmsg_put(msg, info->snd_portid, info->snd_seq,
1378 			  &net_drop_monitor_family, 0, NET_DM_CMD_CONFIG_NEW);
1379 	if (!hdr)
1380 		return -EMSGSIZE;
1381 
1382 	if (nla_put_u8(msg, NET_DM_ATTR_ALERT_MODE, net_dm_alert_mode))
1383 		goto nla_put_failure;
1384 
1385 	if (nla_put_u32(msg, NET_DM_ATTR_TRUNC_LEN, net_dm_trunc_len))
1386 		goto nla_put_failure;
1387 
1388 	if (nla_put_u32(msg, NET_DM_ATTR_QUEUE_LEN, net_dm_queue_len))
1389 		goto nla_put_failure;
1390 
1391 	genlmsg_end(msg, hdr);
1392 
1393 	return 0;
1394 
1395 nla_put_failure:
1396 	genlmsg_cancel(msg, hdr);
1397 	return -EMSGSIZE;
1398 }
1399 
1400 static int net_dm_cmd_config_get(struct sk_buff *skb, struct genl_info *info)
1401 {
1402 	struct sk_buff *msg;
1403 	int rc;
1404 
1405 	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1406 	if (!msg)
1407 		return -ENOMEM;
1408 
1409 	rc = net_dm_config_fill(msg, info);
1410 	if (rc)
1411 		goto free_msg;
1412 
1413 	return genlmsg_reply(msg, info);
1414 
1415 free_msg:
1416 	nlmsg_free(msg);
1417 	return rc;
1418 }
1419 
1420 static void net_dm_stats_read(struct net_dm_stats *stats)
1421 {
1422 	int cpu;
1423 
1424 	memset(stats, 0, sizeof(*stats));
1425 	for_each_possible_cpu(cpu) {
1426 		struct per_cpu_dm_data *data = &per_cpu(dm_cpu_data, cpu);
1427 		struct net_dm_stats *cpu_stats = &data->stats;
1428 		unsigned int start;
1429 		u64 dropped;
1430 
1431 		do {
1432 			start = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
1433 			dropped = cpu_stats->dropped;
1434 		} while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, start));
1435 
1436 		stats->dropped += dropped;
1437 	}
1438 }
1439 
1440 static int net_dm_stats_put(struct sk_buff *msg)
1441 {
1442 	struct net_dm_stats stats;
1443 	struct nlattr *attr;
1444 
1445 	net_dm_stats_read(&stats);
1446 
1447 	attr = nla_nest_start(msg, NET_DM_ATTR_STATS);
1448 	if (!attr)
1449 		return -EMSGSIZE;
1450 
1451 	if (nla_put_u64_64bit(msg, NET_DM_ATTR_STATS_DROPPED,
1452 			      stats.dropped, NET_DM_ATTR_PAD))
1453 		goto nla_put_failure;
1454 
1455 	nla_nest_end(msg, attr);
1456 
1457 	return 0;
1458 
1459 nla_put_failure:
1460 	nla_nest_cancel(msg, attr);
1461 	return -EMSGSIZE;
1462 }
1463 
1464 static void net_dm_hw_stats_read(struct net_dm_stats *stats)
1465 {
1466 	int cpu;
1467 
1468 	memset(stats, 0, sizeof(*stats));
1469 	for_each_possible_cpu(cpu) {
1470 		struct per_cpu_dm_data *hw_data = &per_cpu(dm_hw_cpu_data, cpu);
1471 		struct net_dm_stats *cpu_stats = &hw_data->stats;
1472 		unsigned int start;
1473 		u64 dropped;
1474 
1475 		do {
1476 			start = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
1477 			dropped = cpu_stats->dropped;
1478 		} while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, start));
1479 
1480 		stats->dropped += dropped;
1481 	}
1482 }
1483 
1484 static int net_dm_hw_stats_put(struct sk_buff *msg)
1485 {
1486 	struct net_dm_stats stats;
1487 	struct nlattr *attr;
1488 
1489 	net_dm_hw_stats_read(&stats);
1490 
1491 	attr = nla_nest_start(msg, NET_DM_ATTR_HW_STATS);
1492 	if (!attr)
1493 		return -EMSGSIZE;
1494 
1495 	if (nla_put_u64_64bit(msg, NET_DM_ATTR_STATS_DROPPED,
1496 			      stats.dropped, NET_DM_ATTR_PAD))
1497 		goto nla_put_failure;
1498 
1499 	nla_nest_end(msg, attr);
1500 
1501 	return 0;
1502 
1503 nla_put_failure:
1504 	nla_nest_cancel(msg, attr);
1505 	return -EMSGSIZE;
1506 }
1507 
1508 static int net_dm_stats_fill(struct sk_buff *msg, struct genl_info *info)
1509 {
1510 	void *hdr;
1511 	int rc;
1512 
1513 	hdr = genlmsg_put(msg, info->snd_portid, info->snd_seq,
1514 			  &net_drop_monitor_family, 0, NET_DM_CMD_STATS_NEW);
1515 	if (!hdr)
1516 		return -EMSGSIZE;
1517 
1518 	rc = net_dm_stats_put(msg);
1519 	if (rc)
1520 		goto nla_put_failure;
1521 
1522 	rc = net_dm_hw_stats_put(msg);
1523 	if (rc)
1524 		goto nla_put_failure;
1525 
1526 	genlmsg_end(msg, hdr);
1527 
1528 	return 0;
1529 
1530 nla_put_failure:
1531 	genlmsg_cancel(msg, hdr);
1532 	return -EMSGSIZE;
1533 }
1534 
1535 static int net_dm_cmd_stats_get(struct sk_buff *skb, struct genl_info *info)
1536 {
1537 	struct sk_buff *msg;
1538 	int rc;
1539 
1540 	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1541 	if (!msg)
1542 		return -ENOMEM;
1543 
1544 	rc = net_dm_stats_fill(msg, info);
1545 	if (rc)
1546 		goto free_msg;
1547 
1548 	return genlmsg_reply(msg, info);
1549 
1550 free_msg:
1551 	nlmsg_free(msg);
1552 	return rc;
1553 }
1554 
1555 static int dropmon_net_event(struct notifier_block *ev_block,
1556 			     unsigned long event, void *ptr)
1557 {
1558 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1559 	struct dm_hw_stat_delta *new_stat = NULL;
1560 	struct dm_hw_stat_delta *tmp;
1561 
1562 	switch (event) {
1563 	case NETDEV_REGISTER:
1564 		new_stat = kzalloc(sizeof(struct dm_hw_stat_delta), GFP_KERNEL);
1565 
1566 		if (!new_stat)
1567 			goto out;
1568 
1569 		new_stat->dev = dev;
1570 		new_stat->last_rx = jiffies;
1571 		mutex_lock(&net_dm_mutex);
1572 		list_add_rcu(&new_stat->list, &hw_stats_list);
1573 		mutex_unlock(&net_dm_mutex);
1574 		break;
1575 	case NETDEV_UNREGISTER:
1576 		mutex_lock(&net_dm_mutex);
1577 		list_for_each_entry_safe(new_stat, tmp, &hw_stats_list, list) {
1578 			if (new_stat->dev == dev) {
1579 				new_stat->dev = NULL;
1580 				if (trace_state == TRACE_OFF) {
1581 					list_del_rcu(&new_stat->list);
1582 					kfree_rcu(new_stat, rcu);
1583 					break;
1584 				}
1585 			}
1586 		}
1587 		mutex_unlock(&net_dm_mutex);
1588 		break;
1589 	}
1590 out:
1591 	return NOTIFY_DONE;
1592 }
1593 
1594 static const struct nla_policy net_dm_nl_policy[NET_DM_ATTR_MAX + 1] = {
1595 	[NET_DM_ATTR_UNSPEC] = { .strict_start_type = NET_DM_ATTR_UNSPEC + 1 },
1596 	[NET_DM_ATTR_ALERT_MODE] = { .type = NLA_U8 },
1597 	[NET_DM_ATTR_TRUNC_LEN] = { .type = NLA_U32 },
1598 	[NET_DM_ATTR_QUEUE_LEN] = { .type = NLA_U32 },
1599 	[NET_DM_ATTR_SW_DROPS]	= {. type = NLA_FLAG },
1600 	[NET_DM_ATTR_HW_DROPS]	= {. type = NLA_FLAG },
1601 };
1602 
1603 static const struct genl_small_ops dropmon_ops[] = {
1604 	{
1605 		.cmd = NET_DM_CMD_CONFIG,
1606 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
1607 		.doit = net_dm_cmd_config,
1608 		.flags = GENL_ADMIN_PERM,
1609 	},
1610 	{
1611 		.cmd = NET_DM_CMD_START,
1612 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
1613 		.doit = net_dm_cmd_trace,
1614 	},
1615 	{
1616 		.cmd = NET_DM_CMD_STOP,
1617 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
1618 		.doit = net_dm_cmd_trace,
1619 	},
1620 	{
1621 		.cmd = NET_DM_CMD_CONFIG_GET,
1622 		.doit = net_dm_cmd_config_get,
1623 	},
1624 	{
1625 		.cmd = NET_DM_CMD_STATS_GET,
1626 		.doit = net_dm_cmd_stats_get,
1627 	},
1628 };
1629 
1630 static int net_dm_nl_pre_doit(const struct genl_ops *ops,
1631 			      struct sk_buff *skb, struct genl_info *info)
1632 {
1633 	mutex_lock(&net_dm_mutex);
1634 
1635 	return 0;
1636 }
1637 
1638 static void net_dm_nl_post_doit(const struct genl_ops *ops,
1639 				struct sk_buff *skb, struct genl_info *info)
1640 {
1641 	mutex_unlock(&net_dm_mutex);
1642 }
1643 
1644 static struct genl_family net_drop_monitor_family __ro_after_init = {
1645 	.hdrsize        = 0,
1646 	.name           = "NET_DM",
1647 	.version        = 2,
1648 	.maxattr	= NET_DM_ATTR_MAX,
1649 	.policy		= net_dm_nl_policy,
1650 	.pre_doit	= net_dm_nl_pre_doit,
1651 	.post_doit	= net_dm_nl_post_doit,
1652 	.module		= THIS_MODULE,
1653 	.small_ops	= dropmon_ops,
1654 	.n_small_ops	= ARRAY_SIZE(dropmon_ops),
1655 	.mcgrps		= dropmon_mcgrps,
1656 	.n_mcgrps	= ARRAY_SIZE(dropmon_mcgrps),
1657 };
1658 
1659 static struct notifier_block dropmon_net_notifier = {
1660 	.notifier_call = dropmon_net_event
1661 };
1662 
1663 static void __net_dm_cpu_data_init(struct per_cpu_dm_data *data)
1664 {
1665 	spin_lock_init(&data->lock);
1666 	skb_queue_head_init(&data->drop_queue);
1667 	u64_stats_init(&data->stats.syncp);
1668 }
1669 
1670 static void __net_dm_cpu_data_fini(struct per_cpu_dm_data *data)
1671 {
1672 	WARN_ON(!skb_queue_empty(&data->drop_queue));
1673 }
1674 
1675 static void net_dm_cpu_data_init(int cpu)
1676 {
1677 	struct per_cpu_dm_data *data;
1678 
1679 	data = &per_cpu(dm_cpu_data, cpu);
1680 	__net_dm_cpu_data_init(data);
1681 }
1682 
1683 static void net_dm_cpu_data_fini(int cpu)
1684 {
1685 	struct per_cpu_dm_data *data;
1686 
1687 	data = &per_cpu(dm_cpu_data, cpu);
1688 	/* At this point, we should have exclusive access
1689 	 * to this struct and can free the skb inside it.
1690 	 */
1691 	consume_skb(data->skb);
1692 	__net_dm_cpu_data_fini(data);
1693 }
1694 
1695 static void net_dm_hw_cpu_data_init(int cpu)
1696 {
1697 	struct per_cpu_dm_data *hw_data;
1698 
1699 	hw_data = &per_cpu(dm_hw_cpu_data, cpu);
1700 	__net_dm_cpu_data_init(hw_data);
1701 }
1702 
1703 static void net_dm_hw_cpu_data_fini(int cpu)
1704 {
1705 	struct per_cpu_dm_data *hw_data;
1706 
1707 	hw_data = &per_cpu(dm_hw_cpu_data, cpu);
1708 	kfree(hw_data->hw_entries);
1709 	__net_dm_cpu_data_fini(hw_data);
1710 }
1711 
1712 static int __init init_net_drop_monitor(void)
1713 {
1714 	int cpu, rc;
1715 
1716 	pr_info("Initializing network drop monitor service\n");
1717 
1718 	if (sizeof(void *) > 8) {
1719 		pr_err("Unable to store program counters on this arch, Drop monitor failed\n");
1720 		return -ENOSPC;
1721 	}
1722 
1723 	rc = genl_register_family(&net_drop_monitor_family);
1724 	if (rc) {
1725 		pr_err("Could not create drop monitor netlink family\n");
1726 		return rc;
1727 	}
1728 	WARN_ON(net_drop_monitor_family.mcgrp_offset != NET_DM_GRP_ALERT);
1729 
1730 	rc = register_netdevice_notifier(&dropmon_net_notifier);
1731 	if (rc < 0) {
1732 		pr_crit("Failed to register netdevice notifier\n");
1733 		goto out_unreg;
1734 	}
1735 
1736 	rc = 0;
1737 
1738 	for_each_possible_cpu(cpu) {
1739 		net_dm_cpu_data_init(cpu);
1740 		net_dm_hw_cpu_data_init(cpu);
1741 	}
1742 
1743 	goto out;
1744 
1745 out_unreg:
1746 	genl_unregister_family(&net_drop_monitor_family);
1747 out:
1748 	return rc;
1749 }
1750 
1751 static void exit_net_drop_monitor(void)
1752 {
1753 	int cpu;
1754 
1755 	BUG_ON(unregister_netdevice_notifier(&dropmon_net_notifier));
1756 
1757 	/*
1758 	 * Because of the module_get/put we do in the trace state change path
1759 	 * we are guaranteed not to have any current users when we get here
1760 	 */
1761 
1762 	for_each_possible_cpu(cpu) {
1763 		net_dm_hw_cpu_data_fini(cpu);
1764 		net_dm_cpu_data_fini(cpu);
1765 	}
1766 
1767 	BUG_ON(genl_unregister_family(&net_drop_monitor_family));
1768 }
1769 
1770 module_init(init_net_drop_monitor);
1771 module_exit(exit_net_drop_monitor);
1772 
1773 MODULE_LICENSE("GPL v2");
1774 MODULE_AUTHOR("Neil Horman <nhorman@tuxdriver.com>");
1775 MODULE_ALIAS_GENL_FAMILY("NET_DM");
1776 MODULE_DESCRIPTION("Monitoring code for network dropped packet alerts");
1777