Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/linville/wirel...
[linux-drm-fsl-dcu.git] / drivers / net / ethernet / tile / tilegx.c
1 /*
2  * Copyright 2012 Tilera Corporation. All Rights Reserved.
3  *
4  *   This program is free software; you can redistribute it and/or
5  *   modify it under the terms of the GNU General Public License
6  *   as published by the Free Software Foundation, version 2.
7  *
8  *   This program is distributed in the hope that it will be useful, but
9  *   WITHOUT ANY WARRANTY; without even the implied warranty of
10  *   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
11  *   NON INFRINGEMENT.  See the GNU General Public License for
12  *   more details.
13  */
14
15 #include <linux/module.h>
16 #include <linux/init.h>
17 #include <linux/moduleparam.h>
18 #include <linux/sched.h>
19 #include <linux/kernel.h>      /* printk() */
20 #include <linux/slab.h>        /* kmalloc() */
21 #include <linux/errno.h>       /* error codes */
22 #include <linux/types.h>       /* size_t */
23 #include <linux/interrupt.h>
24 #include <linux/in.h>
25 #include <linux/irq.h>
26 #include <linux/netdevice.h>   /* struct device, and other headers */
27 #include <linux/etherdevice.h> /* eth_type_trans */
28 #include <linux/skbuff.h>
29 #include <linux/ioctl.h>
30 #include <linux/cdev.h>
31 #include <linux/hugetlb.h>
32 #include <linux/in6.h>
33 #include <linux/timer.h>
34 #include <linux/hrtimer.h>
35 #include <linux/ktime.h>
36 #include <linux/io.h>
37 #include <linux/ctype.h>
38 #include <linux/ip.h>
39 #include <linux/ipv6.h>
40 #include <linux/tcp.h>
41 #include <linux/net_tstamp.h>
42 #include <linux/ptp_clock_kernel.h>
43
44 #include <asm/checksum.h>
45 #include <asm/homecache.h>
46 #include <gxio/mpipe.h>
47 #include <arch/sim.h>
48
49 /* Default transmit lockup timeout period, in jiffies. */
50 #define TILE_NET_TIMEOUT (5 * HZ)
51
52 /* The maximum number of distinct channels (idesc.channel is 5 bits). */
53 #define TILE_NET_CHANNELS 32
54
55 /* Maximum number of idescs to handle per "poll". */
56 #define TILE_NET_BATCH 128
57
58 /* Maximum number of packets to handle per "poll". */
59 #define TILE_NET_WEIGHT 64
60
61 /* Number of entries in each iqueue. */
62 #define IQUEUE_ENTRIES 512
63
64 /* Number of entries in each equeue. */
65 #define EQUEUE_ENTRIES 2048
66
67 /* Total header bytes per equeue slot.  Must be big enough for 2 bytes
68  * of NET_IP_ALIGN alignment, plus 14 bytes (?) of L2 header, plus up to
69  * 60 bytes of actual TCP header.  We round up to align to cache lines.
70  */
71 #define HEADER_BYTES 128
72
73 /* Maximum completions per cpu per device (must be a power of two).
74  * ISSUE: What is the right number here?  If this is too small, then
75  * egress might block waiting for free space in a completions array.
76  * ISSUE: At the least, allocate these only for initialized echannels.
77  */
78 #define TILE_NET_MAX_COMPS 64
79
80 #define MAX_FRAGS (MAX_SKB_FRAGS + 1)
81
82 /* The "kinds" of buffer stacks (small/large/jumbo). */
83 #define MAX_KINDS 3
84
85 /* Size of completions data to allocate.
86  * ISSUE: Probably more than needed since we don't use all the channels.
87  */
88 #define COMPS_SIZE (TILE_NET_CHANNELS * sizeof(struct tile_net_comps))
89
90 /* Size of NotifRing data to allocate. */
91 #define NOTIF_RING_SIZE (IQUEUE_ENTRIES * sizeof(gxio_mpipe_idesc_t))
92
93 /* Timeout to wake the per-device TX timer after we stop the queue.
94  * We don't want the timeout too short (adds overhead, and might end
95  * up causing stop/wake/stop/wake cycles) or too long (affects performance).
96  * For the 10 Gb NIC, 30 usec means roughly 30+ 1500-byte packets.
97  */
98 #define TX_TIMER_DELAY_USEC 30
99
100 /* Timeout to wake the per-cpu egress timer to free completions. */
101 #define EGRESS_TIMER_DELAY_USEC 1000
102
103 MODULE_AUTHOR("Tilera Corporation");
104 MODULE_LICENSE("GPL");
105
106 /* A "packet fragment" (a chunk of memory). */
107 struct frag {
108         void *buf;
109         size_t length;
110 };
111
112 /* A single completion. */
113 struct tile_net_comp {
114         /* The "complete_count" when the completion will be complete. */
115         s64 when;
116         /* The buffer to be freed when the completion is complete. */
117         struct sk_buff *skb;
118 };
119
120 /* The completions for a given cpu and echannel. */
121 struct tile_net_comps {
122         /* The completions. */
123         struct tile_net_comp comp_queue[TILE_NET_MAX_COMPS];
124         /* The number of completions used. */
125         unsigned long comp_next;
126         /* The number of completions freed. */
127         unsigned long comp_last;
128 };
129
130 /* The transmit wake timer for a given cpu and echannel. */
131 struct tile_net_tx_wake {
132         int tx_queue_idx;
133         struct hrtimer timer;
134         struct net_device *dev;
135 };
136
137 /* Info for a specific cpu. */
138 struct tile_net_info {
139         /* Our cpu. */
140         int my_cpu;
141         /* A timer for handling egress completions. */
142         struct hrtimer egress_timer;
143         /* True if "egress_timer" is scheduled. */
144         bool egress_timer_scheduled;
145         struct info_mpipe {
146                 /* Packet queue. */
147                 gxio_mpipe_iqueue_t iqueue;
148                 /* The NAPI struct. */
149                 struct napi_struct napi;
150                 /* Number of buffers (by kind) which must still be provided. */
151                 unsigned int num_needed_buffers[MAX_KINDS];
152                 /* instance id. */
153                 int instance;
154                 /* True if iqueue is valid. */
155                 bool has_iqueue;
156                 /* NAPI flags. */
157                 bool napi_added;
158                 bool napi_enabled;
159                 /* Comps for each egress channel. */
160                 struct tile_net_comps *comps_for_echannel[TILE_NET_CHANNELS];
161                 /* Transmit wake timer for each egress channel. */
162                 struct tile_net_tx_wake tx_wake[TILE_NET_CHANNELS];
163         } mpipe[NR_MPIPE_MAX];
164 };
165
166 /* Info for egress on a particular egress channel. */
167 struct tile_net_egress {
168         /* The "equeue". */
169         gxio_mpipe_equeue_t *equeue;
170         /* The headers for TSO. */
171         unsigned char *headers;
172 };
173
174 /* Info for a specific device. */
175 struct tile_net_priv {
176         /* Our network device. */
177         struct net_device *dev;
178         /* The primary link. */
179         gxio_mpipe_link_t link;
180         /* The primary channel, if open, else -1. */
181         int channel;
182         /* The "loopify" egress link, if needed. */
183         gxio_mpipe_link_t loopify_link;
184         /* The "loopify" egress channel, if open, else -1. */
185         int loopify_channel;
186         /* The egress channel (channel or loopify_channel). */
187         int echannel;
188         /* mPIPE instance, 0 or 1. */
189         int instance;
190 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
191         /* The timestamp config. */
192         struct hwtstamp_config stamp_cfg;
193 #endif
194 };
195
196 static struct mpipe_data {
197         /* The ingress irq. */
198         int ingress_irq;
199
200         /* The "context" for all devices. */
201         gxio_mpipe_context_t context;
202
203         /* Egress info, indexed by "priv->echannel"
204          * (lazily created as needed).
205          */
206         struct tile_net_egress
207         egress_for_echannel[TILE_NET_CHANNELS];
208
209         /* Devices currently associated with each channel.
210          * NOTE: The array entry can become NULL after ifconfig down, but
211          * we do not free the underlying net_device structures, so it is
212          * safe to use a pointer after reading it from this array.
213          */
214         struct net_device
215         *tile_net_devs_for_channel[TILE_NET_CHANNELS];
216
217         /* The actual memory allocated for the buffer stacks. */
218         void *buffer_stack_vas[MAX_KINDS];
219
220         /* The amount of memory allocated for each buffer stack. */
221         size_t buffer_stack_bytes[MAX_KINDS];
222
223         /* The first buffer stack index
224          * (small = +0, large = +1, jumbo = +2).
225          */
226         int first_buffer_stack;
227
228         /* The buckets. */
229         int first_bucket;
230         int num_buckets;
231
232 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
233         /* PTP-specific data. */
234         struct ptp_clock *ptp_clock;
235         struct ptp_clock_info caps;
236
237         /* Lock for ptp accessors. */
238         struct mutex ptp_lock;
239 #endif
240
241 } mpipe_data[NR_MPIPE_MAX] = {
242         [0 ... (NR_MPIPE_MAX - 1)] {
243                 .ingress_irq = -1,
244                 .first_buffer_stack = -1,
245                 .first_bucket = -1,
246                 .num_buckets = 1
247         }
248 };
249
250 /* A mutex for "tile_net_devs_for_channel". */
251 static DEFINE_MUTEX(tile_net_devs_for_channel_mutex);
252
253 /* The per-cpu info. */
254 static DEFINE_PER_CPU(struct tile_net_info, per_cpu_info);
255
256
257 /* The buffer size enums for each buffer stack.
258  * See arch/tile/include/gxio/mpipe.h for the set of possible values.
259  * We avoid the "10384" size because it can induce "false chaining"
260  * on "cut-through" jumbo packets.
261  */
262 static gxio_mpipe_buffer_size_enum_t buffer_size_enums[MAX_KINDS] = {
263         GXIO_MPIPE_BUFFER_SIZE_128,
264         GXIO_MPIPE_BUFFER_SIZE_1664,
265         GXIO_MPIPE_BUFFER_SIZE_16384
266 };
267
268 /* Text value of tile_net.cpus if passed as a module parameter. */
269 static char *network_cpus_string;
270
271 /* The actual cpus in "network_cpus". */
272 static struct cpumask network_cpus_map;
273
274 /* If "tile_net.loopify=LINK" was specified, this is "LINK". */
275 static char *loopify_link_name;
276
277 /* If "tile_net.custom" was specified, this is true. */
278 static bool custom_flag;
279
280 /* If "tile_net.jumbo=NUM" was specified, this is "NUM". */
281 static uint jumbo_num;
282
283 /* Obtain mpipe instance from struct tile_net_priv given struct net_device. */
284 static inline int mpipe_instance(struct net_device *dev)
285 {
286         struct tile_net_priv *priv = netdev_priv(dev);
287         return priv->instance;
288 }
289
290 /* The "tile_net.cpus" argument specifies the cpus that are dedicated
291  * to handle ingress packets.
292  *
293  * The parameter should be in the form "tile_net.cpus=m-n[,x-y]", where
294  * m, n, x, y are integer numbers that represent the cpus that can be
295  * neither a dedicated cpu nor a dataplane cpu.
296  */
297 static bool network_cpus_init(void)
298 {
299         char buf[1024];
300         int rc;
301
302         if (network_cpus_string == NULL)
303                 return false;
304
305         rc = cpulist_parse_crop(network_cpus_string, &network_cpus_map);
306         if (rc != 0) {
307                 pr_warn("tile_net.cpus=%s: malformed cpu list\n",
308                         network_cpus_string);
309                 return false;
310         }
311
312         /* Remove dedicated cpus. */
313         cpumask_and(&network_cpus_map, &network_cpus_map, cpu_possible_mask);
314
315         if (cpumask_empty(&network_cpus_map)) {
316                 pr_warn("Ignoring empty tile_net.cpus='%s'.\n",
317                         network_cpus_string);
318                 return false;
319         }
320
321         cpulist_scnprintf(buf, sizeof(buf), &network_cpus_map);
322         pr_info("Linux network CPUs: %s\n", buf);
323         return true;
324 }
325
326 module_param_named(cpus, network_cpus_string, charp, 0444);
327 MODULE_PARM_DESC(cpus, "cpulist of cores that handle network interrupts");
328
329 /* The "tile_net.loopify=LINK" argument causes the named device to
330  * actually use "loop0" for ingress, and "loop1" for egress.  This
331  * allows an app to sit between the actual link and linux, passing
332  * (some) packets along to linux, and forwarding (some) packets sent
333  * out by linux.
334  */
335 module_param_named(loopify, loopify_link_name, charp, 0444);
336 MODULE_PARM_DESC(loopify, "name the device to use loop0/1 for ingress/egress");
337
338 /* The "tile_net.custom" argument causes us to ignore the "conventional"
339  * classifier metadata, in particular, the "l2_offset".
340  */
341 module_param_named(custom, custom_flag, bool, 0444);
342 MODULE_PARM_DESC(custom, "indicates a (heavily) customized classifier");
343
344 /* The "tile_net.jumbo" argument causes us to support "jumbo" packets,
345  * and to allocate the given number of "jumbo" buffers.
346  */
347 module_param_named(jumbo, jumbo_num, uint, 0444);
348 MODULE_PARM_DESC(jumbo, "the number of buffers to support jumbo packets");
349
350 /* Atomically update a statistics field.
351  * Note that on TILE-Gx, this operation is fire-and-forget on the
352  * issuing core (single-cycle dispatch) and takes only a few cycles
353  * longer than a regular store when the request reaches the home cache.
354  * No expensive bus management overhead is required.
355  */
356 static void tile_net_stats_add(unsigned long value, unsigned long *field)
357 {
358         BUILD_BUG_ON(sizeof(atomic_long_t) != sizeof(unsigned long));
359         atomic_long_add(value, (atomic_long_t *)field);
360 }
361
362 /* Allocate and push a buffer. */
363 static bool tile_net_provide_buffer(int instance, int kind)
364 {
365         struct mpipe_data *md = &mpipe_data[instance];
366         gxio_mpipe_buffer_size_enum_t bse = buffer_size_enums[kind];
367         size_t bs = gxio_mpipe_buffer_size_enum_to_buffer_size(bse);
368         const unsigned long buffer_alignment = 128;
369         struct sk_buff *skb;
370         int len;
371
372         len = sizeof(struct sk_buff **) + buffer_alignment + bs;
373         skb = dev_alloc_skb(len);
374         if (skb == NULL)
375                 return false;
376
377         /* Make room for a back-pointer to 'skb' and guarantee alignment. */
378         skb_reserve(skb, sizeof(struct sk_buff **));
379         skb_reserve(skb, -(long)skb->data & (buffer_alignment - 1));
380
381         /* Save a back-pointer to 'skb'. */
382         *(struct sk_buff **)(skb->data - sizeof(struct sk_buff **)) = skb;
383
384         /* Make sure "skb" and the back-pointer have been flushed. */
385         wmb();
386
387         gxio_mpipe_push_buffer(&md->context, md->first_buffer_stack + kind,
388                                (void *)va_to_tile_io_addr(skb->data));
389
390         return true;
391 }
392
393 /* Convert a raw mpipe buffer to its matching skb pointer. */
394 static struct sk_buff *mpipe_buf_to_skb(void *va)
395 {
396         /* Acquire the associated "skb". */
397         struct sk_buff **skb_ptr = va - sizeof(*skb_ptr);
398         struct sk_buff *skb = *skb_ptr;
399
400         /* Paranoia. */
401         if (skb->data != va) {
402                 /* Panic here since there's a reasonable chance
403                  * that corrupt buffers means generic memory
404                  * corruption, with unpredictable system effects.
405                  */
406                 panic("Corrupt linux buffer! va=%p, skb=%p, skb->data=%p",
407                       va, skb, skb->data);
408         }
409
410         return skb;
411 }
412
413 static void tile_net_pop_all_buffers(int instance, int stack)
414 {
415         struct mpipe_data *md = &mpipe_data[instance];
416
417         for (;;) {
418                 tile_io_addr_t addr =
419                         (tile_io_addr_t)gxio_mpipe_pop_buffer(&md->context,
420                                                               stack);
421                 if (addr == 0)
422                         break;
423                 dev_kfree_skb_irq(mpipe_buf_to_skb(tile_io_addr_to_va(addr)));
424         }
425 }
426
427 /* Provide linux buffers to mPIPE. */
428 static void tile_net_provide_needed_buffers(void)
429 {
430         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
431         int instance, kind;
432         for (instance = 0; instance < NR_MPIPE_MAX &&
433                      info->mpipe[instance].has_iqueue; instance++)      {
434                 for (kind = 0; kind < MAX_KINDS; kind++) {
435                         while (info->mpipe[instance].num_needed_buffers[kind]
436                                != 0) {
437                                 if (!tile_net_provide_buffer(instance, kind)) {
438                                         pr_notice("Tile %d still needs"
439                                                   " some buffers\n",
440                                                   info->my_cpu);
441                                         return;
442                                 }
443                                 info->mpipe[instance].
444                                         num_needed_buffers[kind]--;
445                         }
446                 }
447         }
448 }
449
450 /* Get RX timestamp, and store it in the skb. */
451 static void tile_rx_timestamp(struct tile_net_priv *priv, struct sk_buff *skb,
452                               gxio_mpipe_idesc_t *idesc)
453 {
454 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
455         if (unlikely(priv->stamp_cfg.rx_filter != HWTSTAMP_FILTER_NONE)) {
456                 struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
457                 memset(shhwtstamps, 0, sizeof(*shhwtstamps));
458                 shhwtstamps->hwtstamp = ktime_set(idesc->time_stamp_sec,
459                                                   idesc->time_stamp_ns);
460         }
461 #endif
462 }
463
464 /* Get TX timestamp, and store it in the skb. */
465 static void tile_tx_timestamp(struct sk_buff *skb, int instance)
466 {
467 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
468         struct skb_shared_info *shtx = skb_shinfo(skb);
469         if (unlikely((shtx->tx_flags & SKBTX_HW_TSTAMP) != 0)) {
470                 struct mpipe_data *md = &mpipe_data[instance];
471                 struct skb_shared_hwtstamps shhwtstamps;
472                 struct timespec ts;
473
474                 shtx->tx_flags |= SKBTX_IN_PROGRESS;
475                 gxio_mpipe_get_timestamp(&md->context, &ts);
476                 memset(&shhwtstamps, 0, sizeof(shhwtstamps));
477                 shhwtstamps.hwtstamp = ktime_set(ts.tv_sec, ts.tv_nsec);
478                 skb_tstamp_tx(skb, &shhwtstamps);
479         }
480 #endif
481 }
482
483 /* Use ioctl() to enable or disable TX or RX timestamping. */
484 static int tile_hwtstamp_set(struct net_device *dev, struct ifreq *rq)
485 {
486 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
487         struct hwtstamp_config config;
488         struct tile_net_priv *priv = netdev_priv(dev);
489
490         if (copy_from_user(&config, rq->ifr_data, sizeof(config)))
491                 return -EFAULT;
492
493         if (config.flags)  /* reserved for future extensions */
494                 return -EINVAL;
495
496         switch (config.tx_type) {
497         case HWTSTAMP_TX_OFF:
498         case HWTSTAMP_TX_ON:
499                 break;
500         default:
501                 return -ERANGE;
502         }
503
504         switch (config.rx_filter) {
505         case HWTSTAMP_FILTER_NONE:
506                 break;
507         case HWTSTAMP_FILTER_ALL:
508         case HWTSTAMP_FILTER_SOME:
509         case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
510         case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
511         case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
512         case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
513         case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
514         case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
515         case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
516         case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
517         case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
518         case HWTSTAMP_FILTER_PTP_V2_EVENT:
519         case HWTSTAMP_FILTER_PTP_V2_SYNC:
520         case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
521                 config.rx_filter = HWTSTAMP_FILTER_ALL;
522                 break;
523         default:
524                 return -ERANGE;
525         }
526
527         if (copy_to_user(rq->ifr_data, &config, sizeof(config)))
528                 return -EFAULT;
529
530         priv->stamp_cfg = config;
531         return 0;
532 #else
533         return -EOPNOTSUPP;
534 #endif
535 }
536
537 static int tile_hwtstamp_get(struct net_device *dev, struct ifreq *rq)
538 {
539 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
540         struct tile_net_priv *priv = netdev_priv(dev);
541
542         if (copy_to_user(rq->ifr_data, &priv->stamp_cfg,
543                          sizeof(priv->stamp_cfg)))
544                 return -EFAULT;
545
546         return 0;
547 #else
548         return -EOPNOTSUPP;
549 #endif
550 }
551
552 static inline bool filter_packet(struct net_device *dev, void *buf)
553 {
554         /* Filter packets received before we're up. */
555         if (dev == NULL || !(dev->flags & IFF_UP))
556                 return true;
557
558         /* Filter out packets that aren't for us. */
559         if (!(dev->flags & IFF_PROMISC) &&
560             !is_multicast_ether_addr(buf) &&
561             !ether_addr_equal(dev->dev_addr, buf))
562                 return true;
563
564         return false;
565 }
566
567 static void tile_net_receive_skb(struct net_device *dev, struct sk_buff *skb,
568                                  gxio_mpipe_idesc_t *idesc, unsigned long len)
569 {
570         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
571         struct tile_net_priv *priv = netdev_priv(dev);
572         int instance = priv->instance;
573
574         /* Encode the actual packet length. */
575         skb_put(skb, len);
576
577         skb->protocol = eth_type_trans(skb, dev);
578
579         /* Acknowledge "good" hardware checksums. */
580         if (idesc->cs && idesc->csum_seed_val == 0xFFFF)
581                 skb->ip_summed = CHECKSUM_UNNECESSARY;
582
583         /* Get RX timestamp from idesc. */
584         tile_rx_timestamp(priv, skb, idesc);
585
586         napi_gro_receive(&info->mpipe[instance].napi, skb);
587
588         /* Update stats. */
589         tile_net_stats_add(1, &dev->stats.rx_packets);
590         tile_net_stats_add(len, &dev->stats.rx_bytes);
591
592         /* Need a new buffer. */
593         if (idesc->size == buffer_size_enums[0])
594                 info->mpipe[instance].num_needed_buffers[0]++;
595         else if (idesc->size == buffer_size_enums[1])
596                 info->mpipe[instance].num_needed_buffers[1]++;
597         else
598                 info->mpipe[instance].num_needed_buffers[2]++;
599 }
600
601 /* Handle a packet.  Return true if "processed", false if "filtered". */
602 static bool tile_net_handle_packet(int instance, gxio_mpipe_idesc_t *idesc)
603 {
604         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
605         struct mpipe_data *md = &mpipe_data[instance];
606         struct net_device *dev = md->tile_net_devs_for_channel[idesc->channel];
607         uint8_t l2_offset;
608         void *va;
609         void *buf;
610         unsigned long len;
611         bool filter;
612
613         /* Drop packets for which no buffer was available (which can
614          * happen under heavy load), or for which the me/tr/ce flags
615          * are set (which can happen for jumbo cut-through packets,
616          * or with a customized classifier).
617          */
618         if (idesc->be || idesc->me || idesc->tr || idesc->ce) {
619                 if (dev)
620                         tile_net_stats_add(1, &dev->stats.rx_errors);
621                 goto drop;
622         }
623
624         /* Get the "l2_offset", if allowed. */
625         l2_offset = custom_flag ? 0 : gxio_mpipe_idesc_get_l2_offset(idesc);
626
627         /* Get the VA (including NET_IP_ALIGN bytes of "headroom"). */
628         va = tile_io_addr_to_va((unsigned long)idesc->va);
629
630         /* Get the actual packet start/length. */
631         buf = va + l2_offset;
632         len = idesc->l2_size - l2_offset;
633
634         /* Point "va" at the raw buffer. */
635         va -= NET_IP_ALIGN;
636
637         filter = filter_packet(dev, buf);
638         if (filter) {
639                 if (dev)
640                         tile_net_stats_add(1, &dev->stats.rx_dropped);
641 drop:
642                 gxio_mpipe_iqueue_drop(&info->mpipe[instance].iqueue, idesc);
643         } else {
644                 struct sk_buff *skb = mpipe_buf_to_skb(va);
645
646                 /* Skip headroom, and any custom header. */
647                 skb_reserve(skb, NET_IP_ALIGN + l2_offset);
648
649                 tile_net_receive_skb(dev, skb, idesc, len);
650         }
651
652         gxio_mpipe_iqueue_consume(&info->mpipe[instance].iqueue, idesc);
653         return !filter;
654 }
655
656 /* Handle some packets for the current CPU.
657  *
658  * This function handles up to TILE_NET_BATCH idescs per call.
659  *
660  * ISSUE: Since we do not provide new buffers until this function is
661  * complete, we must initially provide enough buffers for each network
662  * cpu to fill its iqueue and also its batched idescs.
663  *
664  * ISSUE: The "rotting packet" race condition occurs if a packet
665  * arrives after the queue appears to be empty, and before the
666  * hypervisor interrupt is re-enabled.
667  */
668 static int tile_net_poll(struct napi_struct *napi, int budget)
669 {
670         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
671         unsigned int work = 0;
672         gxio_mpipe_idesc_t *idesc;
673         int instance, i, n;
674         struct mpipe_data *md;
675         struct info_mpipe *info_mpipe =
676                 container_of(napi, struct info_mpipe, napi);
677
678         instance = info_mpipe->instance;
679         while ((n = gxio_mpipe_iqueue_try_peek(
680                         &info_mpipe->iqueue,
681                         &idesc)) > 0) {
682                 for (i = 0; i < n; i++) {
683                         if (i == TILE_NET_BATCH)
684                                 goto done;
685                         if (tile_net_handle_packet(instance,
686                                                    idesc + i)) {
687                                 if (++work >= budget)
688                                         goto done;
689                         }
690                 }
691         }
692
693         /* There are no packets left. */
694         napi_complete(&info_mpipe->napi);
695
696         md = &mpipe_data[instance];
697         /* Re-enable hypervisor interrupts. */
698         gxio_mpipe_enable_notif_ring_interrupt(
699                 &md->context, info->mpipe[instance].iqueue.ring);
700
701         /* HACK: Avoid the "rotting packet" problem. */
702         if (gxio_mpipe_iqueue_try_peek(&info_mpipe->iqueue, &idesc) > 0)
703                 napi_schedule(&info_mpipe->napi);
704
705         /* ISSUE: Handle completions? */
706
707 done:
708         tile_net_provide_needed_buffers();
709
710         return work;
711 }
712
713 /* Handle an ingress interrupt from an instance on the current cpu. */
714 static irqreturn_t tile_net_handle_ingress_irq(int irq, void *id)
715 {
716         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
717         napi_schedule(&info->mpipe[(uint64_t)id].napi);
718         return IRQ_HANDLED;
719 }
720
721 /* Free some completions.  This must be called with interrupts blocked. */
722 static int tile_net_free_comps(gxio_mpipe_equeue_t *equeue,
723                                 struct tile_net_comps *comps,
724                                 int limit, bool force_update)
725 {
726         int n = 0;
727         while (comps->comp_last < comps->comp_next) {
728                 unsigned int cid = comps->comp_last % TILE_NET_MAX_COMPS;
729                 struct tile_net_comp *comp = &comps->comp_queue[cid];
730                 if (!gxio_mpipe_equeue_is_complete(equeue, comp->when,
731                                                    force_update || n == 0))
732                         break;
733                 dev_kfree_skb_irq(comp->skb);
734                 comps->comp_last++;
735                 if (++n == limit)
736                         break;
737         }
738         return n;
739 }
740
741 /* Add a completion.  This must be called with interrupts blocked.
742  * tile_net_equeue_try_reserve() will have ensured a free completion entry.
743  */
744 static void add_comp(gxio_mpipe_equeue_t *equeue,
745                      struct tile_net_comps *comps,
746                      uint64_t when, struct sk_buff *skb)
747 {
748         int cid = comps->comp_next % TILE_NET_MAX_COMPS;
749         comps->comp_queue[cid].when = when;
750         comps->comp_queue[cid].skb = skb;
751         comps->comp_next++;
752 }
753
754 static void tile_net_schedule_tx_wake_timer(struct net_device *dev,
755                                             int tx_queue_idx)
756 {
757         struct tile_net_info *info = &per_cpu(per_cpu_info, tx_queue_idx);
758         struct tile_net_priv *priv = netdev_priv(dev);
759         int instance = priv->instance;
760         struct tile_net_tx_wake *tx_wake =
761                 &info->mpipe[instance].tx_wake[priv->echannel];
762
763         hrtimer_start(&tx_wake->timer,
764                       ktime_set(0, TX_TIMER_DELAY_USEC * 1000UL),
765                       HRTIMER_MODE_REL_PINNED);
766 }
767
768 static enum hrtimer_restart tile_net_handle_tx_wake_timer(struct hrtimer *t)
769 {
770         struct tile_net_tx_wake *tx_wake =
771                 container_of(t, struct tile_net_tx_wake, timer);
772         netif_wake_subqueue(tx_wake->dev, tx_wake->tx_queue_idx);
773         return HRTIMER_NORESTART;
774 }
775
776 /* Make sure the egress timer is scheduled. */
777 static void tile_net_schedule_egress_timer(void)
778 {
779         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
780
781         if (!info->egress_timer_scheduled) {
782                 hrtimer_start(&info->egress_timer,
783                               ktime_set(0, EGRESS_TIMER_DELAY_USEC * 1000UL),
784                               HRTIMER_MODE_REL_PINNED);
785                 info->egress_timer_scheduled = true;
786         }
787 }
788
789 /* The "function" for "info->egress_timer".
790  *
791  * This timer will reschedule itself as long as there are any pending
792  * completions expected for this tile.
793  */
794 static enum hrtimer_restart tile_net_handle_egress_timer(struct hrtimer *t)
795 {
796         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
797         unsigned long irqflags;
798         bool pending = false;
799         int i, instance;
800
801         local_irq_save(irqflags);
802
803         /* The timer is no longer scheduled. */
804         info->egress_timer_scheduled = false;
805
806         /* Free all possible comps for this tile. */
807         for (instance = 0; instance < NR_MPIPE_MAX &&
808                      info->mpipe[instance].has_iqueue; instance++) {
809                 for (i = 0; i < TILE_NET_CHANNELS; i++) {
810                         struct tile_net_egress *egress =
811                                 &mpipe_data[instance].egress_for_echannel[i];
812                         struct tile_net_comps *comps =
813                                 info->mpipe[instance].comps_for_echannel[i];
814                         if (!egress || comps->comp_last >= comps->comp_next)
815                                 continue;
816                         tile_net_free_comps(egress->equeue, comps, -1, true);
817                         pending = pending ||
818                                 (comps->comp_last < comps->comp_next);
819                 }
820         }
821
822         /* Reschedule timer if needed. */
823         if (pending)
824                 tile_net_schedule_egress_timer();
825
826         local_irq_restore(irqflags);
827
828         return HRTIMER_NORESTART;
829 }
830
831 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
832
833 /* PTP clock operations. */
834
835 static int ptp_mpipe_adjfreq(struct ptp_clock_info *ptp, s32 ppb)
836 {
837         int ret = 0;
838         struct mpipe_data *md = container_of(ptp, struct mpipe_data, caps);
839         mutex_lock(&md->ptp_lock);
840         if (gxio_mpipe_adjust_timestamp_freq(&md->context, ppb))
841                 ret = -EINVAL;
842         mutex_unlock(&md->ptp_lock);
843         return ret;
844 }
845
846 static int ptp_mpipe_adjtime(struct ptp_clock_info *ptp, s64 delta)
847 {
848         int ret = 0;
849         struct mpipe_data *md = container_of(ptp, struct mpipe_data, caps);
850         mutex_lock(&md->ptp_lock);
851         if (gxio_mpipe_adjust_timestamp(&md->context, delta))
852                 ret = -EBUSY;
853         mutex_unlock(&md->ptp_lock);
854         return ret;
855 }
856
857 static int ptp_mpipe_gettime(struct ptp_clock_info *ptp, struct timespec *ts)
858 {
859         int ret = 0;
860         struct mpipe_data *md = container_of(ptp, struct mpipe_data, caps);
861         mutex_lock(&md->ptp_lock);
862         if (gxio_mpipe_get_timestamp(&md->context, ts))
863                 ret = -EBUSY;
864         mutex_unlock(&md->ptp_lock);
865         return ret;
866 }
867
868 static int ptp_mpipe_settime(struct ptp_clock_info *ptp,
869                              const struct timespec *ts)
870 {
871         int ret = 0;
872         struct mpipe_data *md = container_of(ptp, struct mpipe_data, caps);
873         mutex_lock(&md->ptp_lock);
874         if (gxio_mpipe_set_timestamp(&md->context, ts))
875                 ret = -EBUSY;
876         mutex_unlock(&md->ptp_lock);
877         return ret;
878 }
879
880 static int ptp_mpipe_enable(struct ptp_clock_info *ptp,
881                             struct ptp_clock_request *request, int on)
882 {
883         return -EOPNOTSUPP;
884 }
885
886 static struct ptp_clock_info ptp_mpipe_caps = {
887         .owner          = THIS_MODULE,
888         .name           = "mPIPE clock",
889         .max_adj        = 999999999,
890         .n_ext_ts       = 0,
891         .pps            = 0,
892         .adjfreq        = ptp_mpipe_adjfreq,
893         .adjtime        = ptp_mpipe_adjtime,
894         .gettime        = ptp_mpipe_gettime,
895         .settime        = ptp_mpipe_settime,
896         .enable         = ptp_mpipe_enable,
897 };
898
899 #endif /* CONFIG_PTP_1588_CLOCK_TILEGX */
900
901 /* Sync mPIPE's timestamp up with Linux system time and register PTP clock. */
902 static void register_ptp_clock(struct net_device *dev, struct mpipe_data *md)
903 {
904 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
905         struct timespec ts;
906
907         getnstimeofday(&ts);
908         gxio_mpipe_set_timestamp(&md->context, &ts);
909
910         mutex_init(&md->ptp_lock);
911         md->caps = ptp_mpipe_caps;
912         md->ptp_clock = ptp_clock_register(&md->caps, NULL);
913         if (IS_ERR(md->ptp_clock))
914                 netdev_err(dev, "ptp_clock_register failed %ld\n",
915                            PTR_ERR(md->ptp_clock));
916 #endif
917 }
918
919 /* Initialize PTP fields in a new device. */
920 static void init_ptp_dev(struct tile_net_priv *priv)
921 {
922 #ifdef CONFIG_PTP_1588_CLOCK_TILEGX
923         priv->stamp_cfg.rx_filter = HWTSTAMP_FILTER_NONE;
924         priv->stamp_cfg.tx_type = HWTSTAMP_TX_OFF;
925 #endif
926 }
927
928 /* Helper functions for "tile_net_update()". */
929 static void enable_ingress_irq(void *irq)
930 {
931         enable_percpu_irq((long)irq, 0);
932 }
933
934 static void disable_ingress_irq(void *irq)
935 {
936         disable_percpu_irq((long)irq);
937 }
938
939 /* Helper function for tile_net_open() and tile_net_stop().
940  * Always called under tile_net_devs_for_channel_mutex.
941  */
942 static int tile_net_update(struct net_device *dev)
943 {
944         static gxio_mpipe_rules_t rules;  /* too big to fit on the stack */
945         bool saw_channel = false;
946         int instance = mpipe_instance(dev);
947         struct mpipe_data *md = &mpipe_data[instance];
948         int channel;
949         int rc;
950         int cpu;
951
952         saw_channel = false;
953         gxio_mpipe_rules_init(&rules, &md->context);
954
955         for (channel = 0; channel < TILE_NET_CHANNELS; channel++) {
956                 if (md->tile_net_devs_for_channel[channel] == NULL)
957                         continue;
958                 if (!saw_channel) {
959                         saw_channel = true;
960                         gxio_mpipe_rules_begin(&rules, md->first_bucket,
961                                                md->num_buckets, NULL);
962                         gxio_mpipe_rules_set_headroom(&rules, NET_IP_ALIGN);
963                 }
964                 gxio_mpipe_rules_add_channel(&rules, channel);
965         }
966
967         /* NOTE: This can fail if there is no classifier.
968          * ISSUE: Can anything else cause it to fail?
969          */
970         rc = gxio_mpipe_rules_commit(&rules);
971         if (rc != 0) {
972                 netdev_warn(dev, "gxio_mpipe_rules_commit: mpipe[%d] %d\n",
973                             instance, rc);
974                 return -EIO;
975         }
976
977         /* Update all cpus, sequentially (to protect "netif_napi_add()").
978          * We use on_each_cpu to handle the IPI mask or unmask.
979          */
980         if (!saw_channel)
981                 on_each_cpu(disable_ingress_irq,
982                             (void *)(long)(md->ingress_irq), 1);
983         for_each_online_cpu(cpu) {
984                 struct tile_net_info *info = &per_cpu(per_cpu_info, cpu);
985
986                 if (!info->mpipe[instance].has_iqueue)
987                         continue;
988                 if (saw_channel) {
989                         if (!info->mpipe[instance].napi_added) {
990                                 netif_napi_add(dev, &info->mpipe[instance].napi,
991                                                tile_net_poll, TILE_NET_WEIGHT);
992                                 info->mpipe[instance].napi_added = true;
993                         }
994                         if (!info->mpipe[instance].napi_enabled) {
995                                 napi_enable(&info->mpipe[instance].napi);
996                                 info->mpipe[instance].napi_enabled = true;
997                         }
998                 } else {
999                         if (info->mpipe[instance].napi_enabled) {
1000                                 napi_disable(&info->mpipe[instance].napi);
1001                                 info->mpipe[instance].napi_enabled = false;
1002                         }
1003                         /* FIXME: Drain the iqueue. */
1004                 }
1005         }
1006         if (saw_channel)
1007                 on_each_cpu(enable_ingress_irq,
1008                             (void *)(long)(md->ingress_irq), 1);
1009
1010         /* HACK: Allow packets to flow in the simulator. */
1011         if (saw_channel)
1012                 sim_enable_mpipe_links(instance, -1);
1013
1014         return 0;
1015 }
1016
1017 /* Initialize a buffer stack. */
1018 static int create_buffer_stack(struct net_device *dev,
1019                                int kind, size_t num_buffers)
1020 {
1021         pte_t hash_pte = pte_set_home((pte_t) { 0 }, PAGE_HOME_HASH);
1022         int instance = mpipe_instance(dev);
1023         struct mpipe_data *md = &mpipe_data[instance];
1024         size_t needed = gxio_mpipe_calc_buffer_stack_bytes(num_buffers);
1025         int stack_idx = md->first_buffer_stack + kind;
1026         void *va;
1027         int i, rc;
1028
1029         /* Round up to 64KB and then use alloc_pages() so we get the
1030          * required 64KB alignment.
1031          */
1032         md->buffer_stack_bytes[kind] =
1033                 ALIGN(needed, 64 * 1024);
1034
1035         va = alloc_pages_exact(md->buffer_stack_bytes[kind], GFP_KERNEL);
1036         if (va == NULL) {
1037                 netdev_err(dev,
1038                            "Could not alloc %zd bytes for buffer stack %d\n",
1039                            md->buffer_stack_bytes[kind], kind);
1040                 return -ENOMEM;
1041         }
1042
1043         /* Initialize the buffer stack. */
1044         rc = gxio_mpipe_init_buffer_stack(&md->context, stack_idx,
1045                                           buffer_size_enums[kind],  va,
1046                                           md->buffer_stack_bytes[kind], 0);
1047         if (rc != 0) {
1048                 netdev_err(dev, "gxio_mpipe_init_buffer_stack: mpipe[%d] %d\n",
1049                            instance, rc);
1050                 free_pages_exact(va, md->buffer_stack_bytes[kind]);
1051                 return rc;
1052         }
1053
1054         md->buffer_stack_vas[kind] = va;
1055
1056         rc = gxio_mpipe_register_client_memory(&md->context, stack_idx,
1057                                                hash_pte, 0);
1058         if (rc != 0) {
1059                 netdev_err(dev,
1060                            "gxio_mpipe_register_client_memory: mpipe[%d] %d\n",
1061                            instance, rc);
1062                 return rc;
1063         }
1064
1065         /* Provide initial buffers. */
1066         for (i = 0; i < num_buffers; i++) {
1067                 if (!tile_net_provide_buffer(instance, kind)) {
1068                         netdev_err(dev, "Cannot allocate initial sk_bufs!\n");
1069                         return -ENOMEM;
1070                 }
1071         }
1072
1073         return 0;
1074 }
1075
1076 /* Allocate and initialize mpipe buffer stacks, and register them in
1077  * the mPIPE TLBs, for small, large, and (possibly) jumbo packet sizes.
1078  * This routine supports tile_net_init_mpipe(), below.
1079  */
1080 static int init_buffer_stacks(struct net_device *dev,
1081                               int network_cpus_count)
1082 {
1083         int num_kinds = MAX_KINDS - (jumbo_num == 0);
1084         size_t num_buffers;
1085         int rc;
1086         int instance = mpipe_instance(dev);
1087         struct mpipe_data *md = &mpipe_data[instance];
1088
1089         /* Allocate the buffer stacks. */
1090         rc = gxio_mpipe_alloc_buffer_stacks(&md->context, num_kinds, 0, 0);
1091         if (rc < 0) {
1092                 netdev_err(dev,
1093                            "gxio_mpipe_alloc_buffer_stacks: mpipe[%d] %d\n",
1094                            instance, rc);
1095                 return rc;
1096         }
1097         md->first_buffer_stack = rc;
1098
1099         /* Enough small/large buffers to (normally) avoid buffer errors. */
1100         num_buffers =
1101                 network_cpus_count * (IQUEUE_ENTRIES + TILE_NET_BATCH);
1102
1103         /* Allocate the small memory stack. */
1104         if (rc >= 0)
1105                 rc = create_buffer_stack(dev, 0, num_buffers);
1106
1107         /* Allocate the large buffer stack. */
1108         if (rc >= 0)
1109                 rc = create_buffer_stack(dev, 1, num_buffers);
1110
1111         /* Allocate the jumbo buffer stack if needed. */
1112         if (rc >= 0 && jumbo_num != 0)
1113                 rc = create_buffer_stack(dev, 2, jumbo_num);
1114
1115         return rc;
1116 }
1117
1118 /* Allocate per-cpu resources (memory for completions and idescs).
1119  * This routine supports tile_net_init_mpipe(), below.
1120  */
1121 static int alloc_percpu_mpipe_resources(struct net_device *dev,
1122                                         int cpu, int ring)
1123 {
1124         struct tile_net_info *info = &per_cpu(per_cpu_info, cpu);
1125         int order, i, rc;
1126         int instance = mpipe_instance(dev);
1127         struct mpipe_data *md = &mpipe_data[instance];
1128         struct page *page;
1129         void *addr;
1130
1131         /* Allocate the "comps". */
1132         order = get_order(COMPS_SIZE);
1133         page = homecache_alloc_pages(GFP_KERNEL, order, cpu);
1134         if (page == NULL) {
1135                 netdev_err(dev, "Failed to alloc %zd bytes comps memory\n",
1136                            COMPS_SIZE);
1137                 return -ENOMEM;
1138         }
1139         addr = pfn_to_kaddr(page_to_pfn(page));
1140         memset(addr, 0, COMPS_SIZE);
1141         for (i = 0; i < TILE_NET_CHANNELS; i++)
1142                 info->mpipe[instance].comps_for_echannel[i] =
1143                         addr + i * sizeof(struct tile_net_comps);
1144
1145         /* If this is a network cpu, create an iqueue. */
1146         if (cpu_isset(cpu, network_cpus_map)) {
1147                 order = get_order(NOTIF_RING_SIZE);
1148                 page = homecache_alloc_pages(GFP_KERNEL, order, cpu);
1149                 if (page == NULL) {
1150                         netdev_err(dev,
1151                                    "Failed to alloc %zd bytes iqueue memory\n",
1152                                    NOTIF_RING_SIZE);
1153                         return -ENOMEM;
1154                 }
1155                 addr = pfn_to_kaddr(page_to_pfn(page));
1156                 rc = gxio_mpipe_iqueue_init(&info->mpipe[instance].iqueue,
1157                                             &md->context, ring++, addr,
1158                                             NOTIF_RING_SIZE, 0);
1159                 if (rc < 0) {
1160                         netdev_err(dev,
1161                                    "gxio_mpipe_iqueue_init failed: %d\n", rc);
1162                         return rc;
1163                 }
1164                 info->mpipe[instance].has_iqueue = true;
1165         }
1166
1167         return ring;
1168 }
1169
1170 /* Initialize NotifGroup and buckets.
1171  * This routine supports tile_net_init_mpipe(), below.
1172  */
1173 static int init_notif_group_and_buckets(struct net_device *dev,
1174                                         int ring, int network_cpus_count)
1175 {
1176         int group, rc;
1177         int instance = mpipe_instance(dev);
1178         struct mpipe_data *md = &mpipe_data[instance];
1179
1180         /* Allocate one NotifGroup. */
1181         rc = gxio_mpipe_alloc_notif_groups(&md->context, 1, 0, 0);
1182         if (rc < 0) {
1183                 netdev_err(dev, "gxio_mpipe_alloc_notif_groups: mpipe[%d] %d\n",
1184                            instance, rc);
1185                 return rc;
1186         }
1187         group = rc;
1188
1189         /* Initialize global num_buckets value. */
1190         if (network_cpus_count > 4)
1191                 md->num_buckets = 256;
1192         else if (network_cpus_count > 1)
1193                 md->num_buckets = 16;
1194
1195         /* Allocate some buckets, and set global first_bucket value. */
1196         rc = gxio_mpipe_alloc_buckets(&md->context, md->num_buckets, 0, 0);
1197         if (rc < 0) {
1198                 netdev_err(dev, "gxio_mpipe_alloc_buckets: mpipe[%d] %d\n",
1199                            instance, rc);
1200                 return rc;
1201         }
1202         md->first_bucket = rc;
1203
1204         /* Init group and buckets. */
1205         rc = gxio_mpipe_init_notif_group_and_buckets(
1206                 &md->context, group, ring, network_cpus_count,
1207                 md->first_bucket, md->num_buckets,
1208                 GXIO_MPIPE_BUCKET_STICKY_FLOW_LOCALITY);
1209         if (rc != 0) {
1210                 netdev_err(dev, "gxio_mpipe_init_notif_group_and_buckets: "
1211                            "mpipe[%d] %d\n", instance, rc);
1212                 return rc;
1213         }
1214
1215         return 0;
1216 }
1217
1218 /* Create an irq and register it, then activate the irq and request
1219  * interrupts on all cores.  Note that "ingress_irq" being initialized
1220  * is how we know not to call tile_net_init_mpipe() again.
1221  * This routine supports tile_net_init_mpipe(), below.
1222  */
1223 static int tile_net_setup_interrupts(struct net_device *dev)
1224 {
1225         int cpu, rc, irq;
1226         int instance = mpipe_instance(dev);
1227         struct mpipe_data *md = &mpipe_data[instance];
1228
1229         irq = md->ingress_irq;
1230         if (irq < 0) {
1231                 irq = create_irq();
1232                 if (irq < 0) {
1233                         netdev_err(dev,
1234                                    "create_irq failed: mpipe[%d] %d\n",
1235                                    instance, irq);
1236                         return irq;
1237                 }
1238                 tile_irq_activate(irq, TILE_IRQ_PERCPU);
1239
1240                 rc = request_irq(irq, tile_net_handle_ingress_irq,
1241                                  0, "tile_net", (void *)((uint64_t)instance));
1242
1243                 if (rc != 0) {
1244                         netdev_err(dev, "request_irq failed: mpipe[%d] %d\n",
1245                                    instance, rc);
1246                         destroy_irq(irq);
1247                         return rc;
1248                 }
1249                 md->ingress_irq = irq;
1250         }
1251
1252         for_each_online_cpu(cpu) {
1253                 struct tile_net_info *info = &per_cpu(per_cpu_info, cpu);
1254                 if (info->mpipe[instance].has_iqueue) {
1255                         gxio_mpipe_request_notif_ring_interrupt(&md->context,
1256                                 cpu_x(cpu), cpu_y(cpu), KERNEL_PL, irq,
1257                                 info->mpipe[instance].iqueue.ring);
1258                 }
1259         }
1260
1261         return 0;
1262 }
1263
1264 /* Undo any state set up partially by a failed call to tile_net_init_mpipe. */
1265 static void tile_net_init_mpipe_fail(int instance)
1266 {
1267         int kind, cpu;
1268         struct mpipe_data *md = &mpipe_data[instance];
1269
1270         /* Do cleanups that require the mpipe context first. */
1271         for (kind = 0; kind < MAX_KINDS; kind++) {
1272                 if (md->buffer_stack_vas[kind] != NULL) {
1273                         tile_net_pop_all_buffers(instance,
1274                                                  md->first_buffer_stack +
1275                                                  kind);
1276                 }
1277         }
1278
1279         /* Destroy mpipe context so the hardware no longer owns any memory. */
1280         gxio_mpipe_destroy(&md->context);
1281
1282         for_each_online_cpu(cpu) {
1283                 struct tile_net_info *info = &per_cpu(per_cpu_info, cpu);
1284                 free_pages(
1285                         (unsigned long)(
1286                                 info->mpipe[instance].comps_for_echannel[0]),
1287                         get_order(COMPS_SIZE));
1288                 info->mpipe[instance].comps_for_echannel[0] = NULL;
1289                 free_pages((unsigned long)(info->mpipe[instance].iqueue.idescs),
1290                            get_order(NOTIF_RING_SIZE));
1291                 info->mpipe[instance].iqueue.idescs = NULL;
1292         }
1293
1294         for (kind = 0; kind < MAX_KINDS; kind++) {
1295                 if (md->buffer_stack_vas[kind] != NULL) {
1296                         free_pages_exact(md->buffer_stack_vas[kind],
1297                                          md->buffer_stack_bytes[kind]);
1298                         md->buffer_stack_vas[kind] = NULL;
1299                 }
1300         }
1301
1302         md->first_buffer_stack = -1;
1303         md->first_bucket = -1;
1304 }
1305
1306 /* The first time any tilegx network device is opened, we initialize
1307  * the global mpipe state.  If this step fails, we fail to open the
1308  * device, but if it succeeds, we never need to do it again, and since
1309  * tile_net can't be unloaded, we never undo it.
1310  *
1311  * Note that some resources in this path (buffer stack indices,
1312  * bindings from init_buffer_stack, etc.) are hypervisor resources
1313  * that are freed implicitly by gxio_mpipe_destroy().
1314  */
1315 static int tile_net_init_mpipe(struct net_device *dev)
1316 {
1317         int rc;
1318         int cpu;
1319         int first_ring, ring;
1320         int instance = mpipe_instance(dev);
1321         struct mpipe_data *md = &mpipe_data[instance];
1322         int network_cpus_count = cpus_weight(network_cpus_map);
1323
1324         if (!hash_default) {
1325                 netdev_err(dev, "Networking requires hash_default!\n");
1326                 return -EIO;
1327         }
1328
1329         rc = gxio_mpipe_init(&md->context, instance);
1330         if (rc != 0) {
1331                 netdev_err(dev, "gxio_mpipe_init: mpipe[%d] %d\n",
1332                            instance, rc);
1333                 return -EIO;
1334         }
1335
1336         /* Set up the buffer stacks. */
1337         rc = init_buffer_stacks(dev, network_cpus_count);
1338         if (rc != 0)
1339                 goto fail;
1340
1341         /* Allocate one NotifRing for each network cpu. */
1342         rc = gxio_mpipe_alloc_notif_rings(&md->context,
1343                                           network_cpus_count, 0, 0);
1344         if (rc < 0) {
1345                 netdev_err(dev, "gxio_mpipe_alloc_notif_rings failed %d\n",
1346                            rc);
1347                 goto fail;
1348         }
1349
1350         /* Init NotifRings per-cpu. */
1351         first_ring = rc;
1352         ring = first_ring;
1353         for_each_online_cpu(cpu) {
1354                 rc = alloc_percpu_mpipe_resources(dev, cpu, ring);
1355                 if (rc < 0)
1356                         goto fail;
1357                 ring = rc;
1358         }
1359
1360         /* Initialize NotifGroup and buckets. */
1361         rc = init_notif_group_and_buckets(dev, first_ring, network_cpus_count);
1362         if (rc != 0)
1363                 goto fail;
1364
1365         /* Create and enable interrupts. */
1366         rc = tile_net_setup_interrupts(dev);
1367         if (rc != 0)
1368                 goto fail;
1369
1370         /* Register PTP clock and set mPIPE timestamp, if configured. */
1371         register_ptp_clock(dev, md);
1372
1373         return 0;
1374
1375 fail:
1376         tile_net_init_mpipe_fail(instance);
1377         return rc;
1378 }
1379
1380 /* Create persistent egress info for a given egress channel.
1381  * Note that this may be shared between, say, "gbe0" and "xgbe0".
1382  * ISSUE: Defer header allocation until TSO is actually needed?
1383  */
1384 static int tile_net_init_egress(struct net_device *dev, int echannel)
1385 {
1386         static int ering = -1;
1387         struct page *headers_page, *edescs_page, *equeue_page;
1388         gxio_mpipe_edesc_t *edescs;
1389         gxio_mpipe_equeue_t *equeue;
1390         unsigned char *headers;
1391         int headers_order, edescs_order, equeue_order;
1392         size_t edescs_size;
1393         int rc = -ENOMEM;
1394         int instance = mpipe_instance(dev);
1395         struct mpipe_data *md = &mpipe_data[instance];
1396
1397         /* Only initialize once. */
1398         if (md->egress_for_echannel[echannel].equeue != NULL)
1399                 return 0;
1400
1401         /* Allocate memory for the "headers". */
1402         headers_order = get_order(EQUEUE_ENTRIES * HEADER_BYTES);
1403         headers_page = alloc_pages(GFP_KERNEL, headers_order);
1404         if (headers_page == NULL) {
1405                 netdev_warn(dev,
1406                             "Could not alloc %zd bytes for TSO headers.\n",
1407                             PAGE_SIZE << headers_order);
1408                 goto fail;
1409         }
1410         headers = pfn_to_kaddr(page_to_pfn(headers_page));
1411
1412         /* Allocate memory for the "edescs". */
1413         edescs_size = EQUEUE_ENTRIES * sizeof(*edescs);
1414         edescs_order = get_order(edescs_size);
1415         edescs_page = alloc_pages(GFP_KERNEL, edescs_order);
1416         if (edescs_page == NULL) {
1417                 netdev_warn(dev,
1418                             "Could not alloc %zd bytes for eDMA ring.\n",
1419                             edescs_size);
1420                 goto fail_headers;
1421         }
1422         edescs = pfn_to_kaddr(page_to_pfn(edescs_page));
1423
1424         /* Allocate memory for the "equeue". */
1425         equeue_order = get_order(sizeof(*equeue));
1426         equeue_page = alloc_pages(GFP_KERNEL, equeue_order);
1427         if (equeue_page == NULL) {
1428                 netdev_warn(dev,
1429                             "Could not alloc %zd bytes for equeue info.\n",
1430                             PAGE_SIZE << equeue_order);
1431                 goto fail_edescs;
1432         }
1433         equeue = pfn_to_kaddr(page_to_pfn(equeue_page));
1434
1435         /* Allocate an edma ring (using a one entry "free list"). */
1436         if (ering < 0) {
1437                 rc = gxio_mpipe_alloc_edma_rings(&md->context, 1, 0, 0);
1438                 if (rc < 0) {
1439                         netdev_warn(dev, "gxio_mpipe_alloc_edma_rings: "
1440                                     "mpipe[%d] %d\n", instance, rc);
1441                         goto fail_equeue;
1442                 }
1443                 ering = rc;
1444         }
1445
1446         /* Initialize the equeue. */
1447         rc = gxio_mpipe_equeue_init(equeue, &md->context, ering, echannel,
1448                                     edescs, edescs_size, 0);
1449         if (rc != 0) {
1450                 netdev_err(dev, "gxio_mpipe_equeue_init: mpipe[%d] %d\n",
1451                            instance, rc);
1452                 goto fail_equeue;
1453         }
1454
1455         /* Don't reuse the ering later. */
1456         ering = -1;
1457
1458         if (jumbo_num != 0) {
1459                 /* Make sure "jumbo" packets can be egressed safely. */
1460                 if (gxio_mpipe_equeue_set_snf_size(equeue, 10368) < 0) {
1461                         /* ISSUE: There is no "gxio_mpipe_equeue_destroy()". */
1462                         netdev_warn(dev, "Jumbo packets may not be egressed"
1463                                     " properly on channel %d\n", echannel);
1464                 }
1465         }
1466
1467         /* Done. */
1468         md->egress_for_echannel[echannel].equeue = equeue;
1469         md->egress_for_echannel[echannel].headers = headers;
1470         return 0;
1471
1472 fail_equeue:
1473         __free_pages(equeue_page, equeue_order);
1474
1475 fail_edescs:
1476         __free_pages(edescs_page, edescs_order);
1477
1478 fail_headers:
1479         __free_pages(headers_page, headers_order);
1480
1481 fail:
1482         return rc;
1483 }
1484
1485 /* Return channel number for a newly-opened link. */
1486 static int tile_net_link_open(struct net_device *dev, gxio_mpipe_link_t *link,
1487                               const char *link_name)
1488 {
1489         int instance = mpipe_instance(dev);
1490         struct mpipe_data *md = &mpipe_data[instance];
1491         int rc = gxio_mpipe_link_open(link, &md->context, link_name, 0);
1492         if (rc < 0) {
1493                 netdev_err(dev, "Failed to open '%s', mpipe[%d], %d\n",
1494                            link_name, instance, rc);
1495                 return rc;
1496         }
1497         if (jumbo_num != 0) {
1498                 u32 attr = GXIO_MPIPE_LINK_RECEIVE_JUMBO;
1499                 rc = gxio_mpipe_link_set_attr(link, attr, 1);
1500                 if (rc != 0) {
1501                         netdev_err(dev,
1502                                    "Cannot receive jumbo packets on '%s'\n",
1503                                    link_name);
1504                         gxio_mpipe_link_close(link);
1505                         return rc;
1506                 }
1507         }
1508         rc = gxio_mpipe_link_channel(link);
1509         if (rc < 0 || rc >= TILE_NET_CHANNELS) {
1510                 netdev_err(dev, "gxio_mpipe_link_channel bad value: %d\n", rc);
1511                 gxio_mpipe_link_close(link);
1512                 return -EINVAL;
1513         }
1514         return rc;
1515 }
1516
1517 /* Help the kernel activate the given network interface. */
1518 static int tile_net_open(struct net_device *dev)
1519 {
1520         struct tile_net_priv *priv = netdev_priv(dev);
1521         int cpu, rc, instance;
1522
1523         mutex_lock(&tile_net_devs_for_channel_mutex);
1524
1525         /* Get the instance info. */
1526         rc = gxio_mpipe_link_instance(dev->name);
1527         if (rc < 0 || rc >= NR_MPIPE_MAX) {
1528                 mutex_unlock(&tile_net_devs_for_channel_mutex);
1529                 return -EIO;
1530         }
1531
1532         priv->instance = rc;
1533         instance = rc;
1534         if (!mpipe_data[rc].context.mmio_fast_base) {
1535                 /* Do one-time initialization per instance the first time
1536                  * any device is opened.
1537                  */
1538                 rc = tile_net_init_mpipe(dev);
1539                 if (rc != 0)
1540                         goto fail;
1541         }
1542
1543         /* Determine if this is the "loopify" device. */
1544         if (unlikely((loopify_link_name != NULL) &&
1545                      !strcmp(dev->name, loopify_link_name))) {
1546                 rc = tile_net_link_open(dev, &priv->link, "loop0");
1547                 if (rc < 0)
1548                         goto fail;
1549                 priv->channel = rc;
1550                 rc = tile_net_link_open(dev, &priv->loopify_link, "loop1");
1551                 if (rc < 0)
1552                         goto fail;
1553                 priv->loopify_channel = rc;
1554                 priv->echannel = rc;
1555         } else {
1556                 rc = tile_net_link_open(dev, &priv->link, dev->name);
1557                 if (rc < 0)
1558                         goto fail;
1559                 priv->channel = rc;
1560                 priv->echannel = rc;
1561         }
1562
1563         /* Initialize egress info (if needed).  Once ever, per echannel. */
1564         rc = tile_net_init_egress(dev, priv->echannel);
1565         if (rc != 0)
1566                 goto fail;
1567
1568         mpipe_data[instance].tile_net_devs_for_channel[priv->channel] = dev;
1569
1570         rc = tile_net_update(dev);
1571         if (rc != 0)
1572                 goto fail;
1573
1574         mutex_unlock(&tile_net_devs_for_channel_mutex);
1575
1576         /* Initialize the transmit wake timer for this device for each cpu. */
1577         for_each_online_cpu(cpu) {
1578                 struct tile_net_info *info = &per_cpu(per_cpu_info, cpu);
1579                 struct tile_net_tx_wake *tx_wake =
1580                         &info->mpipe[instance].tx_wake[priv->echannel];
1581
1582                 hrtimer_init(&tx_wake->timer, CLOCK_MONOTONIC,
1583                              HRTIMER_MODE_REL);
1584                 tx_wake->tx_queue_idx = cpu;
1585                 tx_wake->timer.function = tile_net_handle_tx_wake_timer;
1586                 tx_wake->dev = dev;
1587         }
1588
1589         for_each_online_cpu(cpu)
1590                 netif_start_subqueue(dev, cpu);
1591         netif_carrier_on(dev);
1592         return 0;
1593
1594 fail:
1595         if (priv->loopify_channel >= 0) {
1596                 if (gxio_mpipe_link_close(&priv->loopify_link) != 0)
1597                         netdev_warn(dev, "Failed to close loopify link!\n");
1598                 priv->loopify_channel = -1;
1599         }
1600         if (priv->channel >= 0) {
1601                 if (gxio_mpipe_link_close(&priv->link) != 0)
1602                         netdev_warn(dev, "Failed to close link!\n");
1603                 priv->channel = -1;
1604         }
1605         priv->echannel = -1;
1606         mpipe_data[instance].tile_net_devs_for_channel[priv->channel] = NULL;
1607         mutex_unlock(&tile_net_devs_for_channel_mutex);
1608
1609         /* Don't return raw gxio error codes to generic Linux. */
1610         return (rc > -512) ? rc : -EIO;
1611 }
1612
1613 /* Help the kernel deactivate the given network interface. */
1614 static int tile_net_stop(struct net_device *dev)
1615 {
1616         struct tile_net_priv *priv = netdev_priv(dev);
1617         int cpu;
1618         int instance = priv->instance;
1619         struct mpipe_data *md = &mpipe_data[instance];
1620
1621         for_each_online_cpu(cpu) {
1622                 struct tile_net_info *info = &per_cpu(per_cpu_info, cpu);
1623                 struct tile_net_tx_wake *tx_wake =
1624                         &info->mpipe[instance].tx_wake[priv->echannel];
1625
1626                 hrtimer_cancel(&tx_wake->timer);
1627                 netif_stop_subqueue(dev, cpu);
1628         }
1629
1630         mutex_lock(&tile_net_devs_for_channel_mutex);
1631         md->tile_net_devs_for_channel[priv->channel] = NULL;
1632         (void)tile_net_update(dev);
1633         if (priv->loopify_channel >= 0) {
1634                 if (gxio_mpipe_link_close(&priv->loopify_link) != 0)
1635                         netdev_warn(dev, "Failed to close loopify link!\n");
1636                 priv->loopify_channel = -1;
1637         }
1638         if (priv->channel >= 0) {
1639                 if (gxio_mpipe_link_close(&priv->link) != 0)
1640                         netdev_warn(dev, "Failed to close link!\n");
1641                 priv->channel = -1;
1642         }
1643         priv->echannel = -1;
1644         mutex_unlock(&tile_net_devs_for_channel_mutex);
1645
1646         return 0;
1647 }
1648
1649 /* Determine the VA for a fragment. */
1650 static inline void *tile_net_frag_buf(skb_frag_t *f)
1651 {
1652         unsigned long pfn = page_to_pfn(skb_frag_page(f));
1653         return pfn_to_kaddr(pfn) + f->page_offset;
1654 }
1655
1656 /* Acquire a completion entry and an egress slot, or if we can't,
1657  * stop the queue and schedule the tx_wake timer.
1658  */
1659 static s64 tile_net_equeue_try_reserve(struct net_device *dev,
1660                                        int tx_queue_idx,
1661                                        struct tile_net_comps *comps,
1662                                        gxio_mpipe_equeue_t *equeue,
1663                                        int num_edescs)
1664 {
1665         /* Try to acquire a completion entry. */
1666         if (comps->comp_next - comps->comp_last < TILE_NET_MAX_COMPS - 1 ||
1667             tile_net_free_comps(equeue, comps, 32, false) != 0) {
1668
1669                 /* Try to acquire an egress slot. */
1670                 s64 slot = gxio_mpipe_equeue_try_reserve(equeue, num_edescs);
1671                 if (slot >= 0)
1672                         return slot;
1673
1674                 /* Freeing some completions gives the equeue time to drain. */
1675                 tile_net_free_comps(equeue, comps, TILE_NET_MAX_COMPS, false);
1676
1677                 slot = gxio_mpipe_equeue_try_reserve(equeue, num_edescs);
1678                 if (slot >= 0)
1679                         return slot;
1680         }
1681
1682         /* Still nothing; give up and stop the queue for a short while. */
1683         netif_stop_subqueue(dev, tx_queue_idx);
1684         tile_net_schedule_tx_wake_timer(dev, tx_queue_idx);
1685         return -1;
1686 }
1687
1688 /* Determine how many edesc's are needed for TSO.
1689  *
1690  * Sometimes, if "sendfile()" requires copying, we will be called with
1691  * "data" containing the header and payload, with "frags" being empty.
1692  * Sometimes, for example when using NFS over TCP, a single segment can
1693  * span 3 fragments.  This requires special care.
1694  */
1695 static int tso_count_edescs(struct sk_buff *skb)
1696 {
1697         struct skb_shared_info *sh = skb_shinfo(skb);
1698         unsigned int sh_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
1699         unsigned int data_len = skb->len - sh_len;
1700         unsigned int p_len = sh->gso_size;
1701         long f_id = -1;    /* id of the current fragment */
1702         long f_size = skb_headlen(skb) - sh_len;  /* current fragment size */
1703         long f_used = 0;  /* bytes used from the current fragment */
1704         long n;            /* size of the current piece of payload */
1705         int num_edescs = 0;
1706         int segment;
1707
1708         for (segment = 0; segment < sh->gso_segs; segment++) {
1709
1710                 unsigned int p_used = 0;
1711
1712                 /* One edesc for header and for each piece of the payload. */
1713                 for (num_edescs++; p_used < p_len; num_edescs++) {
1714
1715                         /* Advance as needed. */
1716                         while (f_used >= f_size) {
1717                                 f_id++;
1718                                 f_size = skb_frag_size(&sh->frags[f_id]);
1719                                 f_used = 0;
1720                         }
1721
1722                         /* Use bytes from the current fragment. */
1723                         n = p_len - p_used;
1724                         if (n > f_size - f_used)
1725                                 n = f_size - f_used;
1726                         f_used += n;
1727                         p_used += n;
1728                 }
1729
1730                 /* The last segment may be less than gso_size. */
1731                 data_len -= p_len;
1732                 if (data_len < p_len)
1733                         p_len = data_len;
1734         }
1735
1736         return num_edescs;
1737 }
1738
1739 /* Prepare modified copies of the skbuff headers. */
1740 static void tso_headers_prepare(struct sk_buff *skb, unsigned char *headers,
1741                                 s64 slot)
1742 {
1743         struct skb_shared_info *sh = skb_shinfo(skb);
1744         struct iphdr *ih;
1745         struct ipv6hdr *ih6;
1746         struct tcphdr *th;
1747         unsigned int sh_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
1748         unsigned int data_len = skb->len - sh_len;
1749         unsigned char *data = skb->data;
1750         unsigned int ih_off, th_off, p_len;
1751         unsigned int isum_seed, tsum_seed, seq;
1752         unsigned int uninitialized_var(id);
1753         int is_ipv6;
1754         long f_id = -1;    /* id of the current fragment */
1755         long f_size = skb_headlen(skb) - sh_len;  /* current fragment size */
1756         long f_used = 0;  /* bytes used from the current fragment */
1757         long n;            /* size of the current piece of payload */
1758         int segment;
1759
1760         /* Locate original headers and compute various lengths. */
1761         is_ipv6 = skb_is_gso_v6(skb);
1762         if (is_ipv6) {
1763                 ih6 = ipv6_hdr(skb);
1764                 ih_off = skb_network_offset(skb);
1765         } else {
1766                 ih = ip_hdr(skb);
1767                 ih_off = skb_network_offset(skb);
1768                 isum_seed = ((0xFFFF - ih->check) +
1769                              (0xFFFF - ih->tot_len) +
1770                              (0xFFFF - ih->id));
1771                 id = ntohs(ih->id);
1772         }
1773
1774         th = tcp_hdr(skb);
1775         th_off = skb_transport_offset(skb);
1776         p_len = sh->gso_size;
1777
1778         tsum_seed = th->check + (0xFFFF ^ htons(skb->len));
1779         seq = ntohl(th->seq);
1780
1781         /* Prepare all the headers. */
1782         for (segment = 0; segment < sh->gso_segs; segment++) {
1783                 unsigned char *buf;
1784                 unsigned int p_used = 0;
1785
1786                 /* Copy to the header memory for this segment. */
1787                 buf = headers + (slot % EQUEUE_ENTRIES) * HEADER_BYTES +
1788                         NET_IP_ALIGN;
1789                 memcpy(buf, data, sh_len);
1790
1791                 /* Update copied ip header. */
1792                 if (is_ipv6) {
1793                         ih6 = (struct ipv6hdr *)(buf + ih_off);
1794                         ih6->payload_len = htons(sh_len + p_len - ih_off -
1795                                                  sizeof(*ih6));
1796                 } else {
1797                         ih = (struct iphdr *)(buf + ih_off);
1798                         ih->tot_len = htons(sh_len + p_len - ih_off);
1799                         ih->id = htons(id++);
1800                         ih->check = csum_long(isum_seed + ih->tot_len +
1801                                               ih->id) ^ 0xffff;
1802                 }
1803
1804                 /* Update copied tcp header. */
1805                 th = (struct tcphdr *)(buf + th_off);
1806                 th->seq = htonl(seq);
1807                 th->check = csum_long(tsum_seed + htons(sh_len + p_len));
1808                 if (segment != sh->gso_segs - 1) {
1809                         th->fin = 0;
1810                         th->psh = 0;
1811                 }
1812
1813                 /* Skip past the header. */
1814                 slot++;
1815
1816                 /* Skip past the payload. */
1817                 while (p_used < p_len) {
1818
1819                         /* Advance as needed. */
1820                         while (f_used >= f_size) {
1821                                 f_id++;
1822                                 f_size = skb_frag_size(&sh->frags[f_id]);
1823                                 f_used = 0;
1824                         }
1825
1826                         /* Use bytes from the current fragment. */
1827                         n = p_len - p_used;
1828                         if (n > f_size - f_used)
1829                                 n = f_size - f_used;
1830                         f_used += n;
1831                         p_used += n;
1832
1833                         slot++;
1834                 }
1835
1836                 seq += p_len;
1837
1838                 /* The last segment may be less than gso_size. */
1839                 data_len -= p_len;
1840                 if (data_len < p_len)
1841                         p_len = data_len;
1842         }
1843
1844         /* Flush the headers so they are ready for hardware DMA. */
1845         wmb();
1846 }
1847
1848 /* Pass all the data to mpipe for egress. */
1849 static void tso_egress(struct net_device *dev, gxio_mpipe_equeue_t *equeue,
1850                        struct sk_buff *skb, unsigned char *headers, s64 slot)
1851 {
1852         struct skb_shared_info *sh = skb_shinfo(skb);
1853         int instance = mpipe_instance(dev);
1854         struct mpipe_data *md = &mpipe_data[instance];
1855         unsigned int sh_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
1856         unsigned int data_len = skb->len - sh_len;
1857         unsigned int p_len = sh->gso_size;
1858         gxio_mpipe_edesc_t edesc_head = { { 0 } };
1859         gxio_mpipe_edesc_t edesc_body = { { 0 } };
1860         long f_id = -1;    /* id of the current fragment */
1861         long f_size = skb_headlen(skb) - sh_len;  /* current fragment size */
1862         long f_used = 0;  /* bytes used from the current fragment */
1863         void *f_data = skb->data + sh_len;
1864         long n;            /* size of the current piece of payload */
1865         unsigned long tx_packets = 0, tx_bytes = 0;
1866         unsigned int csum_start;
1867         int segment;
1868
1869         /* Prepare to egress the headers: set up header edesc. */
1870         csum_start = skb_checksum_start_offset(skb);
1871         edesc_head.csum = 1;
1872         edesc_head.csum_start = csum_start;
1873         edesc_head.csum_dest = csum_start + skb->csum_offset;
1874         edesc_head.xfer_size = sh_len;
1875
1876         /* This is only used to specify the TLB. */
1877         edesc_head.stack_idx = md->first_buffer_stack;
1878         edesc_body.stack_idx = md->first_buffer_stack;
1879
1880         /* Egress all the edescs. */
1881         for (segment = 0; segment < sh->gso_segs; segment++) {
1882                 unsigned char *buf;
1883                 unsigned int p_used = 0;
1884
1885                 /* Egress the header. */
1886                 buf = headers + (slot % EQUEUE_ENTRIES) * HEADER_BYTES +
1887                         NET_IP_ALIGN;
1888                 edesc_head.va = va_to_tile_io_addr(buf);
1889                 gxio_mpipe_equeue_put_at(equeue, edesc_head, slot);
1890                 slot++;
1891
1892                 /* Egress the payload. */
1893                 while (p_used < p_len) {
1894                         void *va;
1895
1896                         /* Advance as needed. */
1897                         while (f_used >= f_size) {
1898                                 f_id++;
1899                                 f_size = skb_frag_size(&sh->frags[f_id]);
1900                                 f_data = tile_net_frag_buf(&sh->frags[f_id]);
1901                                 f_used = 0;
1902                         }
1903
1904                         va = f_data + f_used;
1905
1906                         /* Use bytes from the current fragment. */
1907                         n = p_len - p_used;
1908                         if (n > f_size - f_used)
1909                                 n = f_size - f_used;
1910                         f_used += n;
1911                         p_used += n;
1912
1913                         /* Egress a piece of the payload. */
1914                         edesc_body.va = va_to_tile_io_addr(va);
1915                         edesc_body.xfer_size = n;
1916                         edesc_body.bound = !(p_used < p_len);
1917                         gxio_mpipe_equeue_put_at(equeue, edesc_body, slot);
1918                         slot++;
1919                 }
1920
1921                 tx_packets++;
1922                 tx_bytes += sh_len + p_len;
1923
1924                 /* The last segment may be less than gso_size. */
1925                 data_len -= p_len;
1926                 if (data_len < p_len)
1927                         p_len = data_len;
1928         }
1929
1930         /* Update stats. */
1931         tile_net_stats_add(tx_packets, &dev->stats.tx_packets);
1932         tile_net_stats_add(tx_bytes, &dev->stats.tx_bytes);
1933 }
1934
1935 /* Do "TSO" handling for egress.
1936  *
1937  * Normally drivers set NETIF_F_TSO only to support hardware TSO;
1938  * otherwise the stack uses scatter-gather to implement GSO in software.
1939  * On our testing, enabling GSO support (via NETIF_F_SG) drops network
1940  * performance down to around 7.5 Gbps on the 10G interfaces, although
1941  * also dropping cpu utilization way down, to under 8%.  But
1942  * implementing "TSO" in the driver brings performance back up to line
1943  * rate, while dropping cpu usage even further, to less than 4%.  In
1944  * practice, profiling of GSO shows that skb_segment() is what causes
1945  * the performance overheads; we benefit in the driver from using
1946  * preallocated memory to duplicate the TCP/IP headers.
1947  */
1948 static int tile_net_tx_tso(struct sk_buff *skb, struct net_device *dev)
1949 {
1950         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
1951         struct tile_net_priv *priv = netdev_priv(dev);
1952         int channel = priv->echannel;
1953         int instance = priv->instance;
1954         struct mpipe_data *md = &mpipe_data[instance];
1955         struct tile_net_egress *egress = &md->egress_for_echannel[channel];
1956         struct tile_net_comps *comps =
1957                 info->mpipe[instance].comps_for_echannel[channel];
1958         gxio_mpipe_equeue_t *equeue = egress->equeue;
1959         unsigned long irqflags;
1960         int num_edescs;
1961         s64 slot;
1962
1963         /* Determine how many mpipe edesc's are needed. */
1964         num_edescs = tso_count_edescs(skb);
1965
1966         local_irq_save(irqflags);
1967
1968         /* Try to acquire a completion entry and an egress slot. */
1969         slot = tile_net_equeue_try_reserve(dev, skb->queue_mapping, comps,
1970                                            equeue, num_edescs);
1971         if (slot < 0) {
1972                 local_irq_restore(irqflags);
1973                 return NETDEV_TX_BUSY;
1974         }
1975
1976         /* Set up copies of header data properly. */
1977         tso_headers_prepare(skb, egress->headers, slot);
1978
1979         /* Actually pass the data to the network hardware. */
1980         tso_egress(dev, equeue, skb, egress->headers, slot);
1981
1982         /* Add a completion record. */
1983         add_comp(equeue, comps, slot + num_edescs - 1, skb);
1984
1985         local_irq_restore(irqflags);
1986
1987         /* Make sure the egress timer is scheduled. */
1988         tile_net_schedule_egress_timer();
1989
1990         return NETDEV_TX_OK;
1991 }
1992
1993 /* Analyze the body and frags for a transmit request. */
1994 static unsigned int tile_net_tx_frags(struct frag *frags,
1995                                        struct sk_buff *skb,
1996                                        void *b_data, unsigned int b_len)
1997 {
1998         unsigned int i, n = 0;
1999
2000         struct skb_shared_info *sh = skb_shinfo(skb);
2001
2002         if (b_len != 0) {
2003                 frags[n].buf = b_data;
2004                 frags[n++].length = b_len;
2005         }
2006
2007         for (i = 0; i < sh->nr_frags; i++) {
2008                 skb_frag_t *f = &sh->frags[i];
2009                 frags[n].buf = tile_net_frag_buf(f);
2010                 frags[n++].length = skb_frag_size(f);
2011         }
2012
2013         return n;
2014 }
2015
2016 /* Help the kernel transmit a packet. */
2017 static int tile_net_tx(struct sk_buff *skb, struct net_device *dev)
2018 {
2019         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
2020         struct tile_net_priv *priv = netdev_priv(dev);
2021         int instance = priv->instance;
2022         struct mpipe_data *md = &mpipe_data[instance];
2023         struct tile_net_egress *egress =
2024                 &md->egress_for_echannel[priv->echannel];
2025         gxio_mpipe_equeue_t *equeue = egress->equeue;
2026         struct tile_net_comps *comps =
2027                 info->mpipe[instance].comps_for_echannel[priv->echannel];
2028         unsigned int len = skb->len;
2029         unsigned char *data = skb->data;
2030         unsigned int num_edescs;
2031         struct frag frags[MAX_FRAGS];
2032         gxio_mpipe_edesc_t edescs[MAX_FRAGS];
2033         unsigned long irqflags;
2034         gxio_mpipe_edesc_t edesc = { { 0 } };
2035         unsigned int i;
2036         s64 slot;
2037
2038         if (skb_is_gso(skb))
2039                 return tile_net_tx_tso(skb, dev);
2040
2041         num_edescs = tile_net_tx_frags(frags, skb, data, skb_headlen(skb));
2042
2043         /* This is only used to specify the TLB. */
2044         edesc.stack_idx = md->first_buffer_stack;
2045
2046         /* Prepare the edescs. */
2047         for (i = 0; i < num_edescs; i++) {
2048                 edesc.xfer_size = frags[i].length;
2049                 edesc.va = va_to_tile_io_addr(frags[i].buf);
2050                 edescs[i] = edesc;
2051         }
2052
2053         /* Mark the final edesc. */
2054         edescs[num_edescs - 1].bound = 1;
2055
2056         /* Add checksum info to the initial edesc, if needed. */
2057         if (skb->ip_summed == CHECKSUM_PARTIAL) {
2058                 unsigned int csum_start = skb_checksum_start_offset(skb);
2059                 edescs[0].csum = 1;
2060                 edescs[0].csum_start = csum_start;
2061                 edescs[0].csum_dest = csum_start + skb->csum_offset;
2062         }
2063
2064         local_irq_save(irqflags);
2065
2066         /* Try to acquire a completion entry and an egress slot. */
2067         slot = tile_net_equeue_try_reserve(dev, skb->queue_mapping, comps,
2068                                            equeue, num_edescs);
2069         if (slot < 0) {
2070                 local_irq_restore(irqflags);
2071                 return NETDEV_TX_BUSY;
2072         }
2073
2074         for (i = 0; i < num_edescs; i++)
2075                 gxio_mpipe_equeue_put_at(equeue, edescs[i], slot++);
2076
2077         /* Store TX timestamp if needed. */
2078         tile_tx_timestamp(skb, instance);
2079
2080         /* Add a completion record. */
2081         add_comp(equeue, comps, slot - 1, skb);
2082
2083         /* NOTE: Use ETH_ZLEN for short packets (e.g. 42 < 60). */
2084         tile_net_stats_add(1, &dev->stats.tx_packets);
2085         tile_net_stats_add(max_t(unsigned int, len, ETH_ZLEN),
2086                            &dev->stats.tx_bytes);
2087
2088         local_irq_restore(irqflags);
2089
2090         /* Make sure the egress timer is scheduled. */
2091         tile_net_schedule_egress_timer();
2092
2093         return NETDEV_TX_OK;
2094 }
2095
2096 /* Return subqueue id on this core (one per core). */
2097 static u16 tile_net_select_queue(struct net_device *dev, struct sk_buff *skb)
2098 {
2099         return smp_processor_id();
2100 }
2101
2102 /* Deal with a transmit timeout. */
2103 static void tile_net_tx_timeout(struct net_device *dev)
2104 {
2105         int cpu;
2106
2107         for_each_online_cpu(cpu)
2108                 netif_wake_subqueue(dev, cpu);
2109 }
2110
2111 /* Ioctl commands. */
2112 static int tile_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
2113 {
2114         if (cmd == SIOCSHWTSTAMP)
2115                 return tile_hwtstamp_set(dev, rq);
2116         if (cmd == SIOCGHWTSTAMP)
2117                 return tile_hwtstamp_get(dev, rq);
2118
2119         return -EOPNOTSUPP;
2120 }
2121
2122 /* Change the MTU. */
2123 static int tile_net_change_mtu(struct net_device *dev, int new_mtu)
2124 {
2125         if (new_mtu < 68)
2126                 return -EINVAL;
2127         if (new_mtu > ((jumbo_num != 0) ? 9000 : 1500))
2128                 return -EINVAL;
2129         dev->mtu = new_mtu;
2130         return 0;
2131 }
2132
2133 /* Change the Ethernet address of the NIC.
2134  *
2135  * The hypervisor driver does not support changing MAC address.  However,
2136  * the hardware does not do anything with the MAC address, so the address
2137  * which gets used on outgoing packets, and which is accepted on incoming
2138  * packets, is completely up to us.
2139  *
2140  * Returns 0 on success, negative on failure.
2141  */
2142 static int tile_net_set_mac_address(struct net_device *dev, void *p)
2143 {
2144         struct sockaddr *addr = p;
2145
2146         if (!is_valid_ether_addr(addr->sa_data))
2147                 return -EINVAL;
2148         memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
2149         return 0;
2150 }
2151
2152 #ifdef CONFIG_NET_POLL_CONTROLLER
2153 /* Polling 'interrupt' - used by things like netconsole to send skbs
2154  * without having to re-enable interrupts. It's not called while
2155  * the interrupt routine is executing.
2156  */
2157 static void tile_net_netpoll(struct net_device *dev)
2158 {
2159         int instance = mpipe_instance(dev);
2160         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
2161         struct mpipe_data *md = &mpipe_data[instance];
2162
2163         disable_percpu_irq(md->ingress_irq);
2164         napi_schedule(&info->mpipe[instance].napi);
2165         enable_percpu_irq(md->ingress_irq, 0);
2166 }
2167 #endif
2168
2169 static const struct net_device_ops tile_net_ops = {
2170         .ndo_open = tile_net_open,
2171         .ndo_stop = tile_net_stop,
2172         .ndo_start_xmit = tile_net_tx,
2173         .ndo_select_queue = tile_net_select_queue,
2174         .ndo_do_ioctl = tile_net_ioctl,
2175         .ndo_change_mtu = tile_net_change_mtu,
2176         .ndo_tx_timeout = tile_net_tx_timeout,
2177         .ndo_set_mac_address = tile_net_set_mac_address,
2178 #ifdef CONFIG_NET_POLL_CONTROLLER
2179         .ndo_poll_controller = tile_net_netpoll,
2180 #endif
2181 };
2182
2183 /* The setup function.
2184  *
2185  * This uses ether_setup() to assign various fields in dev, including
2186  * setting IFF_BROADCAST and IFF_MULTICAST, then sets some extra fields.
2187  */
2188 static void tile_net_setup(struct net_device *dev)
2189 {
2190         netdev_features_t features = 0;
2191
2192         ether_setup(dev);
2193         dev->netdev_ops = &tile_net_ops;
2194         dev->watchdog_timeo = TILE_NET_TIMEOUT;
2195         dev->mtu = 1500;
2196
2197         features |= NETIF_F_HW_CSUM;
2198         features |= NETIF_F_SG;
2199         features |= NETIF_F_TSO;
2200         features |= NETIF_F_TSO6;
2201
2202         dev->hw_features   |= features;
2203         dev->vlan_features |= features;
2204         dev->features      |= features;
2205 }
2206
2207 /* Allocate the device structure, register the device, and obtain the
2208  * MAC address from the hypervisor.
2209  */
2210 static void tile_net_dev_init(const char *name, const uint8_t *mac)
2211 {
2212         int ret;
2213         int i;
2214         int nz_addr = 0;
2215         struct net_device *dev;
2216         struct tile_net_priv *priv;
2217
2218         /* HACK: Ignore "loop" links. */
2219         if (strncmp(name, "loop", 4) == 0)
2220                 return;
2221
2222         /* Allocate the device structure.  Normally, "name" is a
2223          * template, instantiated by register_netdev(), but not for us.
2224          */
2225         dev = alloc_netdev_mqs(sizeof(*priv), name, tile_net_setup,
2226                                NR_CPUS, 1);
2227         if (!dev) {
2228                 pr_err("alloc_netdev_mqs(%s) failed\n", name);
2229                 return;
2230         }
2231
2232         /* Initialize "priv". */
2233         priv = netdev_priv(dev);
2234         memset(priv, 0, sizeof(*priv));
2235         priv->dev = dev;
2236         priv->channel = -1;
2237         priv->loopify_channel = -1;
2238         priv->echannel = -1;
2239         init_ptp_dev(priv);
2240
2241         /* Get the MAC address and set it in the device struct; this must
2242          * be done before the device is opened.  If the MAC is all zeroes,
2243          * we use a random address, since we're probably on the simulator.
2244          */
2245         for (i = 0; i < 6; i++)
2246                 nz_addr |= mac[i];
2247
2248         if (nz_addr) {
2249                 memcpy(dev->dev_addr, mac, ETH_ALEN);
2250                 dev->addr_len = 6;
2251         } else {
2252                 eth_hw_addr_random(dev);
2253         }
2254
2255         /* Register the network device. */
2256         ret = register_netdev(dev);
2257         if (ret) {
2258                 netdev_err(dev, "register_netdev failed %d\n", ret);
2259                 free_netdev(dev);
2260                 return;
2261         }
2262 }
2263
2264 /* Per-cpu module initialization. */
2265 static void tile_net_init_module_percpu(void *unused)
2266 {
2267         struct tile_net_info *info = &__get_cpu_var(per_cpu_info);
2268         int my_cpu = smp_processor_id();
2269         int instance;
2270
2271         for (instance = 0; instance < NR_MPIPE_MAX; instance++) {
2272                 info->mpipe[instance].has_iqueue = false;
2273                 info->mpipe[instance].instance = instance;
2274         }
2275         info->my_cpu = my_cpu;
2276
2277         /* Initialize the egress timer. */
2278         hrtimer_init(&info->egress_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2279         info->egress_timer.function = tile_net_handle_egress_timer;
2280 }
2281
2282 /* Module initialization. */
2283 static int __init tile_net_init_module(void)
2284 {
2285         int i;
2286         char name[GXIO_MPIPE_LINK_NAME_LEN];
2287         uint8_t mac[6];
2288
2289         pr_info("Tilera Network Driver\n");
2290
2291         BUILD_BUG_ON(NR_MPIPE_MAX != 2);
2292
2293         mutex_init(&tile_net_devs_for_channel_mutex);
2294
2295         /* Initialize each CPU. */
2296         on_each_cpu(tile_net_init_module_percpu, NULL, 1);
2297
2298         /* Find out what devices we have, and initialize them. */
2299         for (i = 0; gxio_mpipe_link_enumerate_mac(i, name, mac) >= 0; i++)
2300                 tile_net_dev_init(name, mac);
2301
2302         if (!network_cpus_init())
2303                 network_cpus_map = *cpu_online_mask;
2304
2305         return 0;
2306 }
2307
2308 module_init(tile_net_init_module);