xref: /linux/drivers/net/netconsole.c (revision 26ba30221c03364d6ed9910be8da4c1fd871b07b)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  linux/drivers/net/netconsole.c
4  *
5  *  Copyright (C) 2001  Ingo Molnar <mingo@redhat.com>
6  *
7  *  This file contains the implementation of an IRQ-safe, crash-safe
8  *  kernel console implementation that outputs kernel messages to the
9  *  network.
10  *
11  * Modification history:
12  *
13  * 2001-09-17    started by Ingo Molnar.
14  * 2003-08-11    2.6 port by Matt Mackall
15  *               simplified options
16  *               generic card hooks
17  *               works non-modular
18  * 2003-09-07    rewritten with netpoll api
19  */
20 
21 /****************************************************************
22  *
23  ****************************************************************/
24 
25 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
26 
27 #include <linux/mm.h>
28 #include <linux/init.h>
29 #include <linux/module.h>
30 #include <linux/slab.h>
31 #include <linux/console.h>
32 #include <linux/moduleparam.h>
33 #include <linux/kernel.h>
34 #include <linux/string.h>
35 #include <linux/ip.h>
36 #include <linux/ipv6.h>
37 #include <linux/udp.h>
38 #include <linux/netpoll.h>
39 #include <linux/inet.h>
40 #include <linux/inetdevice.h>
41 #include <linux/unaligned.h>
42 #include <net/ip6_checksum.h>
43 #include <net/addrconf.h>
44 #include <linux/configfs.h>
45 #include <linux/etherdevice.h>
46 #include <linux/hex.h>
47 #include <linux/u64_stats_sync.h>
48 #include <linux/utsname.h>
49 #include <linux/rtnetlink.h>
50 #include <linux/workqueue.h>
51 #include <linux/delay.h>
52 
53 MODULE_AUTHOR("Matt Mackall <mpm@selenic.com>");
54 MODULE_DESCRIPTION("Console driver for network interfaces");
55 MODULE_LICENSE("GPL");
56 MODULE_IMPORT_NS("NETDEV_INTERNAL");
57 
58 #define MAX_PARAM_LENGTH		256
59 #define MAX_EXTRADATA_ENTRY_LEN		256
60 #define MAX_EXTRADATA_VALUE_LEN	200
61 /* The number 3 comes from userdata entry format characters (' ', '=', '\n') */
62 #define MAX_EXTRADATA_NAME_LEN		(MAX_EXTRADATA_ENTRY_LEN - \
63 					MAX_EXTRADATA_VALUE_LEN - 3)
64 #define MAX_USERDATA_ITEMS		256
65 #define MAX_PRINT_CHUNK			1000
66 
67 /*
68  * Sizing for the per-target fallback skb pool consulted by find_skb()
69  * when its GFP_ATOMIC allocation fails so messages still get out under
70  * memory pressure.
71  */
72 #define MAX_UDP_CHUNK			1460
73 #define MAX_SKBS			32
74 #define MAX_SKB_SIZE							\
75 	(sizeof(struct ethhdr) +					\
76 	 sizeof(struct iphdr) +						\
77 	 sizeof(struct udphdr) +					\
78 	 MAX_UDP_CHUNK)
79 
80 static char config[MAX_PARAM_LENGTH];
81 module_param_string(netconsole, config, MAX_PARAM_LENGTH, 0);
82 MODULE_PARM_DESC(netconsole, " netconsole=[src-port]@[src-ip]/[dev],[tgt-port]@<tgt-ip>/[tgt-macaddr]");
83 
84 static bool oops_only;
85 module_param(oops_only, bool, 0600);
86 MODULE_PARM_DESC(oops_only, "Only log oops messages");
87 
88 #define NETCONSOLE_PARAM_TARGET_PREFIX "cmdline"
89 
90 #ifndef	MODULE
91 static int __init option_setup(char *opt)
92 {
93 	strscpy(config, opt, MAX_PARAM_LENGTH);
94 	return 1;
95 }
96 __setup("netconsole=", option_setup);
97 #endif	/* MODULE */
98 
99 /* Linked list of all configured targets */
100 static LIST_HEAD(target_list);
101 /* target_cleanup_list is used to track targets that need to be cleaned outside
102  * of target_list_lock. It should be cleaned in the same function it is
103  * populated.
104  */
105 static LIST_HEAD(target_cleanup_list);
106 
107 /* This needs to be a spinlock because write_msg() cannot sleep */
108 static DEFINE_SPINLOCK(target_list_lock);
109 /* This needs to be a mutex because netpoll_cleanup might sleep */
110 static DEFINE_MUTEX(target_cleanup_list_lock);
111 
112 static struct workqueue_struct *netconsole_wq;
113 
114 /*
115  * Console driver for netconsoles.  Register only consoles that have
116  * an associated target of the same type.
117  */
118 static struct console netconsole_ext, netconsole;
119 
120 struct netconsole_target_stats  {
121 	u64_stats_t xmit_drop_count;
122 	u64_stats_t enomem_count;
123 	struct u64_stats_sync syncp;
124 };
125 
126 enum console_type {
127 	CONS_BASIC = BIT(0),
128 	CONS_EXTENDED = BIT(1),
129 };
130 
131 /* Features enabled in sysdata. Contrary to userdata, this data is populated by
132  * the kernel. The fields are designed as bitwise flags, allowing multiple
133  * features to be set in sysdata_fields.
134  */
135 enum sysdata_feature {
136 	/* Populate the CPU that sends the message */
137 	SYSDATA_CPU_NR = BIT(0),
138 	/* Populate the task name (as in current->comm) in sysdata */
139 	SYSDATA_TASKNAME = BIT(1),
140 	/* Kernel release/version as part of sysdata */
141 	SYSDATA_RELEASE = BIT(2),
142 	/* Include a per-target message ID as part of sysdata */
143 	SYSDATA_MSGID = BIT(3),
144 	/* Sentinel: highest bit position */
145 	MAX_SYSDATA_ITEMS = 4,
146 };
147 
148 enum target_state {
149 	STATE_DISABLED,
150 	STATE_ENABLED,
151 	STATE_DEACTIVATED,
152 };
153 
154 /**
155  * struct netconsole_target - Represents a configured netconsole target.
156  * @list:	Links this target into the target_list.
157  * @group:	Links us into the configfs subsystem hierarchy.
158  * @userdata_group:	Links to the userdata configfs hierarchy
159  * @userdata:		Cached, formatted string of append
160  * @userdata_length:	String length of userdata.
161  * @sysdata:		Cached, formatted string of append
162  * @sysdata_fields:	Sysdata features enabled.
163  * @msgcounter:	Message sent counter.
164  * @stats:	Packet send stats for the target. Used for debugging.
165  * @state:	State of the target.
166  *		Visible from userspace (read-write).
167  *		From a userspace perspective, the target is either enabled or
168  *		disabled. Internally, although both STATE_DISABLED and
169  *		STATE_DEACTIVATED correspond to inactive targets, the latter is
170  *		due to automatic interface state changes and will try
171  *		recover automatically, if the interface comes back
172  *		online.
173  *		Also, other parameters of a target may be modified at
174  *		runtime only when it is disabled (state != STATE_ENABLED).
175  * @extended:	Denotes whether console is extended or not.
176  * @release:	Denotes whether kernel release version should be prepended
177  *		to the message. Depends on extended console.
178  * @np:		The netpoll structure for this target.
179  *		Contains the other userspace visible parameters:
180  *		dev_name	(read-write)
181  *		local_mac	(read-only)
182  * @local_ip:	Source IP address of the target (read-write).
183  * @remote_ip:	Destination IP address of the target (read-write).
184  * @ipv6:	Whether the target addresses are IPv6 (read-write).
185  * @local_port:	Source UDP port of the target (read-write).
186  * @remote_port: Destination UDP port of the target (read-write).
187  * @remote_mac:	Destination ethernet address of the target (read-write).
188  * @buf:	The buffer used to send the full msg to the network stack
189  * @resume_wq:	Workqueue to resume deactivated target
190  * @skb_pool:	Per-target fallback skb pool consulted by find_skb() when
191  *		its GFP_ATOMIC allocation fails. Lifetime brackets a
192  *		successful netpoll_setup() / netpoll_cleanup() pair on @np.
193  * @refill_wq:	Work item that asynchronously tops @skb_pool back up to
194  *		MAX_SKBS after find_skb() drains an entry.
195  */
196 struct netconsole_target {
197 	struct list_head	list;
198 #ifdef	CONFIG_NETCONSOLE_DYNAMIC
199 	struct config_group	group;
200 	struct config_group	userdata_group;
201 	char			*userdata;
202 	size_t			userdata_length;
203 	char			sysdata[MAX_EXTRADATA_ENTRY_LEN * MAX_SYSDATA_ITEMS];
204 
205 	/* bit-wise with sysdata_feature bits */
206 	u32			sysdata_fields;
207 	/* protected by target_list_lock */
208 	u32			msgcounter;
209 #endif
210 	struct netconsole_target_stats stats;
211 	enum target_state	state;
212 	bool			extended;
213 	bool			release;
214 	struct netpoll		np;
215 	union inet_addr		local_ip, remote_ip;
216 	bool			ipv6;
217 	u16			local_port, remote_port;
218 	u8			remote_mac[ETH_ALEN];
219 	/* protected by target_list_lock; +1 gives scnprintf() room for its
220 	 * NUL terminator so a full MAX_PRINT_CHUNK payload is not truncated
221 	 */
222 	char			buf[MAX_PRINT_CHUNK + 1];
223 	struct work_struct	resume_wq;
224 	struct sk_buff_head	skb_pool;
225 	struct work_struct	refill_wq;
226 };
227 
228 #ifdef	CONFIG_NETCONSOLE_DYNAMIC
229 
230 static struct configfs_subsystem netconsole_subsys;
231 static DEFINE_MUTEX(dynamic_netconsole_mutex);
232 
233 static int __init dynamic_netconsole_init(void)
234 {
235 	config_group_init(&netconsole_subsys.su_group);
236 	mutex_init(&netconsole_subsys.su_mutex);
237 	return configfs_register_subsystem(&netconsole_subsys);
238 }
239 
240 static void __exit dynamic_netconsole_exit(void)
241 {
242 	configfs_unregister_subsystem(&netconsole_subsys);
243 }
244 
245 /*
246  * Targets that were created by parsing the boot/module option string
247  * do not exist in the configfs hierarchy (and have NULL names) and will
248  * never go away, so make these a no-op for them.
249  */
250 static void netconsole_target_get(struct netconsole_target *nt)
251 {
252 	if (config_item_name(&nt->group.cg_item))
253 		config_group_get(&nt->group);
254 }
255 
256 static void netconsole_target_put(struct netconsole_target *nt)
257 {
258 	if (config_item_name(&nt->group.cg_item))
259 		config_group_put(&nt->group);
260 }
261 
262 static void dynamic_netconsole_mutex_lock(void)
263 {
264 	mutex_lock(&dynamic_netconsole_mutex);
265 }
266 
267 static void dynamic_netconsole_mutex_unlock(void)
268 {
269 	mutex_unlock(&dynamic_netconsole_mutex);
270 }
271 
272 #else	/* !CONFIG_NETCONSOLE_DYNAMIC */
273 
274 static int __init dynamic_netconsole_init(void)
275 {
276 	return 0;
277 }
278 
279 static void __exit dynamic_netconsole_exit(void)
280 {
281 }
282 
283 /*
284  * No danger of targets going away from under us when dynamic
285  * reconfigurability is off.
286  */
287 static void netconsole_target_get(struct netconsole_target *nt)
288 {
289 }
290 
291 static void netconsole_target_put(struct netconsole_target *nt)
292 {
293 }
294 
295 static void populate_configfs_item(struct netconsole_target *nt,
296 				   int cmdline_count)
297 {
298 }
299 
300 static void dynamic_netconsole_mutex_lock(void)
301 {
302 }
303 
304 static void dynamic_netconsole_mutex_unlock(void)
305 {
306 }
307 
308 #endif	/* CONFIG_NETCONSOLE_DYNAMIC */
309 
310 /* Check if the target was bound by mac address. */
311 static bool bound_by_mac(struct netconsole_target *nt)
312 {
313 	return is_valid_ether_addr(nt->np.dev_mac);
314 }
315 
316 static void netcons_release_dev(struct netconsole_target *nt)
317 {
318 	do_netpoll_cleanup(&nt->np);
319 	if (bound_by_mac(nt))
320 		memset(&nt->np.dev_name, 0, IFNAMSIZ);
321 }
322 
323 static void refill_skbs(struct netconsole_target *nt)
324 {
325 	struct sk_buff_head *skb_pool = &nt->skb_pool;
326 	struct sk_buff *skb;
327 
328 	while (READ_ONCE(skb_pool->qlen) < MAX_SKBS) {
329 		skb = alloc_skb(MAX_SKB_SIZE, GFP_ATOMIC | __GFP_NOWARN);
330 		if (!skb)
331 			break;
332 
333 		skb_queue_tail(skb_pool, skb);
334 	}
335 }
336 
337 static void refill_skbs_work_handler(struct work_struct *work)
338 {
339 	struct netconsole_target *nt =
340 		container_of(work, struct netconsole_target, refill_wq);
341 
342 	refill_skbs(nt);
343 }
344 
345 /* Seed the per-target skb pool that find_skb() falls back to. The queue
346  * head and refill work are set up once in alloc_and_init(); this only
347  * (re)fills the pool. Pair with netconsole_skb_pool_flush().
348  */
349 static void netconsole_skb_pool_init(struct netconsole_target *nt)
350 {
351 	refill_skbs(nt);
352 }
353 
354 static void netconsole_skb_pool_flush(struct netconsole_target *nt)
355 {
356 	cancel_work_sync(&nt->refill_wq);
357 	skb_queue_purge_reason(&nt->skb_pool, SKB_CONSUMED);
358 }
359 
360 static void netcons_wait_carrier(struct netpoll *np, struct net_device *ndev)
361 {
362 	unsigned long atmost;
363 
364 	atmost = jiffies + netpoll_get_carrier_timeout() * HZ;
365 	while (!netif_carrier_ok(ndev)) {
366 		if (time_after(jiffies, atmost)) {
367 			np_notice(np, "timeout waiting for carrier\n");
368 			break;
369 		}
370 		msleep(1);
371 	}
372 }
373 
374 /*
375  * Returns a pointer to a string representation of the identifier used
376  * to select the egress interface for the given netpoll instance. buf
377  * is used to format np->dev_mac when np->dev_name is empty; bufsz must
378  * be at least MAC_ADDR_STR_LEN + 1 to fit the formatted MAC address
379  * and its NUL terminator.
380  */
381 static char *netcons_egress_dev(struct netpoll *np, char *buf, size_t bufsz)
382 {
383 	if (np->dev_name[0])
384 		return np->dev_name;
385 
386 	snprintf(buf, bufsz, "%pM", np->dev_mac);
387 	return buf;
388 }
389 
390 /*
391  * Populate the target's local_ip with the IPv6 address from ndev.
392  */
393 static int netcons_take_ipv6(struct netconsole_target *nt,
394 			     struct net_device *ndev)
395 {
396 	char buf[MAC_ADDR_STR_LEN + 1];
397 	struct netpoll *np = &nt->np;
398 	int err = -EDESTADDRREQ;
399 	struct inet6_dev *idev;
400 
401 	if (!IS_ENABLED(CONFIG_IPV6)) {
402 		np_err(np, "IPv6 is not supported %s, aborting\n",
403 		       netcons_egress_dev(np, buf, sizeof(buf)));
404 		return -EINVAL;
405 	}
406 
407 	idev = __in6_dev_get(ndev);
408 	if (idev) {
409 		struct inet6_ifaddr *ifp;
410 
411 		read_lock_bh(&idev->lock);
412 		list_for_each_entry(ifp, &idev->addr_list, if_list) {
413 			if (!!(ipv6_addr_type(&ifp->addr) & IPV6_ADDR_LINKLOCAL) !=
414 				!!(ipv6_addr_type(&nt->remote_ip.in6) & IPV6_ADDR_LINKLOCAL))
415 				continue;
416 			/* Got the IP, let's return */
417 			nt->local_ip.in6 = ifp->addr;
418 			err = 0;
419 			break;
420 		}
421 		read_unlock_bh(&idev->lock);
422 	}
423 	if (err) {
424 		np_err(np, "no IPv6 address for %s, aborting\n",
425 		       netcons_egress_dev(np, buf, sizeof(buf)));
426 		return err;
427 	}
428 
429 	np_info(np, "local IPv6 %pI6c\n", &nt->local_ip.in6);
430 	return 0;
431 }
432 
433 /*
434  * Populate the target's local_ip with the IPv4 address from ndev.
435  */
436 static int netcons_take_ipv4(struct netconsole_target *nt,
437 			     struct net_device *ndev)
438 {
439 	char buf[MAC_ADDR_STR_LEN + 1];
440 	struct netpoll *np = &nt->np;
441 	const struct in_ifaddr *ifa;
442 	struct in_device *in_dev;
443 
444 	in_dev = __in_dev_get_rtnl(ndev);
445 	if (!in_dev) {
446 		np_err(np, "no IP address for %s, aborting\n",
447 		       netcons_egress_dev(np, buf, sizeof(buf)));
448 		return -EDESTADDRREQ;
449 	}
450 
451 	ifa = rtnl_dereference(in_dev->ifa_list);
452 	if (!ifa) {
453 		np_err(np, "no IP address for %s, aborting\n",
454 		       netcons_egress_dev(np, buf, sizeof(buf)));
455 		return -EDESTADDRREQ;
456 	}
457 
458 	nt->local_ip.ip = ifa->ifa_local;
459 	np_info(np, "local IP %pI4\n", &nt->local_ip.ip);
460 
461 	return 0;
462 }
463 
464 /*
465  * Test whether the caller left nt->local_ip unset, so that
466  * netcons_netpoll_setup() should auto-populate it from the egress device.
467  *
468  * nt->local_ip is a union of __be32 (IPv4) and struct in6_addr (IPv6),
469  * so an IPv6 address whose first 4 bytes are zero (e.g. ::1, ::2,
470  * IPv4-mapped ::ffff:a.b.c.d) must not be tested via the IPv4 arm —
471  * doing so would misclassify a caller-supplied address as unset and
472  * silently overwrite it with whatever address the device exposes.
473  */
474 static bool netcons_local_ip_unset(const struct netconsole_target *nt)
475 {
476 	if (nt->ipv6)
477 		return ipv6_addr_any(&nt->local_ip.in6);
478 	return !nt->local_ip.ip;
479 }
480 
481 static int netcons_netpoll_setup(struct netconsole_target *nt)
482 {
483 	struct net *net = current->nsproxy->net_ns;
484 	char buf[MAC_ADDR_STR_LEN + 1];
485 	struct net_device *ndev = NULL;
486 	struct netpoll *np = &nt->np;
487 	bool ip_overwritten = false;
488 	int err;
489 
490 	rtnl_lock();
491 	if (np->dev_name[0])
492 		ndev = __dev_get_by_name(net, np->dev_name);
493 	else if (is_valid_ether_addr(np->dev_mac))
494 		ndev = dev_getbyhwaddr(net, ARPHRD_ETHER, np->dev_mac);
495 
496 	if (!ndev) {
497 		np_err(np, "%s doesn't exist, aborting\n",
498 		       netcons_egress_dev(np, buf, sizeof(buf)));
499 		err = -ENODEV;
500 		goto unlock;
501 	}
502 	netdev_hold(ndev, &np->dev_tracker, GFP_KERNEL);
503 
504 	if (netdev_master_upper_dev_get(ndev)) {
505 		np_err(np, "%s is a slave device, aborting\n",
506 		       netcons_egress_dev(np, buf, sizeof(buf)));
507 		err = -EBUSY;
508 		goto put;
509 	}
510 
511 	if (!netif_running(ndev)) {
512 		np_info(np, "device %s not up yet, forcing it\n",
513 			netcons_egress_dev(np, buf, sizeof(buf)));
514 
515 		err = dev_open(ndev, NULL);
516 		if (err) {
517 			np_err(np, "failed to open %s\n", ndev->name);
518 			goto put;
519 		}
520 
521 		rtnl_unlock();
522 		netcons_wait_carrier(np, ndev);
523 		rtnl_lock();
524 	}
525 
526 	if (netcons_local_ip_unset(nt)) {
527 		if (!nt->ipv6) {
528 			err = netcons_take_ipv4(nt, ndev);
529 			if (err)
530 				goto put;
531 		} else {
532 			err = netcons_take_ipv6(nt, ndev);
533 			if (err)
534 				goto put;
535 		}
536 		ip_overwritten = true;
537 	}
538 
539 	err = __netpoll_setup(np, ndev);
540 	if (err)
541 		goto put;
542 	rtnl_unlock();
543 
544 	/* Make sure all NAPI polls which started before dev->npinfo
545 	 * was visible have exited before we start calling NAPI poll.
546 	 * NAPI skips locking if dev->npinfo is NULL.
547 	 */
548 	synchronize_rcu();
549 
550 	return 0;
551 
552 put:
553 	DEBUG_NET_WARN_ON_ONCE(np->dev);
554 	if (ip_overwritten)
555 		memset(&nt->local_ip, 0, sizeof(nt->local_ip));
556 	netdev_put(ndev, &np->dev_tracker);
557 unlock:
558 	rtnl_unlock();
559 	return err;
560 }
561 
562 /* Attempts to resume logging to a deactivated target. */
563 static void resume_target(struct netconsole_target *nt)
564 {
565 	/* Initialise the skb pool before netpoll_setup() makes nt->np.dev
566 	 * visible to target_list walkers (e.g. netconsole_netdev_event),
567 	 * which otherwise may move the target to the cleanup list and
568 	 * call netconsole_skb_pool_flush() on uninitialised state.
569 	 */
570 	netconsole_skb_pool_init(nt);
571 
572 	if (netcons_netpoll_setup(nt)) {
573 		/* netpoll fails setup once, do not try again. */
574 		netconsole_skb_pool_flush(nt);
575 		nt->state = STATE_DISABLED;
576 		return;
577 	}
578 
579 	nt->state = STATE_ENABLED;
580 	pr_info("network logging resumed on interface %s\n", nt->np.dev_name);
581 }
582 
583 /* Checks if a deactivated target matches a device. */
584 static bool deactivated_target_match(struct netconsole_target *nt,
585 				     struct net_device *ndev)
586 {
587 	if (nt->state != STATE_DEACTIVATED)
588 		return false;
589 
590 	if (bound_by_mac(nt))
591 		return !memcmp(nt->np.dev_mac, ndev->dev_addr, ETH_ALEN);
592 	return !strncmp(nt->np.dev_name, ndev->name, IFNAMSIZ);
593 }
594 
595 /* Process work scheduled for target resume. */
596 static void process_resume_target(struct work_struct *work)
597 {
598 	struct netconsole_target *nt;
599 	unsigned long flags;
600 
601 	nt = container_of(work, struct netconsole_target, resume_wq);
602 
603 	dynamic_netconsole_mutex_lock();
604 
605 	spin_lock_irqsave(&target_list_lock, flags);
606 	/* Check if target is still deactivated as it may have been disabled
607 	 * while resume was being scheduled.
608 	 */
609 	if (nt->state != STATE_DEACTIVATED) {
610 		spin_unlock_irqrestore(&target_list_lock, flags);
611 		goto out_unlock;
612 	}
613 
614 	/* resume_target is IRQ unsafe, remove target from
615 	 * target_list in order to resume it with IRQ enabled.
616 	 */
617 	list_del_init(&nt->list);
618 	spin_unlock_irqrestore(&target_list_lock, flags);
619 
620 	resume_target(nt);
621 
622 	/* netpoll_setup() took a net_device reference and dropped the RTNL
623 	 * before returning, all while this target was off target_list and
624 	 * thus invisible to netconsole_netdev_event(). If the device was
625 	 * unregistered in that window the NETDEV_UNREGISTER notifier could not
626 	 * tear this target down, which would leak the reference and hang
627 	 * unregister_netdevice(). Re-check under the RTNL before re-publishing:
628 	 * taking it across the check and the list_add() serialises against the
629 	 * notifier (which also runs under the RTNL), so the device is either
630 	 * still registered (the notifier will find the re-added target) or
631 	 * already unregistering (we drop the reference here).
632 	 */
633 	rtnl_lock();
634 	if (nt->state == STATE_ENABLED && nt->np.dev &&
635 	    nt->np.dev->reg_state != NETREG_REGISTERED) {
636 		netconsole_skb_pool_flush(nt);
637 		netcons_release_dev(nt);
638 		nt->state = STATE_DISABLED;
639 	}
640 
641 	/* At this point the target is either enabled or disabled and
642 	 * was cleaned up before getting deactivated. Either way, add it
643 	 * back to target list.
644 	 */
645 	spin_lock_irqsave(&target_list_lock, flags);
646 	list_add(&nt->list, &target_list);
647 	spin_unlock_irqrestore(&target_list_lock, flags);
648 	rtnl_unlock();
649 
650 out_unlock:
651 	dynamic_netconsole_mutex_unlock();
652 }
653 
654 /* Allocate and initialize with defaults.
655  * Note that these targets get their config_item fields zeroed-out.
656  */
657 static struct netconsole_target *alloc_and_init(void)
658 {
659 	struct netconsole_target *nt;
660 
661 	nt = kzalloc_obj(*nt);
662 	if (!nt)
663 		return nt;
664 
665 	if (IS_ENABLED(CONFIG_NETCONSOLE_EXTENDED_LOG))
666 		nt->extended = true;
667 	if (IS_ENABLED(CONFIG_NETCONSOLE_PREPEND_RELEASE))
668 		nt->release = true;
669 
670 	nt->np.name = "netconsole";
671 	strscpy(nt->np.dev_name, "eth0", IFNAMSIZ);
672 	nt->local_port = 6665;
673 	nt->remote_port = 6666;
674 	eth_broadcast_addr(nt->remote_mac);
675 	nt->state = STATE_DISABLED;
676 	INIT_WORK(&nt->resume_wq, process_resume_target);
677 	/* Set up the skb pool primitives once; enabling only refills it. */
678 	skb_queue_head_init(&nt->skb_pool);
679 	INIT_WORK(&nt->refill_wq, refill_skbs_work_handler);
680 
681 	return nt;
682 }
683 
684 /* Clean up every target in the cleanup_list and move the clean targets back to
685  * the main target_list.
686  */
687 static void netconsole_process_cleanups_core(void)
688 {
689 	struct netconsole_target *nt, *tmp;
690 	unsigned long flags;
691 
692 	/* The cleanup needs RTNL locked */
693 	ASSERT_RTNL();
694 
695 	mutex_lock(&target_cleanup_list_lock);
696 	list_for_each_entry_safe(nt, tmp, &target_cleanup_list, list) {
697 		/* all entries in the cleanup_list needs to be disabled */
698 		WARN_ON_ONCE(nt->state == STATE_ENABLED);
699 		netconsole_skb_pool_flush(nt);
700 		netcons_release_dev(nt);
701 		/* moved the cleaned target to target_list. Need to hold both
702 		 * locks
703 		 */
704 		spin_lock_irqsave(&target_list_lock, flags);
705 		list_move(&nt->list, &target_list);
706 		spin_unlock_irqrestore(&target_list_lock, flags);
707 	}
708 	WARN_ON_ONCE(!list_empty(&target_cleanup_list));
709 	mutex_unlock(&target_cleanup_list_lock);
710 }
711 
712 static void netconsole_print_banner(struct netconsole_target *nt)
713 {
714 	struct netpoll *np = &nt->np;
715 
716 	np_info(np, "local port %d\n", nt->local_port);
717 	if (nt->ipv6)
718 		np_info(np, "local IPv6 address %pI6c\n", &nt->local_ip.in6);
719 	else
720 		np_info(np, "local IPv4 address %pI4\n", &nt->local_ip.ip);
721 	np_info(np, "interface name '%s'\n", np->dev_name);
722 	np_info(np, "local ethernet address '%pM'\n", np->dev_mac);
723 	np_info(np, "remote port %d\n", nt->remote_port);
724 	if (nt->ipv6)
725 		np_info(np, "remote IPv6 address %pI6c\n", &nt->remote_ip.in6);
726 	else
727 		np_info(np, "remote IPv4 address %pI4\n", &nt->remote_ip.ip);
728 	np_info(np, "remote ethernet address %pM\n", nt->remote_mac);
729 }
730 
731 /* Parse the string and populate the `inet_addr` union. Return 0 if IPv4 is
732  * populated, 1 if IPv6 is populated, and -1 upon failure.
733  */
734 static int netpoll_parse_ip_addr(const char *str, union inet_addr *addr)
735 {
736 	const char *end = NULL;
737 	int len;
738 
739 	len = strlen(str);
740 	if (!len)
741 		return -1;
742 
743 	if (str[len - 1] == '\n')
744 		len -= 1;
745 
746 	if (in4_pton(str, len, (void *)addr, -1, &end) > 0 &&
747 	    (!end || *end == 0 || *end == '\n'))
748 		return 0;
749 
750 	if (IS_ENABLED(CONFIG_IPV6) &&
751 	    in6_pton(str, len, (void *)addr, -1, &end) > 0 &&
752 	    (!end || *end == 0 || *end == '\n'))
753 		return 1;
754 
755 	return -1;
756 }
757 
758 #ifdef	CONFIG_NETCONSOLE_DYNAMIC
759 
760 /*
761  * Our subsystem hierarchy is:
762  *
763  * /sys/kernel/config/netconsole/
764  *				|
765  *				<target>/
766  *				|	enabled
767  *				|	release
768  *				|	dev_name
769  *				|	local_port
770  *				|	remote_port
771  *				|	local_ip
772  *				|	remote_ip
773  *				|	local_mac
774  *				|	remote_mac
775  *				|	transmit_errors
776  *				|	userdata/
777  *				|		<key>/
778  *				|			value
779  *				|		...
780  *				|
781  *				<target>/...
782  */
783 
784 static struct netconsole_target *to_target(struct config_item *item)
785 {
786 	struct config_group *cfg_group;
787 
788 	cfg_group = to_config_group(item);
789 	if (!cfg_group)
790 		return NULL;
791 	return container_of(to_config_group(item),
792 			    struct netconsole_target, group);
793 }
794 
795 /* Do the list cleanup with the rtnl lock hold.  rtnl lock is necessary because
796  * netdev might be cleaned-up by calling __netpoll_cleanup(),
797  */
798 static void netconsole_process_cleanups(void)
799 {
800 	/* rtnl lock is called here, because it has precedence over
801 	 * target_cleanup_list_lock mutex and target_cleanup_list
802 	 */
803 	rtnl_lock();
804 	netconsole_process_cleanups_core();
805 	rtnl_unlock();
806 }
807 
808 /* Get rid of possible trailing newline, returning the new length */
809 static void trim_newline(char *s, size_t maxlen)
810 {
811 	size_t len;
812 
813 	len = strnlen(s, maxlen);
814 	if (!len)
815 		return;
816 	if (s[len - 1] == '\n')
817 		s[len - 1] = '\0';
818 }
819 
820 /*
821  * Attribute operations for netconsole_target.
822  */
823 
824 static ssize_t enabled_show(struct config_item *item, char *buf)
825 {
826 	return sysfs_emit(buf, "%d\n", to_target(item)->state == STATE_ENABLED);
827 }
828 
829 static ssize_t extended_show(struct config_item *item, char *buf)
830 {
831 	return sysfs_emit(buf, "%d\n", to_target(item)->extended);
832 }
833 
834 static ssize_t release_show(struct config_item *item, char *buf)
835 {
836 	return sysfs_emit(buf, "%d\n", to_target(item)->release);
837 }
838 
839 static ssize_t dev_name_show(struct config_item *item, char *buf)
840 {
841 	return sysfs_emit(buf, "%s\n", to_target(item)->np.dev_name);
842 }
843 
844 static ssize_t local_port_show(struct config_item *item, char *buf)
845 {
846 	return sysfs_emit(buf, "%d\n", to_target(item)->local_port);
847 }
848 
849 static ssize_t remote_port_show(struct config_item *item, char *buf)
850 {
851 	return sysfs_emit(buf, "%d\n", to_target(item)->remote_port);
852 }
853 
854 static ssize_t local_ip_show(struct config_item *item, char *buf)
855 {
856 	struct netconsole_target *nt = to_target(item);
857 
858 	if (nt->ipv6)
859 		return sysfs_emit(buf, "%pI6c\n", &nt->local_ip.in6);
860 	else
861 		return sysfs_emit(buf, "%pI4\n", &nt->local_ip);
862 }
863 
864 static ssize_t remote_ip_show(struct config_item *item, char *buf)
865 {
866 	struct netconsole_target *nt = to_target(item);
867 
868 	if (nt->ipv6)
869 		return sysfs_emit(buf, "%pI6c\n", &nt->remote_ip.in6);
870 	else
871 		return sysfs_emit(buf, "%pI4\n", &nt->remote_ip);
872 }
873 
874 static ssize_t local_mac_show(struct config_item *item, char *buf)
875 {
876 	struct net_device *dev = to_target(item)->np.dev;
877 	static const u8 bcast[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
878 
879 	return sysfs_emit(buf, "%pM\n", dev ? dev->dev_addr : bcast);
880 }
881 
882 static ssize_t remote_mac_show(struct config_item *item, char *buf)
883 {
884 	return sysfs_emit(buf, "%pM\n", to_target(item)->remote_mac);
885 }
886 
887 static ssize_t transmit_errors_show(struct config_item *item, char *buf)
888 {
889 	struct netconsole_target *nt = to_target(item);
890 	u64 xmit_drop_count, enomem_count;
891 	unsigned int start;
892 
893 	do {
894 		start = u64_stats_fetch_begin(&nt->stats.syncp);
895 		xmit_drop_count = u64_stats_read(&nt->stats.xmit_drop_count);
896 		enomem_count = u64_stats_read(&nt->stats.enomem_count);
897 	} while (u64_stats_fetch_retry(&nt->stats.syncp, start));
898 
899 	return sysfs_emit(buf, "%llu\n", xmit_drop_count + enomem_count);
900 }
901 
902 /* configfs helper to display if cpu_nr sysdata feature is enabled */
903 static ssize_t sysdata_cpu_nr_enabled_show(struct config_item *item, char *buf)
904 {
905 	struct netconsole_target *nt = to_target(item->ci_parent);
906 	bool cpu_nr_enabled;
907 
908 	dynamic_netconsole_mutex_lock();
909 	cpu_nr_enabled = !!(nt->sysdata_fields & SYSDATA_CPU_NR);
910 	dynamic_netconsole_mutex_unlock();
911 
912 	return sysfs_emit(buf, "%d\n", cpu_nr_enabled);
913 }
914 
915 /* configfs helper to display if taskname sysdata feature is enabled */
916 static ssize_t sysdata_taskname_enabled_show(struct config_item *item,
917 					     char *buf)
918 {
919 	struct netconsole_target *nt = to_target(item->ci_parent);
920 	bool taskname_enabled;
921 
922 	dynamic_netconsole_mutex_lock();
923 	taskname_enabled = !!(nt->sysdata_fields & SYSDATA_TASKNAME);
924 	dynamic_netconsole_mutex_unlock();
925 
926 	return sysfs_emit(buf, "%d\n", taskname_enabled);
927 }
928 
929 static ssize_t sysdata_release_enabled_show(struct config_item *item,
930 					    char *buf)
931 {
932 	struct netconsole_target *nt = to_target(item->ci_parent);
933 	bool release_enabled;
934 
935 	dynamic_netconsole_mutex_lock();
936 	release_enabled = !!(nt->sysdata_fields & SYSDATA_RELEASE);
937 	dynamic_netconsole_mutex_unlock();
938 
939 	return sysfs_emit(buf, "%d\n", release_enabled);
940 }
941 
942 /* Iterate in the list of target, and make sure we don't have any console
943  * register without targets of the same type
944  */
945 static void unregister_netcons_consoles(void)
946 {
947 	struct netconsole_target *nt;
948 	u32 console_type_needed = 0;
949 	unsigned long flags;
950 
951 	spin_lock_irqsave(&target_list_lock, flags);
952 	list_for_each_entry(nt, &target_list, list) {
953 		if (nt->extended)
954 			console_type_needed |= CONS_EXTENDED;
955 		else
956 			console_type_needed |= CONS_BASIC;
957 	}
958 	spin_unlock_irqrestore(&target_list_lock, flags);
959 
960 	if (!(console_type_needed & CONS_EXTENDED) &&
961 	    console_is_registered(&netconsole_ext))
962 		unregister_console(&netconsole_ext);
963 
964 	if (!(console_type_needed & CONS_BASIC) &&
965 	    console_is_registered(&netconsole))
966 		unregister_console(&netconsole);
967 }
968 
969 static ssize_t sysdata_msgid_enabled_show(struct config_item *item,
970 					  char *buf)
971 {
972 	struct netconsole_target *nt = to_target(item->ci_parent);
973 	bool msgid_enabled;
974 
975 	dynamic_netconsole_mutex_lock();
976 	msgid_enabled = !!(nt->sysdata_fields & SYSDATA_MSGID);
977 	dynamic_netconsole_mutex_unlock();
978 
979 	return sysfs_emit(buf, "%d\n", msgid_enabled);
980 }
981 
982 /*
983  * This one is special -- targets created through the configfs interface
984  * are not enabled (and the corresponding netpoll activated) by default.
985  * The user is expected to set the desired parameters first (which
986  * would enable him to dynamically add new netpoll targets for new
987  * network interfaces as and when they come up).
988  */
989 static ssize_t enabled_store(struct config_item *item,
990 		const char *buf, size_t count)
991 {
992 	struct netconsole_target *nt = to_target(item);
993 	bool enabled, current_enabled;
994 	unsigned long flags;
995 	ssize_t ret;
996 
997 	dynamic_netconsole_mutex_lock();
998 	ret = kstrtobool(buf, &enabled);
999 	if (ret)
1000 		goto out_unlock;
1001 
1002 	/* When the user explicitly enables or disables a target that is
1003 	 * currently deactivated, reset its state to disabled. The DEACTIVATED
1004 	 * state only tracks interface-driven deactivation and should _not_
1005 	 * persist when the user manually changes the target's enabled state.
1006 	 */
1007 	if (nt->state == STATE_DEACTIVATED)
1008 		nt->state = STATE_DISABLED;
1009 
1010 	ret = -EINVAL;
1011 	current_enabled = nt->state == STATE_ENABLED;
1012 	if (enabled == current_enabled) {
1013 		pr_info("network logging has already %s\n",
1014 			current_enabled ? "started" : "stopped");
1015 		goto out_unlock;
1016 	}
1017 
1018 	if (enabled) {	/* true */
1019 		if (nt->release && !nt->extended) {
1020 			pr_err("Not enabling netconsole. Release feature requires extended log message");
1021 			goto out_unlock;
1022 		}
1023 
1024 		if (nt->extended && !console_is_registered(&netconsole_ext)) {
1025 			netconsole_ext.flags |= CON_ENABLED;
1026 			register_console(&netconsole_ext);
1027 		}
1028 
1029 		/* User might be enabling the basic format target for the very
1030 		 * first time, make sure the console is registered.
1031 		 */
1032 		if (!nt->extended && !console_is_registered(&netconsole)) {
1033 			netconsole.flags |= CON_ENABLED;
1034 			register_console(&netconsole);
1035 		}
1036 
1037 		/*
1038 		 * Skip netconsole_parser_cmdline() -- all the attributes are
1039 		 * already configured via configfs. Just print them out.
1040 		 */
1041 		netconsole_print_banner(nt);
1042 
1043 		/* Initialise the skb pool before netpoll_setup() so the pool
1044 		 * is valid as soon as nt->np.dev becomes visible to
1045 		 * target_list walkers (netconsole_netdev_event), which would
1046 		 * otherwise call netconsole_skb_pool_flush() on uninitialised
1047 		 * state.
1048 		 */
1049 		netconsole_skb_pool_init(nt);
1050 
1051 		ret = netcons_netpoll_setup(nt);
1052 		if (ret) {
1053 			netconsole_skb_pool_flush(nt);
1054 			goto out_unlock;
1055 		}
1056 
1057 		nt->state = STATE_ENABLED;
1058 		pr_info("network logging started\n");
1059 	} else {	/* false */
1060 		/* We need to disable the netconsole before cleaning it up
1061 		 * otherwise we might end up in write_msg() with
1062 		 * nt->np.dev == NULL and nt->state == STATE_ENABLED
1063 		 */
1064 		mutex_lock(&target_cleanup_list_lock);
1065 		spin_lock_irqsave(&target_list_lock, flags);
1066 		nt->state = STATE_DISABLED;
1067 		/* Remove the target from the list, while holding
1068 		 * target_list_lock
1069 		 */
1070 		list_move(&nt->list, &target_cleanup_list);
1071 		spin_unlock_irqrestore(&target_list_lock, flags);
1072 		mutex_unlock(&target_cleanup_list_lock);
1073 		/* Unregister consoles, whose the last target of that type got
1074 		 * disabled.
1075 		 */
1076 		unregister_netcons_consoles();
1077 	}
1078 
1079 	ret = count;
1080 	/* Deferred cleanup */
1081 	netconsole_process_cleanups();
1082 out_unlock:
1083 	dynamic_netconsole_mutex_unlock();
1084 	return ret;
1085 }
1086 
1087 static ssize_t release_store(struct config_item *item, const char *buf,
1088 			     size_t count)
1089 {
1090 	struct netconsole_target *nt = to_target(item);
1091 	bool release;
1092 	ssize_t ret;
1093 
1094 	dynamic_netconsole_mutex_lock();
1095 	if (nt->state == STATE_ENABLED) {
1096 		pr_err("target (%s) is enabled, disable to update parameters\n",
1097 		       config_item_name(&nt->group.cg_item));
1098 		ret = -EINVAL;
1099 		goto out_unlock;
1100 	}
1101 
1102 	ret = kstrtobool(buf, &release);
1103 	if (ret)
1104 		goto out_unlock;
1105 
1106 	nt->release = release;
1107 
1108 	ret = count;
1109 out_unlock:
1110 	dynamic_netconsole_mutex_unlock();
1111 	return ret;
1112 }
1113 
1114 static ssize_t extended_store(struct config_item *item, const char *buf,
1115 		size_t count)
1116 {
1117 	struct netconsole_target *nt = to_target(item);
1118 	bool extended;
1119 	ssize_t ret;
1120 
1121 	dynamic_netconsole_mutex_lock();
1122 	if (nt->state == STATE_ENABLED)  {
1123 		pr_err("target (%s) is enabled, disable to update parameters\n",
1124 		       config_item_name(&nt->group.cg_item));
1125 		ret = -EINVAL;
1126 		goto out_unlock;
1127 	}
1128 
1129 	ret = kstrtobool(buf, &extended);
1130 	if (ret)
1131 		goto out_unlock;
1132 
1133 	nt->extended = extended;
1134 	ret = count;
1135 out_unlock:
1136 	dynamic_netconsole_mutex_unlock();
1137 	return ret;
1138 }
1139 
1140 static ssize_t dev_name_store(struct config_item *item, const char *buf,
1141 		size_t count)
1142 {
1143 	struct netconsole_target *nt = to_target(item);
1144 	size_t len = count;
1145 
1146 	/* Account for a trailing newline appended by tools like echo */
1147 	if (len && buf[len - 1] == '\n')
1148 		len--;
1149 	if (len >= IFNAMSIZ)
1150 		return -ENAMETOOLONG;
1151 
1152 	dynamic_netconsole_mutex_lock();
1153 	if (nt->state == STATE_ENABLED) {
1154 		pr_err("target (%s) is enabled, disable to update parameters\n",
1155 		       config_item_name(&nt->group.cg_item));
1156 		dynamic_netconsole_mutex_unlock();
1157 		return -EINVAL;
1158 	}
1159 
1160 	strscpy(nt->np.dev_name, buf, IFNAMSIZ);
1161 	trim_newline(nt->np.dev_name, IFNAMSIZ);
1162 
1163 	dynamic_netconsole_mutex_unlock();
1164 	return count;
1165 }
1166 
1167 static ssize_t local_port_store(struct config_item *item, const char *buf,
1168 		size_t count)
1169 {
1170 	struct netconsole_target *nt = to_target(item);
1171 	ssize_t ret = -EINVAL;
1172 
1173 	dynamic_netconsole_mutex_lock();
1174 	if (nt->state == STATE_ENABLED) {
1175 		pr_err("target (%s) is enabled, disable to update parameters\n",
1176 		       config_item_name(&nt->group.cg_item));
1177 		goto out_unlock;
1178 	}
1179 
1180 	ret = kstrtou16(buf, 10, &nt->local_port);
1181 	if (ret < 0)
1182 		goto out_unlock;
1183 	ret = count;
1184 out_unlock:
1185 	dynamic_netconsole_mutex_unlock();
1186 	return ret;
1187 }
1188 
1189 static ssize_t remote_port_store(struct config_item *item,
1190 		const char *buf, size_t count)
1191 {
1192 	struct netconsole_target *nt = to_target(item);
1193 	ssize_t ret = -EINVAL;
1194 
1195 	dynamic_netconsole_mutex_lock();
1196 	if (nt->state == STATE_ENABLED) {
1197 		pr_err("target (%s) is enabled, disable to update parameters\n",
1198 		       config_item_name(&nt->group.cg_item));
1199 		goto out_unlock;
1200 	}
1201 
1202 	ret = kstrtou16(buf, 10, &nt->remote_port);
1203 	if (ret < 0)
1204 		goto out_unlock;
1205 	ret = count;
1206 out_unlock:
1207 	dynamic_netconsole_mutex_unlock();
1208 	return ret;
1209 }
1210 
1211 static ssize_t local_ip_store(struct config_item *item, const char *buf,
1212 		size_t count)
1213 {
1214 	struct netconsole_target *nt = to_target(item);
1215 	ssize_t ret = -EINVAL;
1216 	int ipv6;
1217 
1218 	dynamic_netconsole_mutex_lock();
1219 	if (nt->state == STATE_ENABLED) {
1220 		pr_err("target (%s) is enabled, disable to update parameters\n",
1221 		       config_item_name(&nt->group.cg_item));
1222 		goto out_unlock;
1223 	}
1224 
1225 	ipv6 = netpoll_parse_ip_addr(buf, &nt->local_ip);
1226 	if (ipv6 == -1)
1227 		goto out_unlock;
1228 	nt->ipv6 = !!ipv6;
1229 
1230 	ret = count;
1231 out_unlock:
1232 	dynamic_netconsole_mutex_unlock();
1233 	return ret;
1234 }
1235 
1236 static ssize_t remote_ip_store(struct config_item *item, const char *buf,
1237 	       size_t count)
1238 {
1239 	struct netconsole_target *nt = to_target(item);
1240 	ssize_t ret = -EINVAL;
1241 	int ipv6;
1242 
1243 	dynamic_netconsole_mutex_lock();
1244 	if (nt->state == STATE_ENABLED) {
1245 		pr_err("target (%s) is enabled, disable to update parameters\n",
1246 		       config_item_name(&nt->group.cg_item));
1247 		goto out_unlock;
1248 	}
1249 
1250 	ipv6 = netpoll_parse_ip_addr(buf, &nt->remote_ip);
1251 	if (ipv6 == -1)
1252 		goto out_unlock;
1253 	nt->ipv6 = !!ipv6;
1254 
1255 	ret = count;
1256 out_unlock:
1257 	dynamic_netconsole_mutex_unlock();
1258 	return ret;
1259 }
1260 
1261 /* Count number of entries we have in userdata.
1262  * This is important because userdata only supports MAX_USERDATA_ITEMS
1263  * entries. Before enabling any new userdata feature, number of entries needs
1264  * to checked for available space.
1265  */
1266 static size_t count_userdata_entries(struct netconsole_target *nt)
1267 {
1268 	return list_count_nodes(&nt->userdata_group.cg_children);
1269 }
1270 
1271 static ssize_t remote_mac_store(struct config_item *item, const char *buf,
1272 		size_t count)
1273 {
1274 	struct netconsole_target *nt = to_target(item);
1275 	u8 remote_mac[ETH_ALEN];
1276 	ssize_t ret = -EINVAL;
1277 
1278 	dynamic_netconsole_mutex_lock();
1279 	if (nt->state == STATE_ENABLED) {
1280 		pr_err("target (%s) is enabled, disable to update parameters\n",
1281 		       config_item_name(&nt->group.cg_item));
1282 		goto out_unlock;
1283 	}
1284 
1285 	if (!mac_pton(buf, remote_mac))
1286 		goto out_unlock;
1287 	if (buf[MAC_ADDR_STR_LEN] && buf[MAC_ADDR_STR_LEN] != '\n')
1288 		goto out_unlock;
1289 	memcpy(nt->remote_mac, remote_mac, ETH_ALEN);
1290 
1291 	ret = count;
1292 out_unlock:
1293 	dynamic_netconsole_mutex_unlock();
1294 	return ret;
1295 }
1296 
1297 struct userdatum {
1298 	struct config_item item;
1299 	char value[MAX_EXTRADATA_VALUE_LEN];
1300 };
1301 
1302 static struct userdatum *to_userdatum(struct config_item *item)
1303 {
1304 	return container_of(item, struct userdatum, item);
1305 }
1306 
1307 struct userdata {
1308 	struct config_group group;
1309 };
1310 
1311 static struct userdata *to_userdata(struct config_item *item)
1312 {
1313 	return container_of(to_config_group(item), struct userdata, group);
1314 }
1315 
1316 static struct netconsole_target *userdata_to_target(struct userdata *ud)
1317 {
1318 	struct config_group *netconsole_group;
1319 
1320 	netconsole_group = to_config_group(ud->group.cg_item.ci_parent);
1321 	return to_target(&netconsole_group->cg_item);
1322 }
1323 
1324 static ssize_t userdatum_value_show(struct config_item *item, char *buf)
1325 {
1326 	return sysfs_emit(buf, "%s\n", &(to_userdatum(item)->value[0]));
1327 }
1328 
1329 /* Navigate configfs and calculate the lentgh of the formatted string
1330  * representing userdata.
1331  * Must be called holding netconsole_subsys.su_mutex
1332  */
1333 static int calc_userdata_len(struct netconsole_target *nt)
1334 {
1335 	struct userdatum *udm_item;
1336 	struct config_item *item;
1337 	struct list_head *entry;
1338 	int len = 0;
1339 
1340 	list_for_each(entry, &nt->userdata_group.cg_children) {
1341 		item = container_of(entry, struct config_item, ci_entry);
1342 		udm_item = to_userdatum(item);
1343 		/* Skip userdata with no value set */
1344 		if (udm_item->value[0]) {
1345 			len += snprintf(NULL, 0, " %s=%s\n", item->ci_name,
1346 					udm_item->value);
1347 		}
1348 	}
1349 	return len;
1350 }
1351 
1352 static int update_userdata(struct netconsole_target *nt)
1353 {
1354 	struct userdatum *udm_item;
1355 	struct config_item *item;
1356 	struct list_head *entry;
1357 	char *old_buf = NULL;
1358 	char *new_buf = NULL;
1359 	unsigned long flags;
1360 	int offset = 0;
1361 	int len;
1362 
1363 	/* Calculate required buffer size */
1364 	len = calc_userdata_len(nt);
1365 
1366 	if (WARN_ON_ONCE(len > MAX_EXTRADATA_ENTRY_LEN * MAX_USERDATA_ITEMS))
1367 		return -ENOSPC;
1368 
1369 	/* Allocate new buffer */
1370 	if (len) {
1371 		new_buf = kmalloc(len + 1, GFP_KERNEL);
1372 		if (!new_buf)
1373 			return -ENOMEM;
1374 	}
1375 
1376 	/* Write userdata to new buffer */
1377 	list_for_each(entry, &nt->userdata_group.cg_children) {
1378 		item = container_of(entry, struct config_item, ci_entry);
1379 		udm_item = to_userdatum(item);
1380 		/* Skip userdata with no value set */
1381 		if (udm_item->value[0]) {
1382 			offset += scnprintf(&new_buf[offset], len + 1 - offset,
1383 					    " %s=%s\n", item->ci_name,
1384 					    udm_item->value);
1385 		}
1386 	}
1387 
1388 	WARN_ON_ONCE(offset != len);
1389 
1390 	/* Switch to new buffer and free old buffer */
1391 	spin_lock_irqsave(&target_list_lock, flags);
1392 	old_buf = nt->userdata;
1393 	nt->userdata = new_buf;
1394 	nt->userdata_length = offset;
1395 	spin_unlock_irqrestore(&target_list_lock, flags);
1396 
1397 	kfree(old_buf);
1398 
1399 	return 0;
1400 }
1401 
1402 static ssize_t userdatum_value_store(struct config_item *item, const char *buf,
1403 				     size_t count)
1404 {
1405 	struct userdatum *udm = to_userdatum(item);
1406 	char old_value[MAX_EXTRADATA_VALUE_LEN];
1407 	struct netconsole_target *nt;
1408 	struct userdata *ud;
1409 	ssize_t ret;
1410 
1411 	if (count >= MAX_EXTRADATA_VALUE_LEN)
1412 		return -EMSGSIZE;
1413 
1414 	mutex_lock(&netconsole_subsys.su_mutex);
1415 	dynamic_netconsole_mutex_lock();
1416 	/* Snapshot for rollback if update_userdata() fails below */
1417 	strscpy(old_value, udm->value, sizeof(old_value));
1418 	/* count is bounded above, so strscpy() cannot truncate here */
1419 	strscpy(udm->value, buf, sizeof(udm->value));
1420 	trim_newline(udm->value, sizeof(udm->value));
1421 
1422 	ud = to_userdata(item->ci_parent);
1423 	nt = userdata_to_target(ud);
1424 	ret = update_userdata(nt);
1425 	if (ret < 0) {
1426 		/* Restore the previous value so it matches the live payload */
1427 		strscpy(udm->value, old_value, sizeof(udm->value));
1428 		goto out_unlock;
1429 	}
1430 	ret = count;
1431 out_unlock:
1432 	dynamic_netconsole_mutex_unlock();
1433 	mutex_unlock(&netconsole_subsys.su_mutex);
1434 	return ret;
1435 }
1436 
1437 /* disable_sysdata_feature - Disable sysdata feature and clean sysdata
1438  * @nt: target that is disabling the feature
1439  * @feature: feature being disabled
1440  */
1441 static void disable_sysdata_feature(struct netconsole_target *nt,
1442 				    enum sysdata_feature feature)
1443 {
1444 	nt->sysdata_fields &= ~feature;
1445 	nt->sysdata[0] = 0;
1446 }
1447 
1448 static ssize_t sysdata_msgid_enabled_store(struct config_item *item,
1449 					   const char *buf, size_t count)
1450 {
1451 	struct netconsole_target *nt = to_target(item->ci_parent);
1452 	bool msgid_enabled, curr;
1453 	ssize_t ret;
1454 
1455 	ret = kstrtobool(buf, &msgid_enabled);
1456 	if (ret)
1457 		return ret;
1458 
1459 	mutex_lock(&netconsole_subsys.su_mutex);
1460 	dynamic_netconsole_mutex_lock();
1461 	curr = !!(nt->sysdata_fields & SYSDATA_MSGID);
1462 	if (msgid_enabled == curr)
1463 		goto unlock_ok;
1464 
1465 	if (msgid_enabled)
1466 		nt->sysdata_fields |= SYSDATA_MSGID;
1467 	else
1468 		disable_sysdata_feature(nt, SYSDATA_MSGID);
1469 
1470 unlock_ok:
1471 	ret = count;
1472 	dynamic_netconsole_mutex_unlock();
1473 	mutex_unlock(&netconsole_subsys.su_mutex);
1474 	return ret;
1475 }
1476 
1477 static ssize_t sysdata_release_enabled_store(struct config_item *item,
1478 					     const char *buf, size_t count)
1479 {
1480 	struct netconsole_target *nt = to_target(item->ci_parent);
1481 	bool release_enabled, curr;
1482 	ssize_t ret;
1483 
1484 	ret = kstrtobool(buf, &release_enabled);
1485 	if (ret)
1486 		return ret;
1487 
1488 	mutex_lock(&netconsole_subsys.su_mutex);
1489 	dynamic_netconsole_mutex_lock();
1490 	curr = !!(nt->sysdata_fields & SYSDATA_RELEASE);
1491 	if (release_enabled == curr)
1492 		goto unlock_ok;
1493 
1494 	if (release_enabled)
1495 		nt->sysdata_fields |= SYSDATA_RELEASE;
1496 	else
1497 		disable_sysdata_feature(nt, SYSDATA_RELEASE);
1498 
1499 unlock_ok:
1500 	ret = count;
1501 	dynamic_netconsole_mutex_unlock();
1502 	mutex_unlock(&netconsole_subsys.su_mutex);
1503 	return ret;
1504 }
1505 
1506 static ssize_t sysdata_taskname_enabled_store(struct config_item *item,
1507 					      const char *buf, size_t count)
1508 {
1509 	struct netconsole_target *nt = to_target(item->ci_parent);
1510 	bool taskname_enabled, curr;
1511 	ssize_t ret;
1512 
1513 	ret = kstrtobool(buf, &taskname_enabled);
1514 	if (ret)
1515 		return ret;
1516 
1517 	mutex_lock(&netconsole_subsys.su_mutex);
1518 	dynamic_netconsole_mutex_lock();
1519 	curr = !!(nt->sysdata_fields & SYSDATA_TASKNAME);
1520 	if (taskname_enabled == curr)
1521 		goto unlock_ok;
1522 
1523 	if (taskname_enabled)
1524 		nt->sysdata_fields |= SYSDATA_TASKNAME;
1525 	else
1526 		disable_sysdata_feature(nt, SYSDATA_TASKNAME);
1527 
1528 unlock_ok:
1529 	ret = count;
1530 	dynamic_netconsole_mutex_unlock();
1531 	mutex_unlock(&netconsole_subsys.su_mutex);
1532 	return ret;
1533 }
1534 
1535 /* configfs helper to sysdata cpu_nr feature */
1536 static ssize_t sysdata_cpu_nr_enabled_store(struct config_item *item,
1537 					    const char *buf, size_t count)
1538 {
1539 	struct netconsole_target *nt = to_target(item->ci_parent);
1540 	bool cpu_nr_enabled, curr;
1541 	ssize_t ret;
1542 
1543 	ret = kstrtobool(buf, &cpu_nr_enabled);
1544 	if (ret)
1545 		return ret;
1546 
1547 	mutex_lock(&netconsole_subsys.su_mutex);
1548 	dynamic_netconsole_mutex_lock();
1549 	curr = !!(nt->sysdata_fields & SYSDATA_CPU_NR);
1550 	if (cpu_nr_enabled == curr)
1551 		/* no change requested */
1552 		goto unlock_ok;
1553 
1554 	if (cpu_nr_enabled)
1555 		nt->sysdata_fields |= SYSDATA_CPU_NR;
1556 	else
1557 		/* This is special because sysdata might have remaining data
1558 		 * from previous sysdata, and it needs to be cleaned.
1559 		 */
1560 		disable_sysdata_feature(nt, SYSDATA_CPU_NR);
1561 
1562 unlock_ok:
1563 	ret = count;
1564 	dynamic_netconsole_mutex_unlock();
1565 	mutex_unlock(&netconsole_subsys.su_mutex);
1566 	return ret;
1567 }
1568 
1569 CONFIGFS_ATTR(userdatum_, value);
1570 CONFIGFS_ATTR(sysdata_, cpu_nr_enabled);
1571 CONFIGFS_ATTR(sysdata_, taskname_enabled);
1572 CONFIGFS_ATTR(sysdata_, release_enabled);
1573 CONFIGFS_ATTR(sysdata_, msgid_enabled);
1574 
1575 static struct configfs_attribute *userdatum_attrs[] = {
1576 	&userdatum_attr_value,
1577 	NULL,
1578 };
1579 
1580 static void userdatum_release(struct config_item *item)
1581 {
1582 	kfree(to_userdatum(item));
1583 }
1584 
1585 static const struct configfs_item_operations userdatum_ops = {
1586 	.release = userdatum_release,
1587 };
1588 
1589 static const struct config_item_type userdatum_type = {
1590 	.ct_item_ops	= &userdatum_ops,
1591 	.ct_attrs	= userdatum_attrs,
1592 	.ct_owner	= THIS_MODULE,
1593 };
1594 
1595 static struct config_item *userdatum_make_item(struct config_group *group,
1596 					       const char *name)
1597 {
1598 	struct netconsole_target *nt;
1599 	struct userdatum *udm;
1600 	struct userdata *ud;
1601 
1602 	if (strlen(name) > MAX_EXTRADATA_NAME_LEN)
1603 		return ERR_PTR(-ENAMETOOLONG);
1604 
1605 	ud = to_userdata(&group->cg_item);
1606 	nt = userdata_to_target(ud);
1607 	if (count_userdata_entries(nt) >= MAX_USERDATA_ITEMS)
1608 		return ERR_PTR(-ENOSPC);
1609 
1610 	udm = kzalloc_obj(*udm);
1611 	if (!udm)
1612 		return ERR_PTR(-ENOMEM);
1613 
1614 	config_item_init_type_name(&udm->item, name, &userdatum_type);
1615 	return &udm->item;
1616 }
1617 
1618 static void userdatum_drop(struct config_group *group, struct config_item *item)
1619 {
1620 	struct netconsole_target *nt;
1621 	struct userdata *ud;
1622 
1623 	ud = to_userdata(&group->cg_item);
1624 	nt = userdata_to_target(ud);
1625 
1626 	dynamic_netconsole_mutex_lock();
1627 	update_userdata(nt);
1628 	config_item_put(item);
1629 	dynamic_netconsole_mutex_unlock();
1630 }
1631 
1632 static struct configfs_attribute *userdata_attrs[] = {
1633 	&sysdata_attr_cpu_nr_enabled,
1634 	&sysdata_attr_taskname_enabled,
1635 	&sysdata_attr_release_enabled,
1636 	&sysdata_attr_msgid_enabled,
1637 	NULL,
1638 };
1639 
1640 static const struct configfs_group_operations userdata_ops = {
1641 	.make_item		= userdatum_make_item,
1642 	.drop_item		= userdatum_drop,
1643 };
1644 
1645 static const struct config_item_type userdata_type = {
1646 	.ct_item_ops	= &userdatum_ops,
1647 	.ct_group_ops	= &userdata_ops,
1648 	.ct_attrs	= userdata_attrs,
1649 	.ct_owner	= THIS_MODULE,
1650 };
1651 
1652 CONFIGFS_ATTR(, enabled);
1653 CONFIGFS_ATTR(, extended);
1654 CONFIGFS_ATTR(, dev_name);
1655 CONFIGFS_ATTR(, local_port);
1656 CONFIGFS_ATTR(, remote_port);
1657 CONFIGFS_ATTR(, local_ip);
1658 CONFIGFS_ATTR(, remote_ip);
1659 CONFIGFS_ATTR_RO(, local_mac);
1660 CONFIGFS_ATTR(, remote_mac);
1661 CONFIGFS_ATTR(, release);
1662 CONFIGFS_ATTR_RO(, transmit_errors);
1663 
1664 static struct configfs_attribute *netconsole_target_attrs[] = {
1665 	&attr_enabled,
1666 	&attr_extended,
1667 	&attr_release,
1668 	&attr_dev_name,
1669 	&attr_local_port,
1670 	&attr_remote_port,
1671 	&attr_local_ip,
1672 	&attr_remote_ip,
1673 	&attr_local_mac,
1674 	&attr_remote_mac,
1675 	&attr_transmit_errors,
1676 	NULL,
1677 };
1678 
1679 /*
1680  * Item operations and type for netconsole_target.
1681  */
1682 
1683 static void netconsole_target_release(struct config_item *item)
1684 {
1685 	struct netconsole_target *nt = to_target(item);
1686 
1687 	kfree(nt->userdata);
1688 	kfree(nt);
1689 }
1690 
1691 static const struct configfs_item_operations netconsole_target_item_ops = {
1692 	.release		= netconsole_target_release,
1693 };
1694 
1695 static const struct config_item_type netconsole_target_type = {
1696 	.ct_attrs		= netconsole_target_attrs,
1697 	.ct_item_ops		= &netconsole_target_item_ops,
1698 	.ct_owner		= THIS_MODULE,
1699 };
1700 
1701 static void init_target_config_group(struct netconsole_target *nt,
1702 				     const char *name)
1703 {
1704 	config_group_init_type_name(&nt->group, name, &netconsole_target_type);
1705 	config_group_init_type_name(&nt->userdata_group, "userdata",
1706 				    &userdata_type);
1707 	configfs_add_default_group(&nt->userdata_group, &nt->group);
1708 }
1709 
1710 static struct netconsole_target *find_cmdline_target(const char *name)
1711 {
1712 	struct netconsole_target *nt, *ret = NULL;
1713 	unsigned long flags;
1714 
1715 	spin_lock_irqsave(&target_list_lock, flags);
1716 	list_for_each_entry(nt, &target_list, list) {
1717 		if (!strcmp(nt->group.cg_item.ci_name, name)) {
1718 			ret = nt;
1719 			break;
1720 		}
1721 	}
1722 	spin_unlock_irqrestore(&target_list_lock, flags);
1723 
1724 	return ret;
1725 }
1726 
1727 /*
1728  * Group operations and type for netconsole_subsys.
1729  */
1730 
1731 static struct config_group *make_netconsole_target(struct config_group *group,
1732 						   const char *name)
1733 {
1734 	struct netconsole_target *nt;
1735 	unsigned long flags;
1736 
1737 	/* Checking if a target by this name was created at boot time.  If so,
1738 	 * attach a configfs entry to that target.  This enables dynamic
1739 	 * control.
1740 	 */
1741 	if (!strncmp(name, NETCONSOLE_PARAM_TARGET_PREFIX,
1742 		     strlen(NETCONSOLE_PARAM_TARGET_PREFIX))) {
1743 		nt = find_cmdline_target(name);
1744 		if (nt) {
1745 			init_target_config_group(nt, name);
1746 			return &nt->group;
1747 		}
1748 	}
1749 
1750 	nt = alloc_and_init();
1751 	if (!nt)
1752 		return ERR_PTR(-ENOMEM);
1753 
1754 	/* Initialize the config_group member */
1755 	init_target_config_group(nt, name);
1756 
1757 	/* Adding, but it is disabled */
1758 	spin_lock_irqsave(&target_list_lock, flags);
1759 	list_add(&nt->list, &target_list);
1760 	spin_unlock_irqrestore(&target_list_lock, flags);
1761 
1762 	return &nt->group;
1763 }
1764 
1765 static void drop_netconsole_target(struct config_group *group,
1766 				   struct config_item *item)
1767 {
1768 	struct netconsole_target *nt = to_target(item);
1769 	unsigned long flags;
1770 	bool needs_cleanup;
1771 
1772 	dynamic_netconsole_mutex_lock();
1773 
1774 	mutex_lock(&target_cleanup_list_lock);
1775 	spin_lock_irqsave(&target_list_lock, flags);
1776 	/* A target moved to target_cleanup_list by netconsole_netdev_event()
1777 	 * but not yet processed still owns a netpoll; unlinking it below hides
1778 	 * it from the cleanup worker, so this path must tear it down itself.
1779 	 * This covers NETDEV_UNREGISTER (STATE_DEACTIVATED) and
1780 	 * NETDEV_RELEASE / NETDEV_JOIN (STATE_DISABLED); key off nt->np.dev,
1781 	 * which stays set until the netpoll is cleaned up.
1782 	 */
1783 	needs_cleanup = nt->state == STATE_ENABLED ||
1784 			nt->state == STATE_DEACTIVATED || nt->np.dev;
1785 	/* Disable deactivated target to prevent races between resume attempt
1786 	 * and target removal.
1787 	 */
1788 	if (nt->state == STATE_DEACTIVATED)
1789 		nt->state = STATE_DISABLED;
1790 	list_del(&nt->list);
1791 	spin_unlock_irqrestore(&target_list_lock, flags);
1792 	mutex_unlock(&target_cleanup_list_lock);
1793 
1794 	dynamic_netconsole_mutex_unlock();
1795 
1796 	/* Now that the target has been marked disabled no further work
1797 	 * can be scheduled. Existing work will skip as targets are not
1798 	 * deactivated anymore. Cancel any scheduled resume and wait for
1799 	 * completion.
1800 	 */
1801 	cancel_work_sync(&nt->resume_wq);
1802 
1803 	/*
1804 	 * The target may have never been enabled, or was manually disabled
1805 	 * before being removed so netpoll may have already been cleaned up.
1806 	 * netpoll_cleanup() is idempotent (it skips when np->dev is NULL), so
1807 	 * it is safe even if the cleanup worker already tore the netpoll down.
1808 	 */
1809 	if (needs_cleanup) {
1810 		netconsole_skb_pool_flush(nt);
1811 		netpoll_cleanup(&nt->np);
1812 	}
1813 
1814 	config_item_put(&nt->group.cg_item);
1815 }
1816 
1817 static const struct configfs_group_operations netconsole_subsys_group_ops = {
1818 	.make_group	= make_netconsole_target,
1819 	.drop_item	= drop_netconsole_target,
1820 };
1821 
1822 static const struct config_item_type netconsole_subsys_type = {
1823 	.ct_group_ops	= &netconsole_subsys_group_ops,
1824 	.ct_owner	= THIS_MODULE,
1825 };
1826 
1827 /* The netconsole configfs subsystem */
1828 static struct configfs_subsystem netconsole_subsys = {
1829 	.su_group	= {
1830 		.cg_item	= {
1831 			.ci_namebuf	= "netconsole",
1832 			.ci_type	= &netconsole_subsys_type,
1833 		},
1834 	},
1835 };
1836 
1837 static void populate_configfs_item(struct netconsole_target *nt,
1838 				   int cmdline_count)
1839 {
1840 	char target_name[16];
1841 
1842 	snprintf(target_name, sizeof(target_name), "%s%d",
1843 		 NETCONSOLE_PARAM_TARGET_PREFIX, cmdline_count);
1844 	init_target_config_group(nt, target_name);
1845 }
1846 
1847 static int sysdata_append_cpu_nr(struct netconsole_target *nt, int offset,
1848 				 struct nbcon_write_context *wctxt)
1849 {
1850 	return scnprintf(&nt->sysdata[offset],
1851 			 MAX_EXTRADATA_ENTRY_LEN, " cpu=%u\n",
1852 			 wctxt->cpu);
1853 }
1854 
1855 static int sysdata_append_taskname(struct netconsole_target *nt, int offset,
1856 				   struct nbcon_write_context *wctxt)
1857 {
1858 	return scnprintf(&nt->sysdata[offset],
1859 			 MAX_EXTRADATA_ENTRY_LEN, " taskname=%s\n",
1860 			 wctxt->comm);
1861 }
1862 
1863 static int sysdata_append_release(struct netconsole_target *nt, int offset)
1864 {
1865 	return scnprintf(&nt->sysdata[offset],
1866 			 MAX_EXTRADATA_ENTRY_LEN, " release=%s\n",
1867 			 init_utsname()->release);
1868 }
1869 
1870 static int sysdata_append_msgid(struct netconsole_target *nt, int offset)
1871 {
1872 	wrapping_assign_add(nt->msgcounter, 1);
1873 	return scnprintf(&nt->sysdata[offset],
1874 			 MAX_EXTRADATA_ENTRY_LEN, " msgid=%u\n",
1875 			 nt->msgcounter);
1876 }
1877 
1878 /*
1879  * prepare_sysdata - append sysdata in runtime
1880  * @nt: target to send message to
1881  * @wctxt: nbcon write context containing message metadata
1882  */
1883 static int prepare_sysdata(struct netconsole_target *nt,
1884 			   struct nbcon_write_context *wctxt)
1885 {
1886 	int sysdata_len = 0;
1887 
1888 	if (!nt->sysdata_fields)
1889 		goto out;
1890 
1891 	if (nt->sysdata_fields & SYSDATA_CPU_NR)
1892 		sysdata_len += sysdata_append_cpu_nr(nt, sysdata_len, wctxt);
1893 	if (nt->sysdata_fields & SYSDATA_TASKNAME)
1894 		sysdata_len += sysdata_append_taskname(nt, sysdata_len, wctxt);
1895 	if (nt->sysdata_fields & SYSDATA_RELEASE)
1896 		sysdata_len += sysdata_append_release(nt, sysdata_len);
1897 	if (nt->sysdata_fields & SYSDATA_MSGID)
1898 		sysdata_len += sysdata_append_msgid(nt, sysdata_len);
1899 
1900 	WARN_ON_ONCE(sysdata_len >
1901 		     MAX_EXTRADATA_ENTRY_LEN * MAX_SYSDATA_ITEMS);
1902 
1903 out:
1904 	return sysdata_len;
1905 }
1906 #endif	/* CONFIG_NETCONSOLE_DYNAMIC */
1907 
1908 /* Handle network interface device notifications */
1909 static int netconsole_netdev_event(struct notifier_block *this,
1910 				   unsigned long event, void *ptr)
1911 {
1912 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1913 	struct netconsole_target *nt, *tmp;
1914 	bool stopped = false;
1915 	unsigned long flags;
1916 
1917 	if (!(event == NETDEV_CHANGENAME || event == NETDEV_UNREGISTER ||
1918 	      event == NETDEV_RELEASE || event == NETDEV_JOIN ||
1919 	      event == NETDEV_REGISTER))
1920 		goto done;
1921 
1922 	mutex_lock(&target_cleanup_list_lock);
1923 	spin_lock_irqsave(&target_list_lock, flags);
1924 	list_for_each_entry_safe(nt, tmp, &target_list, list) {
1925 		netconsole_target_get(nt);
1926 		if (nt->np.dev == dev) {
1927 			switch (event) {
1928 			case NETDEV_CHANGENAME:
1929 				strscpy(nt->np.dev_name, dev->name, IFNAMSIZ);
1930 				break;
1931 			case NETDEV_RELEASE:
1932 			case NETDEV_JOIN:
1933 				/* transition target to DISABLED instead of
1934 				 * DEACTIVATED when (de)enslaving devices as
1935 				 * their targets should not be automatically
1936 				 * resumed when the interface is brought up.
1937 				 */
1938 				nt->state = STATE_DISABLED;
1939 				list_move(&nt->list, &target_cleanup_list);
1940 				stopped = true;
1941 				break;
1942 			case NETDEV_UNREGISTER:
1943 				nt->state = STATE_DEACTIVATED;
1944 				list_move(&nt->list, &target_cleanup_list);
1945 				stopped = true;
1946 			}
1947 		}
1948 		if ((event == NETDEV_REGISTER || event == NETDEV_CHANGENAME) &&
1949 		    deactivated_target_match(nt, dev))
1950 			/* Schedule resume on a workqueue as it will attempt
1951 			 * to UP the device, which can't be done as part of this
1952 			 * notifier.
1953 			 */
1954 			queue_work(netconsole_wq, &nt->resume_wq);
1955 		netconsole_target_put(nt);
1956 	}
1957 	spin_unlock_irqrestore(&target_list_lock, flags);
1958 	mutex_unlock(&target_cleanup_list_lock);
1959 
1960 	if (stopped) {
1961 		const char *msg = "had an event";
1962 
1963 		switch (event) {
1964 		case NETDEV_UNREGISTER:
1965 			msg = "unregistered";
1966 			break;
1967 		case NETDEV_RELEASE:
1968 			msg = "released slaves";
1969 			break;
1970 		case NETDEV_JOIN:
1971 			msg = "is joining a master device";
1972 			break;
1973 		}
1974 		pr_info("network logging stopped on interface %s as it %s\n",
1975 			dev->name, msg);
1976 	}
1977 
1978 	/* Process target_cleanup_list entries. By the end, target_cleanup_list
1979 	 * should be empty
1980 	 */
1981 	netconsole_process_cleanups_core();
1982 
1983 done:
1984 	return NOTIFY_DONE;
1985 }
1986 
1987 static struct notifier_block netconsole_netdev_notifier = {
1988 	.notifier_call  = netconsole_netdev_event,
1989 };
1990 
1991 /* Pop a pre-allocated skb from the pool and request a refill.
1992  *
1993  * The pool is refilled with MAX_SKB_SIZE buffers, so a pooled skb cannot
1994  * satisfy a larger request. Return NULL in that case rather than handing
1995  * back a too-small skb that would later trip skb_over_panic() in skb_put();
1996  * the caller still polls and retries, and alloc_skb() itself can satisfy the
1997  * oversized request once memory frees up.
1998  *
1999  * The refill is requested via schedule_work(), which takes the workqueue
2000  * pool locks and is therefore not NMI-safe. Skip the refill when called
2001  * from NMI context; the next non-NMI caller will top the pool back up.
2002  */
2003 static struct sk_buff *netcons_skb_pop(struct netconsole_target *nt, int len)
2004 {
2005 	struct sk_buff *skb;
2006 
2007 	if (len > MAX_SKB_SIZE) {
2008 		/* net_warn_ratelimited() pulls in printk machinery that is not
2009 		 * NMI-safe and could recurse into the nbcon console we are
2010 		 * servicing, so only warn outside NMI.
2011 		 */
2012 		if (!in_nmi())
2013 			net_warn_ratelimited("netconsole: dropping message, requested skb len %d exceeds pool buffer size %zu on %s\n",
2014 					     len, (size_t)MAX_SKB_SIZE,
2015 					     nt->np.dev->name);
2016 		return NULL;
2017 	}
2018 
2019 	skb = skb_dequeue(&nt->skb_pool);
2020 	if (!in_nmi())
2021 		schedule_work(&nt->refill_wq);
2022 
2023 	return skb;
2024 }
2025 
2026 static struct sk_buff *find_skb(struct netconsole_target *nt, int len,
2027 				int reserve)
2028 {
2029 	struct netpoll *np = &nt->np;
2030 	int count = 0;
2031 	struct sk_buff *skb;
2032 
2033 	netpoll_zap_completion_queue();
2034 repeat:
2035 
2036 	skb = alloc_skb(len, GFP_ATOMIC | __GFP_NOWARN);
2037 	if (!skb)
2038 		skb = netcons_skb_pop(nt, len);
2039 
2040 	if (!skb) {
2041 		if (++count < 10) {
2042 			netpoll_poll_dev(np->dev);
2043 			goto repeat;
2044 		}
2045 		return NULL;
2046 	}
2047 
2048 	refcount_set(&skb->users, 1);
2049 	skb_reserve(skb, reserve);
2050 	return skb;
2051 }
2052 
2053 static void netpoll_udp_checksum(struct netconsole_target *nt,
2054 				 struct sk_buff *skb, int len)
2055 {
2056 	struct udphdr *udph;
2057 	int udp_len;
2058 
2059 	udp_len = len + sizeof(struct udphdr);
2060 	udph = udp_hdr(skb);
2061 
2062 	/* check needs to be set, since it will be consumed in csum_partial */
2063 	udph->check = 0;
2064 	if (nt->ipv6)
2065 		udph->check = csum_ipv6_magic(&nt->local_ip.in6,
2066 					      &nt->remote_ip.in6,
2067 					      udp_len, IPPROTO_UDP,
2068 					      csum_partial(udph, udp_len, 0));
2069 	else
2070 		udph->check = csum_tcpudp_magic(nt->local_ip.ip,
2071 						nt->remote_ip.ip,
2072 						udp_len, IPPROTO_UDP,
2073 						csum_partial(udph, udp_len, 0));
2074 	if (udph->check == 0)
2075 		udph->check = CSUM_MANGLED_0;
2076 }
2077 
2078 static void push_udp(struct netconsole_target *nt, struct sk_buff *skb, int len)
2079 {
2080 	struct udphdr *udph;
2081 	int udp_len;
2082 
2083 	udp_len = len + sizeof(struct udphdr);
2084 
2085 	skb_push(skb, sizeof(struct udphdr));
2086 	skb_reset_transport_header(skb);
2087 
2088 	udph = udp_hdr(skb);
2089 	udph->source = htons(nt->local_port);
2090 	udph->dest = htons(nt->remote_port);
2091 	udp_set_len_short(udph, udp_len);
2092 
2093 	netpoll_udp_checksum(nt, skb, len);
2094 }
2095 
2096 static void push_eth(struct netconsole_target *nt, struct sk_buff *skb)
2097 {
2098 	struct netpoll *np = &nt->np;
2099 	struct ethhdr *eth;
2100 
2101 	eth = skb_push(skb, ETH_HLEN);
2102 	skb_reset_mac_header(skb);
2103 	ether_addr_copy(eth->h_source, np->dev->dev_addr);
2104 	ether_addr_copy(eth->h_dest, nt->remote_mac);
2105 	if (nt->ipv6)
2106 		eth->h_proto = htons(ETH_P_IPV6);
2107 	else
2108 		eth->h_proto = htons(ETH_P_IP);
2109 }
2110 
2111 static void push_ipv4(struct netconsole_target *nt, struct sk_buff *skb,
2112 		      int len)
2113 {
2114 	static atomic_t ip_ident;
2115 	struct iphdr *iph;
2116 	int ip_len;
2117 
2118 	ip_len = len + sizeof(struct udphdr) + sizeof(struct iphdr);
2119 
2120 	skb_push(skb, sizeof(struct iphdr));
2121 	skb_reset_network_header(skb);
2122 	iph = ip_hdr(skb);
2123 
2124 	/* iph->version = 4; iph->ihl = 5; */
2125 	*(unsigned char *)iph = 0x45;
2126 	iph->tos = 0;
2127 	put_unaligned(htons(ip_len), &iph->tot_len);
2128 	iph->id = htons(atomic_inc_return(&ip_ident));
2129 	iph->frag_off = 0;
2130 	iph->ttl = 64;
2131 	iph->protocol = IPPROTO_UDP;
2132 	iph->check = 0;
2133 	put_unaligned(nt->local_ip.ip, &iph->saddr);
2134 	put_unaligned(nt->remote_ip.ip, &iph->daddr);
2135 	iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
2136 	skb->protocol = htons(ETH_P_IP);
2137 }
2138 
2139 static void push_ipv6(struct netconsole_target *nt, struct sk_buff *skb,
2140 		      int len)
2141 {
2142 	struct ipv6hdr *ip6h;
2143 
2144 	skb_push(skb, sizeof(struct ipv6hdr));
2145 	skb_reset_network_header(skb);
2146 	ip6h = ipv6_hdr(skb);
2147 
2148 	/* ip6h->version = 6; ip6h->priority = 0; */
2149 	*(unsigned char *)ip6h = 0x60;
2150 	ip6h->flow_lbl[0] = 0;
2151 	ip6h->flow_lbl[1] = 0;
2152 	ip6h->flow_lbl[2] = 0;
2153 
2154 	ip6h->payload_len = htons(sizeof(struct udphdr) + len);
2155 	ip6h->nexthdr = IPPROTO_UDP;
2156 	ip6h->hop_limit = 32;
2157 	ip6h->saddr = nt->local_ip.in6;
2158 	ip6h->daddr = nt->remote_ip.in6;
2159 
2160 	skb->protocol = htons(ETH_P_IPV6);
2161 }
2162 
2163 static int netpoll_send_udp(struct netconsole_target *nt, const char *msg,
2164 			    int len)
2165 {
2166 	struct netpoll *np = &nt->np;
2167 	int total_len, ip_len, udp_len;
2168 	struct sk_buff *skb;
2169 
2170 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
2171 		WARN_ON_ONCE(!irqs_disabled());
2172 
2173 	udp_len = len + sizeof(struct udphdr);
2174 	if (nt->ipv6)
2175 		ip_len = udp_len + sizeof(struct ipv6hdr);
2176 	else
2177 		ip_len = udp_len + sizeof(struct iphdr);
2178 
2179 	total_len = ip_len + LL_RESERVED_SPACE(np->dev);
2180 
2181 	skb = find_skb(nt, total_len + np->dev->needed_tailroom,
2182 		       total_len - len);
2183 	if (!skb)
2184 		return -ENOMEM;
2185 
2186 	skb_copy_to_linear_data(skb, msg, len);
2187 	skb_put(skb, len);
2188 
2189 	push_udp(nt, skb, len);
2190 	if (nt->ipv6)
2191 		push_ipv6(nt, skb, len);
2192 	else
2193 		push_ipv4(nt, skb, len);
2194 	push_eth(nt, skb);
2195 	skb->dev = np->dev;
2196 
2197 	return (int)netpoll_send_skb(np, skb);
2198 }
2199 
2200 /**
2201  * send_udp - Wrapper for netpoll_send_udp that counts errors
2202  * @nt: target to send message to
2203  * @msg: message to send
2204  * @len: length of message
2205  *
2206  * Calls netpoll_send_udp and classifies the return value. If an error
2207  * occurred it increments statistics in nt->stats accordingly.
2208  * Only calls netpoll_send_udp if CONFIG_NETCONSOLE_DYNAMIC is disabled.
2209  */
2210 static void send_udp(struct netconsole_target *nt, const char *msg, int len)
2211 {
2212 	int result = netpoll_send_udp(nt, msg, len);
2213 
2214 	if (IS_ENABLED(CONFIG_NETCONSOLE_DYNAMIC)) {
2215 		if (result == NET_XMIT_DROP) {
2216 			u64_stats_update_begin(&nt->stats.syncp);
2217 			u64_stats_inc(&nt->stats.xmit_drop_count);
2218 			u64_stats_update_end(&nt->stats.syncp);
2219 		} else if (result == -ENOMEM) {
2220 			u64_stats_update_begin(&nt->stats.syncp);
2221 			u64_stats_inc(&nt->stats.enomem_count);
2222 			u64_stats_update_end(&nt->stats.syncp);
2223 		}
2224 	}
2225 }
2226 
2227 static void send_msg_no_fragmentation(struct netconsole_target *nt,
2228 				      const char *msg,
2229 				      int msg_len,
2230 				      int release_len)
2231 {
2232 	const char *userdata = NULL;
2233 	const char *sysdata = NULL;
2234 	const char *release;
2235 
2236 #ifdef CONFIG_NETCONSOLE_DYNAMIC
2237 	userdata = nt->userdata;
2238 	sysdata = nt->sysdata;
2239 #endif
2240 
2241 	if (release_len) {
2242 		release = init_utsname()->release;
2243 
2244 		scnprintf(nt->buf, sizeof(nt->buf), "%s,%.*s", release,
2245 			  msg_len, msg);
2246 		msg_len += release_len;
2247 	} else {
2248 		memcpy(nt->buf, msg, msg_len);
2249 	}
2250 
2251 	if (userdata)
2252 		msg_len += scnprintf(&nt->buf[msg_len],
2253 				     sizeof(nt->buf) - msg_len, "%s",
2254 				     userdata);
2255 
2256 	if (sysdata)
2257 		msg_len += scnprintf(&nt->buf[msg_len],
2258 				     sizeof(nt->buf) - msg_len, "%s",
2259 				     sysdata);
2260 
2261 	send_udp(nt, nt->buf, msg_len);
2262 }
2263 
2264 static void append_release(char *buf)
2265 {
2266 	const char *release;
2267 
2268 	release = init_utsname()->release;
2269 	scnprintf(buf, MAX_PRINT_CHUNK, "%s,", release);
2270 }
2271 
2272 static void send_fragmented_body(struct netconsole_target *nt,
2273 				 const char *msgbody_ptr, int header_len,
2274 				 int msgbody_len, int sysdata_len)
2275 {
2276 	const char *userdata_ptr = NULL;
2277 	const char *sysdata_ptr = NULL;
2278 	int data_len, data_sent = 0;
2279 	int userdata_offset = 0;
2280 	int sysdata_offset = 0;
2281 	int msgbody_offset = 0;
2282 	int userdata_len = 0;
2283 
2284 #ifdef CONFIG_NETCONSOLE_DYNAMIC
2285 	userdata_ptr = nt->userdata;
2286 	sysdata_ptr = nt->sysdata;
2287 	userdata_len = nt->userdata_length;
2288 #endif
2289 	if (WARN_ON_ONCE(!userdata_ptr && userdata_len != 0))
2290 		return;
2291 
2292 	if (WARN_ON_ONCE(!sysdata_ptr && sysdata_len != 0))
2293 		return;
2294 
2295 	/* data_len represents the number of bytes that will be sent. This is
2296 	 * bigger than MAX_PRINT_CHUNK, thus, it will be split in multiple
2297 	 * packets
2298 	 */
2299 	data_len = msgbody_len + userdata_len + sysdata_len;
2300 
2301 	/* In each iteration of the while loop below, we send a packet
2302 	 * containing the header and a portion of the data. The data is
2303 	 * composed of three parts: msgbody, userdata, and sysdata.
2304 	 * We keep track of how many bytes have been sent from each part using
2305 	 * the *_offset variables.
2306 	 * We keep track of how many bytes have been sent overall using the
2307 	 * data_sent variable, which ranges from 0 to the total bytes to be
2308 	 * sent.
2309 	 */
2310 	while (data_sent < data_len) {
2311 		int userdata_left = userdata_len - userdata_offset;
2312 		int sysdata_left = sysdata_len - sysdata_offset;
2313 		int msgbody_left = msgbody_len - msgbody_offset;
2314 		int buf_offset = 0;
2315 		int this_chunk = 0;
2316 
2317 		/* header is already populated in nt->buf, just append to it */
2318 		buf_offset = header_len;
2319 
2320 		buf_offset += scnprintf(nt->buf + buf_offset,
2321 					 MAX_PRINT_CHUNK - buf_offset,
2322 					 ",ncfrag=%d/%d;", data_sent,
2323 					 data_len);
2324 
2325 		/* append msgbody first */
2326 		this_chunk = min(msgbody_left, MAX_PRINT_CHUNK - buf_offset);
2327 		memcpy(nt->buf + buf_offset, msgbody_ptr + msgbody_offset,
2328 		       this_chunk);
2329 		msgbody_offset += this_chunk;
2330 		buf_offset += this_chunk;
2331 		data_sent += this_chunk;
2332 
2333 		/* after msgbody, append userdata */
2334 		if (userdata_ptr && userdata_left) {
2335 			this_chunk = min(userdata_left,
2336 					 MAX_PRINT_CHUNK - buf_offset);
2337 			memcpy(nt->buf + buf_offset,
2338 			       userdata_ptr + userdata_offset, this_chunk);
2339 			userdata_offset += this_chunk;
2340 			buf_offset += this_chunk;
2341 			data_sent += this_chunk;
2342 		}
2343 
2344 		/* after userdata, append sysdata */
2345 		if (sysdata_ptr && sysdata_left) {
2346 			this_chunk = min(sysdata_left,
2347 					 MAX_PRINT_CHUNK - buf_offset);
2348 			memcpy(nt->buf + buf_offset,
2349 			       sysdata_ptr + sysdata_offset, this_chunk);
2350 			sysdata_offset += this_chunk;
2351 			buf_offset += this_chunk;
2352 			data_sent += this_chunk;
2353 		}
2354 
2355 		/* if all is good, send the packet out */
2356 		if (WARN_ON_ONCE(data_sent > data_len))
2357 			return;
2358 
2359 		send_udp(nt, nt->buf, buf_offset);
2360 	}
2361 }
2362 
2363 static void send_msg_fragmented(struct netconsole_target *nt,
2364 				const char *msg,
2365 				int msg_len,
2366 				int release_len,
2367 				int sysdata_len)
2368 {
2369 	int header_len, msgbody_len;
2370 	const char *msgbody;
2371 
2372 	/* need to insert extra header fields, detect header and msgbody */
2373 	msgbody = memchr(msg, ';', msg_len);
2374 	if (WARN_ON_ONCE(!msgbody))
2375 		return;
2376 
2377 	header_len = msgbody - msg;
2378 	msgbody_len = msg_len - header_len - 1;
2379 	msgbody++;
2380 
2381 	/*
2382 	 * Transfer multiple chunks with the following extra header.
2383 	 * "ncfrag=<byte-offset>/<total-bytes>"
2384 	 */
2385 	if (release_len)
2386 		append_release(nt->buf);
2387 
2388 	/* Copy the header into the buffer */
2389 	memcpy(nt->buf + release_len, msg, header_len);
2390 	header_len += release_len;
2391 
2392 	/* for now on, the header will be persisted, and the msgbody
2393 	 * will be replaced
2394 	 */
2395 	send_fragmented_body(nt, msgbody, header_len, msgbody_len,
2396 			     sysdata_len);
2397 }
2398 
2399 /**
2400  * send_ext_msg_udp - send extended log message to target
2401  * @nt: target to send message to
2402  * @wctxt: nbcon write context containing message and metadata
2403  *
2404  * Transfer extended log message to @nt.  If message is longer than
2405  * MAX_PRINT_CHUNK, it'll be split and transmitted in multiple chunks with
2406  * ncfrag header field added to identify them.
2407  */
2408 static void send_ext_msg_udp(struct netconsole_target *nt,
2409 			     struct nbcon_write_context *wctxt)
2410 {
2411 	int userdata_len = 0;
2412 	int release_len = 0;
2413 	int sysdata_len = 0;
2414 	int len;
2415 
2416 #ifdef CONFIG_NETCONSOLE_DYNAMIC
2417 	sysdata_len = prepare_sysdata(nt, wctxt);
2418 	userdata_len = nt->userdata_length;
2419 #endif
2420 	if (nt->release)
2421 		release_len = strlen(init_utsname()->release) + 1;
2422 
2423 	len = wctxt->len + release_len + sysdata_len + userdata_len;
2424 	if (len <= MAX_PRINT_CHUNK)
2425 		return send_msg_no_fragmentation(nt, wctxt->outbuf,
2426 						 wctxt->len, release_len);
2427 
2428 	return send_msg_fragmented(nt, wctxt->outbuf, wctxt->len, release_len,
2429 				   sysdata_len);
2430 }
2431 
2432 static void send_msg_udp(struct netconsole_target *nt, const char *msg,
2433 			 unsigned int len)
2434 {
2435 	const char *tmp = msg;
2436 	int frag, left = len;
2437 
2438 	while (left > 0) {
2439 		frag = min(left, MAX_PRINT_CHUNK);
2440 		send_udp(nt, tmp, frag);
2441 		tmp += frag;
2442 		left -= frag;
2443 	}
2444 }
2445 
2446 /**
2447  * netconsole_write - Generic function to send a msg to all targets
2448  * @wctxt: nbcon write context
2449  * @extended: "true" for extended console mode
2450  *
2451  * Given an nbcon write context, send the message to the netconsole targets
2452  */
2453 static void netconsole_write(struct nbcon_write_context *wctxt, bool extended)
2454 {
2455 	struct netconsole_target *nt;
2456 
2457 	if (oops_only && !oops_in_progress)
2458 		return;
2459 
2460 	list_for_each_entry(nt, &target_list, list) {
2461 		if (nt->extended != extended || nt->state != STATE_ENABLED ||
2462 		    !netif_running(nt->np.dev))
2463 			continue;
2464 
2465 		/* If nbcon_enter_unsafe() fails, just return given netconsole
2466 		 * lost the ownership, and iterating over the targets will not
2467 		 * be able to re-acquire.
2468 		 */
2469 		if (!nbcon_enter_unsafe(wctxt))
2470 			return;
2471 
2472 		if (extended)
2473 			send_ext_msg_udp(nt, wctxt);
2474 		else
2475 			send_msg_udp(nt, wctxt->outbuf, wctxt->len);
2476 
2477 		nbcon_exit_unsafe(wctxt);
2478 	}
2479 }
2480 
2481 static void netconsole_write_ext(struct console *con __always_unused,
2482 				 struct nbcon_write_context *wctxt)
2483 {
2484 	netconsole_write(wctxt, true);
2485 }
2486 
2487 static void netconsole_write_basic(struct console *con __always_unused,
2488 				   struct nbcon_write_context *wctxt)
2489 {
2490 	netconsole_write(wctxt, false);
2491 }
2492 
2493 static void netconsole_device_lock(struct console *con __always_unused,
2494 				   unsigned long *flags)
2495 __acquires(&target_list_lock)
2496 {
2497 	spin_lock_irqsave(&target_list_lock, *flags);
2498 }
2499 
2500 static void netconsole_device_unlock(struct console *con __always_unused,
2501 				     unsigned long flags)
2502 __releases(&target_list_lock)
2503 {
2504 	spin_unlock_irqrestore(&target_list_lock, flags);
2505 }
2506 
2507 static int netconsole_parser_cmdline(struct netconsole_target *nt, char *opt)
2508 {
2509 	struct netpoll *np = &nt->np;
2510 	bool ipversion_set = false;
2511 	char *cur = opt;
2512 	char *delim;
2513 	int ipv6;
2514 
2515 	if (*cur != '@') {
2516 		delim = strchr(cur, '@');
2517 		if (!delim)
2518 			goto parse_failed;
2519 		*delim = 0;
2520 		if (kstrtou16(cur, 10, &nt->local_port))
2521 			goto parse_failed;
2522 		cur = delim;
2523 	}
2524 	cur++;
2525 
2526 	if (*cur != '/') {
2527 		ipversion_set = true;
2528 		delim = strchr(cur, '/');
2529 		if (!delim)
2530 			goto parse_failed;
2531 		*delim = 0;
2532 		ipv6 = netpoll_parse_ip_addr(cur, &nt->local_ip);
2533 		if (ipv6 < 0)
2534 			goto parse_failed;
2535 		else
2536 			nt->ipv6 = (bool)ipv6;
2537 		cur = delim;
2538 	}
2539 	cur++;
2540 
2541 	if (*cur != ',') {
2542 		/* parse out dev_name or dev_mac */
2543 		delim = strchr(cur, ',');
2544 		if (!delim)
2545 			goto parse_failed;
2546 		*delim = 0;
2547 
2548 		np->dev_name[0] = '\0';
2549 		eth_broadcast_addr(np->dev_mac);
2550 		if (!strchr(cur, ':'))
2551 			strscpy(np->dev_name, cur, sizeof(np->dev_name));
2552 		else if (!mac_pton(cur, np->dev_mac))
2553 			goto parse_failed;
2554 
2555 		cur = delim;
2556 	}
2557 	cur++;
2558 
2559 	if (*cur != '@') {
2560 		/* dst port */
2561 		delim = strchr(cur, '@');
2562 		if (!delim)
2563 			goto parse_failed;
2564 		*delim = 0;
2565 		if (*cur == ' ' || *cur == '\t')
2566 			np_info(np, "warning: whitespace is not allowed\n");
2567 		if (kstrtou16(cur, 10, &nt->remote_port))
2568 			goto parse_failed;
2569 		cur = delim;
2570 	}
2571 	cur++;
2572 
2573 	/* dst ip */
2574 	delim = strchr(cur, '/');
2575 	if (!delim)
2576 		goto parse_failed;
2577 	*delim = 0;
2578 	ipv6 = netpoll_parse_ip_addr(cur, &nt->remote_ip);
2579 	if (ipv6 < 0)
2580 		goto parse_failed;
2581 	else if (ipversion_set && nt->ipv6 != (bool)ipv6)
2582 		goto parse_failed;
2583 	else
2584 		nt->ipv6 = (bool)ipv6;
2585 	cur = delim + 1;
2586 
2587 	if (*cur != 0) {
2588 		/* MAC address */
2589 		if (!mac_pton(cur, nt->remote_mac))
2590 			goto parse_failed;
2591 	}
2592 
2593 	netconsole_print_banner(nt);
2594 
2595 	return 0;
2596 
2597  parse_failed:
2598 	np_info(np, "couldn't parse config at '%s'!\n", cur);
2599 	return -1;
2600 }
2601 
2602 /* Allocate new target (from boot/module param) and setup netpoll for it */
2603 static struct netconsole_target *alloc_param_target(char *target_config,
2604 						    int cmdline_count)
2605 {
2606 	struct netconsole_target *nt;
2607 	int err;
2608 
2609 	nt = alloc_and_init();
2610 	if (!nt) {
2611 		err = -ENOMEM;
2612 		goto fail;
2613 	}
2614 
2615 	if (*target_config == '+') {
2616 		nt->extended = true;
2617 		target_config++;
2618 	}
2619 
2620 	if (*target_config == 'r') {
2621 		if (!nt->extended) {
2622 			pr_err("Netconsole configuration error. Release feature requires extended log message");
2623 			err = -EINVAL;
2624 			goto fail;
2625 		}
2626 		nt->release = true;
2627 		target_config++;
2628 	}
2629 
2630 	/* Parse parameters and setup netpoll */
2631 	err = netconsole_parser_cmdline(nt, target_config);
2632 	if (err)
2633 		goto fail;
2634 
2635 	/* Initialise the skb pool before netpoll_setup() so the pool is
2636 	 * valid as soon as nt->np.dev becomes visible. The target is not
2637 	 * yet on target_list, so a netdev event cannot reach it here, but
2638 	 * mirror the configfs path for symmetry.
2639 	 */
2640 	netconsole_skb_pool_init(nt);
2641 
2642 	err = netcons_netpoll_setup(nt);
2643 	if (err) {
2644 		pr_err("Not enabling netconsole for %s%d. Netpoll setup failed\n",
2645 		       NETCONSOLE_PARAM_TARGET_PREFIX, cmdline_count);
2646 		netconsole_skb_pool_flush(nt);
2647 		if (!IS_ENABLED(CONFIG_NETCONSOLE_DYNAMIC))
2648 			/* only fail if dynamic reconfiguration is set,
2649 			 * otherwise, keep the target in the list, but disabled.
2650 			 */
2651 			goto fail;
2652 	} else {
2653 		nt->state = STATE_ENABLED;
2654 	}
2655 	populate_configfs_item(nt, cmdline_count);
2656 
2657 	return nt;
2658 
2659 fail:
2660 	kfree(nt);
2661 	return ERR_PTR(err);
2662 }
2663 
2664 /* Cleanup netpoll for given target (from boot/module param) and free it */
2665 static void free_param_target(struct netconsole_target *nt)
2666 {
2667 	cancel_work_sync(&nt->resume_wq);
2668 	if (nt->state == STATE_ENABLED)
2669 		netconsole_skb_pool_flush(nt);
2670 	netpoll_cleanup(&nt->np);
2671 #ifdef	CONFIG_NETCONSOLE_DYNAMIC
2672 	kfree(nt->userdata);
2673 #endif
2674 	kfree(nt);
2675 }
2676 
2677 static struct console netconsole_ext = {
2678 	.name = "netcon_ext",
2679 	.flags = CON_ENABLED | CON_EXTENDED | CON_NBCON | CON_NBCON_ATOMIC_UNSAFE,
2680 	.write_thread = netconsole_write_ext,
2681 	.write_atomic = netconsole_write_ext,
2682 	.device_lock = netconsole_device_lock,
2683 	.device_unlock = netconsole_device_unlock,
2684 };
2685 
2686 static struct console netconsole = {
2687 	.name = "netcon",
2688 	.flags = CON_ENABLED | CON_NBCON | CON_NBCON_ATOMIC_UNSAFE,
2689 	.write_thread = netconsole_write_basic,
2690 	.write_atomic = netconsole_write_basic,
2691 	.device_lock = netconsole_device_lock,
2692 	.device_unlock = netconsole_device_unlock,
2693 };
2694 
2695 static int __init init_netconsole(void)
2696 {
2697 	int err;
2698 	struct netconsole_target *nt, *tmp;
2699 	u32 console_type_needed = 0;
2700 	unsigned int count = 0;
2701 	unsigned long flags;
2702 	char *target_config;
2703 	char *input = config;
2704 
2705 	if (strnlen(input, MAX_PARAM_LENGTH)) {
2706 		while ((target_config = strsep(&input, ";"))) {
2707 			nt = alloc_param_target(target_config, count);
2708 			if (IS_ERR(nt)) {
2709 				if (IS_ENABLED(CONFIG_NETCONSOLE_DYNAMIC))
2710 					continue;
2711 				err = PTR_ERR(nt);
2712 				goto fail;
2713 			}
2714 			/* Dump existing printks when we register */
2715 			if (nt->extended) {
2716 				console_type_needed |= CONS_EXTENDED;
2717 				netconsole_ext.flags |= CON_PRINTBUFFER;
2718 			} else {
2719 				console_type_needed |= CONS_BASIC;
2720 				netconsole.flags |= CON_PRINTBUFFER;
2721 			}
2722 
2723 			spin_lock_irqsave(&target_list_lock, flags);
2724 			list_add(&nt->list, &target_list);
2725 			spin_unlock_irqrestore(&target_list_lock, flags);
2726 			count++;
2727 		}
2728 	}
2729 
2730 	netconsole_wq = alloc_workqueue("netconsole", WQ_UNBOUND, 0);
2731 	if (!netconsole_wq) {
2732 		err = -ENOMEM;
2733 		goto fail;
2734 	}
2735 
2736 	err = register_netdevice_notifier(&netconsole_netdev_notifier);
2737 	if (err)
2738 		goto fail;
2739 
2740 	err = dynamic_netconsole_init();
2741 	if (err)
2742 		goto undonotifier;
2743 
2744 	if (console_type_needed & CONS_EXTENDED)
2745 		register_console(&netconsole_ext);
2746 	if (console_type_needed & CONS_BASIC)
2747 		register_console(&netconsole);
2748 	pr_info("network logging started\n");
2749 
2750 	return err;
2751 
2752 undonotifier:
2753 	unregister_netdevice_notifier(&netconsole_netdev_notifier);
2754 
2755 fail:
2756 	pr_err("cleaning up\n");
2757 
2758 	if (netconsole_wq)
2759 		flush_workqueue(netconsole_wq);
2760 	/*
2761 	 * Remove all targets and destroy them (only targets created
2762 	 * from the boot/module option exist here). Skipping the list
2763 	 * lock is safe here, and netpoll_cleanup() will sleep.
2764 	 */
2765 	list_for_each_entry_safe(nt, tmp, &target_list, list) {
2766 		list_del(&nt->list);
2767 		free_param_target(nt);
2768 	}
2769 
2770 	if (netconsole_wq)
2771 		destroy_workqueue(netconsole_wq);
2772 
2773 	return err;
2774 }
2775 
2776 static void __exit cleanup_netconsole(void)
2777 {
2778 	struct netconsole_target *nt, *tmp;
2779 
2780 	if (console_is_registered(&netconsole_ext))
2781 		unregister_console(&netconsole_ext);
2782 	if (console_is_registered(&netconsole))
2783 		unregister_console(&netconsole);
2784 	dynamic_netconsole_exit();
2785 	unregister_netdevice_notifier(&netconsole_netdev_notifier);
2786 	flush_workqueue(netconsole_wq);
2787 
2788 	/*
2789 	 * Targets created via configfs pin references on our module
2790 	 * and would first be rmdir(2)'ed from userspace. We reach
2791 	 * here only when they are already destroyed, and only those
2792 	 * created from the boot/module option are left, so remove and
2793 	 * destroy them. Skipping the list lock is safe here, and
2794 	 * netpoll_cleanup() will sleep.
2795 	 */
2796 	list_for_each_entry_safe(nt, tmp, &target_list, list) {
2797 		list_del(&nt->list);
2798 		free_param_target(nt);
2799 	}
2800 
2801 	destroy_workqueue(netconsole_wq);
2802 }
2803 
2804 /*
2805  * Use late_initcall to ensure netconsole is
2806  * initialized after network device driver if built-in.
2807  *
2808  * late_initcall() and module_init() are identical if built as module.
2809  */
2810 late_initcall(init_netconsole);
2811 module_exit(cleanup_netconsole);
2812