xref: /linux/net/core/pktgen.c (revision a0285236ab93fdfdd1008afaa04561d142d6c276)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Authors:
4  * Copyright 2001, 2002 by Robert Olsson <robert.olsson@its.uu.se>
5  *                             Uppsala University and
6  *                             Swedish University of Agricultural Sciences
7  *
8  * Alexey Kuznetsov  <kuznet@ms2.inr.ac.ru>
9  * Ben Greear <greearb@candelatech.com>
10  * Jens Låås <jens.laas@data.slu.se>
11  *
12  * A tool for loading the network with preconfigurated packets.
13  * The tool is implemented as a linux module.  Parameters are output
14  * device, delay (to hard_xmit), number of packets, and whether
15  * to use multiple SKBs or just the same one.
16  * pktgen uses the installed interface's output routine.
17  *
18  * Additional hacking by:
19  *
20  * Jens.Laas@data.slu.se
21  * Improved by ANK. 010120.
22  * Improved by ANK even more. 010212.
23  * MAC address typo fixed. 010417 --ro
24  * Integrated.  020301 --DaveM
25  * Added multiskb option 020301 --DaveM
26  * Scaling of results. 020417--sigurdur@linpro.no
27  * Significant re-work of the module:
28  *   *  Convert to threaded model to more efficiently be able to transmit
29  *       and receive on multiple interfaces at once.
30  *   *  Converted many counters to __u64 to allow longer runs.
31  *   *  Allow configuration of ranges, like min/max IP address, MACs,
32  *       and UDP-ports, for both source and destination, and can
33  *       set to use a random distribution or sequentially walk the range.
34  *   *  Can now change most values after starting.
35  *   *  Place 12-byte packet in UDP payload with magic number,
36  *       sequence number, and timestamp.
37  *   *  Add receiver code that detects dropped pkts, re-ordered pkts, and
38  *       latencies (with micro-second) precision.
39  *   *  Add IOCTL interface to easily get counters & configuration.
40  *   --Ben Greear <greearb@candelatech.com>
41  *
42  * Renamed multiskb to clone_skb and cleaned up sending core for two distinct
43  * skb modes. A clone_skb=0 mode for Ben "ranges" work and a clone_skb != 0
44  * as a "fastpath" with a configurable number of clones after alloc's.
45  * clone_skb=0 means all packets are allocated this also means ranges time
46  * stamps etc can be used. clone_skb=100 means 1 malloc is followed by 100
47  * clones.
48  *
49  * Also moved to /proc/net/pktgen/
50  * --ro
51  *
52  * Sept 10:  Fixed threading/locking.  Lots of bone-headed and more clever
53  *    mistakes.  Also merged in DaveM's patch in the -pre6 patch.
54  * --Ben Greear <greearb@candelatech.com>
55  *
56  * Integrated to 2.5.x 021029 --Lucio Maciel (luciomaciel@zipmail.com.br)
57  *
58  * 021124 Finished major redesign and rewrite for new functionality.
59  * See Documentation/networking/pktgen.rst for how to use this.
60  *
61  * The new operation:
62  * For each CPU one thread/process is created at start. This process checks
63  * for running devices in the if_list and sends packets until count is 0 it
64  * also the thread checks the thread->control which is used for inter-process
65  * communication. controlling process "posts" operations to the threads this
66  * way.
67  * The if_list is RCU protected, and the if_lock remains to protect updating
68  * of if_list, from "add_device" as it invoked from userspace (via proc write).
69  *
70  * By design there should only be *one* "controlling" process. In practice
71  * multiple write accesses gives unpredictable result. Understood by "write"
72  * to /proc gives result code that should be read be the "writer".
73  * For practical use this should be no problem.
74  *
75  * Note when adding devices to a specific CPU there good idea to also assign
76  * /proc/irq/XX/smp_affinity so TX-interrupts gets bound to the same CPU.
77  * --ro
78  *
79  * Fix refcount off by one if first packet fails, potential null deref,
80  * memleak 030710- KJP
81  *
82  * First "ranges" functionality for ipv6 030726 --ro
83  *
84  * Included flow support. 030802 ANK.
85  *
86  * Fixed unaligned access on IA-64 Grant Grundler <grundler@parisc-linux.org>
87  *
88  * Remove if fix from added Harald Welte <laforge@netfilter.org> 040419
89  * ia64 compilation fix from  Aron Griffis <aron@hp.com> 040604
90  *
91  * New xmit() return, do_div and misc clean up by Stephen Hemminger
92  * <shemminger@osdl.org> 040923
93  *
94  * Randy Dunlap fixed u64 printk compiler warning
95  *
96  * Remove FCS from BW calculation.  Lennert Buytenhek <buytenh@wantstofly.org>
97  * New time handling. Lennert Buytenhek <buytenh@wantstofly.org> 041213
98  *
99  * Corrections from Nikolai Malykh (nmalykh@bilim.com)
100  * Removed unused flags F_SET_SRCMAC & F_SET_SRCIP 041230
101  *
102  * interruptible_sleep_on_timeout() replaced Nishanth Aravamudan <nacc@us.ibm.com>
103  * 050103
104  *
105  * MPLS support by Steven Whitehouse <steve@chygwyn.com>
106  *
107  * 802.1Q/Q-in-Q support by Francesco Fondelli (FF) <francesco.fondelli@gmail.com>
108  *
109  * Fixed src_mac command to set source mac of packet to value specified in
110  * command by Adit Ranadive <adit.262@gmail.com>
111  */
112 
113 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
114 
115 #include <linux/sys.h>
116 #include <linux/types.h>
117 #include <linux/module.h>
118 #include <linux/moduleparam.h>
119 #include <linux/kernel.h>
120 #include <linux/mutex.h>
121 #include <linux/sched.h>
122 #include <linux/slab.h>
123 #include <linux/vmalloc.h>
124 #include <linux/unistd.h>
125 #include <linux/string.h>
126 #include <linux/ptrace.h>
127 #include <linux/errno.h>
128 #include <linux/ioport.h>
129 #include <linux/interrupt.h>
130 #include <linux/capability.h>
131 #include <linux/hrtimer.h>
132 #include <linux/freezer.h>
133 #include <linux/delay.h>
134 #include <linux/timer.h>
135 #include <linux/list.h>
136 #include <linux/init.h>
137 #include <linux/skbuff.h>
138 #include <linux/netdevice.h>
139 #include <linux/inet.h>
140 #include <linux/inetdevice.h>
141 #include <linux/rtnetlink.h>
142 #include <linux/if_arp.h>
143 #include <linux/if_vlan.h>
144 #include <linux/in.h>
145 #include <linux/ip.h>
146 #include <linux/ipv6.h>
147 #include <linux/udp.h>
148 #include <linux/proc_fs.h>
149 #include <linux/seq_file.h>
150 #include <linux/wait.h>
151 #include <linux/etherdevice.h>
152 #include <linux/kthread.h>
153 #include <linux/prefetch.h>
154 #include <linux/mmzone.h>
155 #include <net/net_namespace.h>
156 #include <net/checksum.h>
157 #include <net/ipv6.h>
158 #include <net/udp.h>
159 #include <net/ip6_checksum.h>
160 #include <net/addrconf.h>
161 #include <net/xfrm.h>
162 #include <net/netns/generic.h>
163 #include <asm/byteorder.h>
164 #include <linux/rcupdate.h>
165 #include <linux/bitops.h>
166 #include <linux/io.h>
167 #include <linux/timex.h>
168 #include <linux/uaccess.h>
169 #include <asm/dma.h>
170 #include <asm/div64.h>		/* do_div */
171 
172 #define VERSION	"2.75"
173 #define IP_NAME_SZ 32
174 #define MAX_MPLS_LABELS 16 /* This is the max label stack depth */
175 #define MPLS_STACK_BOTTOM htonl(0x00000100)
176 /* Max number of internet mix entries that can be specified in imix_weights. */
177 #define MAX_IMIX_ENTRIES 20
178 #define IMIX_PRECISION 100 /* Precision of IMIX distribution */
179 
180 #define func_enter() pr_debug("entering %s\n", __func__)
181 
182 #define PKT_FLAGS							\
183 	pf(IPV6)		/* Interface in IPV6 Mode */		\
184 	pf(IPSRC_RND)		/* IP-Src Random  */			\
185 	pf(IPDST_RND)		/* IP-Dst Random  */			\
186 	pf(TXSIZE_RND)		/* Transmit size is random */		\
187 	pf(UDPSRC_RND)		/* UDP-Src Random */			\
188 	pf(UDPDST_RND)		/* UDP-Dst Random */			\
189 	pf(UDPCSUM)		/* Include UDP checksum */		\
190 	pf(NO_TIMESTAMP)	/* Don't timestamp packets (default TS) */ \
191 	pf(MPLS_RND)		/* Random MPLS labels */		\
192 	pf(QUEUE_MAP_RND)	/* queue map Random */			\
193 	pf(QUEUE_MAP_CPU)	/* queue map mirrors smp_processor_id() */ \
194 	pf(FLOW_SEQ)		/* Sequential flows */			\
195 	pf(IPSEC)		/* ipsec on for flows */		\
196 	pf(MACSRC_RND)		/* MAC-Src Random */			\
197 	pf(MACDST_RND)		/* MAC-Dst Random */			\
198 	pf(VID_RND)		/* Random VLAN ID */			\
199 	pf(SVID_RND)		/* Random SVLAN ID */			\
200 	pf(NODE)		/* Node memory alloc*/			\
201 	pf(SHARED)		/* Shared SKB */			\
202 
203 #define pf(flag)		flag##_SHIFT,
204 enum pkt_flags {
205 	PKT_FLAGS
206 };
207 #undef pf
208 
209 /* Device flag bits */
210 #define pf(flag)		static const __u32 F_##flag = (1<<flag##_SHIFT);
211 PKT_FLAGS
212 #undef pf
213 
214 #define pf(flag)		__stringify(flag),
215 static char *pkt_flag_names[] = {
216 	PKT_FLAGS
217 };
218 #undef pf
219 
220 #define NR_PKT_FLAGS		ARRAY_SIZE(pkt_flag_names)
221 
222 /* Thread control flag bits */
223 #define T_STOP        (1<<0)	/* Stop run */
224 #define T_RUN         (1<<1)	/* Start run */
225 #define T_REMDEVALL   (1<<2)	/* Remove all devs */
226 #define T_REMDEV      (1<<3)	/* Remove one dev */
227 
228 /* Xmit modes */
229 #define M_START_XMIT		0	/* Default normal TX */
230 #define M_NETIF_RECEIVE 	1	/* Inject packets into stack */
231 #define M_QUEUE_XMIT		2	/* Inject packet into qdisc */
232 
233 /* If lock -- protects updating of if_list */
234 #define   if_lock(t)      mutex_lock(&(t->if_lock))
235 #define   if_unlock(t)    mutex_unlock(&(t->if_lock))
236 
237 /* Used to help with determining the pkts on receive */
238 #define PKTGEN_MAGIC 0xbe9be955
239 #define PG_PROC_DIR "pktgen"
240 #define PGCTRL	    "pgctrl"
241 
242 #define MAX_CFLOWS  65536
243 
244 #define VLAN_TAG_SIZE(x) ((x)->vlan_id == 0xffff ? 0 : 4)
245 #define SVLAN_TAG_SIZE(x) ((x)->svlan_id == 0xffff ? 0 : 4)
246 
247 struct imix_pkt {
248 	u64 size;
249 	u64 weight;
250 	u64 count_so_far;
251 };
252 
253 struct flow_state {
254 	__be32 cur_daddr;
255 	int count;
256 #ifdef CONFIG_XFRM
257 	struct xfrm_state *x;
258 #endif
259 	__u32 flags;
260 };
261 
262 /* flow flag bits */
263 #define F_INIT   (1<<0)		/* flow has been initialized */
264 
265 struct pktgen_dev {
266 	/*
267 	 * Try to keep frequent/infrequent used vars. separated.
268 	 */
269 	struct proc_dir_entry *entry;	/* proc file */
270 	struct pktgen_thread *pg_thread;/* the owner */
271 	struct list_head list;		/* chaining in the thread's run-queue */
272 	struct rcu_head	 rcu;		/* freed by RCU */
273 
274 	int running;		/* if false, the test will stop */
275 
276 	/* If min != max, then we will either do a linear iteration, or
277 	 * we will do a random selection from within the range.
278 	 */
279 	__u32 flags;
280 	int xmit_mode;
281 	int min_pkt_size;
282 	int max_pkt_size;
283 	int pkt_overhead;	/* overhead for MPLS, VLANs, IPSEC etc */
284 	int nfrags;
285 	int removal_mark;	/* non-zero => the device is marked for
286 				 * removal by worker thread
287 				 */
288 
289 	struct page *page;
290 	u64 delay;		/* nano-seconds */
291 
292 	__u64 count;		/* Default No packets to send */
293 	__u64 sofar;		/* How many pkts we've sent so far */
294 	__u64 tx_bytes;		/* How many bytes we've transmitted */
295 	__u64 errors;		/* Errors when trying to transmit, */
296 
297 	/* runtime counters relating to clone_skb */
298 
299 	__u32 clone_count;
300 	int last_ok;		/* Was last skb sent?
301 				 * Or a failed transmit of some sort?
302 				 * This will keep sequence numbers in order
303 				 */
304 	ktime_t next_tx;
305 	ktime_t started_at;
306 	ktime_t stopped_at;
307 	u64	idle_acc;	/* nano-seconds */
308 
309 	__u32 seq_num;
310 
311 	int clone_skb;		/*
312 				 * Use multiple SKBs during packet gen.
313 				 * If this number is greater than 1, then
314 				 * that many copies of the same packet will be
315 				 * sent before a new packet is allocated.
316 				 * If you want to send 1024 identical packets
317 				 * before creating a new packet,
318 				 * set clone_skb to 1024.
319 				 */
320 
321 	char dst_min[IP_NAME_SZ];	/* IP, ie 1.2.3.4 */
322 	char dst_max[IP_NAME_SZ];	/* IP, ie 1.2.3.4 */
323 	char src_min[IP_NAME_SZ];	/* IP, ie 1.2.3.4 */
324 	char src_max[IP_NAME_SZ];	/* IP, ie 1.2.3.4 */
325 
326 	struct in6_addr in6_saddr;
327 	struct in6_addr in6_daddr;
328 	struct in6_addr cur_in6_daddr;
329 	struct in6_addr cur_in6_saddr;
330 	/* For ranges */
331 	struct in6_addr min_in6_daddr;
332 	struct in6_addr max_in6_daddr;
333 	struct in6_addr min_in6_saddr;
334 	struct in6_addr max_in6_saddr;
335 
336 	/* If we're doing ranges, random or incremental, then this
337 	 * defines the min/max for those ranges.
338 	 */
339 	__be32 saddr_min;	/* inclusive, source IP address */
340 	__be32 saddr_max;	/* exclusive, source IP address */
341 	__be32 daddr_min;	/* inclusive, dest IP address */
342 	__be32 daddr_max;	/* exclusive, dest IP address */
343 
344 	__u16 udp_src_min;	/* inclusive, source UDP port */
345 	__u16 udp_src_max;	/* exclusive, source UDP port */
346 	__u16 udp_dst_min;	/* inclusive, dest UDP port */
347 	__u16 udp_dst_max;	/* exclusive, dest UDP port */
348 
349 	/* DSCP + ECN */
350 	__u8 tos;		/* six MSB of (former) IPv4 TOS
351 				 * are for dscp codepoint
352 				 */
353 	__u8 traffic_class;	/* ditto for the (former) Traffic Class in IPv6
354 				 * (see RFC 3260, sec. 4)
355 				 */
356 
357 	/* IMIX */
358 	unsigned int n_imix_entries;
359 	struct imix_pkt imix_entries[MAX_IMIX_ENTRIES];
360 	/* Maps 0-IMIX_PRECISION range to imix_entry based on probability*/
361 	__u8 imix_distribution[IMIX_PRECISION];
362 
363 	/* MPLS */
364 	unsigned int nr_labels;	/* Depth of stack, 0 = no MPLS */
365 	__be32 labels[MAX_MPLS_LABELS];
366 
367 	/* VLAN/SVLAN (802.1Q/Q-in-Q) */
368 	__u8  vlan_p;
369 	__u8  vlan_cfi;
370 	__u16 vlan_id;  /* 0xffff means no vlan tag */
371 
372 	__u8  svlan_p;
373 	__u8  svlan_cfi;
374 	__u16 svlan_id; /* 0xffff means no svlan tag */
375 
376 	__u32 src_mac_count;	/* How many MACs to iterate through */
377 	__u32 dst_mac_count;	/* How many MACs to iterate through */
378 
379 	unsigned char dst_mac[ETH_ALEN];
380 	unsigned char src_mac[ETH_ALEN];
381 
382 	__u32 cur_dst_mac_offset;
383 	__u32 cur_src_mac_offset;
384 	__be32 cur_saddr;
385 	__be32 cur_daddr;
386 	__u16 ip_id;
387 	__u16 cur_udp_dst;
388 	__u16 cur_udp_src;
389 	__u16 cur_queue_map;
390 	__u32 cur_pkt_size;
391 	__u32 last_pkt_size;
392 
393 	__u8 hh[14];
394 	/* = {
395 	 * 0x00, 0x80, 0xC8, 0x79, 0xB3, 0xCB,
396 	 *
397 	 * We fill in SRC address later
398 	 * 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
399 	 * 0x08, 0x00
400 	 * };
401 	 */
402 	__u16 pad;		/* pad out the hh struct to an even 16 bytes */
403 
404 	struct sk_buff *skb;	/* skb we are to transmit next, used for when we
405 				 * are transmitting the same one multiple times
406 				 */
407 	struct net_device *odev; /* The out-going device.
408 				  * Note that the device should have it's
409 				  * pg_info pointer pointing back to this
410 				  * device.
411 				  * Set when the user specifies the out-going
412 				  * device name (not when the inject is
413 				  * started as it used to do.)
414 				  */
415 	netdevice_tracker dev_tracker;
416 	char odevname[32];
417 	struct flow_state *flows;
418 	unsigned int cflows;	/* Concurrent flows (config) */
419 	unsigned int lflow;		/* Flow length  (config) */
420 	unsigned int nflows;	/* accumulated flows (stats) */
421 	unsigned int curfl;		/* current sequenced flow (state)*/
422 
423 	u16 queue_map_min;
424 	u16 queue_map_max;
425 	__u32 skb_priority;	/* skb priority field */
426 	unsigned int burst;	/* number of duplicated packets to burst */
427 	int node;               /* Memory node */
428 
429 #ifdef CONFIG_XFRM
430 	__u8	ipsmode;		/* IPSEC mode (config) */
431 	__u8	ipsproto;		/* IPSEC type (config) */
432 	__u32	spi;
433 	struct xfrm_dst xdst;
434 	struct dst_ops dstops;
435 #endif
436 	char result[512];
437 };
438 
439 struct pktgen_hdr {
440 	__be32 pgh_magic;
441 	__be32 seq_num;
442 	__be32 tv_sec;
443 	__be32 tv_usec;
444 };
445 
446 
447 static unsigned int pg_net_id __read_mostly;
448 
449 struct pktgen_net {
450 	struct net		*net;
451 	struct proc_dir_entry	*proc_dir;
452 	struct list_head	pktgen_threads;
453 	bool			pktgen_exiting;
454 };
455 
456 struct pktgen_thread {
457 	struct mutex if_lock;		/* for list of devices */
458 	struct list_head if_list;	/* All device here */
459 	struct list_head th_list;
460 	struct task_struct *tsk;
461 	char result[512];
462 
463 	/* Field for thread to receive "posted" events terminate,
464 	 * stop ifs etc.
465 	 */
466 
467 	u32 control;
468 	int cpu;
469 
470 	wait_queue_head_t queue;
471 	struct completion start_done;
472 	struct pktgen_net *net;
473 };
474 
475 #define REMOVE 1
476 #define FIND   0
477 
478 static const char version[] =
479 	"Packet Generator for packet performance testing. Version: " VERSION "\n";
480 
481 static int pktgen_remove_device(struct pktgen_thread *t, struct pktgen_dev *i);
482 static int pktgen_add_device(struct pktgen_thread *t, const char *ifname);
483 static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
484 					  const char *ifname, bool exact);
485 static int pktgen_device_event(struct notifier_block *, unsigned long, void *);
486 static void pktgen_run_all_threads(struct pktgen_net *pn);
487 static void pktgen_reset_all_threads(struct pktgen_net *pn);
488 static void pktgen_stop_all_threads(struct pktgen_net *pn);
489 
490 static void pktgen_stop(struct pktgen_thread *t);
491 static void pktgen_clear_counters(struct pktgen_dev *pkt_dev);
492 static void fill_imix_distribution(struct pktgen_dev *pkt_dev);
493 
494 /* Module parameters, defaults. */
495 static int pg_count_d __read_mostly = 1000;
496 static int pg_delay_d __read_mostly;
497 static int pg_clone_skb_d  __read_mostly;
498 static int debug  __read_mostly;
499 
500 static DEFINE_MUTEX(pktgen_thread_lock);
501 
502 static struct notifier_block pktgen_notifier_block = {
503 	.notifier_call = pktgen_device_event,
504 };
505 
506 /*
507  * /proc handling functions
508  *
509  */
510 
511 static int pgctrl_show(struct seq_file *seq, void *v)
512 {
513 	seq_puts(seq, version);
514 	return 0;
515 }
516 
517 static ssize_t pgctrl_write(struct file *file, const char __user *buf,
518 			    size_t count, loff_t *ppos)
519 {
520 	char data[128];
521 	size_t max;
522 	struct pktgen_net *pn = net_generic(current->nsproxy->net_ns, pg_net_id);
523 
524 	if (!capable(CAP_NET_ADMIN))
525 		return -EPERM;
526 
527 	if (count < 1)
528 		return -EINVAL;
529 
530 	max = min(count, sizeof(data) - 1);
531 	if (copy_from_user(data, buf, max))
532 		return -EFAULT;
533 
534 	if (data[max - 1] == '\n')
535 		data[max - 1] = 0; /* strip trailing '\n', terminate string */
536 	else
537 		data[max] = 0; /* terminate string */
538 
539 	if (!strcmp(data, "stop"))
540 		pktgen_stop_all_threads(pn);
541 	else if (!strcmp(data, "start"))
542 		pktgen_run_all_threads(pn);
543 	else if (!strcmp(data, "reset"))
544 		pktgen_reset_all_threads(pn);
545 	else
546 		return -EINVAL;
547 
548 	return count;
549 }
550 
551 static int pgctrl_open(struct inode *inode, struct file *file)
552 {
553 	return single_open(file, pgctrl_show, pde_data(inode));
554 }
555 
556 static const struct proc_ops pktgen_proc_ops = {
557 	.proc_open	= pgctrl_open,
558 	.proc_read	= seq_read,
559 	.proc_lseek	= seq_lseek,
560 	.proc_write	= pgctrl_write,
561 	.proc_release	= single_release,
562 };
563 
564 static int pktgen_if_show(struct seq_file *seq, void *v)
565 {
566 	const struct pktgen_dev *pkt_dev = seq->private;
567 	ktime_t stopped;
568 	unsigned int i;
569 	u64 idle;
570 
571 	seq_printf(seq,
572 		   "Params: count %llu  min_pkt_size: %u  max_pkt_size: %u\n",
573 		   (unsigned long long)pkt_dev->count, pkt_dev->min_pkt_size,
574 		   pkt_dev->max_pkt_size);
575 
576 	if (pkt_dev->n_imix_entries > 0) {
577 		seq_puts(seq, "     imix_weights: ");
578 		for (i = 0; i < pkt_dev->n_imix_entries; i++) {
579 			seq_printf(seq, "%llu,%llu ",
580 				   pkt_dev->imix_entries[i].size,
581 				   pkt_dev->imix_entries[i].weight);
582 		}
583 		seq_puts(seq, "\n");
584 	}
585 
586 	seq_printf(seq,
587 		   "     frags: %d  delay: %llu  clone_skb: %d  ifname: %s\n",
588 		   pkt_dev->nfrags, (unsigned long long) pkt_dev->delay,
589 		   pkt_dev->clone_skb, pkt_dev->odevname);
590 
591 	seq_printf(seq, "     flows: %u flowlen: %u\n", pkt_dev->cflows,
592 		   pkt_dev->lflow);
593 
594 	seq_printf(seq,
595 		   "     queue_map_min: %u  queue_map_max: %u\n",
596 		   pkt_dev->queue_map_min,
597 		   pkt_dev->queue_map_max);
598 
599 	if (pkt_dev->skb_priority)
600 		seq_printf(seq, "     skb_priority: %u\n",
601 			   pkt_dev->skb_priority);
602 
603 	if (pkt_dev->flags & F_IPV6) {
604 		seq_printf(seq,
605 			   "     saddr: %pI6c  min_saddr: %pI6c  max_saddr: %pI6c\n"
606 			   "     daddr: %pI6c  min_daddr: %pI6c  max_daddr: %pI6c\n",
607 			   &pkt_dev->in6_saddr,
608 			   &pkt_dev->min_in6_saddr, &pkt_dev->max_in6_saddr,
609 			   &pkt_dev->in6_daddr,
610 			   &pkt_dev->min_in6_daddr, &pkt_dev->max_in6_daddr);
611 	} else {
612 		seq_printf(seq,
613 			   "     dst_min: %s  dst_max: %s\n",
614 			   pkt_dev->dst_min, pkt_dev->dst_max);
615 		seq_printf(seq,
616 			   "     src_min: %s  src_max: %s\n",
617 			   pkt_dev->src_min, pkt_dev->src_max);
618 	}
619 
620 	seq_puts(seq, "     src_mac: ");
621 
622 	seq_printf(seq, "%pM ",
623 		   is_zero_ether_addr(pkt_dev->src_mac) ?
624 			     pkt_dev->odev->dev_addr : pkt_dev->src_mac);
625 
626 	seq_puts(seq, "dst_mac: ");
627 	seq_printf(seq, "%pM\n", pkt_dev->dst_mac);
628 
629 	seq_printf(seq,
630 		   "     udp_src_min: %d  udp_src_max: %d  udp_dst_min: %d  udp_dst_max: %d\n",
631 		   pkt_dev->udp_src_min, pkt_dev->udp_src_max,
632 		   pkt_dev->udp_dst_min, pkt_dev->udp_dst_max);
633 
634 	seq_printf(seq,
635 		   "     src_mac_count: %d  dst_mac_count: %d\n",
636 		   pkt_dev->src_mac_count, pkt_dev->dst_mac_count);
637 
638 	if (pkt_dev->nr_labels) {
639 		seq_puts(seq, "     mpls: ");
640 		for (i = 0; i < pkt_dev->nr_labels; i++)
641 			seq_printf(seq, "%08x%s", ntohl(pkt_dev->labels[i]),
642 				   i == pkt_dev->nr_labels-1 ? "\n" : ", ");
643 	}
644 
645 	if (pkt_dev->vlan_id != 0xffff)
646 		seq_printf(seq, "     vlan_id: %u  vlan_p: %u  vlan_cfi: %u\n",
647 			   pkt_dev->vlan_id, pkt_dev->vlan_p,
648 			   pkt_dev->vlan_cfi);
649 
650 	if (pkt_dev->svlan_id != 0xffff)
651 		seq_printf(seq, "     svlan_id: %u  vlan_p: %u  vlan_cfi: %u\n",
652 			   pkt_dev->svlan_id, pkt_dev->svlan_p,
653 			   pkt_dev->svlan_cfi);
654 
655 	if (pkt_dev->tos)
656 		seq_printf(seq, "     tos: 0x%02x\n", pkt_dev->tos);
657 
658 	if (pkt_dev->traffic_class)
659 		seq_printf(seq, "     traffic_class: 0x%02x\n", pkt_dev->traffic_class);
660 
661 	if (pkt_dev->burst > 1)
662 		seq_printf(seq, "     burst: %d\n", pkt_dev->burst);
663 
664 	if (pkt_dev->node >= 0)
665 		seq_printf(seq, "     node: %d\n", pkt_dev->node);
666 
667 	if (pkt_dev->xmit_mode == M_NETIF_RECEIVE)
668 		seq_puts(seq, "     xmit_mode: netif_receive\n");
669 	else if (pkt_dev->xmit_mode == M_QUEUE_XMIT)
670 		seq_puts(seq, "     xmit_mode: xmit_queue\n");
671 
672 	seq_puts(seq, "     Flags: ");
673 
674 	for (i = 0; i < NR_PKT_FLAGS; i++) {
675 		if (i == FLOW_SEQ_SHIFT)
676 			if (!pkt_dev->cflows)
677 				continue;
678 
679 		if (pkt_dev->flags & (1 << i)) {
680 			seq_printf(seq, "%s  ", pkt_flag_names[i]);
681 #ifdef CONFIG_XFRM
682 			if (i == IPSEC_SHIFT && pkt_dev->spi)
683 				seq_printf(seq, "spi:%u  ", pkt_dev->spi);
684 #endif
685 		} else if (i == FLOW_SEQ_SHIFT) {
686 			seq_puts(seq, "FLOW_RND  ");
687 		}
688 	}
689 
690 	seq_puts(seq, "\n");
691 
692 	/* not really stopped, more like last-running-at */
693 	stopped = pkt_dev->running ? ktime_get() : pkt_dev->stopped_at;
694 	idle = pkt_dev->idle_acc;
695 	do_div(idle, NSEC_PER_USEC);
696 
697 	seq_printf(seq,
698 		   "Current:\n     pkts-sofar: %llu  errors: %llu\n",
699 		   (unsigned long long)pkt_dev->sofar,
700 		   (unsigned long long)pkt_dev->errors);
701 
702 	if (pkt_dev->n_imix_entries > 0) {
703 		int i;
704 
705 		seq_puts(seq, "     imix_size_counts: ");
706 		for (i = 0; i < pkt_dev->n_imix_entries; i++) {
707 			seq_printf(seq, "%llu,%llu ",
708 				   pkt_dev->imix_entries[i].size,
709 				   pkt_dev->imix_entries[i].count_so_far);
710 		}
711 		seq_puts(seq, "\n");
712 	}
713 
714 	seq_printf(seq,
715 		   "     started: %lluus  stopped: %lluus idle: %lluus\n",
716 		   (unsigned long long) ktime_to_us(pkt_dev->started_at),
717 		   (unsigned long long) ktime_to_us(stopped),
718 		   (unsigned long long) idle);
719 
720 	seq_printf(seq,
721 		   "     seq_num: %d  cur_dst_mac_offset: %d  cur_src_mac_offset: %d\n",
722 		   pkt_dev->seq_num, pkt_dev->cur_dst_mac_offset,
723 		   pkt_dev->cur_src_mac_offset);
724 
725 	if (pkt_dev->flags & F_IPV6) {
726 		seq_printf(seq, "     cur_saddr: %pI6c  cur_daddr: %pI6c\n",
727 				&pkt_dev->cur_in6_saddr,
728 				&pkt_dev->cur_in6_daddr);
729 	} else
730 		seq_printf(seq, "     cur_saddr: %pI4  cur_daddr: %pI4\n",
731 			   &pkt_dev->cur_saddr, &pkt_dev->cur_daddr);
732 
733 	seq_printf(seq, "     cur_udp_dst: %d  cur_udp_src: %d\n",
734 		   pkt_dev->cur_udp_dst, pkt_dev->cur_udp_src);
735 
736 	seq_printf(seq, "     cur_queue_map: %u\n", pkt_dev->cur_queue_map);
737 
738 	seq_printf(seq, "     flows: %u\n", pkt_dev->nflows);
739 
740 	if (pkt_dev->result[0])
741 		seq_printf(seq, "Result: %s\n", pkt_dev->result);
742 	else
743 		seq_puts(seq, "Result: Idle\n");
744 
745 	return 0;
746 }
747 
748 
749 static ssize_t hex32_arg(const char __user *user_buffer, size_t maxlen,
750 			 __u32 *num)
751 {
752 	size_t i = 0;
753 
754 	*num = 0;
755 
756 	for (; i < maxlen; i++) {
757 		int value;
758 		char c;
759 
760 		if (get_user(c, &user_buffer[i]))
761 			return -EFAULT;
762 		value = hex_to_bin(c);
763 		if (value >= 0) {
764 			*num <<= 4;
765 			*num |= value;
766 		} else {
767 			break;
768 		}
769 	}
770 	return i;
771 }
772 
773 static ssize_t count_trail_chars(const char __user *user_buffer, size_t maxlen)
774 {
775 	size_t i;
776 
777 	for (i = 0; i < maxlen; i++) {
778 		char c;
779 
780 		if (get_user(c, &user_buffer[i]))
781 			return -EFAULT;
782 		switch (c) {
783 		case '\"':
784 		case '\n':
785 		case '\r':
786 		case '\t':
787 		case ' ':
788 		case '=':
789 			break;
790 		default:
791 			goto done;
792 		}
793 	}
794 done:
795 	return i;
796 }
797 
798 static ssize_t num_arg(const char __user *user_buffer, size_t maxlen,
799 		       unsigned long *num)
800 {
801 	size_t i;
802 	*num = 0;
803 
804 	for (i = 0; i < maxlen; i++) {
805 		char c;
806 
807 		if (get_user(c, &user_buffer[i]))
808 			return -EFAULT;
809 		if ((c >= '0') && (c <= '9')) {
810 			*num *= 10;
811 			*num += c - '0';
812 		} else
813 			break;
814 	}
815 	return i;
816 }
817 
818 static ssize_t strn_len(const char __user *user_buffer, size_t maxlen)
819 {
820 	size_t i;
821 
822 	for (i = 0; i < maxlen; i++) {
823 		char c;
824 
825 		if (get_user(c, &user_buffer[i]))
826 			return -EFAULT;
827 		switch (c) {
828 		case '\"':
829 		case '\n':
830 		case '\r':
831 		case '\t':
832 		case ' ':
833 		case '=':
834 			goto done_str;
835 		default:
836 			break;
837 		}
838 	}
839 done_str:
840 	return i;
841 }
842 
843 /* Parses imix entries from user buffer.
844  * The user buffer should consist of imix entries separated by spaces
845  * where each entry consists of size and weight delimited by commas.
846  * "size1,weight_1 size2,weight_2 ... size_n,weight_n" for example.
847  */
848 static ssize_t get_imix_entries(const char __user *buffer,
849 				size_t maxlen,
850 				struct pktgen_dev *pkt_dev)
851 {
852 	size_t i = 0, max;
853 	ssize_t len;
854 	char c;
855 
856 	pkt_dev->n_imix_entries = 0;
857 
858 	do {
859 		unsigned long weight;
860 		unsigned long size;
861 
862 		if (pkt_dev->n_imix_entries >= MAX_IMIX_ENTRIES)
863 			return -E2BIG;
864 
865 		if (i >= maxlen)
866 			return -EINVAL;
867 
868 		max = min(10, maxlen - i);
869 		len = num_arg(&buffer[i], max, &size);
870 		if (len < 0)
871 			return len;
872 		i += len;
873 		if (i >= maxlen)
874 			return -EINVAL;
875 		if (get_user(c, &buffer[i]))
876 			return -EFAULT;
877 		/* Check for comma between size_i and weight_i */
878 		if (c != ',')
879 			return -EINVAL;
880 		i++;
881 		if (i >= maxlen)
882 			return -EINVAL;
883 
884 		if (size < 14 + 20 + 8)
885 			size = 14 + 20 + 8;
886 
887 		max = min(10, maxlen - i);
888 		len = num_arg(&buffer[i], max, &weight);
889 		if (len < 0)
890 			return len;
891 		if (weight <= 0)
892 			return -EINVAL;
893 
894 		pkt_dev->imix_entries[pkt_dev->n_imix_entries].size = size;
895 		pkt_dev->imix_entries[pkt_dev->n_imix_entries].weight = weight;
896 
897 		i += len;
898 		pkt_dev->n_imix_entries++;
899 
900 		if (i >= maxlen)
901 			break;
902 		if (get_user(c, &buffer[i]))
903 			return -EFAULT;
904 		i++;
905 	} while (c == ' ');
906 
907 	return i;
908 }
909 
910 static ssize_t get_labels(const char __user *buffer,
911 			  size_t maxlen, struct pktgen_dev *pkt_dev)
912 {
913 	unsigned int n = 0;
914 	size_t i = 0, max;
915 	ssize_t len;
916 	char c;
917 
918 	pkt_dev->nr_labels = 0;
919 	do {
920 		__u32 tmp;
921 
922 		if (n >= MAX_MPLS_LABELS)
923 			return -E2BIG;
924 
925 		if (i >= maxlen)
926 			return -EINVAL;
927 
928 		max = min(8, maxlen - i);
929 		len = hex32_arg(&buffer[i], max, &tmp);
930 		if (len < 0)
931 			return len;
932 
933 		/* return empty list in case of invalid input or zero value */
934 		if (len == 0 || tmp == 0)
935 			return maxlen;
936 
937 		pkt_dev->labels[n] = htonl(tmp);
938 		if (pkt_dev->labels[n] & MPLS_STACK_BOTTOM)
939 			pkt_dev->flags |= F_MPLS_RND;
940 		i += len;
941 		n++;
942 		if (i >= maxlen)
943 			break;
944 		if (get_user(c, &buffer[i]))
945 			return -EFAULT;
946 		i++;
947 	} while (c == ',');
948 
949 	pkt_dev->nr_labels = n;
950 	return i;
951 }
952 
953 static __u32 pktgen_read_flag(const char *f, bool *disable)
954 {
955 	__u32 i;
956 
957 	if (f[0] == '!') {
958 		*disable = true;
959 		f++;
960 	}
961 
962 	for (i = 0; i < NR_PKT_FLAGS; i++) {
963 		if (!IS_ENABLED(CONFIG_XFRM) && i == IPSEC_SHIFT)
964 			continue;
965 
966 		/* allow only disabling ipv6 flag */
967 		if (!*disable && i == IPV6_SHIFT)
968 			continue;
969 
970 		if (strcmp(f, pkt_flag_names[i]) == 0)
971 			return 1 << i;
972 	}
973 
974 	if (strcmp(f, "FLOW_RND") == 0) {
975 		*disable = !*disable;
976 		return F_FLOW_SEQ;
977 	}
978 
979 	return 0;
980 }
981 
982 static ssize_t pktgen_if_write(struct file *file,
983 			       const char __user *user_buffer, size_t count,
984 			       loff_t *offset)
985 {
986 	struct seq_file *seq = file->private_data;
987 	struct pktgen_dev *pkt_dev = seq->private;
988 	size_t i, max;
989 	ssize_t len;
990 	char name[16], valstr[32];
991 	unsigned long value = 0;
992 	char *pg_result = NULL;
993 	char buf[128];
994 
995 	pg_result = &(pkt_dev->result[0]);
996 
997 	if (count < 1) {
998 		pr_warn("wrong command format\n");
999 		return -EINVAL;
1000 	}
1001 
1002 	max = count;
1003 	len = count_trail_chars(user_buffer, max);
1004 	if (len < 0) {
1005 		pr_warn("illegal format\n");
1006 		return len;
1007 	}
1008 	i = len;
1009 
1010 	/* Read variable name */
1011 	max = min(sizeof(name) - 1, count - i);
1012 	len = strn_len(&user_buffer[i], max);
1013 	if (len < 0)
1014 		return len;
1015 
1016 	memset(name, 0, sizeof(name));
1017 	if (copy_from_user(name, &user_buffer[i], len))
1018 		return -EFAULT;
1019 	i += len;
1020 
1021 	max = count - i;
1022 	len = count_trail_chars(&user_buffer[i], max);
1023 	if (len < 0)
1024 		return len;
1025 
1026 	i += len;
1027 
1028 	if (debug) {
1029 		size_t copy = min_t(size_t, count + 1, 1024);
1030 		char *tp = strndup_user(user_buffer, copy);
1031 
1032 		if (IS_ERR(tp))
1033 			return PTR_ERR(tp);
1034 
1035 		pr_debug("%s,%zu  buffer -:%s:-\n", name, count, tp);
1036 		kfree(tp);
1037 	}
1038 
1039 	if (!strcmp(name, "min_pkt_size")) {
1040 		max = min(10, count - i);
1041 		len = num_arg(&user_buffer[i], max, &value);
1042 		if (len < 0)
1043 			return len;
1044 
1045 		if (value < 14 + 20 + 8)
1046 			value = 14 + 20 + 8;
1047 		if (value != pkt_dev->min_pkt_size) {
1048 			pkt_dev->min_pkt_size = value;
1049 			pkt_dev->cur_pkt_size = value;
1050 		}
1051 		sprintf(pg_result, "OK: min_pkt_size=%d",
1052 			pkt_dev->min_pkt_size);
1053 		return count;
1054 	}
1055 
1056 	if (!strcmp(name, "max_pkt_size")) {
1057 		max = min(10, count - i);
1058 		len = num_arg(&user_buffer[i], max, &value);
1059 		if (len < 0)
1060 			return len;
1061 
1062 		if (value < 14 + 20 + 8)
1063 			value = 14 + 20 + 8;
1064 		if (value != pkt_dev->max_pkt_size) {
1065 			pkt_dev->max_pkt_size = value;
1066 			pkt_dev->cur_pkt_size = value;
1067 		}
1068 		sprintf(pg_result, "OK: max_pkt_size=%d",
1069 			pkt_dev->max_pkt_size);
1070 		return count;
1071 	}
1072 
1073 	/* Shortcut for min = max */
1074 
1075 	if (!strcmp(name, "pkt_size")) {
1076 		max = min(10, count - i);
1077 		len = num_arg(&user_buffer[i], max, &value);
1078 		if (len < 0)
1079 			return len;
1080 
1081 		if (value < 14 + 20 + 8)
1082 			value = 14 + 20 + 8;
1083 		if (value != pkt_dev->min_pkt_size) {
1084 			pkt_dev->min_pkt_size = value;
1085 			pkt_dev->max_pkt_size = value;
1086 			pkt_dev->cur_pkt_size = value;
1087 		}
1088 		sprintf(pg_result, "OK: pkt_size=%d", pkt_dev->min_pkt_size);
1089 		return count;
1090 	}
1091 
1092 	if (!strcmp(name, "imix_weights")) {
1093 		if (pkt_dev->clone_skb > 0)
1094 			return -EINVAL;
1095 
1096 		max = count - i;
1097 		len = get_imix_entries(&user_buffer[i], max, pkt_dev);
1098 		if (len < 0)
1099 			return len;
1100 
1101 		fill_imix_distribution(pkt_dev);
1102 
1103 		return count;
1104 	}
1105 
1106 	if (!strcmp(name, "debug")) {
1107 		max = min(10, count - i);
1108 		len = num_arg(&user_buffer[i], max, &value);
1109 		if (len < 0)
1110 			return len;
1111 
1112 		debug = value;
1113 		sprintf(pg_result, "OK: debug=%u", debug);
1114 		return count;
1115 	}
1116 
1117 	if (!strcmp(name, "frags")) {
1118 		max = min(10, count - i);
1119 		len = num_arg(&user_buffer[i], max, &value);
1120 		if (len < 0)
1121 			return len;
1122 
1123 		pkt_dev->nfrags = value;
1124 		sprintf(pg_result, "OK: frags=%d", pkt_dev->nfrags);
1125 		return count;
1126 	}
1127 	if (!strcmp(name, "delay")) {
1128 		max = min(10, count - i);
1129 		len = num_arg(&user_buffer[i], max, &value);
1130 		if (len < 0)
1131 			return len;
1132 
1133 		if (value == 0x7FFFFFFF)
1134 			pkt_dev->delay = ULLONG_MAX;
1135 		else
1136 			pkt_dev->delay = (u64)value;
1137 
1138 		sprintf(pg_result, "OK: delay=%llu",
1139 			(unsigned long long) pkt_dev->delay);
1140 		return count;
1141 	}
1142 	if (!strcmp(name, "rate")) {
1143 		max = min(10, count - i);
1144 		len = num_arg(&user_buffer[i], max, &value);
1145 		if (len < 0)
1146 			return len;
1147 
1148 		if (!value)
1149 			return -EINVAL;
1150 		pkt_dev->delay = pkt_dev->min_pkt_size*8*NSEC_PER_USEC/value;
1151 		if (debug)
1152 			pr_info("Delay set at: %llu ns\n", pkt_dev->delay);
1153 
1154 		sprintf(pg_result, "OK: rate=%lu", value);
1155 		return count;
1156 	}
1157 	if (!strcmp(name, "ratep")) {
1158 		max = min(10, count - i);
1159 		len = num_arg(&user_buffer[i], max, &value);
1160 		if (len < 0)
1161 			return len;
1162 
1163 		if (!value)
1164 			return -EINVAL;
1165 		pkt_dev->delay = NSEC_PER_SEC/value;
1166 		if (debug)
1167 			pr_info("Delay set at: %llu ns\n", pkt_dev->delay);
1168 
1169 		sprintf(pg_result, "OK: rate=%lu", value);
1170 		return count;
1171 	}
1172 	if (!strcmp(name, "udp_src_min")) {
1173 		max = min(10, count - i);
1174 		len = num_arg(&user_buffer[i], max, &value);
1175 		if (len < 0)
1176 			return len;
1177 
1178 		if (value != pkt_dev->udp_src_min) {
1179 			pkt_dev->udp_src_min = value;
1180 			pkt_dev->cur_udp_src = value;
1181 		}
1182 		sprintf(pg_result, "OK: udp_src_min=%u", pkt_dev->udp_src_min);
1183 		return count;
1184 	}
1185 	if (!strcmp(name, "udp_dst_min")) {
1186 		max = min(10, count - i);
1187 		len = num_arg(&user_buffer[i], max, &value);
1188 		if (len < 0)
1189 			return len;
1190 
1191 		if (value != pkt_dev->udp_dst_min) {
1192 			pkt_dev->udp_dst_min = value;
1193 			pkt_dev->cur_udp_dst = value;
1194 		}
1195 		sprintf(pg_result, "OK: udp_dst_min=%u", pkt_dev->udp_dst_min);
1196 		return count;
1197 	}
1198 	if (!strcmp(name, "udp_src_max")) {
1199 		max = min(10, count - i);
1200 		len = num_arg(&user_buffer[i], max, &value);
1201 		if (len < 0)
1202 			return len;
1203 
1204 		if (value != pkt_dev->udp_src_max) {
1205 			pkt_dev->udp_src_max = value;
1206 			pkt_dev->cur_udp_src = value;
1207 		}
1208 		sprintf(pg_result, "OK: udp_src_max=%u", pkt_dev->udp_src_max);
1209 		return count;
1210 	}
1211 	if (!strcmp(name, "udp_dst_max")) {
1212 		max = min(10, count - i);
1213 		len = num_arg(&user_buffer[i], max, &value);
1214 		if (len < 0)
1215 			return len;
1216 
1217 		if (value != pkt_dev->udp_dst_max) {
1218 			pkt_dev->udp_dst_max = value;
1219 			pkt_dev->cur_udp_dst = value;
1220 		}
1221 		sprintf(pg_result, "OK: udp_dst_max=%u", pkt_dev->udp_dst_max);
1222 		return count;
1223 	}
1224 	if (!strcmp(name, "clone_skb")) {
1225 		max = min(10, count - i);
1226 		len = num_arg(&user_buffer[i], max, &value);
1227 		if (len < 0)
1228 			return len;
1229 		/* clone_skb is not supported for netif_receive xmit_mode and
1230 		 * IMIX mode.
1231 		 */
1232 		if ((value > 0) &&
1233 		    ((pkt_dev->xmit_mode == M_NETIF_RECEIVE) ||
1234 		     !(pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)))
1235 			return -EOPNOTSUPP;
1236 		if (value > 0 && (pkt_dev->n_imix_entries > 0 ||
1237 				  !(pkt_dev->flags & F_SHARED)))
1238 			return -EINVAL;
1239 
1240 		pkt_dev->clone_skb = value;
1241 
1242 		sprintf(pg_result, "OK: clone_skb=%d", pkt_dev->clone_skb);
1243 		return count;
1244 	}
1245 	if (!strcmp(name, "count")) {
1246 		max = min(10, count - i);
1247 		len = num_arg(&user_buffer[i], max, &value);
1248 		if (len < 0)
1249 			return len;
1250 
1251 		pkt_dev->count = value;
1252 		sprintf(pg_result, "OK: count=%llu",
1253 			(unsigned long long)pkt_dev->count);
1254 		return count;
1255 	}
1256 	if (!strcmp(name, "src_mac_count")) {
1257 		max = min(10, count - i);
1258 		len = num_arg(&user_buffer[i], max, &value);
1259 		if (len < 0)
1260 			return len;
1261 
1262 		if (pkt_dev->src_mac_count != value) {
1263 			pkt_dev->src_mac_count = value;
1264 			pkt_dev->cur_src_mac_offset = 0;
1265 		}
1266 		sprintf(pg_result, "OK: src_mac_count=%d",
1267 			pkt_dev->src_mac_count);
1268 		return count;
1269 	}
1270 	if (!strcmp(name, "dst_mac_count")) {
1271 		max = min(10, count - i);
1272 		len = num_arg(&user_buffer[i], max, &value);
1273 		if (len < 0)
1274 			return len;
1275 
1276 		if (pkt_dev->dst_mac_count != value) {
1277 			pkt_dev->dst_mac_count = value;
1278 			pkt_dev->cur_dst_mac_offset = 0;
1279 		}
1280 		sprintf(pg_result, "OK: dst_mac_count=%d",
1281 			pkt_dev->dst_mac_count);
1282 		return count;
1283 	}
1284 	if (!strcmp(name, "burst")) {
1285 		max = min(10, count - i);
1286 		len = num_arg(&user_buffer[i], max, &value);
1287 		if (len < 0)
1288 			return len;
1289 
1290 		if ((value > 1) &&
1291 		    ((pkt_dev->xmit_mode == M_QUEUE_XMIT) ||
1292 		     ((pkt_dev->xmit_mode == M_START_XMIT) &&
1293 		     (!(pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)))))
1294 			return -EOPNOTSUPP;
1295 
1296 		if (value > 1 && !(pkt_dev->flags & F_SHARED))
1297 			return -EINVAL;
1298 
1299 		pkt_dev->burst = value < 1 ? 1 : value;
1300 		sprintf(pg_result, "OK: burst=%u", pkt_dev->burst);
1301 		return count;
1302 	}
1303 	if (!strcmp(name, "node")) {
1304 		max = min(10, count - i);
1305 		len = num_arg(&user_buffer[i], max, &value);
1306 		if (len < 0)
1307 			return len;
1308 
1309 		if (node_possible(value)) {
1310 			pkt_dev->node = value;
1311 			sprintf(pg_result, "OK: node=%d", pkt_dev->node);
1312 			if (pkt_dev->page) {
1313 				put_page(pkt_dev->page);
1314 				pkt_dev->page = NULL;
1315 			}
1316 		}
1317 		else
1318 			sprintf(pg_result, "ERROR: node not possible");
1319 		return count;
1320 	}
1321 	if (!strcmp(name, "xmit_mode")) {
1322 		char f[32];
1323 
1324 		max = min(sizeof(f) - 1, count - i);
1325 		len = strn_len(&user_buffer[i], max);
1326 		if (len < 0)
1327 			return len;
1328 
1329 		memset(f, 0, sizeof(f));
1330 		if (copy_from_user(f, &user_buffer[i], len))
1331 			return -EFAULT;
1332 
1333 		if (strcmp(f, "start_xmit") == 0) {
1334 			pkt_dev->xmit_mode = M_START_XMIT;
1335 		} else if (strcmp(f, "netif_receive") == 0) {
1336 			/* clone_skb set earlier, not supported in this mode */
1337 			if (pkt_dev->clone_skb > 0)
1338 				return -EOPNOTSUPP;
1339 
1340 			pkt_dev->xmit_mode = M_NETIF_RECEIVE;
1341 
1342 			/* make sure new packet is allocated every time
1343 			 * pktgen_xmit() is called
1344 			 */
1345 			pkt_dev->last_ok = 1;
1346 		} else if (strcmp(f, "queue_xmit") == 0) {
1347 			pkt_dev->xmit_mode = M_QUEUE_XMIT;
1348 			pkt_dev->last_ok = 1;
1349 		} else {
1350 			sprintf(pg_result,
1351 				"xmit_mode -:%s:- unknown\nAvailable modes: %s",
1352 				f, "start_xmit, netif_receive\n");
1353 			return count;
1354 		}
1355 		sprintf(pg_result, "OK: xmit_mode=%s", f);
1356 		return count;
1357 	}
1358 	if (!strcmp(name, "flag")) {
1359 		bool disable = false;
1360 		__u32 flag;
1361 		char f[32];
1362 		char *end;
1363 
1364 		max = min(sizeof(f) - 1, count - i);
1365 		len = strn_len(&user_buffer[i], max);
1366 		if (len < 0)
1367 			return len;
1368 
1369 		memset(f, 0, 32);
1370 		if (copy_from_user(f, &user_buffer[i], len))
1371 			return -EFAULT;
1372 
1373 		flag = pktgen_read_flag(f, &disable);
1374 		if (flag) {
1375 			if (disable) {
1376 				/* If "clone_skb", or "burst" parameters are
1377 				 * configured, it means that the skb still
1378 				 * needs to be referenced by the pktgen, so
1379 				 * the skb must be shared.
1380 				 */
1381 				if (flag == F_SHARED && (pkt_dev->clone_skb ||
1382 							 pkt_dev->burst > 1))
1383 					return -EINVAL;
1384 				pkt_dev->flags &= ~flag;
1385 			} else {
1386 				pkt_dev->flags |= flag;
1387 			}
1388 
1389 			sprintf(pg_result, "OK: flags=0x%x", pkt_dev->flags);
1390 			return count;
1391 		}
1392 
1393 		/* Unknown flag */
1394 		end = pkt_dev->result + sizeof(pkt_dev->result);
1395 		pg_result += sprintf(pg_result,
1396 			"Flag -:%s:- unknown\n"
1397 			"Available flags, (prepend ! to un-set flag):\n", f);
1398 
1399 		for (int n = 0; n < NR_PKT_FLAGS && pg_result < end; n++) {
1400 			if (!IS_ENABLED(CONFIG_XFRM) && n == IPSEC_SHIFT)
1401 				continue;
1402 			pg_result += snprintf(pg_result, end - pg_result,
1403 					      "%s, ", pkt_flag_names[n]);
1404 		}
1405 		if (!WARN_ON_ONCE(pg_result >= end)) {
1406 			/* Remove the comma and whitespace at the end */
1407 			*(pg_result - 2) = '\0';
1408 		}
1409 
1410 		return count;
1411 	}
1412 	if (!strcmp(name, "dst_min") || !strcmp(name, "dst")) {
1413 		max = min(sizeof(pkt_dev->dst_min) - 1, count - i);
1414 		len = strn_len(&user_buffer[i], max);
1415 		if (len < 0)
1416 			return len;
1417 
1418 		if (copy_from_user(buf, &user_buffer[i], len))
1419 			return -EFAULT;
1420 		buf[len] = 0;
1421 		if (strcmp(buf, pkt_dev->dst_min) != 0) {
1422 			memset(pkt_dev->dst_min, 0, sizeof(pkt_dev->dst_min));
1423 			strcpy(pkt_dev->dst_min, buf);
1424 			pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
1425 			pkt_dev->cur_daddr = pkt_dev->daddr_min;
1426 		}
1427 		if (debug)
1428 			pr_debug("dst_min set to: %s\n", pkt_dev->dst_min);
1429 
1430 		sprintf(pg_result, "OK: dst_min=%s", pkt_dev->dst_min);
1431 		return count;
1432 	}
1433 	if (!strcmp(name, "dst_max")) {
1434 		max = min(sizeof(pkt_dev->dst_max) - 1, count - i);
1435 		len = strn_len(&user_buffer[i], max);
1436 		if (len < 0)
1437 			return len;
1438 
1439 		if (copy_from_user(buf, &user_buffer[i], len))
1440 			return -EFAULT;
1441 		buf[len] = 0;
1442 		if (strcmp(buf, pkt_dev->dst_max) != 0) {
1443 			memset(pkt_dev->dst_max, 0, sizeof(pkt_dev->dst_max));
1444 			strcpy(pkt_dev->dst_max, buf);
1445 			pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
1446 			pkt_dev->cur_daddr = pkt_dev->daddr_max;
1447 		}
1448 		if (debug)
1449 			pr_debug("dst_max set to: %s\n", pkt_dev->dst_max);
1450 
1451 		sprintf(pg_result, "OK: dst_max=%s", pkt_dev->dst_max);
1452 		return count;
1453 	}
1454 	if (!strcmp(name, "dst6")) {
1455 		max = min(sizeof(buf) - 1, count - i);
1456 		len = strn_len(&user_buffer[i], max);
1457 		if (len < 0)
1458 			return len;
1459 
1460 		pkt_dev->flags |= F_IPV6;
1461 
1462 		if (copy_from_user(buf, &user_buffer[i], len))
1463 			return -EFAULT;
1464 		buf[len] = 0;
1465 
1466 		in6_pton(buf, -1, pkt_dev->in6_daddr.s6_addr, -1, NULL);
1467 		snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->in6_daddr);
1468 
1469 		pkt_dev->cur_in6_daddr = pkt_dev->in6_daddr;
1470 
1471 		if (debug)
1472 			pr_debug("dst6 set to: %s\n", buf);
1473 
1474 		sprintf(pg_result, "OK: dst6=%s", buf);
1475 		return count;
1476 	}
1477 	if (!strcmp(name, "dst6_min")) {
1478 		max = min(sizeof(buf) - 1, count - i);
1479 		len = strn_len(&user_buffer[i], max);
1480 		if (len < 0)
1481 			return len;
1482 
1483 		pkt_dev->flags |= F_IPV6;
1484 
1485 		if (copy_from_user(buf, &user_buffer[i], len))
1486 			return -EFAULT;
1487 		buf[len] = 0;
1488 
1489 		in6_pton(buf, -1, pkt_dev->min_in6_daddr.s6_addr, -1, NULL);
1490 		snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->min_in6_daddr);
1491 
1492 		pkt_dev->cur_in6_daddr = pkt_dev->min_in6_daddr;
1493 		if (debug)
1494 			pr_debug("dst6_min set to: %s\n", buf);
1495 
1496 		sprintf(pg_result, "OK: dst6_min=%s", buf);
1497 		return count;
1498 	}
1499 	if (!strcmp(name, "dst6_max")) {
1500 		max = min(sizeof(buf) - 1, count - i);
1501 		len = strn_len(&user_buffer[i], max);
1502 		if (len < 0)
1503 			return len;
1504 
1505 		pkt_dev->flags |= F_IPV6;
1506 
1507 		if (copy_from_user(buf, &user_buffer[i], len))
1508 			return -EFAULT;
1509 		buf[len] = 0;
1510 
1511 		in6_pton(buf, -1, pkt_dev->max_in6_daddr.s6_addr, -1, NULL);
1512 		snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->max_in6_daddr);
1513 
1514 		if (debug)
1515 			pr_debug("dst6_max set to: %s\n", buf);
1516 
1517 		sprintf(pg_result, "OK: dst6_max=%s", buf);
1518 		return count;
1519 	}
1520 	if (!strcmp(name, "src6")) {
1521 		max = min(sizeof(buf) - 1, count - i);
1522 		len = strn_len(&user_buffer[i], max);
1523 		if (len < 0)
1524 			return len;
1525 
1526 		pkt_dev->flags |= F_IPV6;
1527 
1528 		if (copy_from_user(buf, &user_buffer[i], len))
1529 			return -EFAULT;
1530 		buf[len] = 0;
1531 
1532 		in6_pton(buf, -1, pkt_dev->in6_saddr.s6_addr, -1, NULL);
1533 		snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->in6_saddr);
1534 
1535 		pkt_dev->cur_in6_saddr = pkt_dev->in6_saddr;
1536 
1537 		if (debug)
1538 			pr_debug("src6 set to: %s\n", buf);
1539 
1540 		sprintf(pg_result, "OK: src6=%s", buf);
1541 		return count;
1542 	}
1543 	if (!strcmp(name, "src_min")) {
1544 		max = min(sizeof(pkt_dev->src_min) - 1, count - i);
1545 		len = strn_len(&user_buffer[i], max);
1546 		if (len < 0)
1547 			return len;
1548 
1549 		if (copy_from_user(buf, &user_buffer[i], len))
1550 			return -EFAULT;
1551 		buf[len] = 0;
1552 		if (strcmp(buf, pkt_dev->src_min) != 0) {
1553 			memset(pkt_dev->src_min, 0, sizeof(pkt_dev->src_min));
1554 			strcpy(pkt_dev->src_min, buf);
1555 			pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
1556 			pkt_dev->cur_saddr = pkt_dev->saddr_min;
1557 		}
1558 		if (debug)
1559 			pr_debug("src_min set to: %s\n", pkt_dev->src_min);
1560 
1561 		sprintf(pg_result, "OK: src_min=%s", pkt_dev->src_min);
1562 		return count;
1563 	}
1564 	if (!strcmp(name, "src_max")) {
1565 		max = min(sizeof(pkt_dev->src_max) - 1, count - i);
1566 		len = strn_len(&user_buffer[i], max);
1567 		if (len < 0)
1568 			return len;
1569 
1570 		if (copy_from_user(buf, &user_buffer[i], len))
1571 			return -EFAULT;
1572 		buf[len] = 0;
1573 		if (strcmp(buf, pkt_dev->src_max) != 0) {
1574 			memset(pkt_dev->src_max, 0, sizeof(pkt_dev->src_max));
1575 			strcpy(pkt_dev->src_max, buf);
1576 			pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
1577 			pkt_dev->cur_saddr = pkt_dev->saddr_max;
1578 		}
1579 		if (debug)
1580 			pr_debug("src_max set to: %s\n", pkt_dev->src_max);
1581 
1582 		sprintf(pg_result, "OK: src_max=%s", pkt_dev->src_max);
1583 		return count;
1584 	}
1585 	if (!strcmp(name, "dst_mac")) {
1586 		max = min(sizeof(valstr) - 1, count - i);
1587 		len = strn_len(&user_buffer[i], max);
1588 		if (len < 0)
1589 			return len;
1590 
1591 		memset(valstr, 0, sizeof(valstr));
1592 		if (copy_from_user(valstr, &user_buffer[i], len))
1593 			return -EFAULT;
1594 
1595 		if (!mac_pton(valstr, pkt_dev->dst_mac))
1596 			return -EINVAL;
1597 		/* Set up Dest MAC */
1598 		ether_addr_copy(&pkt_dev->hh[0], pkt_dev->dst_mac);
1599 
1600 		sprintf(pg_result, "OK: dstmac %pM", pkt_dev->dst_mac);
1601 		return count;
1602 	}
1603 	if (!strcmp(name, "src_mac")) {
1604 		max = min(sizeof(valstr) - 1, count - i);
1605 		len = strn_len(&user_buffer[i], max);
1606 		if (len < 0)
1607 			return len;
1608 
1609 		memset(valstr, 0, sizeof(valstr));
1610 		if (copy_from_user(valstr, &user_buffer[i], len))
1611 			return -EFAULT;
1612 
1613 		if (!mac_pton(valstr, pkt_dev->src_mac))
1614 			return -EINVAL;
1615 		/* Set up Src MAC */
1616 		ether_addr_copy(&pkt_dev->hh[6], pkt_dev->src_mac);
1617 
1618 		sprintf(pg_result, "OK: srcmac %pM", pkt_dev->src_mac);
1619 		return count;
1620 	}
1621 
1622 	if (!strcmp(name, "clear_counters")) {
1623 		pktgen_clear_counters(pkt_dev);
1624 		sprintf(pg_result, "OK: Clearing counters.\n");
1625 		return count;
1626 	}
1627 
1628 	if (!strcmp(name, "flows")) {
1629 		max = min(10, count - i);
1630 		len = num_arg(&user_buffer[i], max, &value);
1631 		if (len < 0)
1632 			return len;
1633 
1634 		if (value > MAX_CFLOWS)
1635 			value = MAX_CFLOWS;
1636 
1637 		pkt_dev->cflows = value;
1638 		sprintf(pg_result, "OK: flows=%u", pkt_dev->cflows);
1639 		return count;
1640 	}
1641 #ifdef CONFIG_XFRM
1642 	if (!strcmp(name, "spi")) {
1643 		max = min(10, count - i);
1644 		len = num_arg(&user_buffer[i], max, &value);
1645 		if (len < 0)
1646 			return len;
1647 
1648 		pkt_dev->spi = value;
1649 		sprintf(pg_result, "OK: spi=%u", pkt_dev->spi);
1650 		return count;
1651 	}
1652 #endif
1653 	if (!strcmp(name, "flowlen")) {
1654 		max = min(10, count - i);
1655 		len = num_arg(&user_buffer[i], max, &value);
1656 		if (len < 0)
1657 			return len;
1658 
1659 		pkt_dev->lflow = value;
1660 		sprintf(pg_result, "OK: flowlen=%u", pkt_dev->lflow);
1661 		return count;
1662 	}
1663 
1664 	if (!strcmp(name, "queue_map_min")) {
1665 		max = min(5, count - i);
1666 		len = num_arg(&user_buffer[i], max, &value);
1667 		if (len < 0)
1668 			return len;
1669 
1670 		pkt_dev->queue_map_min = value;
1671 		sprintf(pg_result, "OK: queue_map_min=%u", pkt_dev->queue_map_min);
1672 		return count;
1673 	}
1674 
1675 	if (!strcmp(name, "queue_map_max")) {
1676 		max = min(5, count - i);
1677 		len = num_arg(&user_buffer[i], max, &value);
1678 		if (len < 0)
1679 			return len;
1680 
1681 		pkt_dev->queue_map_max = value;
1682 		sprintf(pg_result, "OK: queue_map_max=%u", pkt_dev->queue_map_max);
1683 		return count;
1684 	}
1685 
1686 	if (!strcmp(name, "mpls")) {
1687 		unsigned int n, cnt;
1688 
1689 		max = count - i;
1690 		len = get_labels(&user_buffer[i], max, pkt_dev);
1691 		if (len < 0)
1692 			return len;
1693 
1694 		cnt = sprintf(pg_result, "OK: mpls=");
1695 		for (n = 0; n < pkt_dev->nr_labels; n++)
1696 			cnt += sprintf(pg_result + cnt,
1697 				       "%08x%s", ntohl(pkt_dev->labels[n]),
1698 				       n == pkt_dev->nr_labels-1 ? "" : ",");
1699 
1700 		if (pkt_dev->nr_labels && pkt_dev->vlan_id != 0xffff) {
1701 			pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
1702 			pkt_dev->svlan_id = 0xffff;
1703 
1704 			if (debug)
1705 				pr_debug("VLAN/SVLAN auto turned off\n");
1706 		}
1707 		return count;
1708 	}
1709 
1710 	if (!strcmp(name, "vlan_id")) {
1711 		max = min(4, count - i);
1712 		len = num_arg(&user_buffer[i], max, &value);
1713 		if (len < 0)
1714 			return len;
1715 
1716 		if (value <= 4095) {
1717 			pkt_dev->vlan_id = value;  /* turn on VLAN */
1718 
1719 			if (debug)
1720 				pr_debug("VLAN turned on\n");
1721 
1722 			if (debug && pkt_dev->nr_labels)
1723 				pr_debug("MPLS auto turned off\n");
1724 
1725 			pkt_dev->nr_labels = 0;    /* turn off MPLS */
1726 			sprintf(pg_result, "OK: vlan_id=%u", pkt_dev->vlan_id);
1727 		} else {
1728 			pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
1729 			pkt_dev->svlan_id = 0xffff;
1730 
1731 			if (debug)
1732 				pr_debug("VLAN/SVLAN turned off\n");
1733 		}
1734 		return count;
1735 	}
1736 
1737 	if (!strcmp(name, "vlan_p")) {
1738 		max = min(1, count - i);
1739 		len = num_arg(&user_buffer[i], max, &value);
1740 		if (len < 0)
1741 			return len;
1742 
1743 		if ((value <= 7) && (pkt_dev->vlan_id != 0xffff)) {
1744 			pkt_dev->vlan_p = value;
1745 			sprintf(pg_result, "OK: vlan_p=%u", pkt_dev->vlan_p);
1746 		} else {
1747 			sprintf(pg_result, "ERROR: vlan_p must be 0-7");
1748 		}
1749 		return count;
1750 	}
1751 
1752 	if (!strcmp(name, "vlan_cfi")) {
1753 		max = min(1, count - i);
1754 		len = num_arg(&user_buffer[i], max, &value);
1755 		if (len < 0)
1756 			return len;
1757 
1758 		if ((value <= 1) && (pkt_dev->vlan_id != 0xffff)) {
1759 			pkt_dev->vlan_cfi = value;
1760 			sprintf(pg_result, "OK: vlan_cfi=%u", pkt_dev->vlan_cfi);
1761 		} else {
1762 			sprintf(pg_result, "ERROR: vlan_cfi must be 0-1");
1763 		}
1764 		return count;
1765 	}
1766 
1767 	if (!strcmp(name, "svlan_id")) {
1768 		max = min(4, count - i);
1769 		len = num_arg(&user_buffer[i], max, &value);
1770 		if (len < 0)
1771 			return len;
1772 
1773 		if ((value <= 4095) && ((pkt_dev->vlan_id != 0xffff))) {
1774 			pkt_dev->svlan_id = value;  /* turn on SVLAN */
1775 
1776 			if (debug)
1777 				pr_debug("SVLAN turned on\n");
1778 
1779 			if (debug && pkt_dev->nr_labels)
1780 				pr_debug("MPLS auto turned off\n");
1781 
1782 			pkt_dev->nr_labels = 0;    /* turn off MPLS */
1783 			sprintf(pg_result, "OK: svlan_id=%u", pkt_dev->svlan_id);
1784 		} else {
1785 			pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
1786 			pkt_dev->svlan_id = 0xffff;
1787 
1788 			if (debug)
1789 				pr_debug("VLAN/SVLAN turned off\n");
1790 		}
1791 		return count;
1792 	}
1793 
1794 	if (!strcmp(name, "svlan_p")) {
1795 		max = min(1, count - i);
1796 		len = num_arg(&user_buffer[i], max, &value);
1797 		if (len < 0)
1798 			return len;
1799 
1800 		if ((value <= 7) && (pkt_dev->svlan_id != 0xffff)) {
1801 			pkt_dev->svlan_p = value;
1802 			sprintf(pg_result, "OK: svlan_p=%u", pkt_dev->svlan_p);
1803 		} else {
1804 			sprintf(pg_result, "ERROR: svlan_p must be 0-7");
1805 		}
1806 		return count;
1807 	}
1808 
1809 	if (!strcmp(name, "svlan_cfi")) {
1810 		max = min(1, count - i);
1811 		len = num_arg(&user_buffer[i], max, &value);
1812 		if (len < 0)
1813 			return len;
1814 
1815 		if ((value <= 1) && (pkt_dev->svlan_id != 0xffff)) {
1816 			pkt_dev->svlan_cfi = value;
1817 			sprintf(pg_result, "OK: svlan_cfi=%u", pkt_dev->svlan_cfi);
1818 		} else {
1819 			sprintf(pg_result, "ERROR: svlan_cfi must be 0-1");
1820 		}
1821 		return count;
1822 	}
1823 
1824 	if (!strcmp(name, "tos")) {
1825 		__u32 tmp_value;
1826 
1827 		max = min(2, count - i);
1828 		len = hex32_arg(&user_buffer[i], max, &tmp_value);
1829 		if (len < 0)
1830 			return len;
1831 
1832 		if (len == 2) {
1833 			pkt_dev->tos = tmp_value;
1834 			sprintf(pg_result, "OK: tos=0x%02x", pkt_dev->tos);
1835 		} else {
1836 			sprintf(pg_result, "ERROR: tos must be 00-ff");
1837 		}
1838 		return count;
1839 	}
1840 
1841 	if (!strcmp(name, "traffic_class")) {
1842 		__u32 tmp_value;
1843 
1844 		max = min(2, count - i);
1845 		len = hex32_arg(&user_buffer[i], max, &tmp_value);
1846 		if (len < 0)
1847 			return len;
1848 
1849 		if (len == 2) {
1850 			pkt_dev->traffic_class = tmp_value;
1851 			sprintf(pg_result, "OK: traffic_class=0x%02x", pkt_dev->traffic_class);
1852 		} else {
1853 			sprintf(pg_result, "ERROR: traffic_class must be 00-ff");
1854 		}
1855 		return count;
1856 	}
1857 
1858 	if (!strcmp(name, "skb_priority")) {
1859 		max = min(9, count - i);
1860 		len = num_arg(&user_buffer[i], max, &value);
1861 		if (len < 0)
1862 			return len;
1863 
1864 		pkt_dev->skb_priority = value;
1865 		sprintf(pg_result, "OK: skb_priority=%i",
1866 			pkt_dev->skb_priority);
1867 		return count;
1868 	}
1869 
1870 	sprintf(pkt_dev->result, "No such parameter \"%s\"", name);
1871 	return -EINVAL;
1872 }
1873 
1874 static int pktgen_if_open(struct inode *inode, struct file *file)
1875 {
1876 	return single_open(file, pktgen_if_show, pde_data(inode));
1877 }
1878 
1879 static const struct proc_ops pktgen_if_proc_ops = {
1880 	.proc_open	= pktgen_if_open,
1881 	.proc_read	= seq_read,
1882 	.proc_lseek	= seq_lseek,
1883 	.proc_write	= pktgen_if_write,
1884 	.proc_release	= single_release,
1885 };
1886 
1887 static int pktgen_thread_show(struct seq_file *seq, void *v)
1888 {
1889 	struct pktgen_thread *t = seq->private;
1890 	const struct pktgen_dev *pkt_dev;
1891 
1892 	BUG_ON(!t);
1893 
1894 	seq_puts(seq, "Running: ");
1895 
1896 	rcu_read_lock();
1897 	list_for_each_entry_rcu(pkt_dev, &t->if_list, list)
1898 		if (pkt_dev->running)
1899 			seq_printf(seq, "%s ", pkt_dev->odevname);
1900 
1901 	seq_puts(seq, "\nStopped: ");
1902 
1903 	list_for_each_entry_rcu(pkt_dev, &t->if_list, list)
1904 		if (!pkt_dev->running)
1905 			seq_printf(seq, "%s ", pkt_dev->odevname);
1906 
1907 	if (t->result[0])
1908 		seq_printf(seq, "\nResult: %s\n", t->result);
1909 	else
1910 		seq_puts(seq, "\nResult: NA\n");
1911 
1912 	rcu_read_unlock();
1913 
1914 	return 0;
1915 }
1916 
1917 static ssize_t pktgen_thread_write(struct file *file,
1918 				   const char __user *user_buffer,
1919 				   size_t count, loff_t *offset)
1920 {
1921 	struct seq_file *seq = file->private_data;
1922 	struct pktgen_thread *t = seq->private;
1923 	size_t i, max;
1924 	ssize_t len, ret;
1925 	char name[40];
1926 	char *pg_result;
1927 
1928 	if (count < 1) {
1929 		//      sprintf(pg_result, "Wrong command format");
1930 		return -EINVAL;
1931 	}
1932 
1933 	max = count;
1934 	len = count_trail_chars(user_buffer, max);
1935 	if (len < 0)
1936 		return len;
1937 
1938 	i = len;
1939 
1940 	/* Read variable name */
1941 	max = min(sizeof(name) - 1, count - i);
1942 	len = strn_len(&user_buffer[i], max);
1943 	if (len < 0)
1944 		return len;
1945 
1946 	memset(name, 0, sizeof(name));
1947 	if (copy_from_user(name, &user_buffer[i], len))
1948 		return -EFAULT;
1949 	i += len;
1950 
1951 	max = count - i;
1952 	len = count_trail_chars(&user_buffer[i], max);
1953 	if (len < 0)
1954 		return len;
1955 
1956 	i += len;
1957 
1958 	if (debug)
1959 		pr_debug("t=%s, count=%lu\n", name, (unsigned long)count);
1960 
1961 	if (!t) {
1962 		pr_err("ERROR: No thread\n");
1963 		ret = -EINVAL;
1964 		goto out;
1965 	}
1966 
1967 	pg_result = &(t->result[0]);
1968 
1969 	if (!strcmp(name, "add_device")) {
1970 		char f[32];
1971 
1972 		memset(f, 0, 32);
1973 		max = min(sizeof(f) - 1, count - i);
1974 		len = strn_len(&user_buffer[i], max);
1975 		if (len < 0) {
1976 			ret = len;
1977 			goto out;
1978 		}
1979 		if (copy_from_user(f, &user_buffer[i], len))
1980 			return -EFAULT;
1981 
1982 		mutex_lock(&pktgen_thread_lock);
1983 		ret = pktgen_add_device(t, f);
1984 		mutex_unlock(&pktgen_thread_lock);
1985 		if (!ret) {
1986 			ret = count;
1987 			sprintf(pg_result, "OK: add_device=%s", f);
1988 		} else
1989 			sprintf(pg_result, "ERROR: can not add device %s", f);
1990 		goto out;
1991 	}
1992 
1993 	if (!strcmp(name, "rem_device_all")) {
1994 		mutex_lock(&pktgen_thread_lock);
1995 		t->control |= T_REMDEVALL;
1996 		mutex_unlock(&pktgen_thread_lock);
1997 		schedule_timeout_interruptible(msecs_to_jiffies(125));	/* Propagate thread->control  */
1998 		ret = count;
1999 		sprintf(pg_result, "OK: rem_device_all");
2000 		goto out;
2001 	}
2002 
2003 	if (!strcmp(name, "max_before_softirq")) {
2004 		sprintf(pg_result, "OK: Note! max_before_softirq is obsoleted -- Do not use");
2005 		ret = count;
2006 		goto out;
2007 	}
2008 
2009 	ret = -EINVAL;
2010 out:
2011 	return ret;
2012 }
2013 
2014 static int pktgen_thread_open(struct inode *inode, struct file *file)
2015 {
2016 	return single_open(file, pktgen_thread_show, pde_data(inode));
2017 }
2018 
2019 static const struct proc_ops pktgen_thread_proc_ops = {
2020 	.proc_open	= pktgen_thread_open,
2021 	.proc_read	= seq_read,
2022 	.proc_lseek	= seq_lseek,
2023 	.proc_write	= pktgen_thread_write,
2024 	.proc_release	= single_release,
2025 };
2026 
2027 /* Think find or remove for NN */
2028 static struct pktgen_dev *__pktgen_NN_threads(const struct pktgen_net *pn,
2029 					      const char *ifname, int remove)
2030 {
2031 	struct pktgen_thread *t;
2032 	struct pktgen_dev *pkt_dev = NULL;
2033 	bool exact = (remove == FIND);
2034 
2035 	list_for_each_entry(t, &pn->pktgen_threads, th_list) {
2036 		pkt_dev = pktgen_find_dev(t, ifname, exact);
2037 		if (pkt_dev) {
2038 			if (remove) {
2039 				pkt_dev->removal_mark = 1;
2040 				t->control |= T_REMDEV;
2041 			}
2042 			break;
2043 		}
2044 	}
2045 	return pkt_dev;
2046 }
2047 
2048 /*
2049  * mark a device for removal
2050  */
2051 static void pktgen_mark_device(const struct pktgen_net *pn, const char *ifname)
2052 {
2053 	struct pktgen_dev *pkt_dev = NULL;
2054 	const int max_tries = 10, msec_per_try = 125;
2055 	int i = 0;
2056 
2057 	mutex_lock(&pktgen_thread_lock);
2058 	pr_debug("%s: marking %s for removal\n", __func__, ifname);
2059 
2060 	while (1) {
2061 
2062 		pkt_dev = __pktgen_NN_threads(pn, ifname, REMOVE);
2063 		if (pkt_dev == NULL)
2064 			break;	/* success */
2065 
2066 		mutex_unlock(&pktgen_thread_lock);
2067 		pr_debug("%s: waiting for %s to disappear....\n",
2068 			 __func__, ifname);
2069 		schedule_timeout_interruptible(msecs_to_jiffies(msec_per_try));
2070 		mutex_lock(&pktgen_thread_lock);
2071 
2072 		if (++i >= max_tries) {
2073 			pr_err("%s: timed out after waiting %d msec for device %s to be removed\n",
2074 			       __func__, msec_per_try * i, ifname);
2075 			break;
2076 		}
2077 
2078 	}
2079 
2080 	mutex_unlock(&pktgen_thread_lock);
2081 }
2082 
2083 static void pktgen_change_name(const struct pktgen_net *pn, struct net_device *dev)
2084 {
2085 	struct pktgen_thread *t;
2086 
2087 	mutex_lock(&pktgen_thread_lock);
2088 
2089 	list_for_each_entry(t, &pn->pktgen_threads, th_list) {
2090 		struct pktgen_dev *pkt_dev;
2091 
2092 		if_lock(t);
2093 		list_for_each_entry(pkt_dev, &t->if_list, list) {
2094 			if (pkt_dev->odev != dev)
2095 				continue;
2096 
2097 			proc_remove(pkt_dev->entry);
2098 
2099 			pkt_dev->entry = proc_create_data(dev->name, 0600,
2100 							  pn->proc_dir,
2101 							  &pktgen_if_proc_ops,
2102 							  pkt_dev);
2103 			if (!pkt_dev->entry)
2104 				pr_err("can't move proc entry for '%s'\n",
2105 				       dev->name);
2106 			break;
2107 		}
2108 		if_unlock(t);
2109 	}
2110 	mutex_unlock(&pktgen_thread_lock);
2111 }
2112 
2113 static int pktgen_device_event(struct notifier_block *unused,
2114 			       unsigned long event, void *ptr)
2115 {
2116 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
2117 	struct pktgen_net *pn = net_generic(dev_net(dev), pg_net_id);
2118 
2119 	if (pn->pktgen_exiting)
2120 		return NOTIFY_DONE;
2121 
2122 	/* It is OK that we do not hold the group lock right now,
2123 	 * as we run under the RTNL lock.
2124 	 */
2125 
2126 	switch (event) {
2127 	case NETDEV_CHANGENAME:
2128 		pktgen_change_name(pn, dev);
2129 		break;
2130 
2131 	case NETDEV_UNREGISTER:
2132 		pktgen_mark_device(pn, dev->name);
2133 		break;
2134 	}
2135 
2136 	return NOTIFY_DONE;
2137 }
2138 
2139 static struct net_device *pktgen_dev_get_by_name(const struct pktgen_net *pn,
2140 						 struct pktgen_dev *pkt_dev,
2141 						 const char *ifname)
2142 {
2143 	char b[IFNAMSIZ+5];
2144 	int i;
2145 
2146 	for (i = 0; ifname[i] != '@'; i++) {
2147 		if (i == IFNAMSIZ)
2148 			break;
2149 
2150 		b[i] = ifname[i];
2151 	}
2152 	b[i] = 0;
2153 
2154 	return dev_get_by_name(pn->net, b);
2155 }
2156 
2157 
2158 /* Associate pktgen_dev with a device. */
2159 
2160 static int pktgen_setup_dev(const struct pktgen_net *pn,
2161 			    struct pktgen_dev *pkt_dev, const char *ifname)
2162 {
2163 	struct net_device *odev;
2164 	int err;
2165 
2166 	/* Clean old setups */
2167 	if (pkt_dev->odev) {
2168 		netdev_put(pkt_dev->odev, &pkt_dev->dev_tracker);
2169 		pkt_dev->odev = NULL;
2170 	}
2171 
2172 	odev = pktgen_dev_get_by_name(pn, pkt_dev, ifname);
2173 	if (!odev) {
2174 		pr_err("no such netdevice: \"%s\"\n", ifname);
2175 		return -ENODEV;
2176 	}
2177 
2178 	if (odev->type != ARPHRD_ETHER && odev->type != ARPHRD_LOOPBACK) {
2179 		pr_err("not an ethernet or loopback device: \"%s\"\n", ifname);
2180 		err = -EINVAL;
2181 	} else if (!netif_running(odev)) {
2182 		pr_err("device is down: \"%s\"\n", ifname);
2183 		err = -ENETDOWN;
2184 	} else {
2185 		pkt_dev->odev = odev;
2186 		netdev_tracker_alloc(odev, &pkt_dev->dev_tracker, GFP_KERNEL);
2187 		return 0;
2188 	}
2189 
2190 	dev_put(odev);
2191 	return err;
2192 }
2193 
2194 /* Read pkt_dev from the interface and set up internal pktgen_dev
2195  * structure to have the right information to create/send packets
2196  */
2197 static void pktgen_setup_inject(struct pktgen_dev *pkt_dev)
2198 {
2199 	int ntxq;
2200 
2201 	if (!pkt_dev->odev) {
2202 		pr_err("ERROR: pkt_dev->odev == NULL in setup_inject\n");
2203 		sprintf(pkt_dev->result,
2204 			"ERROR: pkt_dev->odev == NULL in setup_inject.\n");
2205 		return;
2206 	}
2207 
2208 	/* make sure that we don't pick a non-existing transmit queue */
2209 	ntxq = pkt_dev->odev->real_num_tx_queues;
2210 
2211 	if (ntxq <= pkt_dev->queue_map_min) {
2212 		pr_warn("WARNING: Requested queue_map_min (zero-based) (%d) exceeds valid range [0 - %d] for (%d) queues on %s, resetting\n",
2213 			pkt_dev->queue_map_min, (ntxq ?: 1) - 1, ntxq,
2214 			pkt_dev->odevname);
2215 		pkt_dev->queue_map_min = (ntxq ?: 1) - 1;
2216 	}
2217 	if (pkt_dev->queue_map_max >= ntxq) {
2218 		pr_warn("WARNING: Requested queue_map_max (zero-based) (%d) exceeds valid range [0 - %d] for (%d) queues on %s, resetting\n",
2219 			pkt_dev->queue_map_max, (ntxq ?: 1) - 1, ntxq,
2220 			pkt_dev->odevname);
2221 		pkt_dev->queue_map_max = (ntxq ?: 1) - 1;
2222 	}
2223 
2224 	/* Default to the interface's mac if not explicitly set. */
2225 
2226 	if (is_zero_ether_addr(pkt_dev->src_mac))
2227 		ether_addr_copy(&(pkt_dev->hh[6]), pkt_dev->odev->dev_addr);
2228 
2229 	/* Set up Dest MAC */
2230 	ether_addr_copy(&(pkt_dev->hh[0]), pkt_dev->dst_mac);
2231 
2232 	if (pkt_dev->flags & F_IPV6) {
2233 		int i, set = 0, err = 1;
2234 		struct inet6_dev *idev;
2235 
2236 		if (pkt_dev->min_pkt_size == 0) {
2237 			pkt_dev->min_pkt_size = 14 + sizeof(struct ipv6hdr)
2238 						+ sizeof(struct udphdr)
2239 						+ sizeof(struct pktgen_hdr)
2240 						+ pkt_dev->pkt_overhead;
2241 		}
2242 
2243 		for (i = 0; i < sizeof(struct in6_addr); i++)
2244 			if (pkt_dev->cur_in6_saddr.s6_addr[i]) {
2245 				set = 1;
2246 				break;
2247 			}
2248 
2249 		if (!set) {
2250 
2251 			/*
2252 			 * Use linklevel address if unconfigured.
2253 			 *
2254 			 * use ipv6_get_lladdr if/when it's get exported
2255 			 */
2256 
2257 			rcu_read_lock();
2258 			idev = __in6_dev_get(pkt_dev->odev);
2259 			if (idev) {
2260 				struct inet6_ifaddr *ifp;
2261 
2262 				read_lock_bh(&idev->lock);
2263 				list_for_each_entry(ifp, &idev->addr_list, if_list) {
2264 					if ((ifp->scope & IFA_LINK) &&
2265 					    !(ifp->flags & IFA_F_TENTATIVE)) {
2266 						pkt_dev->cur_in6_saddr = ifp->addr;
2267 						err = 0;
2268 						break;
2269 					}
2270 				}
2271 				read_unlock_bh(&idev->lock);
2272 			}
2273 			rcu_read_unlock();
2274 			if (err)
2275 				pr_err("ERROR: IPv6 link address not available\n");
2276 		}
2277 	} else {
2278 		if (pkt_dev->min_pkt_size == 0) {
2279 			pkt_dev->min_pkt_size = 14 + sizeof(struct iphdr)
2280 						+ sizeof(struct udphdr)
2281 						+ sizeof(struct pktgen_hdr)
2282 						+ pkt_dev->pkt_overhead;
2283 		}
2284 
2285 		pkt_dev->saddr_min = 0;
2286 		pkt_dev->saddr_max = 0;
2287 		if (strlen(pkt_dev->src_min) == 0) {
2288 
2289 			struct in_device *in_dev;
2290 
2291 			rcu_read_lock();
2292 			in_dev = __in_dev_get_rcu(pkt_dev->odev);
2293 			if (in_dev) {
2294 				const struct in_ifaddr *ifa;
2295 
2296 				ifa = rcu_dereference(in_dev->ifa_list);
2297 				if (ifa) {
2298 					pkt_dev->saddr_min = ifa->ifa_address;
2299 					pkt_dev->saddr_max = pkt_dev->saddr_min;
2300 				}
2301 			}
2302 			rcu_read_unlock();
2303 		} else {
2304 			pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
2305 			pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
2306 		}
2307 
2308 		pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
2309 		pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
2310 	}
2311 	/* Initialize current values. */
2312 	pkt_dev->cur_pkt_size = pkt_dev->min_pkt_size;
2313 	if (pkt_dev->min_pkt_size > pkt_dev->max_pkt_size)
2314 		pkt_dev->max_pkt_size = pkt_dev->min_pkt_size;
2315 
2316 	pkt_dev->cur_dst_mac_offset = 0;
2317 	pkt_dev->cur_src_mac_offset = 0;
2318 	pkt_dev->cur_saddr = pkt_dev->saddr_min;
2319 	pkt_dev->cur_daddr = pkt_dev->daddr_min;
2320 	pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
2321 	pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
2322 	pkt_dev->nflows = 0;
2323 }
2324 
2325 
2326 static void spin(struct pktgen_dev *pkt_dev, ktime_t spin_until)
2327 {
2328 	ktime_t start_time, end_time;
2329 	s64 remaining;
2330 	struct hrtimer_sleeper t;
2331 
2332 	hrtimer_setup_sleeper_on_stack(&t, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
2333 	hrtimer_set_expires(&t.timer, spin_until);
2334 
2335 	remaining = ktime_to_ns(hrtimer_expires_remaining(&t.timer));
2336 	if (remaining <= 0)
2337 		goto out;
2338 
2339 	start_time = ktime_get();
2340 	if (remaining < 100000) {
2341 		/* for small delays (<100us), just loop until limit is reached */
2342 		do {
2343 			end_time = ktime_get();
2344 		} while (ktime_compare(end_time, spin_until) < 0);
2345 	} else {
2346 		do {
2347 			set_current_state(TASK_INTERRUPTIBLE);
2348 			hrtimer_sleeper_start_expires(&t, HRTIMER_MODE_ABS);
2349 
2350 			if (likely(t.task))
2351 				schedule();
2352 
2353 			hrtimer_cancel(&t.timer);
2354 		} while (t.task && pkt_dev->running && !signal_pending(current));
2355 		__set_current_state(TASK_RUNNING);
2356 		end_time = ktime_get();
2357 	}
2358 
2359 	pkt_dev->idle_acc += ktime_to_ns(ktime_sub(end_time, start_time));
2360 out:
2361 	pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
2362 	destroy_hrtimer_on_stack(&t.timer);
2363 }
2364 
2365 static inline void set_pkt_overhead(struct pktgen_dev *pkt_dev)
2366 {
2367 	pkt_dev->pkt_overhead = 0;
2368 	pkt_dev->pkt_overhead += pkt_dev->nr_labels*sizeof(u32);
2369 	pkt_dev->pkt_overhead += VLAN_TAG_SIZE(pkt_dev);
2370 	pkt_dev->pkt_overhead += SVLAN_TAG_SIZE(pkt_dev);
2371 }
2372 
2373 static inline int f_seen(const struct pktgen_dev *pkt_dev, int flow)
2374 {
2375 	return !!(pkt_dev->flows[flow].flags & F_INIT);
2376 }
2377 
2378 static inline int f_pick(struct pktgen_dev *pkt_dev)
2379 {
2380 	int flow = pkt_dev->curfl;
2381 
2382 	if (pkt_dev->flags & F_FLOW_SEQ) {
2383 		if (pkt_dev->flows[flow].count >= pkt_dev->lflow) {
2384 			/* reset time */
2385 			pkt_dev->flows[flow].count = 0;
2386 			pkt_dev->flows[flow].flags = 0;
2387 			pkt_dev->curfl += 1;
2388 			if (pkt_dev->curfl >= pkt_dev->cflows)
2389 				pkt_dev->curfl = 0; /*reset */
2390 		}
2391 	} else {
2392 		flow = get_random_u32_below(pkt_dev->cflows);
2393 		pkt_dev->curfl = flow;
2394 
2395 		if (pkt_dev->flows[flow].count > pkt_dev->lflow) {
2396 			pkt_dev->flows[flow].count = 0;
2397 			pkt_dev->flows[flow].flags = 0;
2398 		}
2399 	}
2400 
2401 	return pkt_dev->curfl;
2402 }
2403 
2404 
2405 /* If there was already an IPSEC SA, we keep it as is, else
2406  * we go look for it ...
2407  */
2408 #define DUMMY_MARK 0
2409 static void get_ipsec_sa(struct pktgen_dev *pkt_dev, int flow)
2410 {
2411 #ifdef CONFIG_XFRM
2412 	struct xfrm_state *x = pkt_dev->flows[flow].x;
2413 	struct pktgen_net *pn = net_generic(dev_net(pkt_dev->odev), pg_net_id);
2414 
2415 	if (!x) {
2416 
2417 		if (pkt_dev->spi) {
2418 			/* We need as quick as possible to find the right SA
2419 			 * Searching with minimum criteria to achieve, this.
2420 			 */
2421 			x = xfrm_state_lookup_byspi(pn->net, htonl(pkt_dev->spi), AF_INET);
2422 		} else {
2423 			/* slow path: we don't already have xfrm_state */
2424 			x = xfrm_stateonly_find(pn->net, DUMMY_MARK, 0,
2425 						(xfrm_address_t *)&pkt_dev->cur_daddr,
2426 						(xfrm_address_t *)&pkt_dev->cur_saddr,
2427 						AF_INET,
2428 						pkt_dev->ipsmode,
2429 						pkt_dev->ipsproto, 0);
2430 		}
2431 		if (x) {
2432 			pkt_dev->flows[flow].x = x;
2433 			set_pkt_overhead(pkt_dev);
2434 			pkt_dev->pkt_overhead += x->props.header_len;
2435 		}
2436 
2437 	}
2438 #endif
2439 }
2440 static void set_cur_queue_map(struct pktgen_dev *pkt_dev)
2441 {
2442 	if (pkt_dev->flags & F_QUEUE_MAP_CPU)
2443 		pkt_dev->cur_queue_map = smp_processor_id();
2444 
2445 	else if (pkt_dev->queue_map_min <= pkt_dev->queue_map_max) {
2446 		__u16 t;
2447 
2448 		if (pkt_dev->flags & F_QUEUE_MAP_RND) {
2449 			t = get_random_u32_inclusive(pkt_dev->queue_map_min,
2450 						     pkt_dev->queue_map_max);
2451 		} else {
2452 			t = pkt_dev->cur_queue_map + 1;
2453 			if (t > pkt_dev->queue_map_max)
2454 				t = pkt_dev->queue_map_min;
2455 		}
2456 		pkt_dev->cur_queue_map = t;
2457 	}
2458 	pkt_dev->cur_queue_map  = pkt_dev->cur_queue_map % pkt_dev->odev->real_num_tx_queues;
2459 }
2460 
2461 /* Increment/randomize headers according to flags and current values
2462  * for IP src/dest, UDP src/dst port, MAC-Addr src/dst
2463  */
2464 static void mod_cur_headers(struct pktgen_dev *pkt_dev)
2465 {
2466 	__u32 imn;
2467 	__u32 imx;
2468 	int flow = 0;
2469 
2470 	if (pkt_dev->cflows)
2471 		flow = f_pick(pkt_dev);
2472 
2473 	/*  Deal with source MAC */
2474 	if (pkt_dev->src_mac_count > 1) {
2475 		__u32 mc;
2476 		__u32 tmp;
2477 
2478 		if (pkt_dev->flags & F_MACSRC_RND)
2479 			mc = get_random_u32_below(pkt_dev->src_mac_count);
2480 		else {
2481 			mc = pkt_dev->cur_src_mac_offset++;
2482 			if (pkt_dev->cur_src_mac_offset >=
2483 			    pkt_dev->src_mac_count)
2484 				pkt_dev->cur_src_mac_offset = 0;
2485 		}
2486 
2487 		tmp = pkt_dev->src_mac[5] + (mc & 0xFF);
2488 		pkt_dev->hh[11] = tmp;
2489 		tmp = (pkt_dev->src_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
2490 		pkt_dev->hh[10] = tmp;
2491 		tmp = (pkt_dev->src_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
2492 		pkt_dev->hh[9] = tmp;
2493 		tmp = (pkt_dev->src_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
2494 		pkt_dev->hh[8] = tmp;
2495 		tmp = (pkt_dev->src_mac[1] + (tmp >> 8));
2496 		pkt_dev->hh[7] = tmp;
2497 	}
2498 
2499 	/*  Deal with Destination MAC */
2500 	if (pkt_dev->dst_mac_count > 1) {
2501 		__u32 mc;
2502 		__u32 tmp;
2503 
2504 		if (pkt_dev->flags & F_MACDST_RND)
2505 			mc = get_random_u32_below(pkt_dev->dst_mac_count);
2506 
2507 		else {
2508 			mc = pkt_dev->cur_dst_mac_offset++;
2509 			if (pkt_dev->cur_dst_mac_offset >=
2510 			    pkt_dev->dst_mac_count) {
2511 				pkt_dev->cur_dst_mac_offset = 0;
2512 			}
2513 		}
2514 
2515 		tmp = pkt_dev->dst_mac[5] + (mc & 0xFF);
2516 		pkt_dev->hh[5] = tmp;
2517 		tmp = (pkt_dev->dst_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
2518 		pkt_dev->hh[4] = tmp;
2519 		tmp = (pkt_dev->dst_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
2520 		pkt_dev->hh[3] = tmp;
2521 		tmp = (pkt_dev->dst_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
2522 		pkt_dev->hh[2] = tmp;
2523 		tmp = (pkt_dev->dst_mac[1] + (tmp >> 8));
2524 		pkt_dev->hh[1] = tmp;
2525 	}
2526 
2527 	if (pkt_dev->flags & F_MPLS_RND) {
2528 		unsigned int i;
2529 
2530 		for (i = 0; i < pkt_dev->nr_labels; i++)
2531 			if (pkt_dev->labels[i] & MPLS_STACK_BOTTOM)
2532 				pkt_dev->labels[i] = MPLS_STACK_BOTTOM |
2533 					     ((__force __be32)get_random_u32() &
2534 						      htonl(0x000fffff));
2535 	}
2536 
2537 	if ((pkt_dev->flags & F_VID_RND) && (pkt_dev->vlan_id != 0xffff)) {
2538 		pkt_dev->vlan_id = get_random_u32_below(4096);
2539 	}
2540 
2541 	if ((pkt_dev->flags & F_SVID_RND) && (pkt_dev->svlan_id != 0xffff)) {
2542 		pkt_dev->svlan_id = get_random_u32_below(4096);
2543 	}
2544 
2545 	if (pkt_dev->udp_src_min < pkt_dev->udp_src_max) {
2546 		if (pkt_dev->flags & F_UDPSRC_RND)
2547 			pkt_dev->cur_udp_src = get_random_u32_inclusive(pkt_dev->udp_src_min,
2548 									pkt_dev->udp_src_max - 1);
2549 
2550 		else {
2551 			pkt_dev->cur_udp_src++;
2552 			if (pkt_dev->cur_udp_src >= pkt_dev->udp_src_max)
2553 				pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
2554 		}
2555 	}
2556 
2557 	if (pkt_dev->udp_dst_min < pkt_dev->udp_dst_max) {
2558 		if (pkt_dev->flags & F_UDPDST_RND) {
2559 			pkt_dev->cur_udp_dst = get_random_u32_inclusive(pkt_dev->udp_dst_min,
2560 									pkt_dev->udp_dst_max - 1);
2561 		} else {
2562 			pkt_dev->cur_udp_dst++;
2563 			if (pkt_dev->cur_udp_dst >= pkt_dev->udp_dst_max)
2564 				pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
2565 		}
2566 	}
2567 
2568 	if (!(pkt_dev->flags & F_IPV6)) {
2569 
2570 		imn = ntohl(pkt_dev->saddr_min);
2571 		imx = ntohl(pkt_dev->saddr_max);
2572 		if (imn < imx) {
2573 			__u32 t;
2574 
2575 			if (pkt_dev->flags & F_IPSRC_RND)
2576 				t = get_random_u32_inclusive(imn, imx - 1);
2577 			else {
2578 				t = ntohl(pkt_dev->cur_saddr);
2579 				t++;
2580 				if (t > imx)
2581 					t = imn;
2582 
2583 			}
2584 			pkt_dev->cur_saddr = htonl(t);
2585 		}
2586 
2587 		if (pkt_dev->cflows && f_seen(pkt_dev, flow)) {
2588 			pkt_dev->cur_daddr = pkt_dev->flows[flow].cur_daddr;
2589 		} else {
2590 			imn = ntohl(pkt_dev->daddr_min);
2591 			imx = ntohl(pkt_dev->daddr_max);
2592 			if (imn < imx) {
2593 				__u32 t;
2594 				__be32 s;
2595 
2596 				if (pkt_dev->flags & F_IPDST_RND) {
2597 
2598 					do {
2599 						t = get_random_u32_inclusive(imn, imx - 1);
2600 						s = htonl(t);
2601 					} while (ipv4_is_loopback(s) ||
2602 						ipv4_is_multicast(s) ||
2603 						ipv4_is_lbcast(s) ||
2604 						ipv4_is_zeronet(s) ||
2605 						ipv4_is_local_multicast(s));
2606 					pkt_dev->cur_daddr = s;
2607 				} else {
2608 					t = ntohl(pkt_dev->cur_daddr);
2609 					t++;
2610 					if (t > imx) {
2611 						t = imn;
2612 					}
2613 					pkt_dev->cur_daddr = htonl(t);
2614 				}
2615 			}
2616 			if (pkt_dev->cflows) {
2617 				pkt_dev->flows[flow].flags |= F_INIT;
2618 				pkt_dev->flows[flow].cur_daddr =
2619 				    pkt_dev->cur_daddr;
2620 				if (pkt_dev->flags & F_IPSEC)
2621 					get_ipsec_sa(pkt_dev, flow);
2622 				pkt_dev->nflows++;
2623 			}
2624 		}
2625 	} else {		/* IPV6 * */
2626 
2627 		if (!ipv6_addr_any(&pkt_dev->min_in6_daddr)) {
2628 			int i;
2629 
2630 			/* Only random destinations yet */
2631 
2632 			for (i = 0; i < 4; i++) {
2633 				pkt_dev->cur_in6_daddr.s6_addr32[i] =
2634 				    (((__force __be32)get_random_u32() |
2635 				      pkt_dev->min_in6_daddr.s6_addr32[i]) &
2636 				     pkt_dev->max_in6_daddr.s6_addr32[i]);
2637 			}
2638 		}
2639 	}
2640 
2641 	if (pkt_dev->min_pkt_size < pkt_dev->max_pkt_size) {
2642 		__u32 t;
2643 
2644 		if (pkt_dev->flags & F_TXSIZE_RND) {
2645 			t = get_random_u32_inclusive(pkt_dev->min_pkt_size,
2646 						     pkt_dev->max_pkt_size - 1);
2647 		} else {
2648 			t = pkt_dev->cur_pkt_size + 1;
2649 			if (t > pkt_dev->max_pkt_size)
2650 				t = pkt_dev->min_pkt_size;
2651 		}
2652 		pkt_dev->cur_pkt_size = t;
2653 	} else if (pkt_dev->n_imix_entries > 0) {
2654 		struct imix_pkt *entry;
2655 		__u32 t = get_random_u32_below(IMIX_PRECISION);
2656 		__u8 entry_index = pkt_dev->imix_distribution[t];
2657 
2658 		entry = &pkt_dev->imix_entries[entry_index];
2659 		entry->count_so_far++;
2660 		pkt_dev->cur_pkt_size = entry->size;
2661 	}
2662 
2663 	set_cur_queue_map(pkt_dev);
2664 
2665 	pkt_dev->flows[flow].count++;
2666 }
2667 
2668 static void fill_imix_distribution(struct pktgen_dev *pkt_dev)
2669 {
2670 	int cumulative_probabilites[MAX_IMIX_ENTRIES];
2671 	int j = 0;
2672 	__u64 cumulative_prob = 0;
2673 	__u64 total_weight = 0;
2674 	int i = 0;
2675 
2676 	for (i = 0; i < pkt_dev->n_imix_entries; i++)
2677 		total_weight += pkt_dev->imix_entries[i].weight;
2678 
2679 	/* Fill cumulative_probabilites with sum of normalized probabilities */
2680 	for (i = 0; i < pkt_dev->n_imix_entries - 1; i++) {
2681 		cumulative_prob += div64_u64(pkt_dev->imix_entries[i].weight *
2682 						     IMIX_PRECISION,
2683 					     total_weight);
2684 		cumulative_probabilites[i] = cumulative_prob;
2685 	}
2686 	cumulative_probabilites[pkt_dev->n_imix_entries - 1] = 100;
2687 
2688 	for (i = 0; i < IMIX_PRECISION; i++) {
2689 		if (i == cumulative_probabilites[j])
2690 			j++;
2691 		pkt_dev->imix_distribution[i] = j;
2692 	}
2693 }
2694 
2695 #ifdef CONFIG_XFRM
2696 static u32 pktgen_dst_metrics[RTAX_MAX + 1] = {
2697 
2698 	[RTAX_HOPLIMIT] = 0x5, /* Set a static hoplimit */
2699 };
2700 
2701 static int pktgen_output_ipsec(struct sk_buff *skb, struct pktgen_dev *pkt_dev)
2702 {
2703 	struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
2704 	int err = 0;
2705 	struct net *net = dev_net(pkt_dev->odev);
2706 
2707 	if (!x)
2708 		return 0;
2709 	/* XXX: we dont support tunnel mode for now until
2710 	 * we resolve the dst issue
2711 	 */
2712 	if ((x->props.mode != XFRM_MODE_TRANSPORT) && (pkt_dev->spi == 0))
2713 		return 0;
2714 
2715 	/* But when user specify an valid SPI, transformation
2716 	 * supports both transport/tunnel mode + ESP/AH type.
2717 	 */
2718 	if ((x->props.mode == XFRM_MODE_TUNNEL) && (pkt_dev->spi != 0))
2719 		skb->_skb_refdst = (unsigned long)&pkt_dev->xdst.u.dst | SKB_DST_NOREF;
2720 
2721 	rcu_read_lock_bh();
2722 	err = pktgen_xfrm_outer_mode_output(x, skb);
2723 	rcu_read_unlock_bh();
2724 	if (err) {
2725 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTSTATEMODEERROR);
2726 		goto error;
2727 	}
2728 	err = x->type->output(x, skb);
2729 	if (err) {
2730 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTSTATEPROTOERROR);
2731 		goto error;
2732 	}
2733 	spin_lock_bh(&x->lock);
2734 	x->curlft.bytes += skb->len;
2735 	x->curlft.packets++;
2736 	spin_unlock_bh(&x->lock);
2737 error:
2738 	return err;
2739 }
2740 
2741 static void free_SAs(struct pktgen_dev *pkt_dev)
2742 {
2743 	if (pkt_dev->cflows) {
2744 		/* let go of the SAs if we have them */
2745 		int i;
2746 
2747 		for (i = 0; i < pkt_dev->cflows; i++) {
2748 			struct xfrm_state *x = pkt_dev->flows[i].x;
2749 
2750 			if (x) {
2751 				xfrm_state_put(x);
2752 				pkt_dev->flows[i].x = NULL;
2753 			}
2754 		}
2755 	}
2756 }
2757 
2758 static int process_ipsec(struct pktgen_dev *pkt_dev,
2759 			      struct sk_buff *skb, __be16 protocol)
2760 {
2761 	if (pkt_dev->flags & F_IPSEC) {
2762 		struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
2763 		int nhead = 0;
2764 
2765 		if (x) {
2766 			struct ethhdr *eth;
2767 			struct iphdr *iph;
2768 			int ret;
2769 
2770 			nhead = x->props.header_len - skb_headroom(skb);
2771 			if (nhead > 0) {
2772 				ret = pskb_expand_head(skb, nhead, 0, GFP_ATOMIC);
2773 				if (ret < 0) {
2774 					pr_err("Error expanding ipsec packet %d\n",
2775 					       ret);
2776 					goto err;
2777 				}
2778 			}
2779 
2780 			/* ipsec is not expecting ll header */
2781 			skb_pull(skb, ETH_HLEN);
2782 			ret = pktgen_output_ipsec(skb, pkt_dev);
2783 			if (ret) {
2784 				pr_err("Error creating ipsec packet %d\n", ret);
2785 				goto err;
2786 			}
2787 			/* restore ll */
2788 			eth = skb_push(skb, ETH_HLEN);
2789 			memcpy(eth, pkt_dev->hh, 2 * ETH_ALEN);
2790 			eth->h_proto = protocol;
2791 
2792 			/* Update IPv4 header len as well as checksum value */
2793 			iph = ip_hdr(skb);
2794 			iph->tot_len = htons(skb->len - ETH_HLEN);
2795 			ip_send_check(iph);
2796 		}
2797 	}
2798 	return 1;
2799 err:
2800 	kfree_skb(skb);
2801 	return 0;
2802 }
2803 #endif
2804 
2805 static void mpls_push(__be32 *mpls, struct pktgen_dev *pkt_dev)
2806 {
2807 	unsigned int i;
2808 
2809 	for (i = 0; i < pkt_dev->nr_labels; i++)
2810 		*mpls++ = pkt_dev->labels[i] & ~MPLS_STACK_BOTTOM;
2811 
2812 	mpls--;
2813 	*mpls |= MPLS_STACK_BOTTOM;
2814 }
2815 
2816 static inline __be16 build_tci(unsigned int id, unsigned int cfi,
2817 			       unsigned int prio)
2818 {
2819 	return htons(id | (cfi << 12) | (prio << 13));
2820 }
2821 
2822 static void pktgen_finalize_skb(struct pktgen_dev *pkt_dev, struct sk_buff *skb,
2823 				int datalen)
2824 {
2825 	struct timespec64 timestamp;
2826 	struct pktgen_hdr *pgh;
2827 
2828 	pgh = skb_put(skb, sizeof(*pgh));
2829 	datalen -= sizeof(*pgh);
2830 
2831 	if (pkt_dev->nfrags <= 0) {
2832 		skb_put_zero(skb, datalen);
2833 	} else {
2834 		int frags = pkt_dev->nfrags;
2835 		int i, len;
2836 		int frag_len;
2837 
2838 
2839 		if (frags > MAX_SKB_FRAGS)
2840 			frags = MAX_SKB_FRAGS;
2841 		len = datalen - frags * PAGE_SIZE;
2842 		if (len > 0) {
2843 			skb_put_zero(skb, len);
2844 			datalen = frags * PAGE_SIZE;
2845 		}
2846 
2847 		i = 0;
2848 		frag_len = (datalen/frags) < PAGE_SIZE ?
2849 			   (datalen/frags) : PAGE_SIZE;
2850 		while (datalen > 0) {
2851 			if (unlikely(!pkt_dev->page)) {
2852 				int node = numa_node_id();
2853 
2854 				if (pkt_dev->node >= 0 && (pkt_dev->flags & F_NODE))
2855 					node = pkt_dev->node;
2856 				pkt_dev->page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
2857 				if (!pkt_dev->page)
2858 					break;
2859 			}
2860 			get_page(pkt_dev->page);
2861 
2862 			/*last fragment, fill rest of data*/
2863 			if (i == (frags - 1))
2864 				skb_frag_fill_page_desc(&skb_shinfo(skb)->frags[i],
2865 							pkt_dev->page, 0,
2866 							(datalen < PAGE_SIZE ?
2867 							 datalen : PAGE_SIZE));
2868 			else
2869 				skb_frag_fill_page_desc(&skb_shinfo(skb)->frags[i],
2870 							pkt_dev->page, 0, frag_len);
2871 
2872 			datalen -= skb_frag_size(&skb_shinfo(skb)->frags[i]);
2873 			skb->len += skb_frag_size(&skb_shinfo(skb)->frags[i]);
2874 			skb->data_len += skb_frag_size(&skb_shinfo(skb)->frags[i]);
2875 			i++;
2876 			skb_shinfo(skb)->nr_frags = i;
2877 		}
2878 	}
2879 
2880 	/* Stamp the time, and sequence number,
2881 	 * convert them to network byte order
2882 	 */
2883 	pgh->pgh_magic = htonl(PKTGEN_MAGIC);
2884 	pgh->seq_num = htonl(pkt_dev->seq_num);
2885 
2886 	if (pkt_dev->flags & F_NO_TIMESTAMP) {
2887 		pgh->tv_sec = 0;
2888 		pgh->tv_usec = 0;
2889 	} else {
2890 		/*
2891 		 * pgh->tv_sec wraps in y2106 when interpreted as unsigned
2892 		 * as done by wireshark, or y2038 when interpreted as signed.
2893 		 * This is probably harmless, but if anyone wants to improve
2894 		 * it, we could introduce a variant that puts 64-bit nanoseconds
2895 		 * into the respective header bytes.
2896 		 * This would also be slightly faster to read.
2897 		 */
2898 		ktime_get_real_ts64(&timestamp);
2899 		pgh->tv_sec = htonl(timestamp.tv_sec);
2900 		pgh->tv_usec = htonl(timestamp.tv_nsec / NSEC_PER_USEC);
2901 	}
2902 }
2903 
2904 static struct sk_buff *pktgen_alloc_skb(struct net_device *dev,
2905 					struct pktgen_dev *pkt_dev)
2906 {
2907 	unsigned int extralen = LL_RESERVED_SPACE(dev);
2908 	struct sk_buff *skb = NULL;
2909 	unsigned int size;
2910 
2911 	size = pkt_dev->cur_pkt_size + 64 + extralen + pkt_dev->pkt_overhead;
2912 	if (pkt_dev->flags & F_NODE) {
2913 		int node = pkt_dev->node >= 0 ? pkt_dev->node : numa_node_id();
2914 
2915 		skb = __alloc_skb(NET_SKB_PAD + size, GFP_NOWAIT, 0, node);
2916 		if (likely(skb)) {
2917 			skb_reserve(skb, NET_SKB_PAD);
2918 			skb->dev = dev;
2919 		}
2920 	} else {
2921 		skb = __netdev_alloc_skb(dev, size, GFP_NOWAIT);
2922 	}
2923 
2924 	/* the caller pre-fetches from skb->data and reserves for the mac hdr */
2925 	if (likely(skb))
2926 		skb_reserve(skb, extralen - 16);
2927 
2928 	return skb;
2929 }
2930 
2931 static struct sk_buff *fill_packet_ipv4(struct net_device *odev,
2932 					struct pktgen_dev *pkt_dev)
2933 {
2934 	struct sk_buff *skb = NULL;
2935 	__u8 *eth;
2936 	struct udphdr *udph;
2937 	int datalen, iplen;
2938 	struct iphdr *iph;
2939 	__be16 protocol = htons(ETH_P_IP);
2940 	__be32 *mpls;
2941 	__be16 *vlan_tci = NULL;                 /* Encapsulates priority and VLAN ID */
2942 	__be16 *vlan_encapsulated_proto = NULL;  /* packet type ID field (or len) for VLAN tag */
2943 	__be16 *svlan_tci = NULL;                /* Encapsulates priority and SVLAN ID */
2944 	__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
2945 	u16 queue_map;
2946 
2947 	if (pkt_dev->nr_labels)
2948 		protocol = htons(ETH_P_MPLS_UC);
2949 
2950 	if (pkt_dev->vlan_id != 0xffff)
2951 		protocol = htons(ETH_P_8021Q);
2952 
2953 	/* Update any of the values, used when we're incrementing various
2954 	 * fields.
2955 	 */
2956 	mod_cur_headers(pkt_dev);
2957 	queue_map = pkt_dev->cur_queue_map;
2958 
2959 	skb = pktgen_alloc_skb(odev, pkt_dev);
2960 	if (!skb) {
2961 		sprintf(pkt_dev->result, "No memory");
2962 		return NULL;
2963 	}
2964 
2965 	prefetchw(skb->data);
2966 	skb_reserve(skb, 16);
2967 
2968 	/*  Reserve for ethernet and IP header  */
2969 	eth = skb_push(skb, 14);
2970 	mpls = skb_put(skb, pkt_dev->nr_labels * sizeof(__u32));
2971 	if (pkt_dev->nr_labels)
2972 		mpls_push(mpls, pkt_dev);
2973 
2974 	if (pkt_dev->vlan_id != 0xffff) {
2975 		if (pkt_dev->svlan_id != 0xffff) {
2976 			svlan_tci = skb_put(skb, sizeof(__be16));
2977 			*svlan_tci = build_tci(pkt_dev->svlan_id,
2978 					       pkt_dev->svlan_cfi,
2979 					       pkt_dev->svlan_p);
2980 			svlan_encapsulated_proto = skb_put(skb,
2981 							   sizeof(__be16));
2982 			*svlan_encapsulated_proto = htons(ETH_P_8021Q);
2983 		}
2984 		vlan_tci = skb_put(skb, sizeof(__be16));
2985 		*vlan_tci = build_tci(pkt_dev->vlan_id,
2986 				      pkt_dev->vlan_cfi,
2987 				      pkt_dev->vlan_p);
2988 		vlan_encapsulated_proto = skb_put(skb, sizeof(__be16));
2989 		*vlan_encapsulated_proto = htons(ETH_P_IP);
2990 	}
2991 
2992 	skb_reset_mac_header(skb);
2993 	skb_set_network_header(skb, skb->len);
2994 	iph = skb_put(skb, sizeof(struct iphdr));
2995 
2996 	skb_set_transport_header(skb, skb->len);
2997 	udph = skb_put(skb, sizeof(struct udphdr));
2998 	skb_set_queue_mapping(skb, queue_map);
2999 	skb->priority = pkt_dev->skb_priority;
3000 
3001 	memcpy(eth, pkt_dev->hh, 12);
3002 	*(__be16 *)&eth[12] = protocol;
3003 
3004 	/* Eth + IPh + UDPh + mpls */
3005 	datalen = pkt_dev->cur_pkt_size - 14 - 20 - 8 -
3006 		  pkt_dev->pkt_overhead;
3007 	if (datalen < 0 || datalen < sizeof(struct pktgen_hdr))
3008 		datalen = sizeof(struct pktgen_hdr);
3009 
3010 	udph->source = htons(pkt_dev->cur_udp_src);
3011 	udph->dest = htons(pkt_dev->cur_udp_dst);
3012 	udph->len = htons(datalen + 8);	/* DATA + udphdr */
3013 	udph->check = 0;
3014 
3015 	iph->ihl = 5;
3016 	iph->version = 4;
3017 	iph->ttl = 32;
3018 	iph->tos = pkt_dev->tos;
3019 	iph->protocol = IPPROTO_UDP;	/* UDP */
3020 	iph->saddr = pkt_dev->cur_saddr;
3021 	iph->daddr = pkt_dev->cur_daddr;
3022 	iph->id = htons(pkt_dev->ip_id);
3023 	pkt_dev->ip_id++;
3024 	iph->frag_off = 0;
3025 	iplen = 20 + 8 + datalen;
3026 	iph->tot_len = htons(iplen);
3027 	ip_send_check(iph);
3028 	skb->protocol = protocol;
3029 	skb->dev = odev;
3030 	skb->pkt_type = PACKET_HOST;
3031 
3032 	pktgen_finalize_skb(pkt_dev, skb, datalen);
3033 
3034 	if (!(pkt_dev->flags & F_UDPCSUM)) {
3035 		skb->ip_summed = CHECKSUM_NONE;
3036 	} else if (odev->features & (NETIF_F_HW_CSUM | NETIF_F_IP_CSUM)) {
3037 		skb->ip_summed = CHECKSUM_PARTIAL;
3038 		skb->csum = 0;
3039 		udp4_hwcsum(skb, iph->saddr, iph->daddr);
3040 	} else {
3041 		__wsum csum = skb_checksum(skb, skb_transport_offset(skb), datalen + 8, 0);
3042 
3043 		/* add protocol-dependent pseudo-header */
3044 		udph->check = csum_tcpudp_magic(iph->saddr, iph->daddr,
3045 						datalen + 8, IPPROTO_UDP, csum);
3046 
3047 		if (udph->check == 0)
3048 			udph->check = CSUM_MANGLED_0;
3049 	}
3050 
3051 #ifdef CONFIG_XFRM
3052 	if (!process_ipsec(pkt_dev, skb, protocol))
3053 		return NULL;
3054 #endif
3055 
3056 	return skb;
3057 }
3058 
3059 static struct sk_buff *fill_packet_ipv6(struct net_device *odev,
3060 					struct pktgen_dev *pkt_dev)
3061 {
3062 	struct sk_buff *skb = NULL;
3063 	__u8 *eth;
3064 	struct udphdr *udph;
3065 	int datalen, udplen;
3066 	struct ipv6hdr *iph;
3067 	__be16 protocol = htons(ETH_P_IPV6);
3068 	__be32 *mpls;
3069 	__be16 *vlan_tci = NULL;                 /* Encapsulates priority and VLAN ID */
3070 	__be16 *vlan_encapsulated_proto = NULL;  /* packet type ID field (or len) for VLAN tag */
3071 	__be16 *svlan_tci = NULL;                /* Encapsulates priority and SVLAN ID */
3072 	__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
3073 	u16 queue_map;
3074 
3075 	if (pkt_dev->nr_labels)
3076 		protocol = htons(ETH_P_MPLS_UC);
3077 
3078 	if (pkt_dev->vlan_id != 0xffff)
3079 		protocol = htons(ETH_P_8021Q);
3080 
3081 	/* Update any of the values, used when we're incrementing various
3082 	 * fields.
3083 	 */
3084 	mod_cur_headers(pkt_dev);
3085 	queue_map = pkt_dev->cur_queue_map;
3086 
3087 	skb = pktgen_alloc_skb(odev, pkt_dev);
3088 	if (!skb) {
3089 		sprintf(pkt_dev->result, "No memory");
3090 		return NULL;
3091 	}
3092 
3093 	prefetchw(skb->data);
3094 	skb_reserve(skb, 16);
3095 
3096 	/*  Reserve for ethernet and IP header  */
3097 	eth = skb_push(skb, 14);
3098 	mpls = skb_put(skb, pkt_dev->nr_labels * sizeof(__u32));
3099 	if (pkt_dev->nr_labels)
3100 		mpls_push(mpls, pkt_dev);
3101 
3102 	if (pkt_dev->vlan_id != 0xffff) {
3103 		if (pkt_dev->svlan_id != 0xffff) {
3104 			svlan_tci = skb_put(skb, sizeof(__be16));
3105 			*svlan_tci = build_tci(pkt_dev->svlan_id,
3106 					       pkt_dev->svlan_cfi,
3107 					       pkt_dev->svlan_p);
3108 			svlan_encapsulated_proto = skb_put(skb,
3109 							   sizeof(__be16));
3110 			*svlan_encapsulated_proto = htons(ETH_P_8021Q);
3111 		}
3112 		vlan_tci = skb_put(skb, sizeof(__be16));
3113 		*vlan_tci = build_tci(pkt_dev->vlan_id,
3114 				      pkt_dev->vlan_cfi,
3115 				      pkt_dev->vlan_p);
3116 		vlan_encapsulated_proto = skb_put(skb, sizeof(__be16));
3117 		*vlan_encapsulated_proto = htons(ETH_P_IPV6);
3118 	}
3119 
3120 	skb_reset_mac_header(skb);
3121 	skb_set_network_header(skb, skb->len);
3122 	iph = skb_put(skb, sizeof(struct ipv6hdr));
3123 
3124 	skb_set_transport_header(skb, skb->len);
3125 	udph = skb_put(skb, sizeof(struct udphdr));
3126 	skb_set_queue_mapping(skb, queue_map);
3127 	skb->priority = pkt_dev->skb_priority;
3128 
3129 	memcpy(eth, pkt_dev->hh, 12);
3130 	*(__be16 *) &eth[12] = protocol;
3131 
3132 	/* Eth + IPh + UDPh + mpls */
3133 	datalen = pkt_dev->cur_pkt_size - 14 -
3134 		  sizeof(struct ipv6hdr) - sizeof(struct udphdr) -
3135 		  pkt_dev->pkt_overhead;
3136 
3137 	if (datalen < 0 || datalen < sizeof(struct pktgen_hdr)) {
3138 		datalen = sizeof(struct pktgen_hdr);
3139 		net_info_ratelimited("increased datalen to %d\n", datalen);
3140 	}
3141 
3142 	udplen = datalen + sizeof(struct udphdr);
3143 	udph->source = htons(pkt_dev->cur_udp_src);
3144 	udph->dest = htons(pkt_dev->cur_udp_dst);
3145 	udph->len = htons(udplen);
3146 	udph->check = 0;
3147 
3148 	*(__be32 *) iph = htonl(0x60000000);	/* Version + flow */
3149 
3150 	if (pkt_dev->traffic_class) {
3151 		/* Version + traffic class + flow (0) */
3152 		*(__be32 *)iph |= htonl(0x60000000 | (pkt_dev->traffic_class << 20));
3153 	}
3154 
3155 	iph->hop_limit = 32;
3156 
3157 	iph->payload_len = htons(udplen);
3158 	iph->nexthdr = IPPROTO_UDP;
3159 
3160 	iph->daddr = pkt_dev->cur_in6_daddr;
3161 	iph->saddr = pkt_dev->cur_in6_saddr;
3162 
3163 	skb->protocol = protocol;
3164 	skb->dev = odev;
3165 	skb->pkt_type = PACKET_HOST;
3166 
3167 	pktgen_finalize_skb(pkt_dev, skb, datalen);
3168 
3169 	if (!(pkt_dev->flags & F_UDPCSUM)) {
3170 		skb->ip_summed = CHECKSUM_NONE;
3171 	} else if (odev->features & (NETIF_F_HW_CSUM | NETIF_F_IPV6_CSUM)) {
3172 		skb->ip_summed = CHECKSUM_PARTIAL;
3173 		skb->csum_start = skb_transport_header(skb) - skb->head;
3174 		skb->csum_offset = offsetof(struct udphdr, check);
3175 		udph->check = ~csum_ipv6_magic(&iph->saddr, &iph->daddr, udplen, IPPROTO_UDP, 0);
3176 	} else {
3177 		__wsum csum = skb_checksum(skb, skb_transport_offset(skb), udplen, 0);
3178 
3179 		/* add protocol-dependent pseudo-header */
3180 		udph->check = csum_ipv6_magic(&iph->saddr, &iph->daddr, udplen, IPPROTO_UDP, csum);
3181 
3182 		if (udph->check == 0)
3183 			udph->check = CSUM_MANGLED_0;
3184 	}
3185 
3186 	return skb;
3187 }
3188 
3189 static struct sk_buff *fill_packet(struct net_device *odev,
3190 				   struct pktgen_dev *pkt_dev)
3191 {
3192 	if (pkt_dev->flags & F_IPV6)
3193 		return fill_packet_ipv6(odev, pkt_dev);
3194 	else
3195 		return fill_packet_ipv4(odev, pkt_dev);
3196 }
3197 
3198 static void pktgen_clear_counters(struct pktgen_dev *pkt_dev)
3199 {
3200 	pkt_dev->seq_num = 1;
3201 	pkt_dev->idle_acc = 0;
3202 	pkt_dev->sofar = 0;
3203 	pkt_dev->tx_bytes = 0;
3204 	pkt_dev->errors = 0;
3205 }
3206 
3207 /* Set up structure for sending pkts, clear counters */
3208 
3209 static void pktgen_run(struct pktgen_thread *t)
3210 {
3211 	struct pktgen_dev *pkt_dev;
3212 	int started = 0;
3213 
3214 	func_enter();
3215 
3216 	rcu_read_lock();
3217 	list_for_each_entry_rcu(pkt_dev, &t->if_list, list) {
3218 
3219 		/*
3220 		 * setup odev and create initial packet.
3221 		 */
3222 		pktgen_setup_inject(pkt_dev);
3223 
3224 		if (pkt_dev->odev) {
3225 			pktgen_clear_counters(pkt_dev);
3226 			pkt_dev->skb = NULL;
3227 			pkt_dev->started_at = pkt_dev->next_tx = ktime_get();
3228 
3229 			set_pkt_overhead(pkt_dev);
3230 
3231 			strcpy(pkt_dev->result, "Starting");
3232 			pkt_dev->running = 1;	/* Cranke yeself! */
3233 			started++;
3234 		} else
3235 			strcpy(pkt_dev->result, "Error starting");
3236 	}
3237 	rcu_read_unlock();
3238 	if (started)
3239 		t->control &= ~(T_STOP);
3240 }
3241 
3242 static void pktgen_handle_all_threads(struct pktgen_net *pn, u32 flags)
3243 {
3244 	struct pktgen_thread *t;
3245 
3246 	mutex_lock(&pktgen_thread_lock);
3247 
3248 	list_for_each_entry(t, &pn->pktgen_threads, th_list)
3249 		t->control |= (flags);
3250 
3251 	mutex_unlock(&pktgen_thread_lock);
3252 }
3253 
3254 static void pktgen_stop_all_threads(struct pktgen_net *pn)
3255 {
3256 	func_enter();
3257 
3258 	pktgen_handle_all_threads(pn, T_STOP);
3259 }
3260 
3261 static int thread_is_running(const struct pktgen_thread *t)
3262 {
3263 	const struct pktgen_dev *pkt_dev;
3264 
3265 	rcu_read_lock();
3266 	list_for_each_entry_rcu(pkt_dev, &t->if_list, list)
3267 		if (pkt_dev->running) {
3268 			rcu_read_unlock();
3269 			return 1;
3270 		}
3271 	rcu_read_unlock();
3272 	return 0;
3273 }
3274 
3275 static int pktgen_wait_thread_run(struct pktgen_thread *t)
3276 {
3277 	while (thread_is_running(t)) {
3278 
3279 		/* note: 't' will still be around even after the unlock/lock
3280 		 * cycle because pktgen_thread threads are only cleared at
3281 		 * net exit
3282 		 */
3283 		mutex_unlock(&pktgen_thread_lock);
3284 		msleep_interruptible(100);
3285 		mutex_lock(&pktgen_thread_lock);
3286 
3287 		if (signal_pending(current))
3288 			goto signal;
3289 	}
3290 	return 1;
3291 signal:
3292 	return 0;
3293 }
3294 
3295 static int pktgen_wait_all_threads_run(struct pktgen_net *pn)
3296 {
3297 	struct pktgen_thread *t;
3298 	int sig = 1;
3299 
3300 	/* prevent from racing with rmmod */
3301 	if (!try_module_get(THIS_MODULE))
3302 		return sig;
3303 
3304 	mutex_lock(&pktgen_thread_lock);
3305 
3306 	list_for_each_entry(t, &pn->pktgen_threads, th_list) {
3307 		sig = pktgen_wait_thread_run(t);
3308 		if (sig == 0)
3309 			break;
3310 	}
3311 
3312 	if (sig == 0)
3313 		list_for_each_entry(t, &pn->pktgen_threads, th_list)
3314 			t->control |= (T_STOP);
3315 
3316 	mutex_unlock(&pktgen_thread_lock);
3317 	module_put(THIS_MODULE);
3318 	return sig;
3319 }
3320 
3321 static void pktgen_run_all_threads(struct pktgen_net *pn)
3322 {
3323 	func_enter();
3324 
3325 	pktgen_handle_all_threads(pn, T_RUN);
3326 
3327 	/* Propagate thread->control  */
3328 	schedule_timeout_interruptible(msecs_to_jiffies(125));
3329 
3330 	pktgen_wait_all_threads_run(pn);
3331 }
3332 
3333 static void pktgen_reset_all_threads(struct pktgen_net *pn)
3334 {
3335 	func_enter();
3336 
3337 	pktgen_handle_all_threads(pn, T_REMDEVALL);
3338 
3339 	/* Propagate thread->control  */
3340 	schedule_timeout_interruptible(msecs_to_jiffies(125));
3341 
3342 	pktgen_wait_all_threads_run(pn);
3343 }
3344 
3345 static void show_results(struct pktgen_dev *pkt_dev, int nr_frags)
3346 {
3347 	__u64 bps, mbps, pps;
3348 	char *p = pkt_dev->result;
3349 	ktime_t elapsed = ktime_sub(pkt_dev->stopped_at,
3350 				    pkt_dev->started_at);
3351 	ktime_t idle = ns_to_ktime(pkt_dev->idle_acc);
3352 
3353 	p += sprintf(p, "OK: %llu(c%llu+d%llu) usec, %llu (%dbyte,%dfrags)\n",
3354 		     (unsigned long long)ktime_to_us(elapsed),
3355 		     (unsigned long long)ktime_to_us(ktime_sub(elapsed, idle)),
3356 		     (unsigned long long)ktime_to_us(idle),
3357 		     (unsigned long long)pkt_dev->sofar,
3358 		     pkt_dev->cur_pkt_size, nr_frags);
3359 
3360 	pps = div64_u64(pkt_dev->sofar * NSEC_PER_SEC,
3361 			ktime_to_ns(elapsed));
3362 
3363 	if (pkt_dev->n_imix_entries > 0) {
3364 		int i;
3365 		struct imix_pkt *entry;
3366 
3367 		bps = 0;
3368 		for (i = 0; i < pkt_dev->n_imix_entries; i++) {
3369 			entry = &pkt_dev->imix_entries[i];
3370 			bps += entry->size * entry->count_so_far;
3371 		}
3372 		bps = div64_u64(bps * 8 * NSEC_PER_SEC, ktime_to_ns(elapsed));
3373 	} else {
3374 		bps = pps * 8 * pkt_dev->cur_pkt_size;
3375 	}
3376 
3377 	mbps = bps;
3378 	do_div(mbps, 1000000);
3379 	p += sprintf(p, "  %llupps %lluMb/sec (%llubps) errors: %llu",
3380 		     (unsigned long long)pps,
3381 		     (unsigned long long)mbps,
3382 		     (unsigned long long)bps,
3383 		     (unsigned long long)pkt_dev->errors);
3384 }
3385 
3386 /* Set stopped-at timer, remove from running list, do counters & statistics */
3387 static int pktgen_stop_device(struct pktgen_dev *pkt_dev)
3388 {
3389 	int nr_frags = pkt_dev->skb ? skb_shinfo(pkt_dev->skb)->nr_frags : -1;
3390 
3391 	if (!pkt_dev->running) {
3392 		pr_warn("interface: %s is already stopped\n",
3393 			pkt_dev->odevname);
3394 		return -EINVAL;
3395 	}
3396 
3397 	pkt_dev->running = 0;
3398 	kfree_skb(pkt_dev->skb);
3399 	pkt_dev->skb = NULL;
3400 	pkt_dev->stopped_at = ktime_get();
3401 
3402 	show_results(pkt_dev, nr_frags);
3403 
3404 	return 0;
3405 }
3406 
3407 static struct pktgen_dev *next_to_run(struct pktgen_thread *t)
3408 {
3409 	struct pktgen_dev *pkt_dev, *best = NULL;
3410 
3411 	rcu_read_lock();
3412 	list_for_each_entry_rcu(pkt_dev, &t->if_list, list) {
3413 		if (!pkt_dev->running)
3414 			continue;
3415 		if (best == NULL)
3416 			best = pkt_dev;
3417 		else if (ktime_compare(pkt_dev->next_tx, best->next_tx) < 0)
3418 			best = pkt_dev;
3419 	}
3420 	rcu_read_unlock();
3421 
3422 	return best;
3423 }
3424 
3425 static void pktgen_stop(struct pktgen_thread *t)
3426 {
3427 	struct pktgen_dev *pkt_dev;
3428 
3429 	func_enter();
3430 
3431 	rcu_read_lock();
3432 
3433 	list_for_each_entry_rcu(pkt_dev, &t->if_list, list) {
3434 		pktgen_stop_device(pkt_dev);
3435 	}
3436 
3437 	rcu_read_unlock();
3438 }
3439 
3440 /*
3441  * one of our devices needs to be removed - find it
3442  * and remove it
3443  */
3444 static void pktgen_rem_one_if(struct pktgen_thread *t)
3445 {
3446 	struct list_head *q, *n;
3447 	struct pktgen_dev *cur;
3448 
3449 	func_enter();
3450 
3451 	list_for_each_safe(q, n, &t->if_list) {
3452 		cur = list_entry(q, struct pktgen_dev, list);
3453 
3454 		if (!cur->removal_mark)
3455 			continue;
3456 
3457 		kfree_skb(cur->skb);
3458 		cur->skb = NULL;
3459 
3460 		pktgen_remove_device(t, cur);
3461 
3462 		break;
3463 	}
3464 }
3465 
3466 static void pktgen_rem_all_ifs(struct pktgen_thread *t)
3467 {
3468 	struct list_head *q, *n;
3469 	struct pktgen_dev *cur;
3470 
3471 	func_enter();
3472 
3473 	/* Remove all devices, free mem */
3474 
3475 	list_for_each_safe(q, n, &t->if_list) {
3476 		cur = list_entry(q, struct pktgen_dev, list);
3477 
3478 		kfree_skb(cur->skb);
3479 		cur->skb = NULL;
3480 
3481 		pktgen_remove_device(t, cur);
3482 	}
3483 }
3484 
3485 static void pktgen_rem_thread(struct pktgen_thread *t)
3486 {
3487 	/* Remove from the thread list */
3488 	remove_proc_entry(t->tsk->comm, t->net->proc_dir);
3489 }
3490 
3491 static void pktgen_resched(struct pktgen_dev *pkt_dev)
3492 {
3493 	ktime_t idle_start = ktime_get();
3494 
3495 	schedule();
3496 	pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_get(), idle_start));
3497 }
3498 
3499 static void pktgen_wait_for_skb(struct pktgen_dev *pkt_dev)
3500 {
3501 	ktime_t idle_start = ktime_get();
3502 
3503 	while (refcount_read(&(pkt_dev->skb->users)) != 1) {
3504 		if (signal_pending(current))
3505 			break;
3506 
3507 		if (need_resched())
3508 			pktgen_resched(pkt_dev);
3509 		else
3510 			cpu_relax();
3511 	}
3512 	pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_get(), idle_start));
3513 }
3514 
3515 static void pktgen_xmit(struct pktgen_dev *pkt_dev)
3516 {
3517 	bool skb_shared = !!(READ_ONCE(pkt_dev->flags) & F_SHARED);
3518 	struct net_device *odev = pkt_dev->odev;
3519 	struct netdev_queue *txq;
3520 	unsigned int burst = 1;
3521 	struct sk_buff *skb;
3522 	int clone_skb = 0;
3523 	int ret;
3524 
3525 	/* If 'skb_shared' is false, the read of possible
3526 	 * new values (if any) for 'burst' and 'clone_skb' will be skipped to
3527 	 * prevent some concurrent changes from slipping in. And the stabilized
3528 	 * config will be read in during the next run of pktgen_xmit.
3529 	 */
3530 	if (skb_shared) {
3531 		burst = READ_ONCE(pkt_dev->burst);
3532 		clone_skb = READ_ONCE(pkt_dev->clone_skb);
3533 	}
3534 
3535 	/* If device is offline, then don't send */
3536 	if (unlikely(!netif_running(odev) || !netif_carrier_ok(odev))) {
3537 		pktgen_stop_device(pkt_dev);
3538 		return;
3539 	}
3540 
3541 	/* This is max DELAY, this has special meaning of
3542 	 * "never transmit"
3543 	 */
3544 	if (unlikely(pkt_dev->delay == ULLONG_MAX)) {
3545 		pkt_dev->next_tx = ktime_add_ns(ktime_get(), ULONG_MAX);
3546 		return;
3547 	}
3548 
3549 	/* If no skb or clone count exhausted then get new one */
3550 	if (!pkt_dev->skb || (pkt_dev->last_ok &&
3551 			      ++pkt_dev->clone_count >= clone_skb)) {
3552 		/* build a new pkt */
3553 		kfree_skb(pkt_dev->skb);
3554 
3555 		pkt_dev->skb = fill_packet(odev, pkt_dev);
3556 		if (pkt_dev->skb == NULL) {
3557 			pr_err("ERROR: couldn't allocate skb in fill_packet\n");
3558 			schedule();
3559 			pkt_dev->clone_count--;	/* back out increment, OOM */
3560 			return;
3561 		}
3562 		pkt_dev->last_pkt_size = pkt_dev->skb->len;
3563 		pkt_dev->clone_count = 0;	/* reset counter */
3564 	}
3565 
3566 	if (pkt_dev->delay && pkt_dev->last_ok)
3567 		spin(pkt_dev, pkt_dev->next_tx);
3568 
3569 	if (pkt_dev->xmit_mode == M_NETIF_RECEIVE) {
3570 		skb = pkt_dev->skb;
3571 		skb->protocol = eth_type_trans(skb, skb->dev);
3572 		if (skb_shared)
3573 			refcount_add(burst, &skb->users);
3574 		local_bh_disable();
3575 		do {
3576 			ret = netif_receive_skb(skb);
3577 			if (ret == NET_RX_DROP)
3578 				pkt_dev->errors++;
3579 			pkt_dev->sofar++;
3580 			pkt_dev->seq_num++;
3581 			if (unlikely(!skb_shared)) {
3582 				pkt_dev->skb = NULL;
3583 				break;
3584 			}
3585 			if (refcount_read(&skb->users) != burst) {
3586 				/* skb was queued by rps/rfs or taps,
3587 				 * so cannot reuse this skb
3588 				 */
3589 				WARN_ON(refcount_sub_and_test(burst - 1, &skb->users));
3590 				/* get out of the loop and wait
3591 				 * until skb is consumed
3592 				 */
3593 				break;
3594 			}
3595 			/* skb was 'freed' by stack, so clean few
3596 			 * bits and reuse it
3597 			 */
3598 			skb_reset_redirect(skb);
3599 		} while (--burst > 0);
3600 		goto out; /* Skips xmit_mode M_START_XMIT */
3601 	} else if (pkt_dev->xmit_mode == M_QUEUE_XMIT) {
3602 		local_bh_disable();
3603 		if (skb_shared)
3604 			refcount_inc(&pkt_dev->skb->users);
3605 
3606 		ret = dev_queue_xmit(pkt_dev->skb);
3607 
3608 		if (!skb_shared && dev_xmit_complete(ret))
3609 			pkt_dev->skb = NULL;
3610 
3611 		switch (ret) {
3612 		case NET_XMIT_SUCCESS:
3613 			pkt_dev->sofar++;
3614 			pkt_dev->seq_num++;
3615 			pkt_dev->tx_bytes += pkt_dev->last_pkt_size;
3616 			break;
3617 		case NET_XMIT_DROP:
3618 		case NET_XMIT_CN:
3619 		/* These are all valid return codes for a qdisc but
3620 		 * indicate packets are being dropped or will likely
3621 		 * be dropped soon.
3622 		 */
3623 		case NETDEV_TX_BUSY:
3624 		/* qdisc may call dev_hard_start_xmit directly in cases
3625 		 * where no queues exist e.g. loopback device, virtual
3626 		 * devices, etc. In this case we need to handle
3627 		 * NETDEV_TX_ codes.
3628 		 */
3629 		default:
3630 			pkt_dev->errors++;
3631 			net_info_ratelimited("%s xmit error: %d\n",
3632 					     pkt_dev->odevname, ret);
3633 			break;
3634 		}
3635 		goto out;
3636 	}
3637 
3638 	txq = skb_get_tx_queue(odev, pkt_dev->skb);
3639 
3640 	local_bh_disable();
3641 
3642 	HARD_TX_LOCK(odev, txq, smp_processor_id());
3643 
3644 	if (unlikely(netif_xmit_frozen_or_drv_stopped(txq))) {
3645 		pkt_dev->last_ok = 0;
3646 		goto unlock;
3647 	}
3648 	if (skb_shared)
3649 		refcount_add(burst, &pkt_dev->skb->users);
3650 
3651 xmit_more:
3652 	ret = netdev_start_xmit(pkt_dev->skb, odev, txq, --burst > 0);
3653 
3654 	if (!skb_shared && dev_xmit_complete(ret))
3655 		pkt_dev->skb = NULL;
3656 
3657 	switch (ret) {
3658 	case NETDEV_TX_OK:
3659 		pkt_dev->last_ok = 1;
3660 		pkt_dev->sofar++;
3661 		pkt_dev->seq_num++;
3662 		pkt_dev->tx_bytes += pkt_dev->last_pkt_size;
3663 		if (burst > 0 && !netif_xmit_frozen_or_drv_stopped(txq))
3664 			goto xmit_more;
3665 		break;
3666 	case NET_XMIT_DROP:
3667 	case NET_XMIT_CN:
3668 		/* skb has been consumed */
3669 		pkt_dev->errors++;
3670 		break;
3671 	default: /* Drivers are not supposed to return other values! */
3672 		net_info_ratelimited("%s xmit error: %d\n",
3673 				     pkt_dev->odevname, ret);
3674 		pkt_dev->errors++;
3675 		fallthrough;
3676 	case NETDEV_TX_BUSY:
3677 		/* Retry it next time */
3678 		if (skb_shared)
3679 			refcount_dec(&pkt_dev->skb->users);
3680 		pkt_dev->last_ok = 0;
3681 	}
3682 	if (unlikely(burst))
3683 		WARN_ON(refcount_sub_and_test(burst, &pkt_dev->skb->users));
3684 unlock:
3685 	HARD_TX_UNLOCK(odev, txq);
3686 
3687 out:
3688 	local_bh_enable();
3689 
3690 	/* If pkt_dev->count is zero, then run forever */
3691 	if ((pkt_dev->count != 0) && (pkt_dev->sofar >= pkt_dev->count)) {
3692 		if (pkt_dev->skb)
3693 			pktgen_wait_for_skb(pkt_dev);
3694 
3695 		/* Done with this */
3696 		pktgen_stop_device(pkt_dev);
3697 	}
3698 }
3699 
3700 /*
3701  * Main loop of the thread goes here
3702  */
3703 
3704 static int pktgen_thread_worker(void *arg)
3705 {
3706 	struct pktgen_thread *t = arg;
3707 	struct pktgen_dev *pkt_dev = NULL;
3708 	int cpu = t->cpu;
3709 
3710 	WARN_ON_ONCE(smp_processor_id() != cpu);
3711 
3712 	init_waitqueue_head(&t->queue);
3713 	complete(&t->start_done);
3714 
3715 	pr_debug("starting pktgen/%d:  pid=%d\n", cpu, task_pid_nr(current));
3716 
3717 	set_freezable();
3718 
3719 	while (!kthread_should_stop()) {
3720 		pkt_dev = next_to_run(t);
3721 
3722 		if (unlikely(!pkt_dev && t->control == 0)) {
3723 			if (t->net->pktgen_exiting)
3724 				break;
3725 			wait_event_freezable_timeout(t->queue,
3726 						     t->control != 0, HZ / 10);
3727 			continue;
3728 		}
3729 
3730 		if (likely(pkt_dev)) {
3731 			pktgen_xmit(pkt_dev);
3732 
3733 			if (need_resched())
3734 				pktgen_resched(pkt_dev);
3735 			else
3736 				cpu_relax();
3737 		}
3738 
3739 		if (t->control & T_STOP) {
3740 			pktgen_stop(t);
3741 			t->control &= ~(T_STOP);
3742 		}
3743 
3744 		if (t->control & T_RUN) {
3745 			pktgen_run(t);
3746 			t->control &= ~(T_RUN);
3747 		}
3748 
3749 		if (t->control & T_REMDEVALL) {
3750 			pktgen_rem_all_ifs(t);
3751 			t->control &= ~(T_REMDEVALL);
3752 		}
3753 
3754 		if (t->control & T_REMDEV) {
3755 			pktgen_rem_one_if(t);
3756 			t->control &= ~(T_REMDEV);
3757 		}
3758 
3759 		try_to_freeze();
3760 	}
3761 
3762 	pr_debug("%s stopping all device\n", t->tsk->comm);
3763 	pktgen_stop(t);
3764 
3765 	pr_debug("%s removing all device\n", t->tsk->comm);
3766 	pktgen_rem_all_ifs(t);
3767 
3768 	pr_debug("%s removing thread\n", t->tsk->comm);
3769 	pktgen_rem_thread(t);
3770 
3771 	return 0;
3772 }
3773 
3774 static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
3775 					  const char *ifname, bool exact)
3776 {
3777 	struct pktgen_dev *p, *pkt_dev = NULL;
3778 	size_t len = strlen(ifname);
3779 
3780 	rcu_read_lock();
3781 	list_for_each_entry_rcu(p, &t->if_list, list)
3782 		if (strncmp(p->odevname, ifname, len) == 0) {
3783 			if (p->odevname[len]) {
3784 				if (exact || p->odevname[len] != '@')
3785 					continue;
3786 			}
3787 			pkt_dev = p;
3788 			break;
3789 		}
3790 
3791 	rcu_read_unlock();
3792 	pr_debug("find_dev(%s) returning %p\n", ifname, pkt_dev);
3793 	return pkt_dev;
3794 }
3795 
3796 /*
3797  * Adds a dev at front of if_list.
3798  */
3799 
3800 static int add_dev_to_thread(struct pktgen_thread *t,
3801 			     struct pktgen_dev *pkt_dev)
3802 {
3803 	int rv = 0;
3804 
3805 	/* This function cannot be called concurrently, as its called
3806 	 * under pktgen_thread_lock mutex, but it can run from
3807 	 * userspace on another CPU than the kthread.  The if_lock()
3808 	 * is used here to sync with concurrent instances of
3809 	 * _rem_dev_from_if_list() invoked via kthread, which is also
3810 	 * updating the if_list
3811 	 */
3812 	if_lock(t);
3813 
3814 	if (pkt_dev->pg_thread) {
3815 		pr_err("ERROR: already assigned to a thread\n");
3816 		rv = -EBUSY;
3817 		goto out;
3818 	}
3819 
3820 	pkt_dev->running = 0;
3821 	pkt_dev->pg_thread = t;
3822 	list_add_rcu(&pkt_dev->list, &t->if_list);
3823 
3824 out:
3825 	if_unlock(t);
3826 	return rv;
3827 }
3828 
3829 /* Called under thread lock */
3830 
3831 static int pktgen_add_device(struct pktgen_thread *t, const char *ifname)
3832 {
3833 	struct pktgen_dev *pkt_dev;
3834 	int err;
3835 	int node = cpu_to_node(t->cpu);
3836 
3837 	/* We don't allow a device to be on several threads */
3838 
3839 	pkt_dev = __pktgen_NN_threads(t->net, ifname, FIND);
3840 	if (pkt_dev) {
3841 		pr_err("ERROR: interface already used\n");
3842 		return -EBUSY;
3843 	}
3844 
3845 	pkt_dev = kzalloc_node(sizeof(struct pktgen_dev), GFP_KERNEL, node);
3846 	if (!pkt_dev)
3847 		return -ENOMEM;
3848 
3849 	strcpy(pkt_dev->odevname, ifname);
3850 	pkt_dev->flows = vzalloc_node(array_size(MAX_CFLOWS,
3851 						 sizeof(struct flow_state)),
3852 				      node);
3853 	if (pkt_dev->flows == NULL) {
3854 		kfree(pkt_dev);
3855 		return -ENOMEM;
3856 	}
3857 
3858 	pkt_dev->removal_mark = 0;
3859 	pkt_dev->nfrags = 0;
3860 	pkt_dev->delay = pg_delay_d;
3861 	pkt_dev->count = pg_count_d;
3862 	pkt_dev->sofar = 0;
3863 	pkt_dev->udp_src_min = 9;	/* sink port */
3864 	pkt_dev->udp_src_max = 9;
3865 	pkt_dev->udp_dst_min = 9;
3866 	pkt_dev->udp_dst_max = 9;
3867 	pkt_dev->vlan_p = 0;
3868 	pkt_dev->vlan_cfi = 0;
3869 	pkt_dev->vlan_id = 0xffff;
3870 	pkt_dev->svlan_p = 0;
3871 	pkt_dev->svlan_cfi = 0;
3872 	pkt_dev->svlan_id = 0xffff;
3873 	pkt_dev->burst = 1;
3874 	pkt_dev->node = NUMA_NO_NODE;
3875 	pkt_dev->flags = F_SHARED;	/* SKB shared by default */
3876 
3877 	err = pktgen_setup_dev(t->net, pkt_dev, ifname);
3878 	if (err)
3879 		goto out1;
3880 	if (pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)
3881 		pkt_dev->clone_skb = pg_clone_skb_d;
3882 
3883 	pkt_dev->entry = proc_create_data(ifname, 0600, t->net->proc_dir,
3884 					  &pktgen_if_proc_ops, pkt_dev);
3885 	if (!pkt_dev->entry) {
3886 		pr_err("cannot create %s/%s procfs entry\n",
3887 		       PG_PROC_DIR, ifname);
3888 		err = -EINVAL;
3889 		goto out2;
3890 	}
3891 #ifdef CONFIG_XFRM
3892 	pkt_dev->ipsmode = XFRM_MODE_TRANSPORT;
3893 	pkt_dev->ipsproto = IPPROTO_ESP;
3894 
3895 	/* xfrm tunnel mode needs additional dst to extract outer
3896 	 * ip header protocol/ttl/id field, here create a phony one.
3897 	 * instead of looking for a valid rt, which definitely hurting
3898 	 * performance under such circumstance.
3899 	 */
3900 	pkt_dev->dstops.family = AF_INET;
3901 	pkt_dev->xdst.u.dst.dev = pkt_dev->odev;
3902 	dst_init_metrics(&pkt_dev->xdst.u.dst, pktgen_dst_metrics, false);
3903 	pkt_dev->xdst.child = &pkt_dev->xdst.u.dst;
3904 	pkt_dev->xdst.u.dst.ops = &pkt_dev->dstops;
3905 #endif
3906 
3907 	return add_dev_to_thread(t, pkt_dev);
3908 out2:
3909 	netdev_put(pkt_dev->odev, &pkt_dev->dev_tracker);
3910 out1:
3911 #ifdef CONFIG_XFRM
3912 	free_SAs(pkt_dev);
3913 #endif
3914 	vfree(pkt_dev->flows);
3915 	kfree(pkt_dev);
3916 	return err;
3917 }
3918 
3919 static int __net_init pktgen_create_thread(int cpu, struct pktgen_net *pn)
3920 {
3921 	struct pktgen_thread *t;
3922 	struct proc_dir_entry *pe;
3923 	struct task_struct *p;
3924 
3925 	t = kzalloc_node(sizeof(struct pktgen_thread), GFP_KERNEL,
3926 			 cpu_to_node(cpu));
3927 	if (!t) {
3928 		pr_err("ERROR: out of memory, can't create new thread\n");
3929 		return -ENOMEM;
3930 	}
3931 
3932 	mutex_init(&t->if_lock);
3933 	t->cpu = cpu;
3934 
3935 	INIT_LIST_HEAD(&t->if_list);
3936 
3937 	list_add_tail(&t->th_list, &pn->pktgen_threads);
3938 	init_completion(&t->start_done);
3939 
3940 	p = kthread_create_on_cpu(pktgen_thread_worker, t, cpu, "kpktgend_%d");
3941 	if (IS_ERR(p)) {
3942 		pr_err("kthread_create_on_node() failed for cpu %d\n", t->cpu);
3943 		list_del(&t->th_list);
3944 		kfree(t);
3945 		return PTR_ERR(p);
3946 	}
3947 
3948 	t->tsk = p;
3949 
3950 	pe = proc_create_data(t->tsk->comm, 0600, pn->proc_dir,
3951 			      &pktgen_thread_proc_ops, t);
3952 	if (!pe) {
3953 		pr_err("cannot create %s/%s procfs entry\n",
3954 		       PG_PROC_DIR, t->tsk->comm);
3955 		kthread_stop(p);
3956 		list_del(&t->th_list);
3957 		kfree(t);
3958 		return -EINVAL;
3959 	}
3960 
3961 	t->net = pn;
3962 	get_task_struct(p);
3963 	wake_up_process(p);
3964 	wait_for_completion(&t->start_done);
3965 
3966 	return 0;
3967 }
3968 
3969 /*
3970  * Removes a device from the thread if_list.
3971  */
3972 static void _rem_dev_from_if_list(struct pktgen_thread *t,
3973 				  struct pktgen_dev *pkt_dev)
3974 {
3975 	struct list_head *q, *n;
3976 	struct pktgen_dev *p;
3977 
3978 	if_lock(t);
3979 	list_for_each_safe(q, n, &t->if_list) {
3980 		p = list_entry(q, struct pktgen_dev, list);
3981 		if (p == pkt_dev)
3982 			list_del_rcu(&p->list);
3983 	}
3984 	if_unlock(t);
3985 }
3986 
3987 static int pktgen_remove_device(struct pktgen_thread *t,
3988 				struct pktgen_dev *pkt_dev)
3989 {
3990 	pr_debug("remove_device pkt_dev=%p\n", pkt_dev);
3991 
3992 	if (pkt_dev->running) {
3993 		pr_warn("WARNING: trying to remove a running interface, stopping it now\n");
3994 		pktgen_stop_device(pkt_dev);
3995 	}
3996 
3997 	/* Dis-associate from the interface */
3998 
3999 	if (pkt_dev->odev) {
4000 		netdev_put(pkt_dev->odev, &pkt_dev->dev_tracker);
4001 		pkt_dev->odev = NULL;
4002 	}
4003 
4004 	/* Remove proc before if_list entry, because add_device uses
4005 	 * list to determine if interface already exist, avoid race
4006 	 * with proc_create_data()
4007 	 */
4008 	proc_remove(pkt_dev->entry);
4009 
4010 	/* And update the thread if_list */
4011 	_rem_dev_from_if_list(t, pkt_dev);
4012 
4013 #ifdef CONFIG_XFRM
4014 	free_SAs(pkt_dev);
4015 #endif
4016 	vfree(pkt_dev->flows);
4017 	if (pkt_dev->page)
4018 		put_page(pkt_dev->page);
4019 	kfree_rcu(pkt_dev, rcu);
4020 	return 0;
4021 }
4022 
4023 static int __net_init pg_net_init(struct net *net)
4024 {
4025 	struct pktgen_net *pn = net_generic(net, pg_net_id);
4026 	struct proc_dir_entry *pe;
4027 	int cpu, ret = 0;
4028 
4029 	pn->net = net;
4030 	INIT_LIST_HEAD(&pn->pktgen_threads);
4031 	pn->pktgen_exiting = false;
4032 	pn->proc_dir = proc_mkdir(PG_PROC_DIR, pn->net->proc_net);
4033 	if (!pn->proc_dir) {
4034 		pr_warn("cannot create /proc/net/%s\n", PG_PROC_DIR);
4035 		return -ENODEV;
4036 	}
4037 	pe = proc_create(PGCTRL, 0600, pn->proc_dir, &pktgen_proc_ops);
4038 	if (pe == NULL) {
4039 		pr_err("cannot create %s procfs entry\n", PGCTRL);
4040 		ret = -EINVAL;
4041 		goto remove;
4042 	}
4043 
4044 	cpus_read_lock();
4045 	for_each_online_cpu(cpu) {
4046 		int err;
4047 
4048 		err = pktgen_create_thread(cpu, pn);
4049 		if (err)
4050 			pr_warn("Cannot create thread for cpu %d (%d)\n",
4051 				   cpu, err);
4052 	}
4053 	cpus_read_unlock();
4054 
4055 	if (list_empty(&pn->pktgen_threads)) {
4056 		pr_err("Initialization failed for all threads\n");
4057 		ret = -ENODEV;
4058 		goto remove_entry;
4059 	}
4060 
4061 	return 0;
4062 
4063 remove_entry:
4064 	remove_proc_entry(PGCTRL, pn->proc_dir);
4065 remove:
4066 	remove_proc_entry(PG_PROC_DIR, pn->net->proc_net);
4067 	return ret;
4068 }
4069 
4070 static void __net_exit pg_net_exit(struct net *net)
4071 {
4072 	struct pktgen_net *pn = net_generic(net, pg_net_id);
4073 	struct pktgen_thread *t;
4074 	struct list_head *q, *n;
4075 	LIST_HEAD(list);
4076 
4077 	/* Stop all interfaces & threads */
4078 	pn->pktgen_exiting = true;
4079 
4080 	mutex_lock(&pktgen_thread_lock);
4081 	list_splice_init(&pn->pktgen_threads, &list);
4082 	mutex_unlock(&pktgen_thread_lock);
4083 
4084 	list_for_each_safe(q, n, &list) {
4085 		t = list_entry(q, struct pktgen_thread, th_list);
4086 		list_del(&t->th_list);
4087 		kthread_stop_put(t->tsk);
4088 		kfree(t);
4089 	}
4090 
4091 	remove_proc_entry(PGCTRL, pn->proc_dir);
4092 	remove_proc_entry(PG_PROC_DIR, pn->net->proc_net);
4093 }
4094 
4095 static struct pernet_operations pg_net_ops = {
4096 	.init = pg_net_init,
4097 	.exit = pg_net_exit,
4098 	.id   = &pg_net_id,
4099 	.size = sizeof(struct pktgen_net),
4100 };
4101 
4102 static int __init pg_init(void)
4103 {
4104 	int ret = 0;
4105 
4106 	pr_info("%s", version);
4107 	ret = register_pernet_subsys(&pg_net_ops);
4108 	if (ret)
4109 		return ret;
4110 	ret = register_netdevice_notifier(&pktgen_notifier_block);
4111 	if (ret)
4112 		unregister_pernet_subsys(&pg_net_ops);
4113 
4114 	return ret;
4115 }
4116 
4117 static void __exit pg_cleanup(void)
4118 {
4119 	unregister_netdevice_notifier(&pktgen_notifier_block);
4120 	unregister_pernet_subsys(&pg_net_ops);
4121 	/* Don't need rcu_barrier() due to use of kfree_rcu() */
4122 }
4123 
4124 module_init(pg_init);
4125 module_exit(pg_cleanup);
4126 
4127 MODULE_AUTHOR("Robert Olsson <robert.olsson@its.uu.se>");
4128 MODULE_DESCRIPTION("Packet Generator tool");
4129 MODULE_LICENSE("GPL");
4130 MODULE_VERSION(VERSION);
4131 module_param(pg_count_d, int, 0);
4132 MODULE_PARM_DESC(pg_count_d, "Default number of packets to inject");
4133 module_param(pg_delay_d, int, 0);
4134 MODULE_PARM_DESC(pg_delay_d, "Default delay between packets (nanoseconds)");
4135 module_param(pg_clone_skb_d, int, 0);
4136 MODULE_PARM_DESC(pg_clone_skb_d, "Default number of copies of the same packet");
4137 module_param(debug, int, 0);
4138 MODULE_PARM_DESC(debug, "Enable debugging of pktgen module");
4139