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