GNU Linux-libre 4.14.290-gnu1
[releases.git] / drivers / net / ethernet / altera / altera_tse_main.c
1 /* Altera Triple-Speed Ethernet MAC driver
2  * Copyright (C) 2008-2014 Altera Corporation. All rights reserved
3  *
4  * Contributors:
5  *   Dalon Westergreen
6  *   Thomas Chou
7  *   Ian Abbott
8  *   Yuriy Kozlov
9  *   Tobias Klauser
10  *   Andriy Smolskyy
11  *   Roman Bulgakov
12  *   Dmytro Mytarchuk
13  *   Matthew Gerlach
14  *
15  * Original driver contributed by SLS.
16  * Major updates contributed by GlobalLogic
17  *
18  * This program is free software; you can redistribute it and/or modify it
19  * under the terms and conditions of the GNU General Public License,
20  * version 2, as published by the Free Software Foundation.
21  *
22  * This program is distributed in the hope it will be useful, but WITHOUT
23  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
24  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
25  * more details.
26  *
27  * You should have received a copy of the GNU General Public License along with
28  * this program.  If not, see <http://www.gnu.org/licenses/>.
29  */
30
31 #include <linux/atomic.h>
32 #include <linux/delay.h>
33 #include <linux/etherdevice.h>
34 #include <linux/if_vlan.h>
35 #include <linux/init.h>
36 #include <linux/interrupt.h>
37 #include <linux/io.h>
38 #include <linux/kernel.h>
39 #include <linux/module.h>
40 #include <linux/mii.h>
41 #include <linux/netdevice.h>
42 #include <linux/of_device.h>
43 #include <linux/of_mdio.h>
44 #include <linux/of_net.h>
45 #include <linux/of_platform.h>
46 #include <linux/phy.h>
47 #include <linux/platform_device.h>
48 #include <linux/skbuff.h>
49 #include <asm/cacheflush.h>
50
51 #include "altera_utils.h"
52 #include "altera_tse.h"
53 #include "altera_sgdma.h"
54 #include "altera_msgdma.h"
55
56 static atomic_t instance_count = ATOMIC_INIT(~0);
57 /* Module parameters */
58 static int debug = -1;
59 module_param(debug, int, S_IRUGO | S_IWUSR);
60 MODULE_PARM_DESC(debug, "Message Level (-1: default, 0: no output, 16: all)");
61
62 static const u32 default_msg_level = (NETIF_MSG_DRV | NETIF_MSG_PROBE |
63                                         NETIF_MSG_LINK | NETIF_MSG_IFUP |
64                                         NETIF_MSG_IFDOWN);
65
66 #define RX_DESCRIPTORS 64
67 static int dma_rx_num = RX_DESCRIPTORS;
68 module_param(dma_rx_num, int, S_IRUGO | S_IWUSR);
69 MODULE_PARM_DESC(dma_rx_num, "Number of descriptors in the RX list");
70
71 #define TX_DESCRIPTORS 64
72 static int dma_tx_num = TX_DESCRIPTORS;
73 module_param(dma_tx_num, int, S_IRUGO | S_IWUSR);
74 MODULE_PARM_DESC(dma_tx_num, "Number of descriptors in the TX list");
75
76
77 #define POLL_PHY (-1)
78
79 /* Make sure DMA buffer size is larger than the max frame size
80  * plus some alignment offset and a VLAN header. If the max frame size is
81  * 1518, a VLAN header would be additional 4 bytes and additional
82  * headroom for alignment is 2 bytes, 2048 is just fine.
83  */
84 #define ALTERA_RXDMABUFFER_SIZE 2048
85
86 /* Allow network stack to resume queueing packets after we've
87  * finished transmitting at least 1/4 of the packets in the queue.
88  */
89 #define TSE_TX_THRESH(x)        (x->tx_ring_size / 4)
90
91 #define TXQUEUESTOP_THRESHHOLD  2
92
93 static const struct of_device_id altera_tse_ids[];
94
95 static inline u32 tse_tx_avail(struct altera_tse_private *priv)
96 {
97         return priv->tx_cons + priv->tx_ring_size - priv->tx_prod - 1;
98 }
99
100 /* PCS Register read/write functions
101  */
102 static u16 sgmii_pcs_read(struct altera_tse_private *priv, int regnum)
103 {
104         return csrrd32(priv->mac_dev,
105                        tse_csroffs(mdio_phy0) + regnum * 4) & 0xffff;
106 }
107
108 static void sgmii_pcs_write(struct altera_tse_private *priv, int regnum,
109                                 u16 value)
110 {
111         csrwr32(value, priv->mac_dev, tse_csroffs(mdio_phy0) + regnum * 4);
112 }
113
114 /* Check PCS scratch memory */
115 static int sgmii_pcs_scratch_test(struct altera_tse_private *priv, u16 value)
116 {
117         sgmii_pcs_write(priv, SGMII_PCS_SCRATCH, value);
118         return (sgmii_pcs_read(priv, SGMII_PCS_SCRATCH) == value);
119 }
120
121 /* MDIO specific functions
122  */
123 static int altera_tse_mdio_read(struct mii_bus *bus, int mii_id, int regnum)
124 {
125         struct net_device *ndev = bus->priv;
126         struct altera_tse_private *priv = netdev_priv(ndev);
127
128         /* set MDIO address */
129         csrwr32((mii_id & 0x1f), priv->mac_dev,
130                 tse_csroffs(mdio_phy1_addr));
131
132         /* get the data */
133         return csrrd32(priv->mac_dev,
134                        tse_csroffs(mdio_phy1) + regnum * 4) & 0xffff;
135 }
136
137 static int altera_tse_mdio_write(struct mii_bus *bus, int mii_id, int regnum,
138                                  u16 value)
139 {
140         struct net_device *ndev = bus->priv;
141         struct altera_tse_private *priv = netdev_priv(ndev);
142
143         /* set MDIO address */
144         csrwr32((mii_id & 0x1f), priv->mac_dev,
145                 tse_csroffs(mdio_phy1_addr));
146
147         /* write the data */
148         csrwr32(value, priv->mac_dev, tse_csroffs(mdio_phy1) + regnum * 4);
149         return 0;
150 }
151
152 static int altera_tse_mdio_create(struct net_device *dev, unsigned int id)
153 {
154         struct altera_tse_private *priv = netdev_priv(dev);
155         int ret;
156         struct device_node *mdio_node = NULL;
157         struct mii_bus *mdio = NULL;
158         struct device_node *child_node = NULL;
159
160         for_each_child_of_node(priv->device->of_node, child_node) {
161                 if (of_device_is_compatible(child_node, "altr,tse-mdio")) {
162                         mdio_node = child_node;
163                         break;
164                 }
165         }
166
167         if (mdio_node) {
168                 netdev_dbg(dev, "FOUND MDIO subnode\n");
169         } else {
170                 netdev_dbg(dev, "NO MDIO subnode\n");
171                 return 0;
172         }
173
174         mdio = mdiobus_alloc();
175         if (mdio == NULL) {
176                 netdev_err(dev, "Error allocating MDIO bus\n");
177                 ret = -ENOMEM;
178                 goto put_node;
179         }
180
181         mdio->name = ALTERA_TSE_RESOURCE_NAME;
182         mdio->read = &altera_tse_mdio_read;
183         mdio->write = &altera_tse_mdio_write;
184         snprintf(mdio->id, MII_BUS_ID_SIZE, "%s-%u", mdio->name, id);
185
186         mdio->priv = dev;
187         mdio->parent = priv->device;
188
189         ret = of_mdiobus_register(mdio, mdio_node);
190         if (ret != 0) {
191                 netdev_err(dev, "Cannot register MDIO bus %s\n",
192                            mdio->id);
193                 goto out_free_mdio;
194         }
195         of_node_put(mdio_node);
196
197         if (netif_msg_drv(priv))
198                 netdev_info(dev, "MDIO bus %s: created\n", mdio->id);
199
200         priv->mdio = mdio;
201         return 0;
202 out_free_mdio:
203         mdiobus_free(mdio);
204         mdio = NULL;
205 put_node:
206         of_node_put(mdio_node);
207         return ret;
208 }
209
210 static void altera_tse_mdio_destroy(struct net_device *dev)
211 {
212         struct altera_tse_private *priv = netdev_priv(dev);
213
214         if (priv->mdio == NULL)
215                 return;
216
217         if (netif_msg_drv(priv))
218                 netdev_info(dev, "MDIO bus %s: removed\n",
219                             priv->mdio->id);
220
221         mdiobus_unregister(priv->mdio);
222         mdiobus_free(priv->mdio);
223         priv->mdio = NULL;
224 }
225
226 static int tse_init_rx_buffer(struct altera_tse_private *priv,
227                               struct tse_buffer *rxbuffer, int len)
228 {
229         rxbuffer->skb = netdev_alloc_skb_ip_align(priv->dev, len);
230         if (!rxbuffer->skb)
231                 return -ENOMEM;
232
233         rxbuffer->dma_addr = dma_map_single(priv->device, rxbuffer->skb->data,
234                                                 len,
235                                                 DMA_FROM_DEVICE);
236
237         if (dma_mapping_error(priv->device, rxbuffer->dma_addr)) {
238                 netdev_err(priv->dev, "%s: DMA mapping error\n", __func__);
239                 dev_kfree_skb_any(rxbuffer->skb);
240                 return -EINVAL;
241         }
242         rxbuffer->dma_addr &= (dma_addr_t)~3;
243         rxbuffer->len = len;
244         return 0;
245 }
246
247 static void tse_free_rx_buffer(struct altera_tse_private *priv,
248                                struct tse_buffer *rxbuffer)
249 {
250         struct sk_buff *skb = rxbuffer->skb;
251         dma_addr_t dma_addr = rxbuffer->dma_addr;
252
253         if (skb != NULL) {
254                 if (dma_addr)
255                         dma_unmap_single(priv->device, dma_addr,
256                                          rxbuffer->len,
257                                          DMA_FROM_DEVICE);
258                 dev_kfree_skb_any(skb);
259                 rxbuffer->skb = NULL;
260                 rxbuffer->dma_addr = 0;
261         }
262 }
263
264 /* Unmap and free Tx buffer resources
265  */
266 static void tse_free_tx_buffer(struct altera_tse_private *priv,
267                                struct tse_buffer *buffer)
268 {
269         if (buffer->dma_addr) {
270                 if (buffer->mapped_as_page)
271                         dma_unmap_page(priv->device, buffer->dma_addr,
272                                        buffer->len, DMA_TO_DEVICE);
273                 else
274                         dma_unmap_single(priv->device, buffer->dma_addr,
275                                          buffer->len, DMA_TO_DEVICE);
276                 buffer->dma_addr = 0;
277         }
278         if (buffer->skb) {
279                 dev_kfree_skb_any(buffer->skb);
280                 buffer->skb = NULL;
281         }
282 }
283
284 static int alloc_init_skbufs(struct altera_tse_private *priv)
285 {
286         unsigned int rx_descs = priv->rx_ring_size;
287         unsigned int tx_descs = priv->tx_ring_size;
288         int ret = -ENOMEM;
289         int i;
290
291         /* Create Rx ring buffer */
292         priv->rx_ring = kcalloc(rx_descs, sizeof(struct tse_buffer),
293                                 GFP_KERNEL);
294         if (!priv->rx_ring)
295                 goto err_rx_ring;
296
297         /* Create Tx ring buffer */
298         priv->tx_ring = kcalloc(tx_descs, sizeof(struct tse_buffer),
299                                 GFP_KERNEL);
300         if (!priv->tx_ring)
301                 goto err_tx_ring;
302
303         priv->tx_cons = 0;
304         priv->tx_prod = 0;
305
306         /* Init Rx ring */
307         for (i = 0; i < rx_descs; i++) {
308                 ret = tse_init_rx_buffer(priv, &priv->rx_ring[i],
309                                          priv->rx_dma_buf_sz);
310                 if (ret)
311                         goto err_init_rx_buffers;
312         }
313
314         priv->rx_cons = 0;
315         priv->rx_prod = 0;
316
317         return 0;
318 err_init_rx_buffers:
319         while (--i >= 0)
320                 tse_free_rx_buffer(priv, &priv->rx_ring[i]);
321         kfree(priv->tx_ring);
322 err_tx_ring:
323         kfree(priv->rx_ring);
324 err_rx_ring:
325         return ret;
326 }
327
328 static void free_skbufs(struct net_device *dev)
329 {
330         struct altera_tse_private *priv = netdev_priv(dev);
331         unsigned int rx_descs = priv->rx_ring_size;
332         unsigned int tx_descs = priv->tx_ring_size;
333         int i;
334
335         /* Release the DMA TX/RX socket buffers */
336         for (i = 0; i < rx_descs; i++)
337                 tse_free_rx_buffer(priv, &priv->rx_ring[i]);
338         for (i = 0; i < tx_descs; i++)
339                 tse_free_tx_buffer(priv, &priv->tx_ring[i]);
340
341
342         kfree(priv->tx_ring);
343 }
344
345 /* Reallocate the skb for the reception process
346  */
347 static inline void tse_rx_refill(struct altera_tse_private *priv)
348 {
349         unsigned int rxsize = priv->rx_ring_size;
350         unsigned int entry;
351         int ret;
352
353         for (; priv->rx_cons - priv->rx_prod > 0;
354                         priv->rx_prod++) {
355                 entry = priv->rx_prod % rxsize;
356                 if (likely(priv->rx_ring[entry].skb == NULL)) {
357                         ret = tse_init_rx_buffer(priv, &priv->rx_ring[entry],
358                                 priv->rx_dma_buf_sz);
359                         if (unlikely(ret != 0))
360                                 break;
361                         priv->dmaops->add_rx_desc(priv, &priv->rx_ring[entry]);
362                 }
363         }
364 }
365
366 /* Pull out the VLAN tag and fix up the packet
367  */
368 static inline void tse_rx_vlan(struct net_device *dev, struct sk_buff *skb)
369 {
370         struct ethhdr *eth_hdr;
371         u16 vid;
372         if ((dev->features & NETIF_F_HW_VLAN_CTAG_RX) &&
373             !__vlan_get_tag(skb, &vid)) {
374                 eth_hdr = (struct ethhdr *)skb->data;
375                 memmove(skb->data + VLAN_HLEN, eth_hdr, ETH_ALEN * 2);
376                 skb_pull(skb, VLAN_HLEN);
377                 __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid);
378         }
379 }
380
381 /* Receive a packet: retrieve and pass over to upper levels
382  */
383 static int tse_rx(struct altera_tse_private *priv, int limit)
384 {
385         unsigned int count = 0;
386         unsigned int next_entry;
387         struct sk_buff *skb;
388         unsigned int entry = priv->rx_cons % priv->rx_ring_size;
389         u32 rxstatus;
390         u16 pktlength;
391         u16 pktstatus;
392
393         /* Check for count < limit first as get_rx_status is changing
394         * the response-fifo so we must process the next packet
395         * after calling get_rx_status if a response is pending.
396         * (reading the last byte of the response pops the value from the fifo.)
397         */
398         while ((count < limit) &&
399                ((rxstatus = priv->dmaops->get_rx_status(priv)) != 0)) {
400                 pktstatus = rxstatus >> 16;
401                 pktlength = rxstatus & 0xffff;
402
403                 if ((pktstatus & 0xFF) || (pktlength == 0))
404                         netdev_err(priv->dev,
405                                    "RCV pktstatus %08X pktlength %08X\n",
406                                    pktstatus, pktlength);
407
408                 /* DMA trasfer from TSE starts with 2 aditional bytes for
409                  * IP payload alignment. Status returned by get_rx_status()
410                  * contains DMA transfer length. Packet is 2 bytes shorter.
411                  */
412                 pktlength -= 2;
413
414                 count++;
415                 next_entry = (++priv->rx_cons) % priv->rx_ring_size;
416
417                 skb = priv->rx_ring[entry].skb;
418                 if (unlikely(!skb)) {
419                         netdev_err(priv->dev,
420                                    "%s: Inconsistent Rx descriptor chain\n",
421                                    __func__);
422                         priv->dev->stats.rx_dropped++;
423                         break;
424                 }
425                 priv->rx_ring[entry].skb = NULL;
426
427                 skb_put(skb, pktlength);
428
429                 dma_unmap_single(priv->device, priv->rx_ring[entry].dma_addr,
430                                  priv->rx_ring[entry].len, DMA_FROM_DEVICE);
431
432                 if (netif_msg_pktdata(priv)) {
433                         netdev_info(priv->dev, "frame received %d bytes\n",
434                                     pktlength);
435                         print_hex_dump(KERN_ERR, "data: ", DUMP_PREFIX_OFFSET,
436                                        16, 1, skb->data, pktlength, true);
437                 }
438
439                 tse_rx_vlan(priv->dev, skb);
440
441                 skb->protocol = eth_type_trans(skb, priv->dev);
442                 skb_checksum_none_assert(skb);
443
444                 napi_gro_receive(&priv->napi, skb);
445
446                 priv->dev->stats.rx_packets++;
447                 priv->dev->stats.rx_bytes += pktlength;
448
449                 entry = next_entry;
450
451                 tse_rx_refill(priv);
452         }
453
454         return count;
455 }
456
457 /* Reclaim resources after transmission completes
458  */
459 static int tse_tx_complete(struct altera_tse_private *priv)
460 {
461         unsigned int txsize = priv->tx_ring_size;
462         u32 ready;
463         unsigned int entry;
464         struct tse_buffer *tx_buff;
465         int txcomplete = 0;
466
467         spin_lock(&priv->tx_lock);
468
469         ready = priv->dmaops->tx_completions(priv);
470
471         /* Free sent buffers */
472         while (ready && (priv->tx_cons != priv->tx_prod)) {
473                 entry = priv->tx_cons % txsize;
474                 tx_buff = &priv->tx_ring[entry];
475
476                 if (netif_msg_tx_done(priv))
477                         netdev_dbg(priv->dev, "%s: curr %d, dirty %d\n",
478                                    __func__, priv->tx_prod, priv->tx_cons);
479
480                 if (likely(tx_buff->skb))
481                         priv->dev->stats.tx_packets++;
482
483                 tse_free_tx_buffer(priv, tx_buff);
484                 priv->tx_cons++;
485
486                 txcomplete++;
487                 ready--;
488         }
489
490         if (unlikely(netif_queue_stopped(priv->dev) &&
491                      tse_tx_avail(priv) > TSE_TX_THRESH(priv))) {
492                 if (netif_queue_stopped(priv->dev) &&
493                     tse_tx_avail(priv) > TSE_TX_THRESH(priv)) {
494                         if (netif_msg_tx_done(priv))
495                                 netdev_dbg(priv->dev, "%s: restart transmit\n",
496                                            __func__);
497                         netif_wake_queue(priv->dev);
498                 }
499         }
500
501         spin_unlock(&priv->tx_lock);
502         return txcomplete;
503 }
504
505 /* NAPI polling function
506  */
507 static int tse_poll(struct napi_struct *napi, int budget)
508 {
509         struct altera_tse_private *priv =
510                         container_of(napi, struct altera_tse_private, napi);
511         int rxcomplete = 0;
512         unsigned long int flags;
513
514         tse_tx_complete(priv);
515
516         rxcomplete = tse_rx(priv, budget);
517
518         if (rxcomplete < budget) {
519
520                 napi_complete_done(napi, rxcomplete);
521
522                 netdev_dbg(priv->dev,
523                            "NAPI Complete, did %d packets with budget %d\n",
524                            rxcomplete, budget);
525
526                 spin_lock_irqsave(&priv->rxdma_irq_lock, flags);
527                 priv->dmaops->enable_rxirq(priv);
528                 priv->dmaops->enable_txirq(priv);
529                 spin_unlock_irqrestore(&priv->rxdma_irq_lock, flags);
530         }
531         return rxcomplete;
532 }
533
534 /* DMA TX & RX FIFO interrupt routing
535  */
536 static irqreturn_t altera_isr(int irq, void *dev_id)
537 {
538         struct net_device *dev = dev_id;
539         struct altera_tse_private *priv;
540
541         if (unlikely(!dev)) {
542                 pr_err("%s: invalid dev pointer\n", __func__);
543                 return IRQ_NONE;
544         }
545         priv = netdev_priv(dev);
546
547         spin_lock(&priv->rxdma_irq_lock);
548         /* reset IRQs */
549         priv->dmaops->clear_rxirq(priv);
550         priv->dmaops->clear_txirq(priv);
551         spin_unlock(&priv->rxdma_irq_lock);
552
553         if (likely(napi_schedule_prep(&priv->napi))) {
554                 spin_lock(&priv->rxdma_irq_lock);
555                 priv->dmaops->disable_rxirq(priv);
556                 priv->dmaops->disable_txirq(priv);
557                 spin_unlock(&priv->rxdma_irq_lock);
558                 __napi_schedule(&priv->napi);
559         }
560
561
562         return IRQ_HANDLED;
563 }
564
565 /* Transmit a packet (called by the kernel). Dispatches
566  * either the SGDMA method for transmitting or the
567  * MSGDMA method, assumes no scatter/gather support,
568  * implying an assumption that there's only one
569  * physically contiguous fragment starting at
570  * skb->data, for length of skb_headlen(skb).
571  */
572 static int tse_start_xmit(struct sk_buff *skb, struct net_device *dev)
573 {
574         struct altera_tse_private *priv = netdev_priv(dev);
575         unsigned int txsize = priv->tx_ring_size;
576         unsigned int entry;
577         struct tse_buffer *buffer = NULL;
578         int nfrags = skb_shinfo(skb)->nr_frags;
579         unsigned int nopaged_len = skb_headlen(skb);
580         enum netdev_tx ret = NETDEV_TX_OK;
581         dma_addr_t dma_addr;
582
583         spin_lock_bh(&priv->tx_lock);
584
585         if (unlikely(tse_tx_avail(priv) < nfrags + 1)) {
586                 if (!netif_queue_stopped(dev)) {
587                         netif_stop_queue(dev);
588                         /* This is a hard error, log it. */
589                         netdev_err(priv->dev,
590                                    "%s: Tx list full when queue awake\n",
591                                    __func__);
592                 }
593                 ret = NETDEV_TX_BUSY;
594                 goto out;
595         }
596
597         /* Map the first skb fragment */
598         entry = priv->tx_prod % txsize;
599         buffer = &priv->tx_ring[entry];
600
601         dma_addr = dma_map_single(priv->device, skb->data, nopaged_len,
602                                   DMA_TO_DEVICE);
603         if (dma_mapping_error(priv->device, dma_addr)) {
604                 netdev_err(priv->dev, "%s: DMA mapping error\n", __func__);
605                 ret = NETDEV_TX_OK;
606                 goto out;
607         }
608
609         buffer->skb = skb;
610         buffer->dma_addr = dma_addr;
611         buffer->len = nopaged_len;
612
613         priv->dmaops->tx_buffer(priv, buffer);
614
615         skb_tx_timestamp(skb);
616
617         priv->tx_prod++;
618         dev->stats.tx_bytes += skb->len;
619
620         if (unlikely(tse_tx_avail(priv) <= TXQUEUESTOP_THRESHHOLD)) {
621                 if (netif_msg_hw(priv))
622                         netdev_dbg(priv->dev, "%s: stop transmitted packets\n",
623                                    __func__);
624                 netif_stop_queue(dev);
625         }
626
627 out:
628         spin_unlock_bh(&priv->tx_lock);
629
630         return ret;
631 }
632
633 /* Called every time the controller might need to be made
634  * aware of new link state.  The PHY code conveys this
635  * information through variables in the phydev structure, and this
636  * function converts those variables into the appropriate
637  * register values, and can bring down the device if needed.
638  */
639 static void altera_tse_adjust_link(struct net_device *dev)
640 {
641         struct altera_tse_private *priv = netdev_priv(dev);
642         struct phy_device *phydev = dev->phydev;
643         int new_state = 0;
644
645         /* only change config if there is a link */
646         spin_lock(&priv->mac_cfg_lock);
647         if (phydev->link) {
648                 /* Read old config */
649                 u32 cfg_reg = ioread32(&priv->mac_dev->command_config);
650
651                 /* Check duplex */
652                 if (phydev->duplex != priv->oldduplex) {
653                         new_state = 1;
654                         if (!(phydev->duplex))
655                                 cfg_reg |= MAC_CMDCFG_HD_ENA;
656                         else
657                                 cfg_reg &= ~MAC_CMDCFG_HD_ENA;
658
659                         netdev_dbg(priv->dev, "%s: Link duplex = 0x%x\n",
660                                    dev->name, phydev->duplex);
661
662                         priv->oldduplex = phydev->duplex;
663                 }
664
665                 /* Check speed */
666                 if (phydev->speed != priv->oldspeed) {
667                         new_state = 1;
668                         switch (phydev->speed) {
669                         case 1000:
670                                 cfg_reg |= MAC_CMDCFG_ETH_SPEED;
671                                 cfg_reg &= ~MAC_CMDCFG_ENA_10;
672                                 break;
673                         case 100:
674                                 cfg_reg &= ~MAC_CMDCFG_ETH_SPEED;
675                                 cfg_reg &= ~MAC_CMDCFG_ENA_10;
676                                 break;
677                         case 10:
678                                 cfg_reg &= ~MAC_CMDCFG_ETH_SPEED;
679                                 cfg_reg |= MAC_CMDCFG_ENA_10;
680                                 break;
681                         default:
682                                 if (netif_msg_link(priv))
683                                         netdev_warn(dev, "Speed (%d) is not 10/100/1000!\n",
684                                                     phydev->speed);
685                                 break;
686                         }
687                         priv->oldspeed = phydev->speed;
688                 }
689                 iowrite32(cfg_reg, &priv->mac_dev->command_config);
690
691                 if (!priv->oldlink) {
692                         new_state = 1;
693                         priv->oldlink = 1;
694                 }
695         } else if (priv->oldlink) {
696                 new_state = 1;
697                 priv->oldlink = 0;
698                 priv->oldspeed = 0;
699                 priv->oldduplex = -1;
700         }
701
702         if (new_state && netif_msg_link(priv))
703                 phy_print_status(phydev);
704
705         spin_unlock(&priv->mac_cfg_lock);
706 }
707 static struct phy_device *connect_local_phy(struct net_device *dev)
708 {
709         struct altera_tse_private *priv = netdev_priv(dev);
710         struct phy_device *phydev = NULL;
711         char phy_id_fmt[MII_BUS_ID_SIZE + 3];
712
713         if (priv->phy_addr != POLL_PHY) {
714                 snprintf(phy_id_fmt, MII_BUS_ID_SIZE + 3, PHY_ID_FMT,
715                          priv->mdio->id, priv->phy_addr);
716
717                 netdev_dbg(dev, "trying to attach to %s\n", phy_id_fmt);
718
719                 phydev = phy_connect(dev, phy_id_fmt, &altera_tse_adjust_link,
720                                      priv->phy_iface);
721                 if (IS_ERR(phydev)) {
722                         netdev_err(dev, "Could not attach to PHY\n");
723                         phydev = NULL;
724                 }
725
726         } else {
727                 int ret;
728                 phydev = phy_find_first(priv->mdio);
729                 if (phydev == NULL) {
730                         netdev_err(dev, "No PHY found\n");
731                         return phydev;
732                 }
733
734                 ret = phy_connect_direct(dev, phydev, &altera_tse_adjust_link,
735                                 priv->phy_iface);
736                 if (ret != 0) {
737                         netdev_err(dev, "Could not attach to PHY\n");
738                         phydev = NULL;
739                 }
740         }
741         return phydev;
742 }
743
744 static int altera_tse_phy_get_addr_mdio_create(struct net_device *dev)
745 {
746         struct altera_tse_private *priv = netdev_priv(dev);
747         struct device_node *np = priv->device->of_node;
748         int ret = 0;
749
750         priv->phy_iface = of_get_phy_mode(np);
751
752         /* Avoid get phy addr and create mdio if no phy is present */
753         if (!priv->phy_iface)
754                 return 0;
755
756         /* try to get PHY address from device tree, use PHY autodetection if
757          * no valid address is given
758          */
759
760         if (of_property_read_u32(priv->device->of_node, "phy-addr",
761                          &priv->phy_addr)) {
762                 priv->phy_addr = POLL_PHY;
763         }
764
765         if (!((priv->phy_addr == POLL_PHY) ||
766                   ((priv->phy_addr >= 0) && (priv->phy_addr < PHY_MAX_ADDR)))) {
767                 netdev_err(dev, "invalid phy-addr specified %d\n",
768                         priv->phy_addr);
769                 return -ENODEV;
770         }
771
772         /* Create/attach to MDIO bus */
773         ret = altera_tse_mdio_create(dev,
774                                          atomic_add_return(1, &instance_count));
775
776         if (ret)
777                 return -ENODEV;
778
779         return 0;
780 }
781
782 /* Initialize driver's PHY state, and attach to the PHY
783  */
784 static int init_phy(struct net_device *dev)
785 {
786         struct altera_tse_private *priv = netdev_priv(dev);
787         struct phy_device *phydev;
788         struct device_node *phynode;
789         bool fixed_link = false;
790         int rc = 0;
791
792         /* Avoid init phy in case of no phy present */
793         if (!priv->phy_iface)
794                 return 0;
795
796         priv->oldlink = 0;
797         priv->oldspeed = 0;
798         priv->oldduplex = -1;
799
800         phynode = of_parse_phandle(priv->device->of_node, "phy-handle", 0);
801
802         if (!phynode) {
803                 /* check if a fixed-link is defined in device-tree */
804                 if (of_phy_is_fixed_link(priv->device->of_node)) {
805                         rc = of_phy_register_fixed_link(priv->device->of_node);
806                         if (rc < 0) {
807                                 netdev_err(dev, "cannot register fixed PHY\n");
808                                 return rc;
809                         }
810
811                         /* In the case of a fixed PHY, the DT node associated
812                          * to the PHY is the Ethernet MAC DT node.
813                          */
814                         phynode = of_node_get(priv->device->of_node);
815                         fixed_link = true;
816
817                         netdev_dbg(dev, "fixed-link detected\n");
818                         phydev = of_phy_connect(dev, phynode,
819                                                 &altera_tse_adjust_link,
820                                                 0, priv->phy_iface);
821                 } else {
822                         netdev_dbg(dev, "no phy-handle found\n");
823                         if (!priv->mdio) {
824                                 netdev_err(dev, "No phy-handle nor local mdio specified\n");
825                                 return -ENODEV;
826                         }
827                         phydev = connect_local_phy(dev);
828                 }
829         } else {
830                 netdev_dbg(dev, "phy-handle found\n");
831                 phydev = of_phy_connect(dev, phynode,
832                         &altera_tse_adjust_link, 0, priv->phy_iface);
833         }
834         of_node_put(phynode);
835
836         if (!phydev) {
837                 netdev_err(dev, "Could not find the PHY\n");
838                 if (fixed_link)
839                         of_phy_deregister_fixed_link(priv->device->of_node);
840                 return -ENODEV;
841         }
842
843         /* Stop Advertising 1000BASE Capability if interface is not GMII
844          * Note: Checkpatch throws CHECKs for the camel case defines below,
845          * it's ok to ignore.
846          */
847         if ((priv->phy_iface == PHY_INTERFACE_MODE_MII) ||
848             (priv->phy_iface == PHY_INTERFACE_MODE_RMII))
849                 phydev->advertising &= ~(SUPPORTED_1000baseT_Half |
850                                          SUPPORTED_1000baseT_Full);
851
852         /* Broken HW is sometimes missing the pull-up resistor on the
853          * MDIO line, which results in reads to non-existent devices returning
854          * 0 rather than 0xffff. Catch this here and treat 0 as a non-existent
855          * device as well. If a fixed-link is used the phy_id is always 0.
856          * Note: phydev->phy_id is the result of reading the UID PHY registers.
857          */
858         if ((phydev->phy_id == 0) && !fixed_link) {
859                 netdev_err(dev, "Bad PHY UID 0x%08x\n", phydev->phy_id);
860                 phy_disconnect(phydev);
861                 return -ENODEV;
862         }
863
864         netdev_dbg(dev, "attached to PHY %d UID 0x%08x Link = %d\n",
865                    phydev->mdio.addr, phydev->phy_id, phydev->link);
866
867         return 0;
868 }
869
870 static void tse_update_mac_addr(struct altera_tse_private *priv, u8 *addr)
871 {
872         u32 msb;
873         u32 lsb;
874
875         msb = (addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) | addr[0];
876         lsb = ((addr[5] << 8) | addr[4]) & 0xffff;
877
878         /* Set primary MAC address */
879         csrwr32(msb, priv->mac_dev, tse_csroffs(mac_addr_0));
880         csrwr32(lsb, priv->mac_dev, tse_csroffs(mac_addr_1));
881 }
882
883 /* MAC software reset.
884  * When reset is triggered, the MAC function completes the current
885  * transmission or reception, and subsequently disables the transmit and
886  * receive logic, flushes the receive FIFO buffer, and resets the statistics
887  * counters.
888  */
889 static int reset_mac(struct altera_tse_private *priv)
890 {
891         int counter;
892         u32 dat;
893
894         dat = csrrd32(priv->mac_dev, tse_csroffs(command_config));
895         dat &= ~(MAC_CMDCFG_TX_ENA | MAC_CMDCFG_RX_ENA);
896         dat |= MAC_CMDCFG_SW_RESET | MAC_CMDCFG_CNT_RESET;
897         csrwr32(dat, priv->mac_dev, tse_csroffs(command_config));
898
899         counter = 0;
900         while (counter++ < ALTERA_TSE_SW_RESET_WATCHDOG_CNTR) {
901                 if (tse_bit_is_clear(priv->mac_dev, tse_csroffs(command_config),
902                                      MAC_CMDCFG_SW_RESET))
903                         break;
904                 udelay(1);
905         }
906
907         if (counter >= ALTERA_TSE_SW_RESET_WATCHDOG_CNTR) {
908                 dat = csrrd32(priv->mac_dev, tse_csroffs(command_config));
909                 dat &= ~MAC_CMDCFG_SW_RESET;
910                 csrwr32(dat, priv->mac_dev, tse_csroffs(command_config));
911                 return -1;
912         }
913         return 0;
914 }
915
916 /* Initialize MAC core registers
917 */
918 static int init_mac(struct altera_tse_private *priv)
919 {
920         unsigned int cmd = 0;
921         u32 frm_length;
922
923         /* Setup Rx FIFO */
924         csrwr32(priv->rx_fifo_depth - ALTERA_TSE_RX_SECTION_EMPTY,
925                 priv->mac_dev, tse_csroffs(rx_section_empty));
926
927         csrwr32(ALTERA_TSE_RX_SECTION_FULL, priv->mac_dev,
928                 tse_csroffs(rx_section_full));
929
930         csrwr32(ALTERA_TSE_RX_ALMOST_EMPTY, priv->mac_dev,
931                 tse_csroffs(rx_almost_empty));
932
933         csrwr32(ALTERA_TSE_RX_ALMOST_FULL, priv->mac_dev,
934                 tse_csroffs(rx_almost_full));
935
936         /* Setup Tx FIFO */
937         csrwr32(priv->tx_fifo_depth - ALTERA_TSE_TX_SECTION_EMPTY,
938                 priv->mac_dev, tse_csroffs(tx_section_empty));
939
940         csrwr32(ALTERA_TSE_TX_SECTION_FULL, priv->mac_dev,
941                 tse_csroffs(tx_section_full));
942
943         csrwr32(ALTERA_TSE_TX_ALMOST_EMPTY, priv->mac_dev,
944                 tse_csroffs(tx_almost_empty));
945
946         csrwr32(ALTERA_TSE_TX_ALMOST_FULL, priv->mac_dev,
947                 tse_csroffs(tx_almost_full));
948
949         /* MAC Address Configuration */
950         tse_update_mac_addr(priv, priv->dev->dev_addr);
951
952         /* MAC Function Configuration */
953         frm_length = ETH_HLEN + priv->dev->mtu + ETH_FCS_LEN;
954         csrwr32(frm_length, priv->mac_dev, tse_csroffs(frm_length));
955
956         csrwr32(ALTERA_TSE_TX_IPG_LENGTH, priv->mac_dev,
957                 tse_csroffs(tx_ipg_length));
958
959         /* Disable RX/TX shift 16 for alignment of all received frames on 16-bit
960          * start address
961          */
962         tse_set_bit(priv->mac_dev, tse_csroffs(rx_cmd_stat),
963                     ALTERA_TSE_RX_CMD_STAT_RX_SHIFT16);
964
965         tse_clear_bit(priv->mac_dev, tse_csroffs(tx_cmd_stat),
966                       ALTERA_TSE_TX_CMD_STAT_TX_SHIFT16 |
967                       ALTERA_TSE_TX_CMD_STAT_OMIT_CRC);
968
969         /* Set the MAC options */
970         cmd = csrrd32(priv->mac_dev, tse_csroffs(command_config));
971         cmd &= ~MAC_CMDCFG_PAD_EN;      /* No padding Removal on Receive */
972         cmd &= ~MAC_CMDCFG_CRC_FWD;     /* CRC Removal */
973         cmd |= MAC_CMDCFG_RX_ERR_DISC;  /* Automatically discard frames
974                                          * with CRC errors
975                                          */
976         cmd |= MAC_CMDCFG_CNTL_FRM_ENA;
977         cmd &= ~MAC_CMDCFG_TX_ENA;
978         cmd &= ~MAC_CMDCFG_RX_ENA;
979
980         /* Default speed and duplex setting, full/100 */
981         cmd &= ~MAC_CMDCFG_HD_ENA;
982         cmd &= ~MAC_CMDCFG_ETH_SPEED;
983         cmd &= ~MAC_CMDCFG_ENA_10;
984
985         csrwr32(cmd, priv->mac_dev, tse_csroffs(command_config));
986
987         csrwr32(ALTERA_TSE_PAUSE_QUANTA, priv->mac_dev,
988                 tse_csroffs(pause_quanta));
989
990         if (netif_msg_hw(priv))
991                 dev_dbg(priv->device,
992                         "MAC post-initialization: CMD_CONFIG = 0x%08x\n", cmd);
993
994         return 0;
995 }
996
997 /* Start/stop MAC transmission logic
998  */
999 static void tse_set_mac(struct altera_tse_private *priv, bool enable)
1000 {
1001         u32 value = csrrd32(priv->mac_dev, tse_csroffs(command_config));
1002
1003         if (enable)
1004                 value |= MAC_CMDCFG_TX_ENA | MAC_CMDCFG_RX_ENA;
1005         else
1006                 value &= ~(MAC_CMDCFG_TX_ENA | MAC_CMDCFG_RX_ENA);
1007
1008         csrwr32(value, priv->mac_dev, tse_csroffs(command_config));
1009 }
1010
1011 /* Change the MTU
1012  */
1013 static int tse_change_mtu(struct net_device *dev, int new_mtu)
1014 {
1015         if (netif_running(dev)) {
1016                 netdev_err(dev, "must be stopped to change its MTU\n");
1017                 return -EBUSY;
1018         }
1019
1020         dev->mtu = new_mtu;
1021         netdev_update_features(dev);
1022
1023         return 0;
1024 }
1025
1026 static void altera_tse_set_mcfilter(struct net_device *dev)
1027 {
1028         struct altera_tse_private *priv = netdev_priv(dev);
1029         int i;
1030         struct netdev_hw_addr *ha;
1031
1032         /* clear the hash filter */
1033         for (i = 0; i < 64; i++)
1034                 csrwr32(0, priv->mac_dev, tse_csroffs(hash_table) + i * 4);
1035
1036         netdev_for_each_mc_addr(ha, dev) {
1037                 unsigned int hash = 0;
1038                 int mac_octet;
1039
1040                 for (mac_octet = 5; mac_octet >= 0; mac_octet--) {
1041                         unsigned char xor_bit = 0;
1042                         unsigned char octet = ha->addr[mac_octet];
1043                         unsigned int bitshift;
1044
1045                         for (bitshift = 0; bitshift < 8; bitshift++)
1046                                 xor_bit ^= ((octet >> bitshift) & 0x01);
1047
1048                         hash = (hash << 1) | xor_bit;
1049                 }
1050                 csrwr32(1, priv->mac_dev, tse_csroffs(hash_table) + hash * 4);
1051         }
1052 }
1053
1054
1055 static void altera_tse_set_mcfilterall(struct net_device *dev)
1056 {
1057         struct altera_tse_private *priv = netdev_priv(dev);
1058         int i;
1059
1060         /* set the hash filter */
1061         for (i = 0; i < 64; i++)
1062                 csrwr32(1, priv->mac_dev, tse_csroffs(hash_table) + i * 4);
1063 }
1064
1065 /* Set or clear the multicast filter for this adaptor
1066  */
1067 static void tse_set_rx_mode_hashfilter(struct net_device *dev)
1068 {
1069         struct altera_tse_private *priv = netdev_priv(dev);
1070
1071         spin_lock(&priv->mac_cfg_lock);
1072
1073         if (dev->flags & IFF_PROMISC)
1074                 tse_set_bit(priv->mac_dev, tse_csroffs(command_config),
1075                             MAC_CMDCFG_PROMIS_EN);
1076
1077         if (dev->flags & IFF_ALLMULTI)
1078                 altera_tse_set_mcfilterall(dev);
1079         else
1080                 altera_tse_set_mcfilter(dev);
1081
1082         spin_unlock(&priv->mac_cfg_lock);
1083 }
1084
1085 /* Set or clear the multicast filter for this adaptor
1086  */
1087 static void tse_set_rx_mode(struct net_device *dev)
1088 {
1089         struct altera_tse_private *priv = netdev_priv(dev);
1090
1091         spin_lock(&priv->mac_cfg_lock);
1092
1093         if ((dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI) ||
1094             !netdev_mc_empty(dev) || !netdev_uc_empty(dev))
1095                 tse_set_bit(priv->mac_dev, tse_csroffs(command_config),
1096                             MAC_CMDCFG_PROMIS_EN);
1097         else
1098                 tse_clear_bit(priv->mac_dev, tse_csroffs(command_config),
1099                               MAC_CMDCFG_PROMIS_EN);
1100
1101         spin_unlock(&priv->mac_cfg_lock);
1102 }
1103
1104 /* Initialise (if necessary) the SGMII PCS component
1105  */
1106 static int init_sgmii_pcs(struct net_device *dev)
1107 {
1108         struct altera_tse_private *priv = netdev_priv(dev);
1109         int n;
1110         unsigned int tmp_reg = 0;
1111
1112         if (priv->phy_iface != PHY_INTERFACE_MODE_SGMII)
1113                 return 0; /* Nothing to do, not in SGMII mode */
1114
1115         /* The TSE SGMII PCS block looks a little like a PHY, it is
1116          * mapped into the zeroth MDIO space of the MAC and it has
1117          * ID registers like a PHY would.  Sadly this is often
1118          * configured to zeroes, so don't be surprised if it does
1119          * show 0x00000000.
1120          */
1121
1122         if (sgmii_pcs_scratch_test(priv, 0x0000) &&
1123                 sgmii_pcs_scratch_test(priv, 0xffff) &&
1124                 sgmii_pcs_scratch_test(priv, 0xa5a5) &&
1125                 sgmii_pcs_scratch_test(priv, 0x5a5a)) {
1126                 netdev_info(dev, "PCS PHY ID: 0x%04x%04x\n",
1127                                 sgmii_pcs_read(priv, MII_PHYSID1),
1128                                 sgmii_pcs_read(priv, MII_PHYSID2));
1129         } else {
1130                 netdev_err(dev, "SGMII PCS Scratch memory test failed.\n");
1131                 return -ENOMEM;
1132         }
1133
1134         /* Starting on page 5-29 of the MegaCore Function User Guide
1135          * Set SGMII Link timer to 1.6ms
1136          */
1137         sgmii_pcs_write(priv, SGMII_PCS_LINK_TIMER_0, 0x0D40);
1138         sgmii_pcs_write(priv, SGMII_PCS_LINK_TIMER_1, 0x03);
1139
1140         /* Enable SGMII Interface and Enable SGMII Auto Negotiation */
1141         sgmii_pcs_write(priv, SGMII_PCS_IF_MODE, 0x3);
1142
1143         /* Enable Autonegotiation */
1144         tmp_reg = sgmii_pcs_read(priv, MII_BMCR);
1145         tmp_reg |= (BMCR_SPEED1000 | BMCR_FULLDPLX | BMCR_ANENABLE);
1146         sgmii_pcs_write(priv, MII_BMCR, tmp_reg);
1147
1148         /* Reset PCS block */
1149         tmp_reg |= BMCR_RESET;
1150         sgmii_pcs_write(priv, MII_BMCR, tmp_reg);
1151         for (n = 0; n < SGMII_PCS_SW_RESET_TIMEOUT; n++) {
1152                 if (!(sgmii_pcs_read(priv, MII_BMCR) & BMCR_RESET)) {
1153                         netdev_info(dev, "SGMII PCS block initialised OK\n");
1154                         return 0;
1155                 }
1156                 udelay(1);
1157         }
1158
1159         /* We failed to reset the block, return a timeout */
1160         netdev_err(dev, "SGMII PCS block reset failed.\n");
1161         return -ETIMEDOUT;
1162 }
1163
1164 /* Open and initialize the interface
1165  */
1166 static int tse_open(struct net_device *dev)
1167 {
1168         struct altera_tse_private *priv = netdev_priv(dev);
1169         int ret = 0;
1170         int i;
1171         unsigned long int flags;
1172
1173         /* Reset and configure TSE MAC and probe associated PHY */
1174         ret = priv->dmaops->init_dma(priv);
1175         if (ret != 0) {
1176                 netdev_err(dev, "Cannot initialize DMA\n");
1177                 goto phy_error;
1178         }
1179
1180         if (netif_msg_ifup(priv))
1181                 netdev_warn(dev, "device MAC address %pM\n",
1182                             dev->dev_addr);
1183
1184         if ((priv->revision < 0xd00) || (priv->revision > 0xe00))
1185                 netdev_warn(dev, "TSE revision %x\n", priv->revision);
1186
1187         spin_lock(&priv->mac_cfg_lock);
1188         /* no-op if MAC not operating in SGMII mode*/
1189         ret = init_sgmii_pcs(dev);
1190         if (ret) {
1191                 netdev_err(dev,
1192                            "Cannot init the SGMII PCS (error: %d)\n", ret);
1193                 spin_unlock(&priv->mac_cfg_lock);
1194                 goto phy_error;
1195         }
1196
1197         ret = reset_mac(priv);
1198         /* Note that reset_mac will fail if the clocks are gated by the PHY
1199          * due to the PHY being put into isolation or power down mode.
1200          * This is not an error if reset fails due to no clock.
1201          */
1202         if (ret)
1203                 netdev_dbg(dev, "Cannot reset MAC core (error: %d)\n", ret);
1204
1205         ret = init_mac(priv);
1206         spin_unlock(&priv->mac_cfg_lock);
1207         if (ret) {
1208                 netdev_err(dev, "Cannot init MAC core (error: %d)\n", ret);
1209                 goto alloc_skbuf_error;
1210         }
1211
1212         priv->dmaops->reset_dma(priv);
1213
1214         /* Create and initialize the TX/RX descriptors chains. */
1215         priv->rx_ring_size = dma_rx_num;
1216         priv->tx_ring_size = dma_tx_num;
1217         ret = alloc_init_skbufs(priv);
1218         if (ret) {
1219                 netdev_err(dev, "DMA descriptors initialization failed\n");
1220                 goto alloc_skbuf_error;
1221         }
1222
1223
1224         /* Register RX interrupt */
1225         ret = request_irq(priv->rx_irq, altera_isr, IRQF_SHARED,
1226                           dev->name, dev);
1227         if (ret) {
1228                 netdev_err(dev, "Unable to register RX interrupt %d\n",
1229                            priv->rx_irq);
1230                 goto init_error;
1231         }
1232
1233         /* Register TX interrupt */
1234         ret = request_irq(priv->tx_irq, altera_isr, IRQF_SHARED,
1235                           dev->name, dev);
1236         if (ret) {
1237                 netdev_err(dev, "Unable to register TX interrupt %d\n",
1238                            priv->tx_irq);
1239                 goto tx_request_irq_error;
1240         }
1241
1242         /* Enable DMA interrupts */
1243         spin_lock_irqsave(&priv->rxdma_irq_lock, flags);
1244         priv->dmaops->enable_rxirq(priv);
1245         priv->dmaops->enable_txirq(priv);
1246
1247         /* Setup RX descriptor chain */
1248         for (i = 0; i < priv->rx_ring_size; i++)
1249                 priv->dmaops->add_rx_desc(priv, &priv->rx_ring[i]);
1250
1251         spin_unlock_irqrestore(&priv->rxdma_irq_lock, flags);
1252
1253         if (dev->phydev)
1254                 phy_start(dev->phydev);
1255
1256         napi_enable(&priv->napi);
1257         netif_start_queue(dev);
1258
1259         priv->dmaops->start_rxdma(priv);
1260
1261         /* Start MAC Rx/Tx */
1262         spin_lock(&priv->mac_cfg_lock);
1263         tse_set_mac(priv, true);
1264         spin_unlock(&priv->mac_cfg_lock);
1265
1266         return 0;
1267
1268 tx_request_irq_error:
1269         free_irq(priv->rx_irq, dev);
1270 init_error:
1271         free_skbufs(dev);
1272 alloc_skbuf_error:
1273 phy_error:
1274         return ret;
1275 }
1276
1277 /* Stop TSE MAC interface and put the device in an inactive state
1278  */
1279 static int tse_shutdown(struct net_device *dev)
1280 {
1281         struct altera_tse_private *priv = netdev_priv(dev);
1282         int ret;
1283         unsigned long int flags;
1284
1285         /* Stop the PHY */
1286         if (dev->phydev)
1287                 phy_stop(dev->phydev);
1288
1289         netif_stop_queue(dev);
1290         napi_disable(&priv->napi);
1291
1292         /* Disable DMA interrupts */
1293         spin_lock_irqsave(&priv->rxdma_irq_lock, flags);
1294         priv->dmaops->disable_rxirq(priv);
1295         priv->dmaops->disable_txirq(priv);
1296         spin_unlock_irqrestore(&priv->rxdma_irq_lock, flags);
1297
1298         /* Free the IRQ lines */
1299         free_irq(priv->rx_irq, dev);
1300         free_irq(priv->tx_irq, dev);
1301
1302         /* disable and reset the MAC, empties fifo */
1303         spin_lock(&priv->mac_cfg_lock);
1304         spin_lock(&priv->tx_lock);
1305
1306         ret = reset_mac(priv);
1307         /* Note that reset_mac will fail if the clocks are gated by the PHY
1308          * due to the PHY being put into isolation or power down mode.
1309          * This is not an error if reset fails due to no clock.
1310          */
1311         if (ret)
1312                 netdev_dbg(dev, "Cannot reset MAC core (error: %d)\n", ret);
1313         priv->dmaops->reset_dma(priv);
1314         free_skbufs(dev);
1315
1316         spin_unlock(&priv->tx_lock);
1317         spin_unlock(&priv->mac_cfg_lock);
1318
1319         priv->dmaops->uninit_dma(priv);
1320
1321         return 0;
1322 }
1323
1324 static struct net_device_ops altera_tse_netdev_ops = {
1325         .ndo_open               = tse_open,
1326         .ndo_stop               = tse_shutdown,
1327         .ndo_start_xmit         = tse_start_xmit,
1328         .ndo_set_mac_address    = eth_mac_addr,
1329         .ndo_set_rx_mode        = tse_set_rx_mode,
1330         .ndo_change_mtu         = tse_change_mtu,
1331         .ndo_validate_addr      = eth_validate_addr,
1332 };
1333
1334 static int request_and_map(struct platform_device *pdev, const char *name,
1335                            struct resource **res, void __iomem **ptr)
1336 {
1337         struct resource *region;
1338         struct device *device = &pdev->dev;
1339
1340         *res = platform_get_resource_byname(pdev, IORESOURCE_MEM, name);
1341         if (*res == NULL) {
1342                 dev_err(device, "resource %s not defined\n", name);
1343                 return -ENODEV;
1344         }
1345
1346         region = devm_request_mem_region(device, (*res)->start,
1347                                          resource_size(*res), dev_name(device));
1348         if (region == NULL) {
1349                 dev_err(device, "unable to request %s\n", name);
1350                 return -EBUSY;
1351         }
1352
1353         *ptr = devm_ioremap_nocache(device, region->start,
1354                                     resource_size(region));
1355         if (*ptr == NULL) {
1356                 dev_err(device, "ioremap_nocache of %s failed!", name);
1357                 return -ENOMEM;
1358         }
1359
1360         return 0;
1361 }
1362
1363 /* Probe Altera TSE MAC device
1364  */
1365 static int altera_tse_probe(struct platform_device *pdev)
1366 {
1367         struct net_device *ndev;
1368         int ret = -ENODEV;
1369         struct resource *control_port;
1370         struct resource *dma_res;
1371         struct altera_tse_private *priv;
1372         const unsigned char *macaddr;
1373         void __iomem *descmap;
1374         const struct of_device_id *of_id = NULL;
1375
1376         ndev = alloc_etherdev(sizeof(struct altera_tse_private));
1377         if (!ndev) {
1378                 dev_err(&pdev->dev, "Could not allocate network device\n");
1379                 return -ENODEV;
1380         }
1381
1382         SET_NETDEV_DEV(ndev, &pdev->dev);
1383
1384         priv = netdev_priv(ndev);
1385         priv->device = &pdev->dev;
1386         priv->dev = ndev;
1387         priv->msg_enable = netif_msg_init(debug, default_msg_level);
1388
1389         of_id = of_match_device(altera_tse_ids, &pdev->dev);
1390
1391         if (of_id)
1392                 priv->dmaops = (struct altera_dmaops *)of_id->data;
1393
1394
1395         if (priv->dmaops &&
1396             priv->dmaops->altera_dtype == ALTERA_DTYPE_SGDMA) {
1397                 /* Get the mapped address to the SGDMA descriptor memory */
1398                 ret = request_and_map(pdev, "s1", &dma_res, &descmap);
1399                 if (ret)
1400                         goto err_free_netdev;
1401
1402                 /* Start of that memory is for transmit descriptors */
1403                 priv->tx_dma_desc = descmap;
1404
1405                 /* First half is for tx descriptors, other half for tx */
1406                 priv->txdescmem = resource_size(dma_res)/2;
1407
1408                 priv->txdescmem_busaddr = (dma_addr_t)dma_res->start;
1409
1410                 priv->rx_dma_desc = (void __iomem *)((uintptr_t)(descmap +
1411                                                      priv->txdescmem));
1412                 priv->rxdescmem = resource_size(dma_res)/2;
1413                 priv->rxdescmem_busaddr = dma_res->start;
1414                 priv->rxdescmem_busaddr += priv->txdescmem;
1415
1416                 if (upper_32_bits(priv->rxdescmem_busaddr)) {
1417                         dev_dbg(priv->device,
1418                                 "SGDMA bus addresses greater than 32-bits\n");
1419                         ret = -EINVAL;
1420                         goto err_free_netdev;
1421                 }
1422                 if (upper_32_bits(priv->txdescmem_busaddr)) {
1423                         dev_dbg(priv->device,
1424                                 "SGDMA bus addresses greater than 32-bits\n");
1425                         ret = -EINVAL;
1426                         goto err_free_netdev;
1427                 }
1428         } else if (priv->dmaops &&
1429                    priv->dmaops->altera_dtype == ALTERA_DTYPE_MSGDMA) {
1430                 ret = request_and_map(pdev, "rx_resp", &dma_res,
1431                                       &priv->rx_dma_resp);
1432                 if (ret)
1433                         goto err_free_netdev;
1434
1435                 ret = request_and_map(pdev, "tx_desc", &dma_res,
1436                                       &priv->tx_dma_desc);
1437                 if (ret)
1438                         goto err_free_netdev;
1439
1440                 priv->txdescmem = resource_size(dma_res);
1441                 priv->txdescmem_busaddr = dma_res->start;
1442
1443                 ret = request_and_map(pdev, "rx_desc", &dma_res,
1444                                       &priv->rx_dma_desc);
1445                 if (ret)
1446                         goto err_free_netdev;
1447
1448                 priv->rxdescmem = resource_size(dma_res);
1449                 priv->rxdescmem_busaddr = dma_res->start;
1450
1451         } else {
1452                 ret = -ENODEV;
1453                 goto err_free_netdev;
1454         }
1455
1456         if (!dma_set_mask(priv->device, DMA_BIT_MASK(priv->dmaops->dmamask))) {
1457                 dma_set_coherent_mask(priv->device,
1458                                       DMA_BIT_MASK(priv->dmaops->dmamask));
1459         } else if (!dma_set_mask(priv->device, DMA_BIT_MASK(32))) {
1460                 dma_set_coherent_mask(priv->device, DMA_BIT_MASK(32));
1461         } else {
1462                 ret = -EIO;
1463                 goto err_free_netdev;
1464         }
1465
1466         /* MAC address space */
1467         ret = request_and_map(pdev, "control_port", &control_port,
1468                               (void __iomem **)&priv->mac_dev);
1469         if (ret)
1470                 goto err_free_netdev;
1471
1472         /* xSGDMA Rx Dispatcher address space */
1473         ret = request_and_map(pdev, "rx_csr", &dma_res,
1474                               &priv->rx_dma_csr);
1475         if (ret)
1476                 goto err_free_netdev;
1477
1478
1479         /* xSGDMA Tx Dispatcher address space */
1480         ret = request_and_map(pdev, "tx_csr", &dma_res,
1481                               &priv->tx_dma_csr);
1482         if (ret)
1483                 goto err_free_netdev;
1484
1485
1486         /* Rx IRQ */
1487         priv->rx_irq = platform_get_irq_byname(pdev, "rx_irq");
1488         if (priv->rx_irq == -ENXIO) {
1489                 dev_err(&pdev->dev, "cannot obtain Rx IRQ\n");
1490                 ret = -ENXIO;
1491                 goto err_free_netdev;
1492         }
1493
1494         /* Tx IRQ */
1495         priv->tx_irq = platform_get_irq_byname(pdev, "tx_irq");
1496         if (priv->tx_irq == -ENXIO) {
1497                 dev_err(&pdev->dev, "cannot obtain Tx IRQ\n");
1498                 ret = -ENXIO;
1499                 goto err_free_netdev;
1500         }
1501
1502         /* get FIFO depths from device tree */
1503         if (of_property_read_u32(pdev->dev.of_node, "rx-fifo-depth",
1504                                  &priv->rx_fifo_depth)) {
1505                 dev_err(&pdev->dev, "cannot obtain rx-fifo-depth\n");
1506                 ret = -ENXIO;
1507                 goto err_free_netdev;
1508         }
1509
1510         if (of_property_read_u32(pdev->dev.of_node, "tx-fifo-depth",
1511                                  &priv->tx_fifo_depth)) {
1512                 dev_err(&pdev->dev, "cannot obtain tx-fifo-depth\n");
1513                 ret = -ENXIO;
1514                 goto err_free_netdev;
1515         }
1516
1517         /* get hash filter settings for this instance */
1518         priv->hash_filter =
1519                 of_property_read_bool(pdev->dev.of_node,
1520                                       "altr,has-hash-multicast-filter");
1521
1522         /* Set hash filter to not set for now until the
1523          * multicast filter receive issue is debugged
1524          */
1525         priv->hash_filter = 0;
1526
1527         /* get supplemental address settings for this instance */
1528         priv->added_unicast =
1529                 of_property_read_bool(pdev->dev.of_node,
1530                                       "altr,has-supplementary-unicast");
1531
1532         priv->dev->min_mtu = ETH_ZLEN + ETH_FCS_LEN;
1533         /* Max MTU is 1500, ETH_DATA_LEN */
1534         priv->dev->max_mtu = ETH_DATA_LEN;
1535
1536         /* Get the max mtu from the device tree. Note that the
1537          * "max-frame-size" parameter is actually max mtu. Definition
1538          * in the ePAPR v1.1 spec and usage differ, so go with usage.
1539          */
1540         of_property_read_u32(pdev->dev.of_node, "max-frame-size",
1541                              &priv->dev->max_mtu);
1542
1543         /* The DMA buffer size already accounts for an alignment bias
1544          * to avoid unaligned access exceptions for the NIOS processor,
1545          */
1546         priv->rx_dma_buf_sz = ALTERA_RXDMABUFFER_SIZE;
1547
1548         /* get default MAC address from device tree */
1549         macaddr = of_get_mac_address(pdev->dev.of_node);
1550         if (macaddr)
1551                 ether_addr_copy(ndev->dev_addr, macaddr);
1552         else
1553                 eth_hw_addr_random(ndev);
1554
1555         /* get phy addr and create mdio */
1556         ret = altera_tse_phy_get_addr_mdio_create(ndev);
1557
1558         if (ret)
1559                 goto err_free_netdev;
1560
1561         /* initialize netdev */
1562         ndev->mem_start = control_port->start;
1563         ndev->mem_end = control_port->end;
1564         ndev->netdev_ops = &altera_tse_netdev_ops;
1565         altera_tse_set_ethtool_ops(ndev);
1566
1567         altera_tse_netdev_ops.ndo_set_rx_mode = tse_set_rx_mode;
1568
1569         if (priv->hash_filter)
1570                 altera_tse_netdev_ops.ndo_set_rx_mode =
1571                         tse_set_rx_mode_hashfilter;
1572
1573         /* Scatter/gather IO is not supported,
1574          * so it is turned off
1575          */
1576         ndev->hw_features &= ~NETIF_F_SG;
1577         ndev->features |= ndev->hw_features | NETIF_F_HIGHDMA;
1578
1579         /* VLAN offloading of tagging, stripping and filtering is not
1580          * supported by hardware, but driver will accommodate the
1581          * extra 4-byte VLAN tag for processing by upper layers
1582          */
1583         ndev->features |= NETIF_F_HW_VLAN_CTAG_RX;
1584
1585         /* setup NAPI interface */
1586         netif_napi_add(ndev, &priv->napi, tse_poll, NAPI_POLL_WEIGHT);
1587
1588         spin_lock_init(&priv->mac_cfg_lock);
1589         spin_lock_init(&priv->tx_lock);
1590         spin_lock_init(&priv->rxdma_irq_lock);
1591
1592         netif_carrier_off(ndev);
1593         ret = register_netdev(ndev);
1594         if (ret) {
1595                 dev_err(&pdev->dev, "failed to register TSE net device\n");
1596                 goto err_register_netdev;
1597         }
1598
1599         platform_set_drvdata(pdev, ndev);
1600
1601         priv->revision = ioread32(&priv->mac_dev->megacore_revision);
1602
1603         if (netif_msg_probe(priv))
1604                 dev_info(&pdev->dev, "Altera TSE MAC version %d.%d at 0x%08lx irq %d/%d\n",
1605                          (priv->revision >> 8) & 0xff,
1606                          priv->revision & 0xff,
1607                          (unsigned long) control_port->start, priv->rx_irq,
1608                          priv->tx_irq);
1609
1610         ret = init_phy(ndev);
1611         if (ret != 0) {
1612                 netdev_err(ndev, "Cannot attach to PHY (error: %d)\n", ret);
1613                 goto err_init_phy;
1614         }
1615         return 0;
1616
1617 err_init_phy:
1618         unregister_netdev(ndev);
1619 err_register_netdev:
1620         netif_napi_del(&priv->napi);
1621         altera_tse_mdio_destroy(ndev);
1622 err_free_netdev:
1623         free_netdev(ndev);
1624         return ret;
1625 }
1626
1627 /* Remove Altera TSE MAC device
1628  */
1629 static int altera_tse_remove(struct platform_device *pdev)
1630 {
1631         struct net_device *ndev = platform_get_drvdata(pdev);
1632         struct altera_tse_private *priv = netdev_priv(ndev);
1633
1634         if (ndev->phydev) {
1635                 phy_disconnect(ndev->phydev);
1636
1637                 if (of_phy_is_fixed_link(priv->device->of_node))
1638                         of_phy_deregister_fixed_link(priv->device->of_node);
1639         }
1640
1641         platform_set_drvdata(pdev, NULL);
1642         altera_tse_mdio_destroy(ndev);
1643         unregister_netdev(ndev);
1644         free_netdev(ndev);
1645
1646         return 0;
1647 }
1648
1649 static const struct altera_dmaops altera_dtype_sgdma = {
1650         .altera_dtype = ALTERA_DTYPE_SGDMA,
1651         .dmamask = 32,
1652         .reset_dma = sgdma_reset,
1653         .enable_txirq = sgdma_enable_txirq,
1654         .enable_rxirq = sgdma_enable_rxirq,
1655         .disable_txirq = sgdma_disable_txirq,
1656         .disable_rxirq = sgdma_disable_rxirq,
1657         .clear_txirq = sgdma_clear_txirq,
1658         .clear_rxirq = sgdma_clear_rxirq,
1659         .tx_buffer = sgdma_tx_buffer,
1660         .tx_completions = sgdma_tx_completions,
1661         .add_rx_desc = sgdma_add_rx_desc,
1662         .get_rx_status = sgdma_rx_status,
1663         .init_dma = sgdma_initialize,
1664         .uninit_dma = sgdma_uninitialize,
1665         .start_rxdma = sgdma_start_rxdma,
1666 };
1667
1668 static const struct altera_dmaops altera_dtype_msgdma = {
1669         .altera_dtype = ALTERA_DTYPE_MSGDMA,
1670         .dmamask = 64,
1671         .reset_dma = msgdma_reset,
1672         .enable_txirq = msgdma_enable_txirq,
1673         .enable_rxirq = msgdma_enable_rxirq,
1674         .disable_txirq = msgdma_disable_txirq,
1675         .disable_rxirq = msgdma_disable_rxirq,
1676         .clear_txirq = msgdma_clear_txirq,
1677         .clear_rxirq = msgdma_clear_rxirq,
1678         .tx_buffer = msgdma_tx_buffer,
1679         .tx_completions = msgdma_tx_completions,
1680         .add_rx_desc = msgdma_add_rx_desc,
1681         .get_rx_status = msgdma_rx_status,
1682         .init_dma = msgdma_initialize,
1683         .uninit_dma = msgdma_uninitialize,
1684         .start_rxdma = msgdma_start_rxdma,
1685 };
1686
1687 static const struct of_device_id altera_tse_ids[] = {
1688         { .compatible = "altr,tse-msgdma-1.0", .data = &altera_dtype_msgdma, },
1689         { .compatible = "altr,tse-1.0", .data = &altera_dtype_sgdma, },
1690         { .compatible = "ALTR,tse-1.0", .data = &altera_dtype_sgdma, },
1691         {},
1692 };
1693 MODULE_DEVICE_TABLE(of, altera_tse_ids);
1694
1695 static struct platform_driver altera_tse_driver = {
1696         .probe          = altera_tse_probe,
1697         .remove         = altera_tse_remove,
1698         .suspend        = NULL,
1699         .resume         = NULL,
1700         .driver         = {
1701                 .name   = ALTERA_TSE_RESOURCE_NAME,
1702                 .of_match_table = altera_tse_ids,
1703         },
1704 };
1705
1706 module_platform_driver(altera_tse_driver);
1707
1708 MODULE_AUTHOR("Altera Corporation");
1709 MODULE_DESCRIPTION("Altera Triple Speed Ethernet MAC driver");
1710 MODULE_LICENSE("GPL v2");