]> err.no Git - linux-2.6/blob - net/core/pktgen.c
[PKTGEN]: Convert thread lock to mutexes.
[linux-2.6] / net / core / pktgen.c
1 /*
2  * Authors:
3  * Copyright 2001, 2002 by Robert Olsson <robert.olsson@its.uu.se>
4  *                             Uppsala University and
5  *                             Swedish University of Agricultural Sciences
6  *
7  * Alexey Kuznetsov  <kuznet@ms2.inr.ac.ru>
8  * Ben Greear <greearb@candelatech.com>
9  * Jens Låås <jens.laas@data.slu.se>
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version
14  * 2 of the License, or (at your option) any later version.
15  *
16  *
17  * A tool for loading the network with preconfigurated packets.
18  * The tool is implemented as a linux module.  Parameters are output 
19  * device, delay (to hard_xmit), number of packets, and whether
20  * to use multiple SKBs or just the same one.
21  * pktgen uses the installed interface's output routine.
22  *
23  * Additional hacking by:
24  *
25  * Jens.Laas@data.slu.se
26  * Improved by ANK. 010120.
27  * Improved by ANK even more. 010212.
28  * MAC address typo fixed. 010417 --ro
29  * Integrated.  020301 --DaveM
30  * Added multiskb option 020301 --DaveM
31  * Scaling of results. 020417--sigurdur@linpro.no
32  * Significant re-work of the module:
33  *   *  Convert to threaded model to more efficiently be able to transmit
34  *       and receive on multiple interfaces at once.
35  *   *  Converted many counters to __u64 to allow longer runs.
36  *   *  Allow configuration of ranges, like min/max IP address, MACs,
37  *       and UDP-ports, for both source and destination, and can
38  *       set to use a random distribution or sequentially walk the range.
39  *   *  Can now change most values after starting.
40  *   *  Place 12-byte packet in UDP payload with magic number,
41  *       sequence number, and timestamp.
42  *   *  Add receiver code that detects dropped pkts, re-ordered pkts, and
43  *       latencies (with micro-second) precision.
44  *   *  Add IOCTL interface to easily get counters & configuration.
45  *   --Ben Greear <greearb@candelatech.com>
46  *
47  * Renamed multiskb to clone_skb and cleaned up sending core for two distinct 
48  * skb modes. A clone_skb=0 mode for Ben "ranges" work and a clone_skb != 0 
49  * as a "fastpath" with a configurable number of clones after alloc's.
50  * clone_skb=0 means all packets are allocated this also means ranges time 
51  * stamps etc can be used. clone_skb=100 means 1 malloc is followed by 100 
52  * clones.
53  *
54  * Also moved to /proc/net/pktgen/ 
55  * --ro
56  *
57  * Sept 10:  Fixed threading/locking.  Lots of bone-headed and more clever
58  *    mistakes.  Also merged in DaveM's patch in the -pre6 patch.
59  * --Ben Greear <greearb@candelatech.com>
60  *
61  * Integrated to 2.5.x 021029 --Lucio Maciel (luciomaciel@zipmail.com.br)
62  *
63  * 
64  * 021124 Finished major redesign and rewrite for new functionality.
65  * See Documentation/networking/pktgen.txt for how to use this.
66  *
67  * The new operation:
68  * For each CPU one thread/process is created at start. This process checks 
69  * for running devices in the if_list and sends packets until count is 0 it 
70  * also the thread checks the thread->control which is used for inter-process 
71  * communication. controlling process "posts" operations to the threads this 
72  * way. The if_lock should be possible to remove when add/rem_device is merged
73  * into this too.
74  *
75  * By design there should only be *one* "controlling" process. In practice 
76  * multiple write accesses gives unpredictable result. Understood by "write" 
77  * to /proc gives result code thats should be read be the "writer".
78  * For practical use this should be no problem.
79  *
80  * Note when adding devices to a specific CPU there good idea to also assign 
81  * /proc/irq/XX/smp_affinity so TX-interrupts gets bound to the same CPU. 
82  * --ro
83  *
84  * Fix refcount off by one if first packet fails, potential null deref, 
85  * memleak 030710- KJP
86  *
87  * First "ranges" functionality for ipv6 030726 --ro
88  *
89  * Included flow support. 030802 ANK.
90  *
91  * Fixed unaligned access on IA-64 Grant Grundler <grundler@parisc-linux.org>
92  * 
93  * Remove if fix from added Harald Welte <laforge@netfilter.org> 040419
94  * ia64 compilation fix from  Aron Griffis <aron@hp.com> 040604
95  *
96  * New xmit() return, do_div and misc clean up by Stephen Hemminger 
97  * <shemminger@osdl.org> 040923
98  *
99  * Randy Dunlap fixed u64 printk compiler waring 
100  *
101  * Remove FCS from BW calculation.  Lennert Buytenhek <buytenh@wantstofly.org>
102  * New time handling. Lennert Buytenhek <buytenh@wantstofly.org> 041213
103  *
104  * Corrections from Nikolai Malykh (nmalykh@bilim.com) 
105  * Removed unused flags F_SET_SRCMAC & F_SET_SRCIP 041230
106  *
107  * interruptible_sleep_on_timeout() replaced Nishanth Aravamudan <nacc@us.ibm.com> 
108  * 050103
109  */
110 #include <linux/sys.h>
111 #include <linux/types.h>
112 #include <linux/module.h>
113 #include <linux/moduleparam.h>
114 #include <linux/kernel.h>
115 #include <linux/smp_lock.h>
116 #include <linux/mutex.h>
117 #include <linux/sched.h>
118 #include <linux/slab.h>
119 #include <linux/vmalloc.h>
120 #include <linux/unistd.h>
121 #include <linux/string.h>
122 #include <linux/ptrace.h>
123 #include <linux/errno.h>
124 #include <linux/ioport.h>
125 #include <linux/interrupt.h>
126 #include <linux/capability.h>
127 #include <linux/delay.h>
128 #include <linux/timer.h>
129 #include <linux/list.h>
130 #include <linux/init.h>
131 #include <linux/skbuff.h>
132 #include <linux/netdevice.h>
133 #include <linux/inet.h>
134 #include <linux/inetdevice.h>
135 #include <linux/rtnetlink.h>
136 #include <linux/if_arp.h>
137 #include <linux/in.h>
138 #include <linux/ip.h>
139 #include <linux/ipv6.h>
140 #include <linux/udp.h>
141 #include <linux/proc_fs.h>
142 #include <linux/seq_file.h>
143 #include <linux/wait.h>
144 #include <linux/etherdevice.h>
145 #include <net/checksum.h>
146 #include <net/ipv6.h>
147 #include <net/addrconf.h>
148 #include <asm/byteorder.h>
149 #include <linux/rcupdate.h>
150 #include <asm/bitops.h>
151 #include <asm/io.h>
152 #include <asm/dma.h>
153 #include <asm/uaccess.h>
154 #include <asm/div64.h>          /* do_div */
155 #include <asm/timex.h>
156
157 #define VERSION  "pktgen v2.65: Packet Generator for packet performance testing.\n"
158
159 /* #define PG_DEBUG(a) a */
160 #define PG_DEBUG(a)
161
162 /* The buckets are exponential in 'width' */
163 #define LAT_BUCKETS_MAX 32
164 #define IP_NAME_SZ 32
165
166 /* Device flag bits */
167 #define F_IPSRC_RND   (1<<0)    /* IP-Src Random  */
168 #define F_IPDST_RND   (1<<1)    /* IP-Dst Random  */
169 #define F_UDPSRC_RND  (1<<2)    /* UDP-Src Random */
170 #define F_UDPDST_RND  (1<<3)    /* UDP-Dst Random */
171 #define F_MACSRC_RND  (1<<4)    /* MAC-Src Random */
172 #define F_MACDST_RND  (1<<5)    /* MAC-Dst Random */
173 #define F_TXSIZE_RND  (1<<6)    /* Transmit size is random */
174 #define F_IPV6        (1<<7)    /* Interface in IPV6 Mode */
175
176 /* Thread control flag bits */
177 #define T_TERMINATE   (1<<0)
178 #define T_STOP        (1<<1)    /* Stop run */
179 #define T_RUN         (1<<2)    /* Start run */
180 #define T_REMDEVALL   (1<<3)    /* Remove all devs */
181 #define T_REMDEV      (1<<4)    /* Remove one dev */
182
183 /* Locks */
184 #define   thread_lock()        mutex_lock(&pktgen_thread_lock)
185 #define   thread_unlock()      mutex_unlock(&pktgen_thread_lock)
186
187 /* If lock -- can be removed after some work */
188 #define   if_lock(t)           spin_lock(&(t->if_lock));
189 #define   if_unlock(t)           spin_unlock(&(t->if_lock));
190
191 /* Used to help with determining the pkts on receive */
192 #define PKTGEN_MAGIC 0xbe9be955
193 #define PG_PROC_DIR "pktgen"
194 #define PGCTRL      "pgctrl"
195 static struct proc_dir_entry *pg_proc_dir = NULL;
196
197 #define MAX_CFLOWS  65536
198
199 struct flow_state {
200         __u32 cur_daddr;
201         int count;
202 };
203
204 struct pktgen_dev {
205
206         /*
207          * Try to keep frequent/infrequent used vars. separated.
208          */
209
210         char ifname[IFNAMSIZ];
211         char result[512];
212
213         struct pktgen_thread *pg_thread;        /* the owner */
214         struct list_head list;          /* Used for chaining in the thread's run-queue */
215
216         int running;            /* if this changes to false, the test will stop */
217
218         /* If min != max, then we will either do a linear iteration, or
219          * we will do a random selection from within the range.
220          */
221         __u32 flags;
222         int removal_mark;       /* non-zero => the device is marked for
223                                  * removal by worker thread */
224
225         int min_pkt_size;       /* = ETH_ZLEN; */
226         int max_pkt_size;       /* = ETH_ZLEN; */
227         int nfrags;
228         __u32 delay_us;         /* Default delay */
229         __u32 delay_ns;
230         __u64 count;            /* Default No packets to send */
231         __u64 sofar;            /* How many pkts we've sent so far */
232         __u64 tx_bytes;         /* How many bytes we've transmitted */
233         __u64 errors;           /* Errors when trying to transmit, pkts will be re-sent */
234
235         /* runtime counters relating to clone_skb */
236         __u64 next_tx_us;       /* timestamp of when to tx next */
237         __u32 next_tx_ns;
238
239         __u64 allocated_skbs;
240         __u32 clone_count;
241         int last_ok;            /* Was last skb sent?
242                                  * Or a failed transmit of some sort?  This will keep
243                                  * sequence numbers in order, for example.
244                                  */
245         __u64 started_at;       /* micro-seconds */
246         __u64 stopped_at;       /* micro-seconds */
247         __u64 idle_acc;         /* micro-seconds */
248         __u32 seq_num;
249
250         int clone_skb;          /* Use multiple SKBs during packet gen.  If this number
251                                  * is greater than 1, then that many copies of the same
252                                  * packet will be sent before a new packet is allocated.
253                                  * For instance, if you want to send 1024 identical packets
254                                  * before creating a new packet, set clone_skb to 1024.
255                                  */
256
257         char dst_min[IP_NAME_SZ];       /* IP, ie 1.2.3.4 */
258         char dst_max[IP_NAME_SZ];       /* IP, ie 1.2.3.4 */
259         char src_min[IP_NAME_SZ];       /* IP, ie 1.2.3.4 */
260         char src_max[IP_NAME_SZ];       /* IP, ie 1.2.3.4 */
261
262         struct in6_addr in6_saddr;
263         struct in6_addr in6_daddr;
264         struct in6_addr cur_in6_daddr;
265         struct in6_addr cur_in6_saddr;
266         /* For ranges */
267         struct in6_addr min_in6_daddr;
268         struct in6_addr max_in6_daddr;
269         struct in6_addr min_in6_saddr;
270         struct in6_addr max_in6_saddr;
271
272         /* If we're doing ranges, random or incremental, then this
273          * defines the min/max for those ranges.
274          */
275         __u32 saddr_min;        /* inclusive, source IP address */
276         __u32 saddr_max;        /* exclusive, source IP address */
277         __u32 daddr_min;        /* inclusive, dest IP address */
278         __u32 daddr_max;        /* exclusive, dest IP address */
279
280         __u16 udp_src_min;      /* inclusive, source UDP port */
281         __u16 udp_src_max;      /* exclusive, source UDP port */
282         __u16 udp_dst_min;      /* inclusive, dest UDP port */
283         __u16 udp_dst_max;      /* exclusive, dest UDP port */
284
285         __u32 src_mac_count;    /* How many MACs to iterate through */
286         __u32 dst_mac_count;    /* How many MACs to iterate through */
287
288         unsigned char dst_mac[ETH_ALEN];
289         unsigned char src_mac[ETH_ALEN];
290
291         __u32 cur_dst_mac_offset;
292         __u32 cur_src_mac_offset;
293         __u32 cur_saddr;
294         __u32 cur_daddr;
295         __u16 cur_udp_dst;
296         __u16 cur_udp_src;
297         __u32 cur_pkt_size;
298
299         __u8 hh[14];
300         /* = {
301            0x00, 0x80, 0xC8, 0x79, 0xB3, 0xCB,
302
303            We fill in SRC address later
304            0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
305            0x08, 0x00
306            };
307          */
308         __u16 pad;              /* pad out the hh struct to an even 16 bytes */
309
310         struct sk_buff *skb;    /* skb we are to transmit next, mainly used for when we
311                                  * are transmitting the same one multiple times
312                                  */
313         struct net_device *odev;        /* The out-going device.  Note that the device should
314                                          * have it's pg_info pointer pointing back to this
315                                          * device.  This will be set when the user specifies
316                                          * the out-going device name (not when the inject is
317                                          * started as it used to do.)
318                                          */
319         struct flow_state *flows;
320         unsigned cflows;        /* Concurrent flows (config) */
321         unsigned lflow;         /* Flow length  (config) */
322         unsigned nflows;        /* accumulated flows (stats) */
323 };
324
325 struct pktgen_hdr {
326         __u32 pgh_magic;
327         __u32 seq_num;
328         __u32 tv_sec;
329         __u32 tv_usec;
330 };
331
332 struct pktgen_thread {
333         spinlock_t if_lock;
334         struct list_head if_list;       /* All device here */
335         struct list_head th_list;
336         int removed;
337         char name[32];
338         char result[512];
339         u32 max_before_softirq; /* We'll call do_softirq to prevent starvation. */
340
341         /* Field for thread to receive "posted" events terminate, stop ifs etc. */
342
343         u32 control;
344         int pid;
345         int cpu;
346
347         wait_queue_head_t queue;
348 };
349
350 #define REMOVE 1
351 #define FIND   0
352
353 /*  This code works around the fact that do_div cannot handle two 64-bit
354     numbers, and regular 64-bit division doesn't work on x86 kernels.
355     --Ben
356 */
357
358 #define PG_DIV 0
359
360 /* This was emailed to LMKL by: Chris Caputo <ccaputo@alt.net>
361  * Function copied/adapted/optimized from:
362  *
363  *  nemesis.sourceforge.net/browse/lib/static/intmath/ix86/intmath.c.html
364  *
365  * Copyright 1994, University of Cambridge Computer Laboratory
366  * All Rights Reserved.
367  *
368  */
369 static inline s64 divremdi3(s64 x, s64 y, int type)
370 {
371         u64 a = (x < 0) ? -x : x;
372         u64 b = (y < 0) ? -y : y;
373         u64 res = 0, d = 1;
374
375         if (b > 0) {
376                 while (b < a) {
377                         b <<= 1;
378                         d <<= 1;
379                 }
380         }
381
382         do {
383                 if (a >= b) {
384                         a -= b;
385                         res += d;
386                 }
387                 b >>= 1;
388                 d >>= 1;
389         }
390         while (d);
391
392         if (PG_DIV == type) {
393                 return (((x ^ y) & (1ll << 63)) == 0) ? res : -(s64) res;
394         } else {
395                 return ((x & (1ll << 63)) == 0) ? a : -(s64) a;
396         }
397 }
398
399 /* End of hacks to deal with 64-bit math on x86 */
400
401 /** Convert to milliseconds */
402 static inline __u64 tv_to_ms(const struct timeval *tv)
403 {
404         __u64 ms = tv->tv_usec / 1000;
405         ms += (__u64) tv->tv_sec * (__u64) 1000;
406         return ms;
407 }
408
409 /** Convert to micro-seconds */
410 static inline __u64 tv_to_us(const struct timeval *tv)
411 {
412         __u64 us = tv->tv_usec;
413         us += (__u64) tv->tv_sec * (__u64) 1000000;
414         return us;
415 }
416
417 static inline __u64 pg_div(__u64 n, __u32 base)
418 {
419         __u64 tmp = n;
420         do_div(tmp, base);
421         /* printk("pktgen: pg_div, n: %llu  base: %d  rv: %llu\n",
422            n, base, tmp); */
423         return tmp;
424 }
425
426 static inline __u64 pg_div64(__u64 n, __u64 base)
427 {
428         __u64 tmp = n;
429 /*
430  * How do we know if the architecture we are running on
431  * supports division with 64 bit base?
432  * 
433  */
434 #if defined(__sparc_v9__) || defined(__powerpc64__) || defined(__alpha__) || defined(__x86_64__) || defined(__ia64__)
435
436         do_div(tmp, base);
437 #else
438         tmp = divremdi3(n, base, PG_DIV);
439 #endif
440         return tmp;
441 }
442
443 static inline u32 pktgen_random(void)
444 {
445 #if 0
446         __u32 n;
447         get_random_bytes(&n, 4);
448         return n;
449 #else
450         return net_random();
451 #endif
452 }
453
454 static inline __u64 getCurMs(void)
455 {
456         struct timeval tv;
457         do_gettimeofday(&tv);
458         return tv_to_ms(&tv);
459 }
460
461 static inline __u64 getCurUs(void)
462 {
463         struct timeval tv;
464         do_gettimeofday(&tv);
465         return tv_to_us(&tv);
466 }
467
468 static inline __u64 tv_diff(const struct timeval *a, const struct timeval *b)
469 {
470         return tv_to_us(a) - tv_to_us(b);
471 }
472
473 /* old include end */
474
475 static char version[] __initdata = VERSION;
476
477 static int pktgen_remove_device(struct pktgen_thread *t, struct pktgen_dev *i);
478 static int pktgen_add_device(struct pktgen_thread *t, const char *ifname);
479 static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
480                                           const char *ifname);
481 static int pktgen_device_event(struct notifier_block *, unsigned long, void *);
482 static void pktgen_run_all_threads(void);
483 static void pktgen_stop_all_threads_ifs(void);
484 static int pktgen_stop_device(struct pktgen_dev *pkt_dev);
485 static void pktgen_stop(struct pktgen_thread *t);
486 static void pktgen_clear_counters(struct pktgen_dev *pkt_dev);
487 static int pktgen_mark_device(const char *ifname);
488 static unsigned int scan_ip6(const char *s, char ip[16]);
489 static unsigned int fmt_ip6(char *s, const char ip[16]);
490
491 /* Module parameters, defaults. */
492 static int pg_count_d = 1000;   /* 1000 pkts by default */
493 static int pg_delay_d;
494 static int pg_clone_skb_d;
495 static int debug;
496
497 static DEFINE_MUTEX(pktgen_thread_lock);
498 static LIST_HEAD(pktgen_threads);
499
500 static struct notifier_block pktgen_notifier_block = {
501         .notifier_call = pktgen_device_event,
502 };
503
504 /*
505  * /proc handling functions 
506  *
507  */
508
509 static int pgctrl_show(struct seq_file *seq, void *v)
510 {
511         seq_puts(seq, VERSION);
512         return 0;
513 }
514
515 static ssize_t pgctrl_write(struct file *file, const char __user * buf,
516                             size_t count, loff_t * ppos)
517 {
518         int err = 0;
519         char data[128];
520
521         if (!capable(CAP_NET_ADMIN)) {
522                 err = -EPERM;
523                 goto out;
524         }
525
526         if (count > sizeof(data))
527                 count = sizeof(data);
528
529         if (copy_from_user(data, buf, count)) {
530                 err = -EFAULT;
531                 goto out;
532         }
533         data[count - 1] = 0;    /* Make string */
534
535         if (!strcmp(data, "stop"))
536                 pktgen_stop_all_threads_ifs();
537
538         else if (!strcmp(data, "start"))
539                 pktgen_run_all_threads();
540
541         else
542                 printk("pktgen: Unknown command: %s\n", data);
543
544         err = count;
545
546 out:
547         return err;
548 }
549
550 static int pgctrl_open(struct inode *inode, struct file *file)
551 {
552         return single_open(file, pgctrl_show, PDE(inode)->data);
553 }
554
555 static struct file_operations pktgen_fops = {
556         .owner   = THIS_MODULE,
557         .open    = pgctrl_open,
558         .read    = seq_read,
559         .llseek  = seq_lseek,
560         .write   = pgctrl_write,
561         .release = single_release,
562 };
563
564 static int pktgen_if_show(struct seq_file *seq, void *v)
565 {
566         int i;
567         struct pktgen_dev *pkt_dev = seq->private;
568         __u64 sa;
569         __u64 stopped;
570         __u64 now = getCurUs();
571
572         seq_printf(seq,
573                    "Params: count %llu  min_pkt_size: %u  max_pkt_size: %u\n",
574                    (unsigned long long)pkt_dev->count, pkt_dev->min_pkt_size,
575                    pkt_dev->max_pkt_size);
576
577         seq_printf(seq,
578                    "     frags: %d  delay: %u  clone_skb: %d  ifname: %s\n",
579                    pkt_dev->nfrags,
580                    1000 * pkt_dev->delay_us + pkt_dev->delay_ns,
581                    pkt_dev->clone_skb, pkt_dev->ifname);
582
583         seq_printf(seq, "     flows: %u flowlen: %u\n", pkt_dev->cflows,
584                    pkt_dev->lflow);
585
586         if (pkt_dev->flags & F_IPV6) {
587                 char b1[128], b2[128], b3[128];
588                 fmt_ip6(b1, pkt_dev->in6_saddr.s6_addr);
589                 fmt_ip6(b2, pkt_dev->min_in6_saddr.s6_addr);
590                 fmt_ip6(b3, pkt_dev->max_in6_saddr.s6_addr);
591                 seq_printf(seq,
592                            "     saddr: %s  min_saddr: %s  max_saddr: %s\n", b1,
593                            b2, b3);
594
595                 fmt_ip6(b1, pkt_dev->in6_daddr.s6_addr);
596                 fmt_ip6(b2, pkt_dev->min_in6_daddr.s6_addr);
597                 fmt_ip6(b3, pkt_dev->max_in6_daddr.s6_addr);
598                 seq_printf(seq,
599                            "     daddr: %s  min_daddr: %s  max_daddr: %s\n", b1,
600                            b2, b3);
601
602         } else
603                 seq_printf(seq,
604                            "     dst_min: %s  dst_max: %s\n     src_min: %s  src_max: %s\n",
605                            pkt_dev->dst_min, pkt_dev->dst_max, pkt_dev->src_min,
606                            pkt_dev->src_max);
607
608         seq_puts(seq, "     src_mac: ");
609
610         if (is_zero_ether_addr(pkt_dev->src_mac))
611                 for (i = 0; i < 6; i++)
612                         seq_printf(seq, "%02X%s", pkt_dev->odev->dev_addr[i],
613                                    i == 5 ? "  " : ":");
614         else
615                 for (i = 0; i < 6; i++)
616                         seq_printf(seq, "%02X%s", pkt_dev->src_mac[i],
617                                    i == 5 ? "  " : ":");
618
619         seq_printf(seq, "dst_mac: ");
620         for (i = 0; i < 6; i++)
621                 seq_printf(seq, "%02X%s", pkt_dev->dst_mac[i],
622                            i == 5 ? "\n" : ":");
623
624         seq_printf(seq,
625                    "     udp_src_min: %d  udp_src_max: %d  udp_dst_min: %d  udp_dst_max: %d\n",
626                    pkt_dev->udp_src_min, pkt_dev->udp_src_max,
627                    pkt_dev->udp_dst_min, pkt_dev->udp_dst_max);
628
629         seq_printf(seq,
630                    "     src_mac_count: %d  dst_mac_count: %d \n     Flags: ",
631                    pkt_dev->src_mac_count, pkt_dev->dst_mac_count);
632
633         if (pkt_dev->flags & F_IPV6)
634                 seq_printf(seq, "IPV6  ");
635
636         if (pkt_dev->flags & F_IPSRC_RND)
637                 seq_printf(seq, "IPSRC_RND  ");
638
639         if (pkt_dev->flags & F_IPDST_RND)
640                 seq_printf(seq, "IPDST_RND  ");
641
642         if (pkt_dev->flags & F_TXSIZE_RND)
643                 seq_printf(seq, "TXSIZE_RND  ");
644
645         if (pkt_dev->flags & F_UDPSRC_RND)
646                 seq_printf(seq, "UDPSRC_RND  ");
647
648         if (pkt_dev->flags & F_UDPDST_RND)
649                 seq_printf(seq, "UDPDST_RND  ");
650
651         if (pkt_dev->flags & F_MACSRC_RND)
652                 seq_printf(seq, "MACSRC_RND  ");
653
654         if (pkt_dev->flags & F_MACDST_RND)
655                 seq_printf(seq, "MACDST_RND  ");
656
657         seq_puts(seq, "\n");
658
659         sa = pkt_dev->started_at;
660         stopped = pkt_dev->stopped_at;
661         if (pkt_dev->running)
662                 stopped = now;  /* not really stopped, more like last-running-at */
663
664         seq_printf(seq,
665                    "Current:\n     pkts-sofar: %llu  errors: %llu\n     started: %lluus  stopped: %lluus idle: %lluus\n",
666                    (unsigned long long)pkt_dev->sofar,
667                    (unsigned long long)pkt_dev->errors, (unsigned long long)sa,
668                    (unsigned long long)stopped,
669                    (unsigned long long)pkt_dev->idle_acc);
670
671         seq_printf(seq,
672                    "     seq_num: %d  cur_dst_mac_offset: %d  cur_src_mac_offset: %d\n",
673                    pkt_dev->seq_num, pkt_dev->cur_dst_mac_offset,
674                    pkt_dev->cur_src_mac_offset);
675
676         if (pkt_dev->flags & F_IPV6) {
677                 char b1[128], b2[128];
678                 fmt_ip6(b1, pkt_dev->cur_in6_daddr.s6_addr);
679                 fmt_ip6(b2, pkt_dev->cur_in6_saddr.s6_addr);
680                 seq_printf(seq, "     cur_saddr: %s  cur_daddr: %s\n", b2, b1);
681         } else
682                 seq_printf(seq, "     cur_saddr: 0x%x  cur_daddr: 0x%x\n",
683                            pkt_dev->cur_saddr, pkt_dev->cur_daddr);
684
685         seq_printf(seq, "     cur_udp_dst: %d  cur_udp_src: %d\n",
686                    pkt_dev->cur_udp_dst, pkt_dev->cur_udp_src);
687
688         seq_printf(seq, "     flows: %u\n", pkt_dev->nflows);
689
690         if (pkt_dev->result[0])
691                 seq_printf(seq, "Result: %s\n", pkt_dev->result);
692         else
693                 seq_printf(seq, "Result: Idle\n");
694
695         return 0;
696 }
697
698 static int count_trail_chars(const char __user * user_buffer,
699                              unsigned int maxlen)
700 {
701         int i;
702
703         for (i = 0; i < maxlen; i++) {
704                 char c;
705                 if (get_user(c, &user_buffer[i]))
706                         return -EFAULT;
707                 switch (c) {
708                 case '\"':
709                 case '\n':
710                 case '\r':
711                 case '\t':
712                 case ' ':
713                 case '=':
714                         break;
715                 default:
716                         goto done;
717                 };
718         }
719 done:
720         return i;
721 }
722
723 static unsigned long num_arg(const char __user * user_buffer,
724                              unsigned long maxlen, unsigned long *num)
725 {
726         int i = 0;
727         *num = 0;
728
729         for (; i < maxlen; i++) {
730                 char c;
731                 if (get_user(c, &user_buffer[i]))
732                         return -EFAULT;
733                 if ((c >= '0') && (c <= '9')) {
734                         *num *= 10;
735                         *num += c - '0';
736                 } else
737                         break;
738         }
739         return i;
740 }
741
742 static int strn_len(const char __user * user_buffer, unsigned int maxlen)
743 {
744         int i = 0;
745
746         for (; i < maxlen; i++) {
747                 char c;
748                 if (get_user(c, &user_buffer[i]))
749                         return -EFAULT;
750                 switch (c) {
751                 case '\"':
752                 case '\n':
753                 case '\r':
754                 case '\t':
755                 case ' ':
756                         goto done_str;
757                         break;
758                 default:
759                         break;
760                 };
761         }
762 done_str:
763         return i;
764 }
765
766 static ssize_t pktgen_if_write(struct file *file,
767                                const char __user * user_buffer, size_t count,
768                                loff_t * offset)
769 {
770         struct seq_file *seq = (struct seq_file *)file->private_data;
771         struct pktgen_dev *pkt_dev = seq->private;
772         int i = 0, max, len;
773         char name[16], valstr[32];
774         unsigned long value = 0;
775         char *pg_result = NULL;
776         int tmp = 0;
777         char buf[128];
778
779         pg_result = &(pkt_dev->result[0]);
780
781         if (count < 1) {
782                 printk("pktgen: wrong command format\n");
783                 return -EINVAL;
784         }
785
786         max = count - i;
787         tmp = count_trail_chars(&user_buffer[i], max);
788         if (tmp < 0) {
789                 printk("pktgen: illegal format\n");
790                 return tmp;
791         }
792         i += tmp;
793
794         /* Read variable name */
795
796         len = strn_len(&user_buffer[i], sizeof(name) - 1);
797         if (len < 0) {
798                 return len;
799         }
800         memset(name, 0, sizeof(name));
801         if (copy_from_user(name, &user_buffer[i], len))
802                 return -EFAULT;
803         i += len;
804
805         max = count - i;
806         len = count_trail_chars(&user_buffer[i], max);
807         if (len < 0)
808                 return len;
809
810         i += len;
811
812         if (debug) {
813                 char tb[count + 1];
814                 if (copy_from_user(tb, user_buffer, count))
815                         return -EFAULT;
816                 tb[count] = 0;
817                 printk("pktgen: %s,%lu  buffer -:%s:-\n", name,
818                        (unsigned long)count, tb);
819         }
820
821         if (!strcmp(name, "min_pkt_size")) {
822                 len = num_arg(&user_buffer[i], 10, &value);
823                 if (len < 0) {
824                         return len;
825                 }
826                 i += len;
827                 if (value < 14 + 20 + 8)
828                         value = 14 + 20 + 8;
829                 if (value != pkt_dev->min_pkt_size) {
830                         pkt_dev->min_pkt_size = value;
831                         pkt_dev->cur_pkt_size = value;
832                 }
833                 sprintf(pg_result, "OK: min_pkt_size=%u",
834                         pkt_dev->min_pkt_size);
835                 return count;
836         }
837
838         if (!strcmp(name, "max_pkt_size")) {
839                 len = num_arg(&user_buffer[i], 10, &value);
840                 if (len < 0) {
841                         return len;
842                 }
843                 i += len;
844                 if (value < 14 + 20 + 8)
845                         value = 14 + 20 + 8;
846                 if (value != pkt_dev->max_pkt_size) {
847                         pkt_dev->max_pkt_size = value;
848                         pkt_dev->cur_pkt_size = value;
849                 }
850                 sprintf(pg_result, "OK: max_pkt_size=%u",
851                         pkt_dev->max_pkt_size);
852                 return count;
853         }
854
855         /* Shortcut for min = max */
856
857         if (!strcmp(name, "pkt_size")) {
858                 len = num_arg(&user_buffer[i], 10, &value);
859                 if (len < 0) {
860                         return len;
861                 }
862                 i += len;
863                 if (value < 14 + 20 + 8)
864                         value = 14 + 20 + 8;
865                 if (value != pkt_dev->min_pkt_size) {
866                         pkt_dev->min_pkt_size = value;
867                         pkt_dev->max_pkt_size = value;
868                         pkt_dev->cur_pkt_size = value;
869                 }
870                 sprintf(pg_result, "OK: pkt_size=%u", pkt_dev->min_pkt_size);
871                 return count;
872         }
873
874         if (!strcmp(name, "debug")) {
875                 len = num_arg(&user_buffer[i], 10, &value);
876                 if (len < 0) {
877                         return len;
878                 }
879                 i += len;
880                 debug = value;
881                 sprintf(pg_result, "OK: debug=%u", debug);
882                 return count;
883         }
884
885         if (!strcmp(name, "frags")) {
886                 len = num_arg(&user_buffer[i], 10, &value);
887                 if (len < 0) {
888                         return len;
889                 }
890                 i += len;
891                 pkt_dev->nfrags = value;
892                 sprintf(pg_result, "OK: frags=%u", pkt_dev->nfrags);
893                 return count;
894         }
895         if (!strcmp(name, "delay")) {
896                 len = num_arg(&user_buffer[i], 10, &value);
897                 if (len < 0) {
898                         return len;
899                 }
900                 i += len;
901                 if (value == 0x7FFFFFFF) {
902                         pkt_dev->delay_us = 0x7FFFFFFF;
903                         pkt_dev->delay_ns = 0;
904                 } else {
905                         pkt_dev->delay_us = value / 1000;
906                         pkt_dev->delay_ns = value % 1000;
907                 }
908                 sprintf(pg_result, "OK: delay=%u",
909                         1000 * pkt_dev->delay_us + pkt_dev->delay_ns);
910                 return count;
911         }
912         if (!strcmp(name, "udp_src_min")) {
913                 len = num_arg(&user_buffer[i], 10, &value);
914                 if (len < 0) {
915                         return len;
916                 }
917                 i += len;
918                 if (value != pkt_dev->udp_src_min) {
919                         pkt_dev->udp_src_min = value;
920                         pkt_dev->cur_udp_src = value;
921                 }
922                 sprintf(pg_result, "OK: udp_src_min=%u", pkt_dev->udp_src_min);
923                 return count;
924         }
925         if (!strcmp(name, "udp_dst_min")) {
926                 len = num_arg(&user_buffer[i], 10, &value);
927                 if (len < 0) {
928                         return len;
929                 }
930                 i += len;
931                 if (value != pkt_dev->udp_dst_min) {
932                         pkt_dev->udp_dst_min = value;
933                         pkt_dev->cur_udp_dst = value;
934                 }
935                 sprintf(pg_result, "OK: udp_dst_min=%u", pkt_dev->udp_dst_min);
936                 return count;
937         }
938         if (!strcmp(name, "udp_src_max")) {
939                 len = num_arg(&user_buffer[i], 10, &value);
940                 if (len < 0) {
941                         return len;
942                 }
943                 i += len;
944                 if (value != pkt_dev->udp_src_max) {
945                         pkt_dev->udp_src_max = value;
946                         pkt_dev->cur_udp_src = value;
947                 }
948                 sprintf(pg_result, "OK: udp_src_max=%u", pkt_dev->udp_src_max);
949                 return count;
950         }
951         if (!strcmp(name, "udp_dst_max")) {
952                 len = num_arg(&user_buffer[i], 10, &value);
953                 if (len < 0) {
954                         return len;
955                 }
956                 i += len;
957                 if (value != pkt_dev->udp_dst_max) {
958                         pkt_dev->udp_dst_max = value;
959                         pkt_dev->cur_udp_dst = value;
960                 }
961                 sprintf(pg_result, "OK: udp_dst_max=%u", pkt_dev->udp_dst_max);
962                 return count;
963         }
964         if (!strcmp(name, "clone_skb")) {
965                 len = num_arg(&user_buffer[i], 10, &value);
966                 if (len < 0) {
967                         return len;
968                 }
969                 i += len;
970                 pkt_dev->clone_skb = value;
971
972                 sprintf(pg_result, "OK: clone_skb=%d", pkt_dev->clone_skb);
973                 return count;
974         }
975         if (!strcmp(name, "count")) {
976                 len = num_arg(&user_buffer[i], 10, &value);
977                 if (len < 0) {
978                         return len;
979                 }
980                 i += len;
981                 pkt_dev->count = value;
982                 sprintf(pg_result, "OK: count=%llu",
983                         (unsigned long long)pkt_dev->count);
984                 return count;
985         }
986         if (!strcmp(name, "src_mac_count")) {
987                 len = num_arg(&user_buffer[i], 10, &value);
988                 if (len < 0) {
989                         return len;
990                 }
991                 i += len;
992                 if (pkt_dev->src_mac_count != value) {
993                         pkt_dev->src_mac_count = value;
994                         pkt_dev->cur_src_mac_offset = 0;
995                 }
996                 sprintf(pg_result, "OK: src_mac_count=%d",
997                         pkt_dev->src_mac_count);
998                 return count;
999         }
1000         if (!strcmp(name, "dst_mac_count")) {
1001                 len = num_arg(&user_buffer[i], 10, &value);
1002                 if (len < 0) {
1003                         return len;
1004                 }
1005                 i += len;
1006                 if (pkt_dev->dst_mac_count != value) {
1007                         pkt_dev->dst_mac_count = value;
1008                         pkt_dev->cur_dst_mac_offset = 0;
1009                 }
1010                 sprintf(pg_result, "OK: dst_mac_count=%d",
1011                         pkt_dev->dst_mac_count);
1012                 return count;
1013         }
1014         if (!strcmp(name, "flag")) {
1015                 char f[32];
1016                 memset(f, 0, 32);
1017                 len = strn_len(&user_buffer[i], sizeof(f) - 1);
1018                 if (len < 0) {
1019                         return len;
1020                 }
1021                 if (copy_from_user(f, &user_buffer[i], len))
1022                         return -EFAULT;
1023                 i += len;
1024                 if (strcmp(f, "IPSRC_RND") == 0)
1025                         pkt_dev->flags |= F_IPSRC_RND;
1026
1027                 else if (strcmp(f, "!IPSRC_RND") == 0)
1028                         pkt_dev->flags &= ~F_IPSRC_RND;
1029
1030                 else if (strcmp(f, "TXSIZE_RND") == 0)
1031                         pkt_dev->flags |= F_TXSIZE_RND;
1032
1033                 else if (strcmp(f, "!TXSIZE_RND") == 0)
1034                         pkt_dev->flags &= ~F_TXSIZE_RND;
1035
1036                 else if (strcmp(f, "IPDST_RND") == 0)
1037                         pkt_dev->flags |= F_IPDST_RND;
1038
1039                 else if (strcmp(f, "!IPDST_RND") == 0)
1040                         pkt_dev->flags &= ~F_IPDST_RND;
1041
1042                 else if (strcmp(f, "UDPSRC_RND") == 0)
1043                         pkt_dev->flags |= F_UDPSRC_RND;
1044
1045                 else if (strcmp(f, "!UDPSRC_RND") == 0)
1046                         pkt_dev->flags &= ~F_UDPSRC_RND;
1047
1048                 else if (strcmp(f, "UDPDST_RND") == 0)
1049                         pkt_dev->flags |= F_UDPDST_RND;
1050
1051                 else if (strcmp(f, "!UDPDST_RND") == 0)
1052                         pkt_dev->flags &= ~F_UDPDST_RND;
1053
1054                 else if (strcmp(f, "MACSRC_RND") == 0)
1055                         pkt_dev->flags |= F_MACSRC_RND;
1056
1057                 else if (strcmp(f, "!MACSRC_RND") == 0)
1058                         pkt_dev->flags &= ~F_MACSRC_RND;
1059
1060                 else if (strcmp(f, "MACDST_RND") == 0)
1061                         pkt_dev->flags |= F_MACDST_RND;
1062
1063                 else if (strcmp(f, "!MACDST_RND") == 0)
1064                         pkt_dev->flags &= ~F_MACDST_RND;
1065
1066                 else {
1067                         sprintf(pg_result,
1068                                 "Flag -:%s:- unknown\nAvailable flags, (prepend ! to un-set flag):\n%s",
1069                                 f,
1070                                 "IPSRC_RND, IPDST_RND, TXSIZE_RND, UDPSRC_RND, UDPDST_RND, MACSRC_RND, MACDST_RND\n");
1071                         return count;
1072                 }
1073                 sprintf(pg_result, "OK: flags=0x%x", pkt_dev->flags);
1074                 return count;
1075         }
1076         if (!strcmp(name, "dst_min") || !strcmp(name, "dst")) {
1077                 len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_min) - 1);
1078                 if (len < 0) {
1079                         return len;
1080                 }
1081
1082                 if (copy_from_user(buf, &user_buffer[i], len))
1083                         return -EFAULT;
1084                 buf[len] = 0;
1085                 if (strcmp(buf, pkt_dev->dst_min) != 0) {
1086                         memset(pkt_dev->dst_min, 0, sizeof(pkt_dev->dst_min));
1087                         strncpy(pkt_dev->dst_min, buf, len);
1088                         pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
1089                         pkt_dev->cur_daddr = pkt_dev->daddr_min;
1090                 }
1091                 if (debug)
1092                         printk("pktgen: dst_min set to: %s\n",
1093                                pkt_dev->dst_min);
1094                 i += len;
1095                 sprintf(pg_result, "OK: dst_min=%s", pkt_dev->dst_min);
1096                 return count;
1097         }
1098         if (!strcmp(name, "dst_max")) {
1099                 len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_max) - 1);
1100                 if (len < 0) {
1101                         return len;
1102                 }
1103
1104                 if (copy_from_user(buf, &user_buffer[i], len))
1105                         return -EFAULT;
1106
1107                 buf[len] = 0;
1108                 if (strcmp(buf, pkt_dev->dst_max) != 0) {
1109                         memset(pkt_dev->dst_max, 0, sizeof(pkt_dev->dst_max));
1110                         strncpy(pkt_dev->dst_max, buf, len);
1111                         pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
1112                         pkt_dev->cur_daddr = pkt_dev->daddr_max;
1113                 }
1114                 if (debug)
1115                         printk("pktgen: dst_max set to: %s\n",
1116                                pkt_dev->dst_max);
1117                 i += len;
1118                 sprintf(pg_result, "OK: dst_max=%s", pkt_dev->dst_max);
1119                 return count;
1120         }
1121         if (!strcmp(name, "dst6")) {
1122                 len = strn_len(&user_buffer[i], sizeof(buf) - 1);
1123                 if (len < 0)
1124                         return len;
1125
1126                 pkt_dev->flags |= F_IPV6;
1127
1128                 if (copy_from_user(buf, &user_buffer[i], len))
1129                         return -EFAULT;
1130                 buf[len] = 0;
1131
1132                 scan_ip6(buf, pkt_dev->in6_daddr.s6_addr);
1133                 fmt_ip6(buf, pkt_dev->in6_daddr.s6_addr);
1134
1135                 ipv6_addr_copy(&pkt_dev->cur_in6_daddr, &pkt_dev->in6_daddr);
1136
1137                 if (debug)
1138                         printk("pktgen: dst6 set to: %s\n", buf);
1139
1140                 i += len;
1141                 sprintf(pg_result, "OK: dst6=%s", buf);
1142                 return count;
1143         }
1144         if (!strcmp(name, "dst6_min")) {
1145                 len = strn_len(&user_buffer[i], sizeof(buf) - 1);
1146                 if (len < 0)
1147                         return len;
1148
1149                 pkt_dev->flags |= F_IPV6;
1150
1151                 if (copy_from_user(buf, &user_buffer[i], len))
1152                         return -EFAULT;
1153                 buf[len] = 0;
1154
1155                 scan_ip6(buf, pkt_dev->min_in6_daddr.s6_addr);
1156                 fmt_ip6(buf, pkt_dev->min_in6_daddr.s6_addr);
1157
1158                 ipv6_addr_copy(&pkt_dev->cur_in6_daddr,
1159                                &pkt_dev->min_in6_daddr);
1160                 if (debug)
1161                         printk("pktgen: dst6_min set to: %s\n", buf);
1162
1163                 i += len;
1164                 sprintf(pg_result, "OK: dst6_min=%s", buf);
1165                 return count;
1166         }
1167         if (!strcmp(name, "dst6_max")) {
1168                 len = strn_len(&user_buffer[i], sizeof(buf) - 1);
1169                 if (len < 0)
1170                         return len;
1171
1172                 pkt_dev->flags |= F_IPV6;
1173
1174                 if (copy_from_user(buf, &user_buffer[i], len))
1175                         return -EFAULT;
1176                 buf[len] = 0;
1177
1178                 scan_ip6(buf, pkt_dev->max_in6_daddr.s6_addr);
1179                 fmt_ip6(buf, pkt_dev->max_in6_daddr.s6_addr);
1180
1181                 if (debug)
1182                         printk("pktgen: dst6_max set to: %s\n", buf);
1183
1184                 i += len;
1185                 sprintf(pg_result, "OK: dst6_max=%s", buf);
1186                 return count;
1187         }
1188         if (!strcmp(name, "src6")) {
1189                 len = strn_len(&user_buffer[i], sizeof(buf) - 1);
1190                 if (len < 0)
1191                         return len;
1192
1193                 pkt_dev->flags |= F_IPV6;
1194
1195                 if (copy_from_user(buf, &user_buffer[i], len))
1196                         return -EFAULT;
1197                 buf[len] = 0;
1198
1199                 scan_ip6(buf, pkt_dev->in6_saddr.s6_addr);
1200                 fmt_ip6(buf, pkt_dev->in6_saddr.s6_addr);
1201
1202                 ipv6_addr_copy(&pkt_dev->cur_in6_saddr, &pkt_dev->in6_saddr);
1203
1204                 if (debug)
1205                         printk("pktgen: src6 set to: %s\n", buf);
1206
1207                 i += len;
1208                 sprintf(pg_result, "OK: src6=%s", buf);
1209                 return count;
1210         }
1211         if (!strcmp(name, "src_min")) {
1212                 len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_min) - 1);
1213                 if (len < 0) {
1214                         return len;
1215                 }
1216                 if (copy_from_user(buf, &user_buffer[i], len))
1217                         return -EFAULT;
1218                 buf[len] = 0;
1219                 if (strcmp(buf, pkt_dev->src_min) != 0) {
1220                         memset(pkt_dev->src_min, 0, sizeof(pkt_dev->src_min));
1221                         strncpy(pkt_dev->src_min, buf, len);
1222                         pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
1223                         pkt_dev->cur_saddr = pkt_dev->saddr_min;
1224                 }
1225                 if (debug)
1226                         printk("pktgen: src_min set to: %s\n",
1227                                pkt_dev->src_min);
1228                 i += len;
1229                 sprintf(pg_result, "OK: src_min=%s", pkt_dev->src_min);
1230                 return count;
1231         }
1232         if (!strcmp(name, "src_max")) {
1233                 len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_max) - 1);
1234                 if (len < 0) {
1235                         return len;
1236                 }
1237                 if (copy_from_user(buf, &user_buffer[i], len))
1238                         return -EFAULT;
1239                 buf[len] = 0;
1240                 if (strcmp(buf, pkt_dev->src_max) != 0) {
1241                         memset(pkt_dev->src_max, 0, sizeof(pkt_dev->src_max));
1242                         strncpy(pkt_dev->src_max, buf, len);
1243                         pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
1244                         pkt_dev->cur_saddr = pkt_dev->saddr_max;
1245                 }
1246                 if (debug)
1247                         printk("pktgen: src_max set to: %s\n",
1248                                pkt_dev->src_max);
1249                 i += len;
1250                 sprintf(pg_result, "OK: src_max=%s", pkt_dev->src_max);
1251                 return count;
1252         }
1253         if (!strcmp(name, "dst_mac")) {
1254                 char *v = valstr;
1255                 unsigned char old_dmac[ETH_ALEN];
1256                 unsigned char *m = pkt_dev->dst_mac;
1257                 memcpy(old_dmac, pkt_dev->dst_mac, ETH_ALEN);
1258
1259                 len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
1260                 if (len < 0) {
1261                         return len;
1262                 }
1263                 memset(valstr, 0, sizeof(valstr));
1264                 if (copy_from_user(valstr, &user_buffer[i], len))
1265                         return -EFAULT;
1266                 i += len;
1267
1268                 for (*m = 0; *v && m < pkt_dev->dst_mac + 6; v++) {
1269                         if (*v >= '0' && *v <= '9') {
1270                                 *m *= 16;
1271                                 *m += *v - '0';
1272                         }
1273                         if (*v >= 'A' && *v <= 'F') {
1274                                 *m *= 16;
1275                                 *m += *v - 'A' + 10;
1276                         }
1277                         if (*v >= 'a' && *v <= 'f') {
1278                                 *m *= 16;
1279                                 *m += *v - 'a' + 10;
1280                         }
1281                         if (*v == ':') {
1282                                 m++;
1283                                 *m = 0;
1284                         }
1285                 }
1286
1287                 /* Set up Dest MAC */
1288                 if (compare_ether_addr(old_dmac, pkt_dev->dst_mac))
1289                         memcpy(&(pkt_dev->hh[0]), pkt_dev->dst_mac, ETH_ALEN);
1290
1291                 sprintf(pg_result, "OK: dstmac");
1292                 return count;
1293         }
1294         if (!strcmp(name, "src_mac")) {
1295                 char *v = valstr;
1296                 unsigned char *m = pkt_dev->src_mac;
1297
1298                 len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
1299                 if (len < 0) {
1300                         return len;
1301                 }
1302                 memset(valstr, 0, sizeof(valstr));
1303                 if (copy_from_user(valstr, &user_buffer[i], len))
1304                         return -EFAULT;
1305                 i += len;
1306
1307                 for (*m = 0; *v && m < pkt_dev->src_mac + 6; v++) {
1308                         if (*v >= '0' && *v <= '9') {
1309                                 *m *= 16;
1310                                 *m += *v - '0';
1311                         }
1312                         if (*v >= 'A' && *v <= 'F') {
1313                                 *m *= 16;
1314                                 *m += *v - 'A' + 10;
1315                         }
1316                         if (*v >= 'a' && *v <= 'f') {
1317                                 *m *= 16;
1318                                 *m += *v - 'a' + 10;
1319                         }
1320                         if (*v == ':') {
1321                                 m++;
1322                                 *m = 0;
1323                         }
1324                 }
1325
1326                 sprintf(pg_result, "OK: srcmac");
1327                 return count;
1328         }
1329
1330         if (!strcmp(name, "clear_counters")) {
1331                 pktgen_clear_counters(pkt_dev);
1332                 sprintf(pg_result, "OK: Clearing counters.\n");
1333                 return count;
1334         }
1335
1336         if (!strcmp(name, "flows")) {
1337                 len = num_arg(&user_buffer[i], 10, &value);
1338                 if (len < 0) {
1339                         return len;
1340                 }
1341                 i += len;
1342                 if (value > MAX_CFLOWS)
1343                         value = MAX_CFLOWS;
1344
1345                 pkt_dev->cflows = value;
1346                 sprintf(pg_result, "OK: flows=%u", pkt_dev->cflows);
1347                 return count;
1348         }
1349
1350         if (!strcmp(name, "flowlen")) {
1351                 len = num_arg(&user_buffer[i], 10, &value);
1352                 if (len < 0) {
1353                         return len;
1354                 }
1355                 i += len;
1356                 pkt_dev->lflow = value;
1357                 sprintf(pg_result, "OK: flowlen=%u", pkt_dev->lflow);
1358                 return count;
1359         }
1360
1361         sprintf(pkt_dev->result, "No such parameter \"%s\"", name);
1362         return -EINVAL;
1363 }
1364
1365 static int pktgen_if_open(struct inode *inode, struct file *file)
1366 {
1367         return single_open(file, pktgen_if_show, PDE(inode)->data);
1368 }
1369
1370 static struct file_operations pktgen_if_fops = {
1371         .owner   = THIS_MODULE,
1372         .open    = pktgen_if_open,
1373         .read    = seq_read,
1374         .llseek  = seq_lseek,
1375         .write   = pktgen_if_write,
1376         .release = single_release,
1377 };
1378
1379 static int pktgen_thread_show(struct seq_file *seq, void *v)
1380 {
1381         struct pktgen_thread *t = seq->private;
1382         struct pktgen_dev *pkt_dev;
1383
1384         BUG_ON(!t);
1385
1386         seq_printf(seq, "Name: %s  max_before_softirq: %d\n",
1387                    t->name, t->max_before_softirq);
1388
1389         seq_printf(seq, "Running: ");
1390
1391         if_lock(t);
1392         list_for_each_entry(pkt_dev, &t->if_list, list)
1393                 if (pkt_dev->running)
1394                         seq_printf(seq, "%s ", pkt_dev->ifname);
1395
1396         seq_printf(seq, "\nStopped: ");
1397
1398         list_for_each_entry(pkt_dev, &t->if_list, list)
1399                 if (!pkt_dev->running)
1400                         seq_printf(seq, "%s ", pkt_dev->ifname);
1401
1402         if (t->result[0])
1403                 seq_printf(seq, "\nResult: %s\n", t->result);
1404         else
1405                 seq_printf(seq, "\nResult: NA\n");
1406
1407         if_unlock(t);
1408
1409         return 0;
1410 }
1411
1412 static ssize_t pktgen_thread_write(struct file *file,
1413                                    const char __user * user_buffer,
1414                                    size_t count, loff_t * offset)
1415 {
1416         struct seq_file *seq = (struct seq_file *)file->private_data;
1417         struct pktgen_thread *t = seq->private;
1418         int i = 0, max, len, ret;
1419         char name[40];
1420         char *pg_result;
1421         unsigned long value = 0;
1422
1423         if (count < 1) {
1424                 //      sprintf(pg_result, "Wrong command format");
1425                 return -EINVAL;
1426         }
1427
1428         max = count - i;
1429         len = count_trail_chars(&user_buffer[i], max);
1430         if (len < 0)
1431                 return len;
1432
1433         i += len;
1434
1435         /* Read variable name */
1436
1437         len = strn_len(&user_buffer[i], sizeof(name) - 1);
1438         if (len < 0)
1439                 return len;
1440
1441         memset(name, 0, sizeof(name));
1442         if (copy_from_user(name, &user_buffer[i], len))
1443                 return -EFAULT;
1444         i += len;
1445
1446         max = count - i;
1447         len = count_trail_chars(&user_buffer[i], max);
1448         if (len < 0)
1449                 return len;
1450
1451         i += len;
1452
1453         if (debug)
1454                 printk("pktgen: t=%s, count=%lu\n", name, (unsigned long)count);
1455
1456         if (!t) {
1457                 printk("pktgen: ERROR: No thread\n");
1458                 ret = -EINVAL;
1459                 goto out;
1460         }
1461
1462         pg_result = &(t->result[0]);
1463
1464         if (!strcmp(name, "add_device")) {
1465                 char f[32];
1466                 memset(f, 0, 32);
1467                 len = strn_len(&user_buffer[i], sizeof(f) - 1);
1468                 if (len < 0) {
1469                         ret = len;
1470                         goto out;
1471                 }
1472                 if (copy_from_user(f, &user_buffer[i], len))
1473                         return -EFAULT;
1474                 i += len;
1475                 thread_lock();
1476                 pktgen_add_device(t, f);
1477                 thread_unlock();
1478                 ret = count;
1479                 sprintf(pg_result, "OK: add_device=%s", f);
1480                 goto out;
1481         }
1482
1483         if (!strcmp(name, "rem_device_all")) {
1484                 thread_lock();
1485                 t->control |= T_REMDEVALL;
1486                 thread_unlock();
1487                 schedule_timeout_interruptible(msecs_to_jiffies(125));  /* Propagate thread->control  */
1488                 ret = count;
1489                 sprintf(pg_result, "OK: rem_device_all");
1490                 goto out;
1491         }
1492
1493         if (!strcmp(name, "max_before_softirq")) {
1494                 len = num_arg(&user_buffer[i], 10, &value);
1495                 thread_lock();
1496                 t->max_before_softirq = value;
1497                 thread_unlock();
1498                 ret = count;
1499                 sprintf(pg_result, "OK: max_before_softirq=%lu", value);
1500                 goto out;
1501         }
1502
1503         ret = -EINVAL;
1504 out:
1505         return ret;
1506 }
1507
1508 static int pktgen_thread_open(struct inode *inode, struct file *file)
1509 {
1510         return single_open(file, pktgen_thread_show, PDE(inode)->data);
1511 }
1512
1513 static struct file_operations pktgen_thread_fops = {
1514         .owner   = THIS_MODULE,
1515         .open    = pktgen_thread_open,
1516         .read    = seq_read,
1517         .llseek  = seq_lseek,
1518         .write   = pktgen_thread_write,
1519         .release = single_release,
1520 };
1521
1522 /* Think find or remove for NN */
1523 static struct pktgen_dev *__pktgen_NN_threads(const char *ifname, int remove)
1524 {
1525         struct pktgen_thread *t;
1526         struct pktgen_dev *pkt_dev = NULL;
1527
1528         list_for_each_entry(t, &pktgen_threads, th_list) {
1529                 pkt_dev = pktgen_find_dev(t, ifname);
1530                 if (pkt_dev) {
1531                         if (remove) {
1532                                 if_lock(t);
1533                                 pkt_dev->removal_mark = 1;
1534                                 t->control |= T_REMDEV;
1535                                 if_unlock(t);
1536                         }
1537                         break;
1538                 }
1539         }
1540         return pkt_dev;
1541 }
1542
1543 /*
1544  * mark a device for removal
1545  */
1546 static int pktgen_mark_device(const char *ifname)
1547 {
1548         struct pktgen_dev *pkt_dev = NULL;
1549         const int max_tries = 10, msec_per_try = 125;
1550         int i = 0;
1551         int ret = 0;
1552
1553         thread_lock();
1554         PG_DEBUG(printk("pktgen: pktgen_mark_device marking %s for removal\n",
1555                         ifname));
1556
1557         while (1) {
1558
1559                 pkt_dev = __pktgen_NN_threads(ifname, REMOVE);
1560                 if (pkt_dev == NULL)
1561                         break;  /* success */
1562
1563                 thread_unlock();
1564                 PG_DEBUG(printk("pktgen: pktgen_mark_device waiting for %s "
1565                                 "to disappear....\n", ifname));
1566                 schedule_timeout_interruptible(msecs_to_jiffies(msec_per_try));
1567                 thread_lock();
1568
1569                 if (++i >= max_tries) {
1570                         printk("pktgen_mark_device: timed out after waiting "
1571                                "%d msec for device %s to be removed\n",
1572                                msec_per_try * i, ifname);
1573                         ret = 1;
1574                         break;
1575                 }
1576
1577         }
1578
1579         thread_unlock();
1580
1581         return ret;
1582 }
1583
1584 static int pktgen_device_event(struct notifier_block *unused,
1585                                unsigned long event, void *ptr)
1586 {
1587         struct net_device *dev = (struct net_device *)(ptr);
1588
1589         /* It is OK that we do not hold the group lock right now,
1590          * as we run under the RTNL lock.
1591          */
1592
1593         switch (event) {
1594         case NETDEV_CHANGEADDR:
1595         case NETDEV_GOING_DOWN:
1596         case NETDEV_DOWN:
1597         case NETDEV_UP:
1598                 /* Ignore for now */
1599                 break;
1600
1601         case NETDEV_UNREGISTER:
1602                 pktgen_mark_device(dev->name);
1603                 break;
1604         };
1605
1606         return NOTIFY_DONE;
1607 }
1608
1609 /* Associate pktgen_dev with a device. */
1610
1611 static struct net_device *pktgen_setup_dev(struct pktgen_dev *pkt_dev)
1612 {
1613         struct net_device *odev;
1614
1615         /* Clean old setups */
1616
1617         if (pkt_dev->odev) {
1618                 dev_put(pkt_dev->odev);
1619                 pkt_dev->odev = NULL;
1620         }
1621
1622         odev = dev_get_by_name(pkt_dev->ifname);
1623
1624         if (!odev) {
1625                 printk("pktgen: no such netdevice: \"%s\"\n", pkt_dev->ifname);
1626                 goto out;
1627         }
1628         if (odev->type != ARPHRD_ETHER) {
1629                 printk("pktgen: not an ethernet device: \"%s\"\n",
1630                        pkt_dev->ifname);
1631                 goto out_put;
1632         }
1633         if (!netif_running(odev)) {
1634                 printk("pktgen: device is down: \"%s\"\n", pkt_dev->ifname);
1635                 goto out_put;
1636         }
1637         pkt_dev->odev = odev;
1638
1639         return pkt_dev->odev;
1640
1641 out_put:
1642         dev_put(odev);
1643 out:
1644         return NULL;
1645
1646 }
1647
1648 /* Read pkt_dev from the interface and set up internal pktgen_dev
1649  * structure to have the right information to create/send packets
1650  */
1651 static void pktgen_setup_inject(struct pktgen_dev *pkt_dev)
1652 {
1653         /* Try once more, just in case it works now. */
1654         if (!pkt_dev->odev)
1655                 pktgen_setup_dev(pkt_dev);
1656
1657         if (!pkt_dev->odev) {
1658                 printk("pktgen: ERROR: pkt_dev->odev == NULL in setup_inject.\n");
1659                 sprintf(pkt_dev->result,
1660                         "ERROR: pkt_dev->odev == NULL in setup_inject.\n");
1661                 return;
1662         }
1663
1664         /* Default to the interface's mac if not explicitly set. */
1665
1666         if (is_zero_ether_addr(pkt_dev->src_mac))
1667                 memcpy(&(pkt_dev->hh[6]), pkt_dev->odev->dev_addr, ETH_ALEN);
1668
1669         /* Set up Dest MAC */
1670         memcpy(&(pkt_dev->hh[0]), pkt_dev->dst_mac, ETH_ALEN);
1671
1672         /* Set up pkt size */
1673         pkt_dev->cur_pkt_size = pkt_dev->min_pkt_size;
1674
1675         if (pkt_dev->flags & F_IPV6) {
1676                 /*
1677                  * Skip this automatic address setting until locks or functions 
1678                  * gets exported
1679                  */
1680
1681 #ifdef NOTNOW
1682                 int i, set = 0, err = 1;
1683                 struct inet6_dev *idev;
1684
1685                 for (i = 0; i < IN6_ADDR_HSIZE; i++)
1686                         if (pkt_dev->cur_in6_saddr.s6_addr[i]) {
1687                                 set = 1;
1688                                 break;
1689                         }
1690
1691                 if (!set) {
1692
1693                         /*
1694                          * Use linklevel address if unconfigured.
1695                          *
1696                          * use ipv6_get_lladdr if/when it's get exported
1697                          */
1698
1699                         read_lock(&addrconf_lock);
1700                         if ((idev = __in6_dev_get(pkt_dev->odev)) != NULL) {
1701                                 struct inet6_ifaddr *ifp;
1702
1703                                 read_lock_bh(&idev->lock);
1704                                 for (ifp = idev->addr_list; ifp;
1705                                      ifp = ifp->if_next) {
1706                                         if (ifp->scope == IFA_LINK
1707                                             && !(ifp->
1708                                                  flags & IFA_F_TENTATIVE)) {
1709                                                 ipv6_addr_copy(&pkt_dev->
1710                                                                cur_in6_saddr,
1711                                                                &ifp->addr);
1712                                                 err = 0;
1713                                                 break;
1714                                         }
1715                                 }
1716                                 read_unlock_bh(&idev->lock);
1717                         }
1718                         read_unlock(&addrconf_lock);
1719                         if (err)
1720                                 printk("pktgen: ERROR: IPv6 link address not availble.\n");
1721                 }
1722 #endif
1723         } else {
1724                 pkt_dev->saddr_min = 0;
1725                 pkt_dev->saddr_max = 0;
1726                 if (strlen(pkt_dev->src_min) == 0) {
1727
1728                         struct in_device *in_dev;
1729
1730                         rcu_read_lock();
1731                         in_dev = __in_dev_get_rcu(pkt_dev->odev);
1732                         if (in_dev) {
1733                                 if (in_dev->ifa_list) {
1734                                         pkt_dev->saddr_min =
1735                                             in_dev->ifa_list->ifa_address;
1736                                         pkt_dev->saddr_max = pkt_dev->saddr_min;
1737                                 }
1738                         }
1739                         rcu_read_unlock();
1740                 } else {
1741                         pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
1742                         pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
1743                 }
1744
1745                 pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
1746                 pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
1747         }
1748         /* Initialize current values. */
1749         pkt_dev->cur_dst_mac_offset = 0;
1750         pkt_dev->cur_src_mac_offset = 0;
1751         pkt_dev->cur_saddr = pkt_dev->saddr_min;
1752         pkt_dev->cur_daddr = pkt_dev->daddr_min;
1753         pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
1754         pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
1755         pkt_dev->nflows = 0;
1756 }
1757
1758 static void spin(struct pktgen_dev *pkt_dev, __u64 spin_until_us)
1759 {
1760         __u64 start;
1761         __u64 now;
1762
1763         start = now = getCurUs();
1764         printk(KERN_INFO "sleeping for %d\n", (int)(spin_until_us - now));
1765         while (now < spin_until_us) {
1766                 /* TODO: optimize sleeping behavior */
1767                 if (spin_until_us - now > jiffies_to_usecs(1) + 1)
1768                         schedule_timeout_interruptible(1);
1769                 else if (spin_until_us - now > 100) {
1770                         do_softirq();
1771                         if (!pkt_dev->running)
1772                                 return;
1773                         if (need_resched())
1774                                 schedule();
1775                 }
1776
1777                 now = getCurUs();
1778         }
1779
1780         pkt_dev->idle_acc += now - start;
1781 }
1782
1783 /* Increment/randomize headers according to flags and current values
1784  * for IP src/dest, UDP src/dst port, MAC-Addr src/dst
1785  */
1786 static void mod_cur_headers(struct pktgen_dev *pkt_dev)
1787 {
1788         __u32 imn;
1789         __u32 imx;
1790         int flow = 0;
1791
1792         if (pkt_dev->cflows) {
1793                 flow = pktgen_random() % pkt_dev->cflows;
1794
1795                 if (pkt_dev->flows[flow].count > pkt_dev->lflow)
1796                         pkt_dev->flows[flow].count = 0;
1797         }
1798
1799         /*  Deal with source MAC */
1800         if (pkt_dev->src_mac_count > 1) {
1801                 __u32 mc;
1802                 __u32 tmp;
1803
1804                 if (pkt_dev->flags & F_MACSRC_RND)
1805                         mc = pktgen_random() % (pkt_dev->src_mac_count);
1806                 else {
1807                         mc = pkt_dev->cur_src_mac_offset++;
1808                         if (pkt_dev->cur_src_mac_offset >
1809                             pkt_dev->src_mac_count)
1810                                 pkt_dev->cur_src_mac_offset = 0;
1811                 }
1812
1813                 tmp = pkt_dev->src_mac[5] + (mc & 0xFF);
1814                 pkt_dev->hh[11] = tmp;
1815                 tmp = (pkt_dev->src_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
1816                 pkt_dev->hh[10] = tmp;
1817                 tmp = (pkt_dev->src_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
1818                 pkt_dev->hh[9] = tmp;
1819                 tmp = (pkt_dev->src_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
1820                 pkt_dev->hh[8] = tmp;
1821                 tmp = (pkt_dev->src_mac[1] + (tmp >> 8));
1822                 pkt_dev->hh[7] = tmp;
1823         }
1824
1825         /*  Deal with Destination MAC */
1826         if (pkt_dev->dst_mac_count > 1) {
1827                 __u32 mc;
1828                 __u32 tmp;
1829
1830                 if (pkt_dev->flags & F_MACDST_RND)
1831                         mc = pktgen_random() % (pkt_dev->dst_mac_count);
1832
1833                 else {
1834                         mc = pkt_dev->cur_dst_mac_offset++;
1835                         if (pkt_dev->cur_dst_mac_offset >
1836                             pkt_dev->dst_mac_count) {
1837                                 pkt_dev->cur_dst_mac_offset = 0;
1838                         }
1839                 }
1840
1841                 tmp = pkt_dev->dst_mac[5] + (mc & 0xFF);
1842                 pkt_dev->hh[5] = tmp;
1843                 tmp = (pkt_dev->dst_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
1844                 pkt_dev->hh[4] = tmp;
1845                 tmp = (pkt_dev->dst_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
1846                 pkt_dev->hh[3] = tmp;
1847                 tmp = (pkt_dev->dst_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
1848                 pkt_dev->hh[2] = tmp;
1849                 tmp = (pkt_dev->dst_mac[1] + (tmp >> 8));
1850                 pkt_dev->hh[1] = tmp;
1851         }
1852
1853         if (pkt_dev->udp_src_min < pkt_dev->udp_src_max) {
1854                 if (pkt_dev->flags & F_UDPSRC_RND)
1855                         pkt_dev->cur_udp_src =
1856                             ((pktgen_random() %
1857                               (pkt_dev->udp_src_max - pkt_dev->udp_src_min)) +
1858                              pkt_dev->udp_src_min);
1859
1860                 else {
1861                         pkt_dev->cur_udp_src++;
1862                         if (pkt_dev->cur_udp_src >= pkt_dev->udp_src_max)
1863                                 pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
1864                 }
1865         }
1866
1867         if (pkt_dev->udp_dst_min < pkt_dev->udp_dst_max) {
1868                 if (pkt_dev->flags & F_UDPDST_RND) {
1869                         pkt_dev->cur_udp_dst =
1870                             ((pktgen_random() %
1871                               (pkt_dev->udp_dst_max - pkt_dev->udp_dst_min)) +
1872                              pkt_dev->udp_dst_min);
1873                 } else {
1874                         pkt_dev->cur_udp_dst++;
1875                         if (pkt_dev->cur_udp_dst >= pkt_dev->udp_dst_max)
1876                                 pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
1877                 }
1878         }
1879
1880         if (!(pkt_dev->flags & F_IPV6)) {
1881
1882                 if ((imn = ntohl(pkt_dev->saddr_min)) < (imx =
1883                                                          ntohl(pkt_dev->
1884                                                                saddr_max))) {
1885                         __u32 t;
1886                         if (pkt_dev->flags & F_IPSRC_RND)
1887                                 t = ((pktgen_random() % (imx - imn)) + imn);
1888                         else {
1889                                 t = ntohl(pkt_dev->cur_saddr);
1890                                 t++;
1891                                 if (t > imx) {
1892                                         t = imn;
1893                                 }
1894                         }
1895                         pkt_dev->cur_saddr = htonl(t);
1896                 }
1897
1898                 if (pkt_dev->cflows && pkt_dev->flows[flow].count != 0) {
1899                         pkt_dev->cur_daddr = pkt_dev->flows[flow].cur_daddr;
1900                 } else {
1901
1902                         if ((imn = ntohl(pkt_dev->daddr_min)) < (imx =
1903                                                                  ntohl(pkt_dev->
1904                                                                        daddr_max)))
1905                         {
1906                                 __u32 t;
1907                                 if (pkt_dev->flags & F_IPDST_RND) {
1908
1909                                         t = ((pktgen_random() % (imx - imn)) +
1910                                              imn);
1911                                         t = htonl(t);
1912
1913                                         while (LOOPBACK(t) || MULTICAST(t)
1914                                                || BADCLASS(t) || ZERONET(t)
1915                                                || LOCAL_MCAST(t)) {
1916                                                 t = ((pktgen_random() %
1917                                                       (imx - imn)) + imn);
1918                                                 t = htonl(t);
1919                                         }
1920                                         pkt_dev->cur_daddr = t;
1921                                 }
1922
1923                                 else {
1924                                         t = ntohl(pkt_dev->cur_daddr);
1925                                         t++;
1926                                         if (t > imx) {
1927                                                 t = imn;
1928                                         }
1929                                         pkt_dev->cur_daddr = htonl(t);
1930                                 }
1931                         }
1932                         if (pkt_dev->cflows) {
1933                                 pkt_dev->flows[flow].cur_daddr =
1934                                     pkt_dev->cur_daddr;
1935                                 pkt_dev->nflows++;
1936                         }
1937                 }
1938         } else {                /* IPV6 * */
1939
1940                 if (pkt_dev->min_in6_daddr.s6_addr32[0] == 0 &&
1941                     pkt_dev->min_in6_daddr.s6_addr32[1] == 0 &&
1942                     pkt_dev->min_in6_daddr.s6_addr32[2] == 0 &&
1943                     pkt_dev->min_in6_daddr.s6_addr32[3] == 0) ;
1944                 else {
1945                         int i;
1946
1947                         /* Only random destinations yet */
1948
1949                         for (i = 0; i < 4; i++) {
1950                                 pkt_dev->cur_in6_daddr.s6_addr32[i] =
1951                                     ((pktgen_random() |
1952                                       pkt_dev->min_in6_daddr.s6_addr32[i]) &
1953                                      pkt_dev->max_in6_daddr.s6_addr32[i]);
1954                         }
1955                 }
1956         }
1957
1958         if (pkt_dev->min_pkt_size < pkt_dev->max_pkt_size) {
1959                 __u32 t;
1960                 if (pkt_dev->flags & F_TXSIZE_RND) {
1961                         t = ((pktgen_random() %
1962                               (pkt_dev->max_pkt_size - pkt_dev->min_pkt_size))
1963                              + pkt_dev->min_pkt_size);
1964                 } else {
1965                         t = pkt_dev->cur_pkt_size + 1;
1966                         if (t > pkt_dev->max_pkt_size)
1967                                 t = pkt_dev->min_pkt_size;
1968                 }
1969                 pkt_dev->cur_pkt_size = t;
1970         }
1971
1972         pkt_dev->flows[flow].count++;
1973 }
1974
1975 static struct sk_buff *fill_packet_ipv4(struct net_device *odev,
1976                                         struct pktgen_dev *pkt_dev)
1977 {
1978         struct sk_buff *skb = NULL;
1979         __u8 *eth;
1980         struct udphdr *udph;
1981         int datalen, iplen;
1982         struct iphdr *iph;
1983         struct pktgen_hdr *pgh = NULL;
1984
1985         /* Update any of the values, used when we're incrementing various
1986          * fields.
1987          */
1988         mod_cur_headers(pkt_dev);
1989
1990         datalen = (odev->hard_header_len + 16) & ~0xf;
1991         skb = alloc_skb(pkt_dev->cur_pkt_size + 64 + datalen, GFP_ATOMIC);
1992         if (!skb) {
1993                 sprintf(pkt_dev->result, "No memory");
1994                 return NULL;
1995         }
1996
1997         skb_reserve(skb, datalen);
1998
1999         /*  Reserve for ethernet and IP header  */
2000         eth = (__u8 *) skb_push(skb, 14);
2001         iph = (struct iphdr *)skb_put(skb, sizeof(struct iphdr));
2002         udph = (struct udphdr *)skb_put(skb, sizeof(struct udphdr));
2003
2004         memcpy(eth, pkt_dev->hh, 12);
2005         *(u16 *) & eth[12] = __constant_htons(ETH_P_IP);
2006
2007         datalen = pkt_dev->cur_pkt_size - 14 - 20 - 8;  /* Eth + IPh + UDPh */
2008         if (datalen < sizeof(struct pktgen_hdr))
2009                 datalen = sizeof(struct pktgen_hdr);
2010
2011         udph->source = htons(pkt_dev->cur_udp_src);
2012         udph->dest = htons(pkt_dev->cur_udp_dst);
2013         udph->len = htons(datalen + 8); /* DATA + udphdr */
2014         udph->check = 0;        /* No checksum */
2015
2016         iph->ihl = 5;
2017         iph->version = 4;
2018         iph->ttl = 32;
2019         iph->tos = 0;
2020         iph->protocol = IPPROTO_UDP;    /* UDP */
2021         iph->saddr = pkt_dev->cur_saddr;
2022         iph->daddr = pkt_dev->cur_daddr;
2023         iph->frag_off = 0;
2024         iplen = 20 + 8 + datalen;
2025         iph->tot_len = htons(iplen);
2026         iph->check = 0;
2027         iph->check = ip_fast_csum((void *)iph, iph->ihl);
2028         skb->protocol = __constant_htons(ETH_P_IP);
2029         skb->mac.raw = ((u8 *) iph) - 14;
2030         skb->dev = odev;
2031         skb->pkt_type = PACKET_HOST;
2032
2033         if (pkt_dev->nfrags <= 0)
2034                 pgh = (struct pktgen_hdr *)skb_put(skb, datalen);
2035         else {
2036                 int frags = pkt_dev->nfrags;
2037                 int i;
2038
2039                 pgh = (struct pktgen_hdr *)(((char *)(udph)) + 8);
2040
2041                 if (frags > MAX_SKB_FRAGS)
2042                         frags = MAX_SKB_FRAGS;
2043                 if (datalen > frags * PAGE_SIZE) {
2044                         skb_put(skb, datalen - frags * PAGE_SIZE);
2045                         datalen = frags * PAGE_SIZE;
2046                 }
2047
2048                 i = 0;
2049                 while (datalen > 0) {
2050                         struct page *page = alloc_pages(GFP_KERNEL, 0);
2051                         skb_shinfo(skb)->frags[i].page = page;
2052                         skb_shinfo(skb)->frags[i].page_offset = 0;
2053                         skb_shinfo(skb)->frags[i].size =
2054                             (datalen < PAGE_SIZE ? datalen : PAGE_SIZE);
2055                         datalen -= skb_shinfo(skb)->frags[i].size;
2056                         skb->len += skb_shinfo(skb)->frags[i].size;
2057                         skb->data_len += skb_shinfo(skb)->frags[i].size;
2058                         i++;
2059                         skb_shinfo(skb)->nr_frags = i;
2060                 }
2061
2062                 while (i < frags) {
2063                         int rem;
2064
2065                         if (i == 0)
2066                                 break;
2067
2068                         rem = skb_shinfo(skb)->frags[i - 1].size / 2;
2069                         if (rem == 0)
2070                                 break;
2071
2072                         skb_shinfo(skb)->frags[i - 1].size -= rem;
2073
2074                         skb_shinfo(skb)->frags[i] =
2075                             skb_shinfo(skb)->frags[i - 1];
2076                         get_page(skb_shinfo(skb)->frags[i].page);
2077                         skb_shinfo(skb)->frags[i].page =
2078                             skb_shinfo(skb)->frags[i - 1].page;
2079                         skb_shinfo(skb)->frags[i].page_offset +=
2080                             skb_shinfo(skb)->frags[i - 1].size;
2081                         skb_shinfo(skb)->frags[i].size = rem;
2082                         i++;
2083                         skb_shinfo(skb)->nr_frags = i;
2084                 }
2085         }
2086
2087         /* Stamp the time, and sequence number, convert them to network byte order */
2088
2089         if (pgh) {
2090                 struct timeval timestamp;
2091
2092                 pgh->pgh_magic = htonl(PKTGEN_MAGIC);
2093                 pgh->seq_num = htonl(pkt_dev->seq_num);
2094
2095                 do_gettimeofday(&timestamp);
2096                 pgh->tv_sec = htonl(timestamp.tv_sec);
2097                 pgh->tv_usec = htonl(timestamp.tv_usec);
2098         }
2099         pkt_dev->seq_num++;
2100
2101         return skb;
2102 }
2103
2104 /*
2105  * scan_ip6, fmt_ip taken from dietlibc-0.21 
2106  * Author Felix von Leitner <felix-dietlibc@fefe.de>
2107  *
2108  * Slightly modified for kernel. 
2109  * Should be candidate for net/ipv4/utils.c
2110  * --ro
2111  */
2112
2113 static unsigned int scan_ip6(const char *s, char ip[16])
2114 {
2115         unsigned int i;
2116         unsigned int len = 0;
2117         unsigned long u;
2118         char suffix[16];
2119         unsigned int prefixlen = 0;
2120         unsigned int suffixlen = 0;
2121         __u32 tmp;
2122
2123         for (i = 0; i < 16; i++)
2124                 ip[i] = 0;
2125
2126         for (;;) {
2127                 if (*s == ':') {
2128                         len++;
2129                         if (s[1] == ':') {      /* Found "::", skip to part 2 */
2130                                 s += 2;
2131                                 len++;
2132                                 break;
2133                         }
2134                         s++;
2135                 }
2136                 {
2137                         char *tmp;
2138                         u = simple_strtoul(s, &tmp, 16);
2139                         i = tmp - s;
2140                 }
2141
2142                 if (!i)
2143                         return 0;
2144                 if (prefixlen == 12 && s[i] == '.') {
2145
2146                         /* the last 4 bytes may be written as IPv4 address */
2147
2148                         tmp = in_aton(s);
2149                         memcpy((struct in_addr *)(ip + 12), &tmp, sizeof(tmp));
2150                         return i + len;
2151                 }
2152                 ip[prefixlen++] = (u >> 8);
2153                 ip[prefixlen++] = (u & 255);
2154                 s += i;
2155                 len += i;
2156                 if (prefixlen == 16)
2157                         return len;
2158         }
2159
2160 /* part 2, after "::" */
2161         for (;;) {
2162                 if (*s == ':') {
2163                         if (suffixlen == 0)
2164                                 break;
2165                         s++;
2166                         len++;
2167                 } else if (suffixlen != 0)
2168                         break;
2169                 {
2170                         char *tmp;
2171                         u = simple_strtol(s, &tmp, 16);
2172                         i = tmp - s;
2173                 }
2174                 if (!i) {
2175                         if (*s)
2176                                 len--;
2177                         break;
2178                 }
2179                 if (suffixlen + prefixlen <= 12 && s[i] == '.') {
2180                         tmp = in_aton(s);
2181                         memcpy((struct in_addr *)(suffix + suffixlen), &tmp,
2182                                sizeof(tmp));
2183                         suffixlen += 4;
2184                         len += strlen(s);
2185                         break;
2186                 }
2187                 suffix[suffixlen++] = (u >> 8);
2188                 suffix[suffixlen++] = (u & 255);
2189                 s += i;
2190                 len += i;
2191                 if (prefixlen + suffixlen == 16)
2192                         break;
2193         }
2194         for (i = 0; i < suffixlen; i++)
2195                 ip[16 - suffixlen + i] = suffix[i];
2196         return len;
2197 }
2198
2199 static char tohex(char hexdigit)
2200 {
2201         return hexdigit > 9 ? hexdigit + 'a' - 10 : hexdigit + '0';
2202 }
2203
2204 static int fmt_xlong(char *s, unsigned int i)
2205 {
2206         char *bak = s;
2207         *s = tohex((i >> 12) & 0xf);
2208         if (s != bak || *s != '0')
2209                 ++s;
2210         *s = tohex((i >> 8) & 0xf);
2211         if (s != bak || *s != '0')
2212                 ++s;
2213         *s = tohex((i >> 4) & 0xf);
2214         if (s != bak || *s != '0')
2215                 ++s;
2216         *s = tohex(i & 0xf);
2217         return s - bak + 1;
2218 }
2219
2220 static unsigned int fmt_ip6(char *s, const char ip[16])
2221 {
2222         unsigned int len;
2223         unsigned int i;
2224         unsigned int temp;
2225         unsigned int compressing;
2226         int j;
2227
2228         len = 0;
2229         compressing = 0;
2230         for (j = 0; j < 16; j += 2) {
2231
2232 #ifdef V4MAPPEDPREFIX
2233                 if (j == 12 && !memcmp(ip, V4mappedprefix, 12)) {
2234                         inet_ntoa_r(*(struct in_addr *)(ip + 12), s);
2235                         temp = strlen(s);
2236                         return len + temp;
2237                 }
2238 #endif
2239                 temp = ((unsigned long)(unsigned char)ip[j] << 8) +
2240                     (unsigned long)(unsigned char)ip[j + 1];
2241                 if (temp == 0) {
2242                         if (!compressing) {
2243                                 compressing = 1;
2244                                 if (j == 0) {
2245                                         *s++ = ':';
2246                                         ++len;
2247                                 }
2248                         }
2249                 } else {
2250                         if (compressing) {
2251                                 compressing = 0;
2252                                 *s++ = ':';
2253                                 ++len;
2254                         }
2255                         i = fmt_xlong(s, temp);
2256                         len += i;
2257                         s += i;
2258                         if (j < 14) {
2259                                 *s++ = ':';
2260                                 ++len;
2261                         }
2262                 }
2263         }
2264         if (compressing) {
2265                 *s++ = ':';
2266                 ++len;
2267         }
2268         *s = 0;
2269         return len;
2270 }
2271
2272 static struct sk_buff *fill_packet_ipv6(struct net_device *odev,
2273                                         struct pktgen_dev *pkt_dev)
2274 {
2275         struct sk_buff *skb = NULL;
2276         __u8 *eth;
2277         struct udphdr *udph;
2278         int datalen;
2279         struct ipv6hdr *iph;
2280         struct pktgen_hdr *pgh = NULL;
2281
2282         /* Update any of the values, used when we're incrementing various
2283          * fields.
2284          */
2285         mod_cur_headers(pkt_dev);
2286
2287         skb = alloc_skb(pkt_dev->cur_pkt_size + 64 + 16, GFP_ATOMIC);
2288         if (!skb) {
2289                 sprintf(pkt_dev->result, "No memory");
2290                 return NULL;
2291         }
2292
2293         skb_reserve(skb, 16);
2294
2295         /*  Reserve for ethernet and IP header  */
2296         eth = (__u8 *) skb_push(skb, 14);
2297         iph = (struct ipv6hdr *)skb_put(skb, sizeof(struct ipv6hdr));
2298         udph = (struct udphdr *)skb_put(skb, sizeof(struct udphdr));
2299
2300         memcpy(eth, pkt_dev->hh, 12);
2301         *(u16 *) & eth[12] = __constant_htons(ETH_P_IPV6);
2302
2303         datalen = pkt_dev->cur_pkt_size - 14 - sizeof(struct ipv6hdr) - sizeof(struct udphdr);  /* Eth + IPh + UDPh */
2304
2305         if (datalen < sizeof(struct pktgen_hdr)) {
2306                 datalen = sizeof(struct pktgen_hdr);
2307                 if (net_ratelimit())
2308                         printk(KERN_INFO "pktgen: increased datalen to %d\n",
2309                                datalen);
2310         }
2311
2312         udph->source = htons(pkt_dev->cur_udp_src);
2313         udph->dest = htons(pkt_dev->cur_udp_dst);
2314         udph->len = htons(datalen + sizeof(struct udphdr));
2315         udph->check = 0;        /* No checksum */
2316
2317         *(u32 *) iph = __constant_htonl(0x60000000);    /* Version + flow */
2318
2319         iph->hop_limit = 32;
2320
2321         iph->payload_len = htons(sizeof(struct udphdr) + datalen);
2322         iph->nexthdr = IPPROTO_UDP;
2323
2324         ipv6_addr_copy(&iph->daddr, &pkt_dev->cur_in6_daddr);
2325         ipv6_addr_copy(&iph->saddr, &pkt_dev->cur_in6_saddr);
2326
2327         skb->mac.raw = ((u8 *) iph) - 14;
2328         skb->protocol = __constant_htons(ETH_P_IPV6);
2329         skb->dev = odev;
2330         skb->pkt_type = PACKET_HOST;
2331
2332         if (pkt_dev->nfrags <= 0)
2333                 pgh = (struct pktgen_hdr *)skb_put(skb, datalen);
2334         else {
2335                 int frags = pkt_dev->nfrags;
2336                 int i;
2337
2338                 pgh = (struct pktgen_hdr *)(((char *)(udph)) + 8);
2339
2340                 if (frags > MAX_SKB_FRAGS)
2341                         frags = MAX_SKB_FRAGS;
2342                 if (datalen > frags * PAGE_SIZE) {
2343                         skb_put(skb, datalen - frags * PAGE_SIZE);
2344                         datalen = frags * PAGE_SIZE;
2345                 }
2346
2347                 i = 0;
2348                 while (datalen > 0) {
2349                         struct page *page = alloc_pages(GFP_KERNEL, 0);
2350                         skb_shinfo(skb)->frags[i].page = page;
2351                         skb_shinfo(skb)->frags[i].page_offset = 0;
2352                         skb_shinfo(skb)->frags[i].size =
2353                             (datalen < PAGE_SIZE ? datalen : PAGE_SIZE);
2354                         datalen -= skb_shinfo(skb)->frags[i].size;
2355                         skb->len += skb_shinfo(skb)->frags[i].size;
2356                         skb->data_len += skb_shinfo(skb)->frags[i].size;
2357                         i++;
2358                         skb_shinfo(skb)->nr_frags = i;
2359                 }
2360
2361                 while (i < frags) {
2362                         int rem;
2363
2364                         if (i == 0)
2365                                 break;
2366
2367                         rem = skb_shinfo(skb)->frags[i - 1].size / 2;
2368                         if (rem == 0)
2369                                 break;
2370
2371                         skb_shinfo(skb)->frags[i - 1].size -= rem;
2372
2373                         skb_shinfo(skb)->frags[i] =
2374                             skb_shinfo(skb)->frags[i - 1];
2375                         get_page(skb_shinfo(skb)->frags[i].page);
2376                         skb_shinfo(skb)->frags[i].page =
2377                             skb_shinfo(skb)->frags[i - 1].page;
2378                         skb_shinfo(skb)->frags[i].page_offset +=
2379                             skb_shinfo(skb)->frags[i - 1].size;
2380                         skb_shinfo(skb)->frags[i].size = rem;
2381                         i++;
2382                         skb_shinfo(skb)->nr_frags = i;
2383                 }
2384         }
2385
2386         /* Stamp the time, and sequence number, convert them to network byte order */
2387         /* should we update cloned packets too ? */
2388         if (pgh) {
2389                 struct timeval timestamp;
2390
2391                 pgh->pgh_magic = htonl(PKTGEN_MAGIC);
2392                 pgh->seq_num = htonl(pkt_dev->seq_num);
2393
2394                 do_gettimeofday(&timestamp);
2395                 pgh->tv_sec = htonl(timestamp.tv_sec);
2396                 pgh->tv_usec = htonl(timestamp.tv_usec);
2397         }
2398         pkt_dev->seq_num++;
2399
2400         return skb;
2401 }
2402
2403 static inline struct sk_buff *fill_packet(struct net_device *odev,
2404                                           struct pktgen_dev *pkt_dev)
2405 {
2406         if (pkt_dev->flags & F_IPV6)
2407                 return fill_packet_ipv6(odev, pkt_dev);
2408         else
2409                 return fill_packet_ipv4(odev, pkt_dev);
2410 }
2411
2412 static void pktgen_clear_counters(struct pktgen_dev *pkt_dev)
2413 {
2414         pkt_dev->seq_num = 1;
2415         pkt_dev->idle_acc = 0;
2416         pkt_dev->sofar = 0;
2417         pkt_dev->tx_bytes = 0;
2418         pkt_dev->errors = 0;
2419 }
2420
2421 /* Set up structure for sending pkts, clear counters */
2422
2423 static void pktgen_run(struct pktgen_thread *t)
2424 {
2425         struct pktgen_dev *pkt_dev;
2426         int started = 0;
2427
2428         PG_DEBUG(printk("pktgen: entering pktgen_run. %p\n", t));
2429
2430         if_lock(t);
2431         list_for_each_entry(pkt_dev, &t->if_list, list) {
2432
2433                 /*
2434                  * setup odev and create initial packet.
2435                  */
2436                 pktgen_setup_inject(pkt_dev);
2437
2438                 if (pkt_dev->odev) {
2439                         pktgen_clear_counters(pkt_dev);
2440                         pkt_dev->running = 1;   /* Cranke yeself! */
2441                         pkt_dev->skb = NULL;
2442                         pkt_dev->started_at = getCurUs();
2443                         pkt_dev->next_tx_us = getCurUs();       /* Transmit immediately */
2444                         pkt_dev->next_tx_ns = 0;
2445
2446                         strcpy(pkt_dev->result, "Starting");
2447                         started++;
2448                 } else
2449                         strcpy(pkt_dev->result, "Error starting");
2450         }
2451         if_unlock(t);
2452         if (started)
2453                 t->control &= ~(T_STOP);
2454 }
2455
2456 static void pktgen_stop_all_threads_ifs(void)
2457 {
2458         struct pktgen_thread *t;
2459
2460         PG_DEBUG(printk("pktgen: entering pktgen_stop_all_threads_ifs.\n"));
2461
2462         thread_lock();
2463
2464         list_for_each_entry(t, &pktgen_threads, th_list)
2465                 t->control |= T_STOP;
2466
2467         thread_unlock();
2468 }
2469
2470 static int thread_is_running(struct pktgen_thread *t)
2471 {
2472         struct pktgen_dev *pkt_dev;
2473         int res = 0;
2474
2475         list_for_each_entry(pkt_dev, &t->if_list, list)
2476                 if (pkt_dev->running) {
2477                         res = 1;
2478                         break;
2479                 }
2480         return res;
2481 }
2482
2483 static int pktgen_wait_thread_run(struct pktgen_thread *t)
2484 {
2485         if_lock(t);
2486
2487         while (thread_is_running(t)) {
2488
2489                 if_unlock(t);
2490
2491                 msleep_interruptible(100);
2492
2493                 if (signal_pending(current))
2494                         goto signal;
2495                 if_lock(t);
2496         }
2497         if_unlock(t);
2498         return 1;
2499 signal:
2500         return 0;
2501 }
2502
2503 static int pktgen_wait_all_threads_run(void)
2504 {
2505         struct pktgen_thread *t;
2506         int sig = 1;
2507
2508         thread_lock();
2509
2510         list_for_each_entry(t, &pktgen_threads, th_list) {
2511                 sig = pktgen_wait_thread_run(t);
2512                 if (sig == 0)
2513                         break;
2514         }
2515
2516         if (sig == 0)
2517                 list_for_each_entry(t, &pktgen_threads, th_list)
2518                         t->control |= (T_STOP);
2519
2520         thread_unlock();
2521         return sig;
2522 }
2523
2524 static void pktgen_run_all_threads(void)
2525 {
2526         struct pktgen_thread *t;
2527
2528         PG_DEBUG(printk("pktgen: entering pktgen_run_all_threads.\n"));
2529
2530         thread_lock();
2531
2532         list_for_each_entry(t, &pktgen_threads, th_list)
2533                 t->control |= (T_RUN);
2534
2535         thread_unlock();
2536
2537         schedule_timeout_interruptible(msecs_to_jiffies(125));  /* Propagate thread->control  */
2538
2539         pktgen_wait_all_threads_run();
2540 }
2541
2542 static void show_results(struct pktgen_dev *pkt_dev, int nr_frags)
2543 {
2544         __u64 total_us, bps, mbps, pps, idle;
2545         char *p = pkt_dev->result;
2546
2547         total_us = pkt_dev->stopped_at - pkt_dev->started_at;
2548
2549         idle = pkt_dev->idle_acc;
2550
2551         p += sprintf(p, "OK: %llu(c%llu+d%llu) usec, %llu (%dbyte,%dfrags)\n",
2552                      (unsigned long long)total_us,
2553                      (unsigned long long)(total_us - idle),
2554                      (unsigned long long)idle,
2555                      (unsigned long long)pkt_dev->sofar,
2556                      pkt_dev->cur_pkt_size, nr_frags);
2557
2558         pps = pkt_dev->sofar * USEC_PER_SEC;
2559
2560         while ((total_us >> 32) != 0) {
2561                 pps >>= 1;
2562                 total_us >>= 1;
2563         }
2564
2565         do_div(pps, total_us);
2566
2567         bps = pps * 8 * pkt_dev->cur_pkt_size;
2568
2569         mbps = bps;
2570         do_div(mbps, 1000000);
2571         p += sprintf(p, "  %llupps %lluMb/sec (%llubps) errors: %llu",
2572                      (unsigned long long)pps,
2573                      (unsigned long long)mbps,
2574                      (unsigned long long)bps,
2575                      (unsigned long long)pkt_dev->errors);
2576 }
2577
2578 /* Set stopped-at timer, remove from running list, do counters & statistics */
2579
2580 static int pktgen_stop_device(struct pktgen_dev *pkt_dev)
2581 {
2582         int nr_frags = pkt_dev->skb ? skb_shinfo(pkt_dev->skb)->nr_frags : -1;
2583
2584         if (!pkt_dev->running) {
2585                 printk("pktgen: interface: %s is already stopped\n",
2586                        pkt_dev->ifname);
2587                 return -EINVAL;
2588         }
2589
2590         pkt_dev->stopped_at = getCurUs();
2591         pkt_dev->running = 0;
2592
2593         show_results(pkt_dev, nr_frags);
2594
2595         return 0;
2596 }
2597
2598 static struct pktgen_dev *next_to_run(struct pktgen_thread *t)
2599 {
2600         struct pktgen_dev *pkt_dev, *best = NULL;
2601
2602         if_lock(t);
2603
2604         list_for_each_entry(pkt_dev, &t->if_list, list) {
2605                 if (!pkt_dev->running)
2606                         continue;
2607                 if (best == NULL)
2608                         best = pkt_dev;
2609                 else if (pkt_dev->next_tx_us < best->next_tx_us)
2610                         best = pkt_dev;
2611         }
2612         if_unlock(t);
2613         return best;
2614 }
2615
2616 static void pktgen_stop(struct pktgen_thread *t)
2617 {
2618         struct pktgen_dev *pkt_dev;
2619
2620         PG_DEBUG(printk("pktgen: entering pktgen_stop\n"));
2621
2622         if_lock(t);
2623
2624         list_for_each_entry(pkt_dev, &t->if_list, list) {
2625                 pktgen_stop_device(pkt_dev);
2626                 if (pkt_dev->skb)
2627                         kfree_skb(pkt_dev->skb);
2628
2629                 pkt_dev->skb = NULL;
2630         }
2631
2632         if_unlock(t);
2633 }
2634
2635 /*
2636  * one of our devices needs to be removed - find it
2637  * and remove it
2638  */
2639 static void pktgen_rem_one_if(struct pktgen_thread *t)
2640 {
2641         struct list_head *q, *n;
2642         struct pktgen_dev *cur;
2643
2644         PG_DEBUG(printk("pktgen: entering pktgen_rem_one_if\n"));
2645
2646         if_lock(t);
2647
2648         list_for_each_safe(q, n, &t->if_list) {
2649                 cur = list_entry(q, struct pktgen_dev, list);
2650
2651                 if (!cur->removal_mark)
2652                         continue;
2653
2654                 if (cur->skb)
2655                         kfree_skb(cur->skb);
2656                 cur->skb = NULL;
2657
2658                 pktgen_remove_device(t, cur);
2659
2660                 break;
2661         }
2662
2663         if_unlock(t);
2664 }
2665
2666 static void pktgen_rem_all_ifs(struct pktgen_thread *t)
2667 {
2668         struct list_head *q, *n;
2669         struct pktgen_dev *cur;
2670
2671         /* Remove all devices, free mem */
2672
2673         PG_DEBUG(printk("pktgen: entering pktgen_rem_all_ifs\n"));
2674         if_lock(t);
2675
2676         list_for_each_safe(q, n, &t->if_list) {
2677                 cur = list_entry(q, struct pktgen_dev, list);
2678
2679                 if (cur->skb)
2680                         kfree_skb(cur->skb);
2681                 cur->skb = NULL;
2682
2683                 pktgen_remove_device(t, cur);
2684         }
2685
2686         if_unlock(t);
2687 }
2688
2689 static void pktgen_rem_thread(struct pktgen_thread *t)
2690 {
2691         /* Remove from the thread list */
2692
2693         remove_proc_entry(t->name, pg_proc_dir);
2694
2695         thread_lock();
2696
2697         list_del(&t->th_list);
2698
2699         thread_unlock();
2700 }
2701
2702 static __inline__ void pktgen_xmit(struct pktgen_dev *pkt_dev)
2703 {
2704         struct net_device *odev = NULL;
2705         __u64 idle_start = 0;
2706         int ret;
2707
2708         odev = pkt_dev->odev;
2709
2710         if (pkt_dev->delay_us || pkt_dev->delay_ns) {
2711                 u64 now;
2712
2713                 now = getCurUs();
2714                 if (now < pkt_dev->next_tx_us)
2715                         spin(pkt_dev, pkt_dev->next_tx_us);
2716
2717                 /* This is max DELAY, this has special meaning of
2718                  * "never transmit"
2719                  */
2720                 if (pkt_dev->delay_us == 0x7FFFFFFF) {
2721                         pkt_dev->next_tx_us = getCurUs() + pkt_dev->delay_us;
2722                         pkt_dev->next_tx_ns = pkt_dev->delay_ns;
2723                         goto out;
2724                 }
2725         }
2726
2727         if (netif_queue_stopped(odev) || need_resched()) {
2728                 idle_start = getCurUs();
2729
2730                 if (!netif_running(odev)) {
2731                         pktgen_stop_device(pkt_dev);
2732                         if (pkt_dev->skb)
2733                                 kfree_skb(pkt_dev->skb);
2734                         pkt_dev->skb = NULL;
2735                         goto out;
2736                 }
2737                 if (need_resched())
2738                         schedule();
2739
2740                 pkt_dev->idle_acc += getCurUs() - idle_start;
2741
2742                 if (netif_queue_stopped(odev)) {
2743                         pkt_dev->next_tx_us = getCurUs();       /* TODO */
2744                         pkt_dev->next_tx_ns = 0;
2745                         goto out;       /* Try the next interface */
2746                 }
2747         }
2748
2749         if (pkt_dev->last_ok || !pkt_dev->skb) {
2750                 if ((++pkt_dev->clone_count >= pkt_dev->clone_skb)
2751                     || (!pkt_dev->skb)) {
2752                         /* build a new pkt */
2753                         if (pkt_dev->skb)
2754                                 kfree_skb(pkt_dev->skb);
2755
2756                         pkt_dev->skb = fill_packet(odev, pkt_dev);
2757                         if (pkt_dev->skb == NULL) {
2758                                 printk("pktgen: ERROR: couldn't allocate skb in fill_packet.\n");
2759                                 schedule();
2760                                 pkt_dev->clone_count--; /* back out increment, OOM */
2761                                 goto out;
2762                         }
2763                         pkt_dev->allocated_skbs++;
2764                         pkt_dev->clone_count = 0;       /* reset counter */
2765                 }
2766         }
2767
2768         spin_lock_bh(&odev->xmit_lock);
2769         if (!netif_queue_stopped(odev)) {
2770
2771                 atomic_inc(&(pkt_dev->skb->users));
2772               retry_now:
2773                 ret = odev->hard_start_xmit(pkt_dev->skb, odev);
2774                 if (likely(ret == NETDEV_TX_OK)) {
2775                         pkt_dev->last_ok = 1;
2776                         pkt_dev->sofar++;
2777                         pkt_dev->seq_num++;
2778                         pkt_dev->tx_bytes += pkt_dev->cur_pkt_size;
2779
2780                 } else if (ret == NETDEV_TX_LOCKED
2781                            && (odev->features & NETIF_F_LLTX)) {
2782                         cpu_relax();
2783                         goto retry_now;
2784                 } else {        /* Retry it next time */
2785
2786                         atomic_dec(&(pkt_dev->skb->users));
2787
2788                         if (debug && net_ratelimit())
2789                                 printk(KERN_INFO "pktgen: Hard xmit error\n");
2790
2791                         pkt_dev->errors++;
2792                         pkt_dev->last_ok = 0;
2793                 }
2794
2795                 pkt_dev->next_tx_us = getCurUs();
2796                 pkt_dev->next_tx_ns = 0;
2797
2798                 pkt_dev->next_tx_us += pkt_dev->delay_us;
2799                 pkt_dev->next_tx_ns += pkt_dev->delay_ns;
2800
2801                 if (pkt_dev->next_tx_ns > 1000) {
2802                         pkt_dev->next_tx_us++;
2803                         pkt_dev->next_tx_ns -= 1000;
2804                 }
2805         }
2806
2807         else {                  /* Retry it next time */
2808                 pkt_dev->last_ok = 0;
2809                 pkt_dev->next_tx_us = getCurUs();       /* TODO */
2810                 pkt_dev->next_tx_ns = 0;
2811         }
2812
2813         spin_unlock_bh(&odev->xmit_lock);
2814
2815         /* If pkt_dev->count is zero, then run forever */
2816         if ((pkt_dev->count != 0) && (pkt_dev->sofar >= pkt_dev->count)) {
2817                 if (atomic_read(&(pkt_dev->skb->users)) != 1) {
2818                         idle_start = getCurUs();
2819                         while (atomic_read(&(pkt_dev->skb->users)) != 1) {
2820                                 if (signal_pending(current)) {
2821                                         break;
2822                                 }
2823                                 schedule();
2824                         }
2825                         pkt_dev->idle_acc += getCurUs() - idle_start;
2826                 }
2827
2828                 /* Done with this */
2829                 pktgen_stop_device(pkt_dev);
2830                 if (pkt_dev->skb)
2831                         kfree_skb(pkt_dev->skb);
2832                 pkt_dev->skb = NULL;
2833         }
2834 out:;
2835 }
2836
2837 /* 
2838  * Main loop of the thread goes here
2839  */
2840
2841 static void pktgen_thread_worker(struct pktgen_thread *t)
2842 {
2843         DEFINE_WAIT(wait);
2844         struct pktgen_dev *pkt_dev = NULL;
2845         int cpu = t->cpu;
2846         sigset_t tmpsig;
2847         u32 max_before_softirq;
2848         u32 tx_since_softirq = 0;
2849
2850         daemonize("pktgen/%d", cpu);
2851
2852         /* Block all signals except SIGKILL, SIGSTOP and SIGTERM */
2853
2854         spin_lock_irq(&current->sighand->siglock);
2855         tmpsig = current->blocked;
2856         siginitsetinv(&current->blocked,
2857                       sigmask(SIGKILL) | sigmask(SIGSTOP) | sigmask(SIGTERM));
2858
2859         recalc_sigpending();
2860         spin_unlock_irq(&current->sighand->siglock);
2861
2862         /* Migrate to the right CPU */
2863         set_cpus_allowed(current, cpumask_of_cpu(cpu));
2864         if (smp_processor_id() != cpu)
2865                 BUG();
2866
2867         init_waitqueue_head(&t->queue);
2868
2869         t->control &= ~(T_TERMINATE);
2870         t->control &= ~(T_RUN);
2871         t->control &= ~(T_STOP);
2872         t->control &= ~(T_REMDEVALL);
2873         t->control &= ~(T_REMDEV);
2874
2875         t->pid = current->pid;
2876
2877         PG_DEBUG(printk("pktgen: starting pktgen/%d:  pid=%d\n", cpu, current->pid));
2878
2879         max_before_softirq = t->max_before_softirq;
2880
2881         __set_current_state(TASK_INTERRUPTIBLE);
2882         mb();
2883
2884         while (1) {
2885
2886                 __set_current_state(TASK_RUNNING);
2887
2888                 /*
2889                  * Get next dev to xmit -- if any.
2890                  */
2891
2892                 pkt_dev = next_to_run(t);
2893
2894                 if (pkt_dev) {
2895
2896                         pktgen_xmit(pkt_dev);
2897
2898                         /*
2899                          * We like to stay RUNNING but must also give
2900                          * others fair share.
2901                          */
2902
2903                         tx_since_softirq += pkt_dev->last_ok;
2904
2905                         if (tx_since_softirq > max_before_softirq) {
2906                                 if (local_softirq_pending())
2907                                         do_softirq();
2908                                 tx_since_softirq = 0;
2909                         }
2910                 } else {
2911                         prepare_to_wait(&(t->queue), &wait, TASK_INTERRUPTIBLE);
2912                         schedule_timeout(HZ / 10);
2913                         finish_wait(&(t->queue), &wait);
2914                 }
2915
2916                 /*
2917                  * Back from sleep, either due to the timeout or signal.
2918                  * We check if we have any "posted" work for us.
2919                  */
2920
2921                 if (t->control & T_TERMINATE || signal_pending(current))
2922                         /* we received a request to terminate ourself */
2923                         break;
2924
2925                 if (t->control & T_STOP) {
2926                         pktgen_stop(t);
2927                         t->control &= ~(T_STOP);
2928                 }
2929
2930                 if (t->control & T_RUN) {
2931                         pktgen_run(t);
2932                         t->control &= ~(T_RUN);
2933                 }
2934
2935                 if (t->control & T_REMDEVALL) {
2936                         pktgen_rem_all_ifs(t);
2937                         t->control &= ~(T_REMDEVALL);
2938                 }
2939
2940                 if (t->control & T_REMDEV) {
2941                         pktgen_rem_one_if(t);
2942                         t->control &= ~(T_REMDEV);
2943                 }
2944
2945                 if (need_resched())
2946                         schedule();
2947         }
2948
2949         PG_DEBUG(printk("pktgen: %s stopping all device\n", t->name));
2950         pktgen_stop(t);
2951
2952         PG_DEBUG(printk("pktgen: %s removing all device\n", t->name));
2953         pktgen_rem_all_ifs(t);
2954
2955         PG_DEBUG(printk("pktgen: %s removing thread.\n", t->name));
2956         pktgen_rem_thread(t);
2957
2958         t->removed = 1;
2959 }
2960
2961 static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
2962                                           const char *ifname)
2963 {
2964         struct pktgen_dev *p, *pkt_dev = NULL;
2965         if_lock(t);
2966
2967         list_for_each_entry(p, &t->if_list, list)
2968                 if (strncmp(p->ifname, ifname, IFNAMSIZ) == 0) {
2969                         pkt_dev = p;
2970                         break;
2971                 }
2972
2973         if_unlock(t);
2974         PG_DEBUG(printk("pktgen: find_dev(%s) returning %p\n", ifname, pkt_dev));
2975         return pkt_dev;
2976 }
2977
2978 /* 
2979  * Adds a dev at front of if_list. 
2980  */
2981
2982 static int add_dev_to_thread(struct pktgen_thread *t,
2983                              struct pktgen_dev *pkt_dev)
2984 {
2985         int rv = 0;
2986
2987         if_lock(t);
2988
2989         if (pkt_dev->pg_thread) {
2990                 printk("pktgen: ERROR:  already assigned to a thread.\n");
2991                 rv = -EBUSY;
2992                 goto out;
2993         }
2994
2995         list_add(&pkt_dev->list, &t->if_list);
2996         pkt_dev->pg_thread = t;
2997         pkt_dev->running = 0;
2998
2999 out:
3000         if_unlock(t);
3001         return rv;
3002 }
3003
3004 /* Called under thread lock */
3005
3006 static int pktgen_add_device(struct pktgen_thread *t, const char *ifname)
3007 {
3008         struct pktgen_dev *pkt_dev;
3009         struct proc_dir_entry *pe;
3010
3011         /* We don't allow a device to be on several threads */
3012
3013         pkt_dev = __pktgen_NN_threads(ifname, FIND);
3014         if (pkt_dev) {
3015                 printk("pktgen: ERROR: interface already used.\n");
3016                 return -EBUSY;
3017         }
3018
3019         pkt_dev = kzalloc(sizeof(struct pktgen_dev), GFP_KERNEL);
3020         if (!pkt_dev)
3021                 return -ENOMEM;
3022
3023         pkt_dev->flows = vmalloc(MAX_CFLOWS * sizeof(struct flow_state));
3024         if (pkt_dev->flows == NULL) {
3025                 kfree(pkt_dev);
3026                 return -ENOMEM;
3027         }
3028         memset(pkt_dev->flows, 0, MAX_CFLOWS * sizeof(struct flow_state));
3029
3030         pkt_dev->removal_mark = 0;
3031         pkt_dev->min_pkt_size = ETH_ZLEN;
3032         pkt_dev->max_pkt_size = ETH_ZLEN;
3033         pkt_dev->nfrags = 0;
3034         pkt_dev->clone_skb = pg_clone_skb_d;
3035         pkt_dev->delay_us = pg_delay_d / 1000;
3036         pkt_dev->delay_ns = pg_delay_d % 1000;
3037         pkt_dev->count = pg_count_d;
3038         pkt_dev->sofar = 0;
3039         pkt_dev->udp_src_min = 9;       /* sink port */
3040         pkt_dev->udp_src_max = 9;
3041         pkt_dev->udp_dst_min = 9;
3042         pkt_dev->udp_dst_max = 9;
3043
3044         strncpy(pkt_dev->ifname, ifname, IFNAMSIZ);
3045
3046         if (!pktgen_setup_dev(pkt_dev)) {
3047                 printk("pktgen: ERROR: pktgen_setup_dev failed.\n");
3048                 if (pkt_dev->flows)
3049                         vfree(pkt_dev->flows);
3050                 kfree(pkt_dev);
3051                 return -ENODEV;
3052         }
3053
3054         pe = create_proc_entry(ifname, 0600, pg_proc_dir);
3055         if (!pe) {
3056                 printk("pktgen: cannot create %s/%s procfs entry.\n",
3057                        PG_PROC_DIR, ifname);
3058                 if (pkt_dev->flows)
3059                         vfree(pkt_dev->flows);
3060                 kfree(pkt_dev);
3061                 return -EINVAL;
3062         }
3063         pe->proc_fops = &pktgen_if_fops;
3064         pe->data = pkt_dev;
3065
3066         return add_dev_to_thread(t, pkt_dev);
3067 }
3068
3069 static struct pktgen_thread *__init pktgen_find_thread(const char *name)
3070 {
3071         struct pktgen_thread *t;
3072
3073         thread_lock();
3074
3075         list_for_each_entry(t, &pktgen_threads, th_list)
3076                 if (strcmp(t->name, name) == 0) {
3077                         thread_unlock();
3078                         return t;
3079                 }
3080
3081         thread_unlock();
3082         return NULL;
3083 }
3084
3085 static int __init pktgen_create_thread(const char *name, int cpu)
3086 {
3087         int err;
3088         struct pktgen_thread *t = NULL;
3089         struct proc_dir_entry *pe;
3090
3091         if (strlen(name) > 31) {
3092                 printk("pktgen: ERROR:  Thread name cannot be more than 31 characters.\n");
3093                 return -EINVAL;
3094         }
3095
3096         if (pktgen_find_thread(name)) {
3097                 printk("pktgen: ERROR: thread: %s already exists\n", name);
3098                 return -EINVAL;
3099         }
3100
3101         t = kzalloc(sizeof(struct pktgen_thread), GFP_KERNEL);
3102         if (!t) {
3103                 printk("pktgen: ERROR: out of memory, can't create new thread.\n");
3104                 return -ENOMEM;
3105         }
3106
3107         strcpy(t->name, name);
3108         spin_lock_init(&t->if_lock);
3109         t->cpu = cpu;
3110
3111         pe = create_proc_entry(t->name, 0600, pg_proc_dir);
3112         if (!pe) {
3113                 printk("pktgen: cannot create %s/%s procfs entry.\n",
3114                        PG_PROC_DIR, t->name);
3115                 kfree(t);
3116                 return -EINVAL;
3117         }
3118
3119         pe->proc_fops = &pktgen_thread_fops;
3120         pe->data = t;
3121
3122         INIT_LIST_HEAD(&t->if_list);
3123
3124         list_add_tail(&t->th_list, &pktgen_threads);
3125
3126         t->removed = 0;
3127
3128         err = kernel_thread((void *)pktgen_thread_worker, (void *)t,
3129                           CLONE_FS | CLONE_FILES | CLONE_SIGHAND);
3130         if (err < 0) {
3131                 printk("pktgen: kernel_thread() failed for cpu %d\n", t->cpu);
3132                 remove_proc_entry(t->name, pg_proc_dir);
3133                 list_del(&t->th_list);
3134                 kfree(t);
3135                 return err;
3136         }
3137
3138         return 0;
3139 }
3140
3141 /* 
3142  * Removes a device from the thread if_list. 
3143  */
3144 static void _rem_dev_from_if_list(struct pktgen_thread *t,
3145                                   struct pktgen_dev *pkt_dev)
3146 {
3147         struct list_head *q, *n;
3148         struct pktgen_dev *p;
3149
3150         list_for_each_safe(q, n, &t->if_list) {
3151                 p = list_entry(q, struct pktgen_dev, list);
3152                 if (p == pkt_dev)
3153                         list_del(&p->list);
3154         }
3155 }
3156
3157 static int pktgen_remove_device(struct pktgen_thread *t,
3158                                 struct pktgen_dev *pkt_dev)
3159 {
3160
3161         PG_DEBUG(printk("pktgen: remove_device pkt_dev=%p\n", pkt_dev));
3162
3163         if (pkt_dev->running) {
3164                 printk("pktgen:WARNING: trying to remove a running interface, stopping it now.\n");
3165                 pktgen_stop_device(pkt_dev);
3166         }
3167
3168         /* Dis-associate from the interface */
3169
3170         if (pkt_dev->odev) {
3171                 dev_put(pkt_dev->odev);
3172                 pkt_dev->odev = NULL;
3173         }
3174
3175         /* And update the thread if_list */
3176
3177         _rem_dev_from_if_list(t, pkt_dev);
3178
3179         /* Clean up proc file system */
3180
3181         remove_proc_entry(pkt_dev->ifname, pg_proc_dir);
3182
3183         if (pkt_dev->flows)
3184                 vfree(pkt_dev->flows);
3185         kfree(pkt_dev);
3186         return 0;
3187 }
3188
3189 static int __init pg_init(void)
3190 {
3191         int cpu;
3192         struct proc_dir_entry *pe;
3193
3194         printk(version);
3195
3196         pg_proc_dir = proc_mkdir(PG_PROC_DIR, proc_net);
3197         if (!pg_proc_dir)
3198                 return -ENODEV;
3199         pg_proc_dir->owner = THIS_MODULE;
3200
3201         pe = create_proc_entry(PGCTRL, 0600, pg_proc_dir);
3202         if (pe == NULL) {
3203                 printk("pktgen: ERROR: cannot create %s procfs entry.\n",
3204                        PGCTRL);
3205                 proc_net_remove(PG_PROC_DIR);
3206                 return -EINVAL;
3207         }
3208
3209         pe->proc_fops = &pktgen_fops;
3210         pe->data = NULL;
3211
3212         /* Register us to receive netdevice events */
3213         register_netdevice_notifier(&pktgen_notifier_block);
3214
3215         for_each_online_cpu(cpu) {
3216                 int err;
3217                 char buf[30];
3218
3219                 sprintf(buf, "kpktgend_%i", cpu);
3220                 err = pktgen_create_thread(buf, cpu);
3221                 if (err)
3222                         printk("pktgen: WARNING: Cannot create thread for cpu %d (%d)\n",
3223                                         cpu, err);
3224         }
3225
3226         if (list_empty(&pktgen_threads)) {
3227                 printk("pktgen: ERROR: Initialization failed for all threads\n");
3228                 unregister_netdevice_notifier(&pktgen_notifier_block);
3229                 remove_proc_entry(PGCTRL, pg_proc_dir);
3230                 proc_net_remove(PG_PROC_DIR);
3231                 return -ENODEV;
3232         }
3233
3234         return 0;
3235 }
3236
3237 static void __exit pg_cleanup(void)
3238 {
3239         struct pktgen_thread *t;
3240         struct list_head *q, *n;
3241         wait_queue_head_t queue;
3242         init_waitqueue_head(&queue);
3243
3244         /* Stop all interfaces & threads */
3245
3246         list_for_each_safe(q, n, &pktgen_threads) {
3247                 t = list_entry(q, struct pktgen_thread, th_list);
3248                 t->control |= (T_TERMINATE);
3249
3250                 wait_event_interruptible_timeout(queue, (t->removed == 1), HZ);
3251         }
3252
3253         /* Un-register us from receiving netdevice events */
3254         unregister_netdevice_notifier(&pktgen_notifier_block);
3255
3256         /* Clean up proc file system */
3257         remove_proc_entry(PGCTRL, pg_proc_dir);
3258         proc_net_remove(PG_PROC_DIR);
3259 }
3260
3261 module_init(pg_init);
3262 module_exit(pg_cleanup);
3263
3264 MODULE_AUTHOR("Robert Olsson <robert.olsson@its.uu.se");
3265 MODULE_DESCRIPTION("Packet Generator tool");
3266 MODULE_LICENSE("GPL");
3267 module_param(pg_count_d, int, 0);
3268 module_param(pg_delay_d, int, 0);
3269 module_param(pg_clone_skb_d, int, 0);
3270 module_param(debug, int, 0);