xref: /openbmc/linux/drivers/net/ethernet/chelsio/cxgb/sge.c (revision 0760aad038b5a032c31ea124feed63d88627d2f1)
1 /*****************************************************************************
2  *                                                                           *
3  * File: sge.c                                                               *
4  * $Revision: 1.26 $                                                         *
5  * $Date: 2005/06/21 18:29:48 $                                              *
6  * Description:                                                              *
7  *  DMA engine.                                                              *
8  *  part of the Chelsio 10Gb Ethernet Driver.                                *
9  *                                                                           *
10  * This program is free software; you can redistribute it and/or modify      *
11  * it under the terms of the GNU General Public License, version 2, as       *
12  * published by the Free Software Foundation.                                *
13  *                                                                           *
14  * You should have received a copy of the GNU General Public License along   *
15  * with this program; if not, see <http://www.gnu.org/licenses/>.            *
16  *                                                                           *
17  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED    *
18  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF      *
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.                     *
20  *                                                                           *
21  * http://www.chelsio.com                                                    *
22  *                                                                           *
23  * Copyright (c) 2003 - 2005 Chelsio Communications, Inc.                    *
24  * All rights reserved.                                                      *
25  *                                                                           *
26  * Maintainers: maintainers@chelsio.com                                      *
27  *                                                                           *
28  * Authors: Dimitrios Michailidis   <dm@chelsio.com>                         *
29  *          Tina Yang               <tainay@chelsio.com>                     *
30  *          Felix Marti             <felix@chelsio.com>                      *
31  *          Scott Bardone           <sbardone@chelsio.com>                   *
32  *          Kurt Ottaway            <kottaway@chelsio.com>                   *
33  *          Frank DiMambro          <frank@chelsio.com>                      *
34  *                                                                           *
35  * History:                                                                  *
36  *                                                                           *
37  ****************************************************************************/
38 
39 #include "common.h"
40 
41 #include <linux/types.h>
42 #include <linux/errno.h>
43 #include <linux/pci.h>
44 #include <linux/ktime.h>
45 #include <linux/netdevice.h>
46 #include <linux/etherdevice.h>
47 #include <linux/if_vlan.h>
48 #include <linux/skbuff.h>
49 #include <linux/mm.h>
50 #include <linux/tcp.h>
51 #include <linux/ip.h>
52 #include <linux/in.h>
53 #include <linux/if_arp.h>
54 #include <linux/slab.h>
55 #include <linux/prefetch.h>
56 
57 #include "cpl5_cmd.h"
58 #include "sge.h"
59 #include "regs.h"
60 #include "espi.h"
61 
62 /* This belongs in if_ether.h */
63 #define ETH_P_CPL5 0xf
64 
65 #define SGE_CMDQ_N		2
66 #define SGE_FREELQ_N		2
67 #define SGE_CMDQ0_E_N		1024
68 #define SGE_CMDQ1_E_N		128
69 #define SGE_FREEL_SIZE		4096
70 #define SGE_JUMBO_FREEL_SIZE	512
71 #define SGE_FREEL_REFILL_THRESH	16
72 #define SGE_RESPQ_E_N		1024
73 #define SGE_INTRTIMER_NRES	1000
74 #define SGE_RX_SM_BUF_SIZE	1536
75 #define SGE_TX_DESC_MAX_PLEN	16384
76 
77 #define SGE_RESPQ_REPLENISH_THRES (SGE_RESPQ_E_N / 4)
78 
79 /*
80  * Period of the TX buffer reclaim timer.  This timer does not need to run
81  * frequently as TX buffers are usually reclaimed by new TX packets.
82  */
83 #define TX_RECLAIM_PERIOD (HZ / 4)
84 
85 #define M_CMD_LEN       0x7fffffff
86 #define V_CMD_LEN(v)    (v)
87 #define G_CMD_LEN(v)    ((v) & M_CMD_LEN)
88 #define V_CMD_GEN1(v)   ((v) << 31)
89 #define V_CMD_GEN2(v)   (v)
90 #define F_CMD_DATAVALID (1 << 1)
91 #define F_CMD_SOP       (1 << 2)
92 #define V_CMD_EOP(v)    ((v) << 3)
93 
94 /*
95  * Command queue, receive buffer list, and response queue descriptors.
96  */
97 #if defined(__BIG_ENDIAN_BITFIELD)
98 struct cmdQ_e {
99 	u32 addr_lo;
100 	u32 len_gen;
101 	u32 flags;
102 	u32 addr_hi;
103 };
104 
105 struct freelQ_e {
106 	u32 addr_lo;
107 	u32 len_gen;
108 	u32 gen2;
109 	u32 addr_hi;
110 };
111 
112 struct respQ_e {
113 	u32 Qsleeping		: 4;
114 	u32 Cmdq1CreditReturn	: 5;
115 	u32 Cmdq1DmaComplete	: 5;
116 	u32 Cmdq0CreditReturn	: 5;
117 	u32 Cmdq0DmaComplete	: 5;
118 	u32 FreelistQid		: 2;
119 	u32 CreditValid		: 1;
120 	u32 DataValid		: 1;
121 	u32 Offload		: 1;
122 	u32 Eop			: 1;
123 	u32 Sop			: 1;
124 	u32 GenerationBit	: 1;
125 	u32 BufferLength;
126 };
127 #elif defined(__LITTLE_ENDIAN_BITFIELD)
128 struct cmdQ_e {
129 	u32 len_gen;
130 	u32 addr_lo;
131 	u32 addr_hi;
132 	u32 flags;
133 };
134 
135 struct freelQ_e {
136 	u32 len_gen;
137 	u32 addr_lo;
138 	u32 addr_hi;
139 	u32 gen2;
140 };
141 
142 struct respQ_e {
143 	u32 BufferLength;
144 	u32 GenerationBit	: 1;
145 	u32 Sop			: 1;
146 	u32 Eop			: 1;
147 	u32 Offload		: 1;
148 	u32 DataValid		: 1;
149 	u32 CreditValid		: 1;
150 	u32 FreelistQid		: 2;
151 	u32 Cmdq0DmaComplete	: 5;
152 	u32 Cmdq0CreditReturn	: 5;
153 	u32 Cmdq1DmaComplete	: 5;
154 	u32 Cmdq1CreditReturn	: 5;
155 	u32 Qsleeping		: 4;
156 } ;
157 #endif
158 
159 /*
160  * SW Context Command and Freelist Queue Descriptors
161  */
162 struct cmdQ_ce {
163 	struct sk_buff *skb;
164 	DEFINE_DMA_UNMAP_ADDR(dma_addr);
165 	DEFINE_DMA_UNMAP_LEN(dma_len);
166 };
167 
168 struct freelQ_ce {
169 	struct sk_buff *skb;
170 	DEFINE_DMA_UNMAP_ADDR(dma_addr);
171 	DEFINE_DMA_UNMAP_LEN(dma_len);
172 };
173 
174 /*
175  * SW command, freelist and response rings
176  */
177 struct cmdQ {
178 	unsigned long   status;         /* HW DMA fetch status */
179 	unsigned int    in_use;         /* # of in-use command descriptors */
180 	unsigned int	size;	        /* # of descriptors */
181 	unsigned int    processed;      /* total # of descs HW has processed */
182 	unsigned int    cleaned;        /* total # of descs SW has reclaimed */
183 	unsigned int    stop_thres;     /* SW TX queue suspend threshold */
184 	u16		pidx;           /* producer index (SW) */
185 	u16		cidx;           /* consumer index (HW) */
186 	u8		genbit;         /* current generation (=valid) bit */
187 	u8              sop;            /* is next entry start of packet? */
188 	struct cmdQ_e  *entries;        /* HW command descriptor Q */
189 	struct cmdQ_ce *centries;       /* SW command context descriptor Q */
190 	dma_addr_t	dma_addr;       /* DMA addr HW command descriptor Q */
191 	spinlock_t	lock;           /* Lock to protect cmdQ enqueuing */
192 };
193 
194 struct freelQ {
195 	unsigned int	credits;        /* # of available RX buffers */
196 	unsigned int	size;	        /* free list capacity */
197 	u16		pidx;           /* producer index (SW) */
198 	u16		cidx;           /* consumer index (HW) */
199 	u16		rx_buffer_size; /* Buffer size on this free list */
200 	u16             dma_offset;     /* DMA offset to align IP headers */
201 	u16             recycleq_idx;   /* skb recycle q to use */
202 	u8		genbit;	        /* current generation (=valid) bit */
203 	struct freelQ_e	*entries;       /* HW freelist descriptor Q */
204 	struct freelQ_ce *centries;     /* SW freelist context descriptor Q */
205 	dma_addr_t	dma_addr;       /* DMA addr HW freelist descriptor Q */
206 };
207 
208 struct respQ {
209 	unsigned int	credits;        /* credits to be returned to SGE */
210 	unsigned int	size;	        /* # of response Q descriptors */
211 	u16		cidx;	        /* consumer index (SW) */
212 	u8		genbit;	        /* current generation(=valid) bit */
213 	struct respQ_e *entries;        /* HW response descriptor Q */
214 	dma_addr_t	dma_addr;       /* DMA addr HW response descriptor Q */
215 };
216 
217 /* Bit flags for cmdQ.status */
218 enum {
219 	CMDQ_STAT_RUNNING = 1,          /* fetch engine is running */
220 	CMDQ_STAT_LAST_PKT_DB = 2       /* last packet rung the doorbell */
221 };
222 
223 /* T204 TX SW scheduler */
224 
225 /* Per T204 TX port */
226 struct sched_port {
227 	unsigned int	avail;		/* available bits - quota */
228 	unsigned int	drain_bits_per_1024ns; /* drain rate */
229 	unsigned int	speed;		/* drain rate, mbps */
230 	unsigned int	mtu;		/* mtu size */
231 	struct sk_buff_head skbq;	/* pending skbs */
232 };
233 
234 /* Per T204 device */
235 struct sched {
236 	ktime_t         last_updated;   /* last time quotas were computed */
237 	unsigned int	max_avail;	/* max bits to be sent to any port */
238 	unsigned int	port;		/* port index (round robin ports) */
239 	unsigned int	num;		/* num skbs in per port queues */
240 	struct sched_port p[MAX_NPORTS];
241 	struct tasklet_struct sched_tsk;/* tasklet used to run scheduler */
242 };
243 static void restart_sched(unsigned long);
244 
245 
246 /*
247  * Main SGE data structure
248  *
249  * Interrupts are handled by a single CPU and it is likely that on a MP system
250  * the application is migrated to another CPU. In that scenario, we try to
251  * separate the RX(in irq context) and TX state in order to decrease memory
252  * contention.
253  */
254 struct sge {
255 	struct adapter *adapter;	/* adapter backpointer */
256 	struct net_device *netdev;      /* netdevice backpointer */
257 	struct freelQ	freelQ[SGE_FREELQ_N]; /* buffer free lists */
258 	struct respQ	respQ;		/* response Q */
259 	unsigned long   stopped_tx_queues; /* bitmap of suspended Tx queues */
260 	unsigned int	rx_pkt_pad;     /* RX padding for L2 packets */
261 	unsigned int	jumbo_fl;       /* jumbo freelist Q index */
262 	unsigned int	intrtimer_nres;	/* no-resource interrupt timer */
263 	unsigned int    fixed_intrtimer;/* non-adaptive interrupt timer */
264 	struct timer_list tx_reclaim_timer; /* reclaims TX buffers */
265 	struct timer_list espibug_timer;
266 	unsigned long	espibug_timeout;
267 	struct sk_buff	*espibug_skb[MAX_NPORTS];
268 	u32		sge_control;	/* shadow value of sge control reg */
269 	struct sge_intr_counts stats;
270 	struct sge_port_stats __percpu *port_stats[MAX_NPORTS];
271 	struct sched	*tx_sched;
272 	struct cmdQ cmdQ[SGE_CMDQ_N] ____cacheline_aligned_in_smp;
273 };
274 
275 static const u8 ch_mac_addr[ETH_ALEN] = {
276 	0x0, 0x7, 0x43, 0x0, 0x0, 0x0
277 };
278 
279 /*
280  * stop tasklet and free all pending skb's
281  */
282 static void tx_sched_stop(struct sge *sge)
283 {
284 	struct sched *s = sge->tx_sched;
285 	int i;
286 
287 	tasklet_kill(&s->sched_tsk);
288 
289 	for (i = 0; i < MAX_NPORTS; i++)
290 		__skb_queue_purge(&s->p[s->port].skbq);
291 }
292 
293 /*
294  * t1_sched_update_parms() is called when the MTU or link speed changes. It
295  * re-computes scheduler parameters to scope with the change.
296  */
297 unsigned int t1_sched_update_parms(struct sge *sge, unsigned int port,
298 				   unsigned int mtu, unsigned int speed)
299 {
300 	struct sched *s = sge->tx_sched;
301 	struct sched_port *p = &s->p[port];
302 	unsigned int max_avail_segs;
303 
304 	pr_debug("%s mtu=%d speed=%d\n", __func__, mtu, speed);
305 	if (speed)
306 		p->speed = speed;
307 	if (mtu)
308 		p->mtu = mtu;
309 
310 	if (speed || mtu) {
311 		unsigned long long drain = 1024ULL * p->speed * (p->mtu - 40);
312 		do_div(drain, (p->mtu + 50) * 1000);
313 		p->drain_bits_per_1024ns = (unsigned int) drain;
314 
315 		if (p->speed < 1000)
316 			p->drain_bits_per_1024ns =
317 				90 * p->drain_bits_per_1024ns / 100;
318 	}
319 
320 	if (board_info(sge->adapter)->board == CHBT_BOARD_CHT204) {
321 		p->drain_bits_per_1024ns -= 16;
322 		s->max_avail = max(4096U, p->mtu + 16 + 14 + 4);
323 		max_avail_segs = max(1U, 4096 / (p->mtu - 40));
324 	} else {
325 		s->max_avail = 16384;
326 		max_avail_segs = max(1U, 9000 / (p->mtu - 40));
327 	}
328 
329 	pr_debug("t1_sched_update_parms: mtu %u speed %u max_avail %u "
330 		 "max_avail_segs %u drain_bits_per_1024ns %u\n", p->mtu,
331 		 p->speed, s->max_avail, max_avail_segs,
332 		 p->drain_bits_per_1024ns);
333 
334 	return max_avail_segs * (p->mtu - 40);
335 }
336 
337 #if 0
338 
339 /*
340  * t1_sched_max_avail_bytes() tells the scheduler the maximum amount of
341  * data that can be pushed per port.
342  */
343 void t1_sched_set_max_avail_bytes(struct sge *sge, unsigned int val)
344 {
345 	struct sched *s = sge->tx_sched;
346 	unsigned int i;
347 
348 	s->max_avail = val;
349 	for (i = 0; i < MAX_NPORTS; i++)
350 		t1_sched_update_parms(sge, i, 0, 0);
351 }
352 
353 /*
354  * t1_sched_set_drain_bits_per_us() tells the scheduler at which rate a port
355  * is draining.
356  */
357 void t1_sched_set_drain_bits_per_us(struct sge *sge, unsigned int port,
358 					 unsigned int val)
359 {
360 	struct sched *s = sge->tx_sched;
361 	struct sched_port *p = &s->p[port];
362 	p->drain_bits_per_1024ns = val * 1024 / 1000;
363 	t1_sched_update_parms(sge, port, 0, 0);
364 }
365 
366 #endif  /*  0  */
367 
368 /*
369  * tx_sched_init() allocates resources and does basic initialization.
370  */
371 static int tx_sched_init(struct sge *sge)
372 {
373 	struct sched *s;
374 	int i;
375 
376 	s = kzalloc(sizeof (struct sched), GFP_KERNEL);
377 	if (!s)
378 		return -ENOMEM;
379 
380 	pr_debug("tx_sched_init\n");
381 	tasklet_init(&s->sched_tsk, restart_sched, (unsigned long) sge);
382 	sge->tx_sched = s;
383 
384 	for (i = 0; i < MAX_NPORTS; i++) {
385 		skb_queue_head_init(&s->p[i].skbq);
386 		t1_sched_update_parms(sge, i, 1500, 1000);
387 	}
388 
389 	return 0;
390 }
391 
392 /*
393  * sched_update_avail() computes the delta since the last time it was called
394  * and updates the per port quota (number of bits that can be sent to the any
395  * port).
396  */
397 static inline int sched_update_avail(struct sge *sge)
398 {
399 	struct sched *s = sge->tx_sched;
400 	ktime_t now = ktime_get();
401 	unsigned int i;
402 	long long delta_time_ns;
403 
404 	delta_time_ns = ktime_to_ns(ktime_sub(now, s->last_updated));
405 
406 	pr_debug("sched_update_avail delta=%lld\n", delta_time_ns);
407 	if (delta_time_ns < 15000)
408 		return 0;
409 
410 	for (i = 0; i < MAX_NPORTS; i++) {
411 		struct sched_port *p = &s->p[i];
412 		unsigned int delta_avail;
413 
414 		delta_avail = (p->drain_bits_per_1024ns * delta_time_ns) >> 13;
415 		p->avail = min(p->avail + delta_avail, s->max_avail);
416 	}
417 
418 	s->last_updated = now;
419 
420 	return 1;
421 }
422 
423 /*
424  * sched_skb() is called from two different places. In the tx path, any
425  * packet generating load on an output port will call sched_skb()
426  * (skb != NULL). In addition, sched_skb() is called from the irq/soft irq
427  * context (skb == NULL).
428  * The scheduler only returns a skb (which will then be sent) if the
429  * length of the skb is <= the current quota of the output port.
430  */
431 static struct sk_buff *sched_skb(struct sge *sge, struct sk_buff *skb,
432 				unsigned int credits)
433 {
434 	struct sched *s = sge->tx_sched;
435 	struct sk_buff_head *skbq;
436 	unsigned int i, len, update = 1;
437 
438 	pr_debug("sched_skb %p\n", skb);
439 	if (!skb) {
440 		if (!s->num)
441 			return NULL;
442 	} else {
443 		skbq = &s->p[skb->dev->if_port].skbq;
444 		__skb_queue_tail(skbq, skb);
445 		s->num++;
446 		skb = NULL;
447 	}
448 
449 	if (credits < MAX_SKB_FRAGS + 1)
450 		goto out;
451 
452 again:
453 	for (i = 0; i < MAX_NPORTS; i++) {
454 		s->port = (s->port + 1) & (MAX_NPORTS - 1);
455 		skbq = &s->p[s->port].skbq;
456 
457 		skb = skb_peek(skbq);
458 
459 		if (!skb)
460 			continue;
461 
462 		len = skb->len;
463 		if (len <= s->p[s->port].avail) {
464 			s->p[s->port].avail -= len;
465 			s->num--;
466 			__skb_unlink(skb, skbq);
467 			goto out;
468 		}
469 		skb = NULL;
470 	}
471 
472 	if (update-- && sched_update_avail(sge))
473 		goto again;
474 
475 out:
476 	/* If there are more pending skbs, we use the hardware to schedule us
477 	 * again.
478 	 */
479 	if (s->num && !skb) {
480 		struct cmdQ *q = &sge->cmdQ[0];
481 		clear_bit(CMDQ_STAT_LAST_PKT_DB, &q->status);
482 		if (test_and_set_bit(CMDQ_STAT_RUNNING, &q->status) == 0) {
483 			set_bit(CMDQ_STAT_LAST_PKT_DB, &q->status);
484 			writel(F_CMDQ0_ENABLE, sge->adapter->regs + A_SG_DOORBELL);
485 		}
486 	}
487 	pr_debug("sched_skb ret %p\n", skb);
488 
489 	return skb;
490 }
491 
492 /*
493  * PIO to indicate that memory mapped Q contains valid descriptor(s).
494  */
495 static inline void doorbell_pio(struct adapter *adapter, u32 val)
496 {
497 	wmb();
498 	writel(val, adapter->regs + A_SG_DOORBELL);
499 }
500 
501 /*
502  * Frees all RX buffers on the freelist Q. The caller must make sure that
503  * the SGE is turned off before calling this function.
504  */
505 static void free_freelQ_buffers(struct pci_dev *pdev, struct freelQ *q)
506 {
507 	unsigned int cidx = q->cidx;
508 
509 	while (q->credits--) {
510 		struct freelQ_ce *ce = &q->centries[cidx];
511 
512 		dma_unmap_single(&pdev->dev, dma_unmap_addr(ce, dma_addr),
513 				 dma_unmap_len(ce, dma_len), DMA_FROM_DEVICE);
514 		dev_kfree_skb(ce->skb);
515 		ce->skb = NULL;
516 		if (++cidx == q->size)
517 			cidx = 0;
518 	}
519 }
520 
521 /*
522  * Free RX free list and response queue resources.
523  */
524 static void free_rx_resources(struct sge *sge)
525 {
526 	struct pci_dev *pdev = sge->adapter->pdev;
527 	unsigned int size, i;
528 
529 	if (sge->respQ.entries) {
530 		size = sizeof(struct respQ_e) * sge->respQ.size;
531 		dma_free_coherent(&pdev->dev, size, sge->respQ.entries,
532 				  sge->respQ.dma_addr);
533 	}
534 
535 	for (i = 0; i < SGE_FREELQ_N; i++) {
536 		struct freelQ *q = &sge->freelQ[i];
537 
538 		if (q->centries) {
539 			free_freelQ_buffers(pdev, q);
540 			kfree(q->centries);
541 		}
542 		if (q->entries) {
543 			size = sizeof(struct freelQ_e) * q->size;
544 			dma_free_coherent(&pdev->dev, size, q->entries,
545 					  q->dma_addr);
546 		}
547 	}
548 }
549 
550 /*
551  * Allocates basic RX resources, consisting of memory mapped freelist Qs and a
552  * response queue.
553  */
554 static int alloc_rx_resources(struct sge *sge, struct sge_params *p)
555 {
556 	struct pci_dev *pdev = sge->adapter->pdev;
557 	unsigned int size, i;
558 
559 	for (i = 0; i < SGE_FREELQ_N; i++) {
560 		struct freelQ *q = &sge->freelQ[i];
561 
562 		q->genbit = 1;
563 		q->size = p->freelQ_size[i];
564 		q->dma_offset = sge->rx_pkt_pad ? 0 : NET_IP_ALIGN;
565 		size = sizeof(struct freelQ_e) * q->size;
566 		q->entries = dma_alloc_coherent(&pdev->dev, size,
567 						&q->dma_addr, GFP_KERNEL);
568 		if (!q->entries)
569 			goto err_no_mem;
570 
571 		size = sizeof(struct freelQ_ce) * q->size;
572 		q->centries = kzalloc(size, GFP_KERNEL);
573 		if (!q->centries)
574 			goto err_no_mem;
575 	}
576 
577 	/*
578 	 * Calculate the buffer sizes for the two free lists.  FL0 accommodates
579 	 * regular sized Ethernet frames, FL1 is sized not to exceed 16K,
580 	 * including all the sk_buff overhead.
581 	 *
582 	 * Note: For T2 FL0 and FL1 are reversed.
583 	 */
584 	sge->freelQ[!sge->jumbo_fl].rx_buffer_size = SGE_RX_SM_BUF_SIZE +
585 		sizeof(struct cpl_rx_data) +
586 		sge->freelQ[!sge->jumbo_fl].dma_offset;
587 
588 	size = (16 * 1024) - SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
589 
590 	sge->freelQ[sge->jumbo_fl].rx_buffer_size = size;
591 
592 	/*
593 	 * Setup which skb recycle Q should be used when recycling buffers from
594 	 * each free list.
595 	 */
596 	sge->freelQ[!sge->jumbo_fl].recycleq_idx = 0;
597 	sge->freelQ[sge->jumbo_fl].recycleq_idx = 1;
598 
599 	sge->respQ.genbit = 1;
600 	sge->respQ.size = SGE_RESPQ_E_N;
601 	sge->respQ.credits = 0;
602 	size = sizeof(struct respQ_e) * sge->respQ.size;
603 	sge->respQ.entries =
604 		dma_alloc_coherent(&pdev->dev, size, &sge->respQ.dma_addr,
605 				   GFP_KERNEL);
606 	if (!sge->respQ.entries)
607 		goto err_no_mem;
608 	return 0;
609 
610 err_no_mem:
611 	free_rx_resources(sge);
612 	return -ENOMEM;
613 }
614 
615 /*
616  * Reclaims n TX descriptors and frees the buffers associated with them.
617  */
618 static void free_cmdQ_buffers(struct sge *sge, struct cmdQ *q, unsigned int n)
619 {
620 	struct cmdQ_ce *ce;
621 	struct pci_dev *pdev = sge->adapter->pdev;
622 	unsigned int cidx = q->cidx;
623 
624 	q->in_use -= n;
625 	ce = &q->centries[cidx];
626 	while (n--) {
627 		if (likely(dma_unmap_len(ce, dma_len))) {
628 			dma_unmap_single(&pdev->dev,
629 					 dma_unmap_addr(ce, dma_addr),
630 					 dma_unmap_len(ce, dma_len),
631 					 DMA_TO_DEVICE);
632 			if (q->sop)
633 				q->sop = 0;
634 		}
635 		if (ce->skb) {
636 			dev_kfree_skb_any(ce->skb);
637 			q->sop = 1;
638 		}
639 		ce++;
640 		if (++cidx == q->size) {
641 			cidx = 0;
642 			ce = q->centries;
643 		}
644 	}
645 	q->cidx = cidx;
646 }
647 
648 /*
649  * Free TX resources.
650  *
651  * Assumes that SGE is stopped and all interrupts are disabled.
652  */
653 static void free_tx_resources(struct sge *sge)
654 {
655 	struct pci_dev *pdev = sge->adapter->pdev;
656 	unsigned int size, i;
657 
658 	for (i = 0; i < SGE_CMDQ_N; i++) {
659 		struct cmdQ *q = &sge->cmdQ[i];
660 
661 		if (q->centries) {
662 			if (q->in_use)
663 				free_cmdQ_buffers(sge, q, q->in_use);
664 			kfree(q->centries);
665 		}
666 		if (q->entries) {
667 			size = sizeof(struct cmdQ_e) * q->size;
668 			dma_free_coherent(&pdev->dev, size, q->entries,
669 					  q->dma_addr);
670 		}
671 	}
672 }
673 
674 /*
675  * Allocates basic TX resources, consisting of memory mapped command Qs.
676  */
677 static int alloc_tx_resources(struct sge *sge, struct sge_params *p)
678 {
679 	struct pci_dev *pdev = sge->adapter->pdev;
680 	unsigned int size, i;
681 
682 	for (i = 0; i < SGE_CMDQ_N; i++) {
683 		struct cmdQ *q = &sge->cmdQ[i];
684 
685 		q->genbit = 1;
686 		q->sop = 1;
687 		q->size = p->cmdQ_size[i];
688 		q->in_use = 0;
689 		q->status = 0;
690 		q->processed = q->cleaned = 0;
691 		q->stop_thres = 0;
692 		spin_lock_init(&q->lock);
693 		size = sizeof(struct cmdQ_e) * q->size;
694 		q->entries = dma_alloc_coherent(&pdev->dev, size,
695 						&q->dma_addr, GFP_KERNEL);
696 		if (!q->entries)
697 			goto err_no_mem;
698 
699 		size = sizeof(struct cmdQ_ce) * q->size;
700 		q->centries = kzalloc(size, GFP_KERNEL);
701 		if (!q->centries)
702 			goto err_no_mem;
703 	}
704 
705 	/*
706 	 * CommandQ 0 handles Ethernet and TOE packets, while queue 1 is TOE
707 	 * only.  For queue 0 set the stop threshold so we can handle one more
708 	 * packet from each port, plus reserve an additional 24 entries for
709 	 * Ethernet packets only.  Queue 1 never suspends nor do we reserve
710 	 * space for Ethernet packets.
711 	 */
712 	sge->cmdQ[0].stop_thres = sge->adapter->params.nports *
713 		(MAX_SKB_FRAGS + 1);
714 	return 0;
715 
716 err_no_mem:
717 	free_tx_resources(sge);
718 	return -ENOMEM;
719 }
720 
721 static inline void setup_ring_params(struct adapter *adapter, u64 addr,
722 				     u32 size, int base_reg_lo,
723 				     int base_reg_hi, int size_reg)
724 {
725 	writel((u32)addr, adapter->regs + base_reg_lo);
726 	writel(addr >> 32, adapter->regs + base_reg_hi);
727 	writel(size, adapter->regs + size_reg);
728 }
729 
730 /*
731  * Enable/disable VLAN acceleration.
732  */
733 void t1_vlan_mode(struct adapter *adapter, netdev_features_t features)
734 {
735 	struct sge *sge = adapter->sge;
736 
737 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
738 		sge->sge_control |= F_VLAN_XTRACT;
739 	else
740 		sge->sge_control &= ~F_VLAN_XTRACT;
741 	if (adapter->open_device_map) {
742 		writel(sge->sge_control, adapter->regs + A_SG_CONTROL);
743 		readl(adapter->regs + A_SG_CONTROL);   /* flush */
744 	}
745 }
746 
747 /*
748  * Programs the various SGE registers. However, the engine is not yet enabled,
749  * but sge->sge_control is setup and ready to go.
750  */
751 static void configure_sge(struct sge *sge, struct sge_params *p)
752 {
753 	struct adapter *ap = sge->adapter;
754 
755 	writel(0, ap->regs + A_SG_CONTROL);
756 	setup_ring_params(ap, sge->cmdQ[0].dma_addr, sge->cmdQ[0].size,
757 			  A_SG_CMD0BASELWR, A_SG_CMD0BASEUPR, A_SG_CMD0SIZE);
758 	setup_ring_params(ap, sge->cmdQ[1].dma_addr, sge->cmdQ[1].size,
759 			  A_SG_CMD1BASELWR, A_SG_CMD1BASEUPR, A_SG_CMD1SIZE);
760 	setup_ring_params(ap, sge->freelQ[0].dma_addr,
761 			  sge->freelQ[0].size, A_SG_FL0BASELWR,
762 			  A_SG_FL0BASEUPR, A_SG_FL0SIZE);
763 	setup_ring_params(ap, sge->freelQ[1].dma_addr,
764 			  sge->freelQ[1].size, A_SG_FL1BASELWR,
765 			  A_SG_FL1BASEUPR, A_SG_FL1SIZE);
766 
767 	/* The threshold comparison uses <. */
768 	writel(SGE_RX_SM_BUF_SIZE + 1, ap->regs + A_SG_FLTHRESHOLD);
769 
770 	setup_ring_params(ap, sge->respQ.dma_addr, sge->respQ.size,
771 			  A_SG_RSPBASELWR, A_SG_RSPBASEUPR, A_SG_RSPSIZE);
772 	writel((u32)sge->respQ.size - 1, ap->regs + A_SG_RSPQUEUECREDIT);
773 
774 	sge->sge_control = F_CMDQ0_ENABLE | F_CMDQ1_ENABLE | F_FL0_ENABLE |
775 		F_FL1_ENABLE | F_CPL_ENABLE | F_RESPONSE_QUEUE_ENABLE |
776 		V_CMDQ_PRIORITY(2) | F_DISABLE_CMDQ1_GTS | F_ISCSI_COALESCE |
777 		V_RX_PKT_OFFSET(sge->rx_pkt_pad);
778 
779 #if defined(__BIG_ENDIAN_BITFIELD)
780 	sge->sge_control |= F_ENABLE_BIG_ENDIAN;
781 #endif
782 
783 	/* Initialize no-resource timer */
784 	sge->intrtimer_nres = SGE_INTRTIMER_NRES * core_ticks_per_usec(ap);
785 
786 	t1_sge_set_coalesce_params(sge, p);
787 }
788 
789 /*
790  * Return the payload capacity of the jumbo free-list buffers.
791  */
792 static inline unsigned int jumbo_payload_capacity(const struct sge *sge)
793 {
794 	return sge->freelQ[sge->jumbo_fl].rx_buffer_size -
795 		sge->freelQ[sge->jumbo_fl].dma_offset -
796 		sizeof(struct cpl_rx_data);
797 }
798 
799 /*
800  * Frees all SGE related resources and the sge structure itself
801  */
802 void t1_sge_destroy(struct sge *sge)
803 {
804 	int i;
805 
806 	for_each_port(sge->adapter, i)
807 		free_percpu(sge->port_stats[i]);
808 
809 	kfree(sge->tx_sched);
810 	free_tx_resources(sge);
811 	free_rx_resources(sge);
812 	kfree(sge);
813 }
814 
815 /*
816  * Allocates new RX buffers on the freelist Q (and tracks them on the freelist
817  * context Q) until the Q is full or alloc_skb fails.
818  *
819  * It is possible that the generation bits already match, indicating that the
820  * buffer is already valid and nothing needs to be done. This happens when we
821  * copied a received buffer into a new sk_buff during the interrupt processing.
822  *
823  * If the SGE doesn't automatically align packets properly (!sge->rx_pkt_pad),
824  * we specify a RX_OFFSET in order to make sure that the IP header is 4B
825  * aligned.
826  */
827 static void refill_free_list(struct sge *sge, struct freelQ *q)
828 {
829 	struct pci_dev *pdev = sge->adapter->pdev;
830 	struct freelQ_ce *ce = &q->centries[q->pidx];
831 	struct freelQ_e *e = &q->entries[q->pidx];
832 	unsigned int dma_len = q->rx_buffer_size - q->dma_offset;
833 
834 	while (q->credits < q->size) {
835 		struct sk_buff *skb;
836 		dma_addr_t mapping;
837 
838 		skb = dev_alloc_skb(q->rx_buffer_size);
839 		if (!skb)
840 			break;
841 
842 		skb_reserve(skb, q->dma_offset);
843 		mapping = dma_map_single(&pdev->dev, skb->data, dma_len,
844 					 DMA_FROM_DEVICE);
845 		skb_reserve(skb, sge->rx_pkt_pad);
846 
847 		ce->skb = skb;
848 		dma_unmap_addr_set(ce, dma_addr, mapping);
849 		dma_unmap_len_set(ce, dma_len, dma_len);
850 		e->addr_lo = (u32)mapping;
851 		e->addr_hi = (u64)mapping >> 32;
852 		e->len_gen = V_CMD_LEN(dma_len) | V_CMD_GEN1(q->genbit);
853 		wmb();
854 		e->gen2 = V_CMD_GEN2(q->genbit);
855 
856 		e++;
857 		ce++;
858 		if (++q->pidx == q->size) {
859 			q->pidx = 0;
860 			q->genbit ^= 1;
861 			ce = q->centries;
862 			e = q->entries;
863 		}
864 		q->credits++;
865 	}
866 }
867 
868 /*
869  * Calls refill_free_list for both free lists. If we cannot fill at least 1/4
870  * of both rings, we go into 'few interrupt mode' in order to give the system
871  * time to free up resources.
872  */
873 static void freelQs_empty(struct sge *sge)
874 {
875 	struct adapter *adapter = sge->adapter;
876 	u32 irq_reg = readl(adapter->regs + A_SG_INT_ENABLE);
877 	u32 irqholdoff_reg;
878 
879 	refill_free_list(sge, &sge->freelQ[0]);
880 	refill_free_list(sge, &sge->freelQ[1]);
881 
882 	if (sge->freelQ[0].credits > (sge->freelQ[0].size >> 2) &&
883 	    sge->freelQ[1].credits > (sge->freelQ[1].size >> 2)) {
884 		irq_reg |= F_FL_EXHAUSTED;
885 		irqholdoff_reg = sge->fixed_intrtimer;
886 	} else {
887 		/* Clear the F_FL_EXHAUSTED interrupts for now */
888 		irq_reg &= ~F_FL_EXHAUSTED;
889 		irqholdoff_reg = sge->intrtimer_nres;
890 	}
891 	writel(irqholdoff_reg, adapter->regs + A_SG_INTRTIMER);
892 	writel(irq_reg, adapter->regs + A_SG_INT_ENABLE);
893 
894 	/* We reenable the Qs to force a freelist GTS interrupt later */
895 	doorbell_pio(adapter, F_FL0_ENABLE | F_FL1_ENABLE);
896 }
897 
898 #define SGE_PL_INTR_MASK (F_PL_INTR_SGE_ERR | F_PL_INTR_SGE_DATA)
899 #define SGE_INT_FATAL (F_RESPQ_OVERFLOW | F_PACKET_TOO_BIG | F_PACKET_MISMATCH)
900 #define SGE_INT_ENABLE (F_RESPQ_EXHAUSTED | F_RESPQ_OVERFLOW | \
901 			F_FL_EXHAUSTED | F_PACKET_TOO_BIG | F_PACKET_MISMATCH)
902 
903 /*
904  * Disable SGE Interrupts
905  */
906 void t1_sge_intr_disable(struct sge *sge)
907 {
908 	u32 val = readl(sge->adapter->regs + A_PL_ENABLE);
909 
910 	writel(val & ~SGE_PL_INTR_MASK, sge->adapter->regs + A_PL_ENABLE);
911 	writel(0, sge->adapter->regs + A_SG_INT_ENABLE);
912 }
913 
914 /*
915  * Enable SGE interrupts.
916  */
917 void t1_sge_intr_enable(struct sge *sge)
918 {
919 	u32 en = SGE_INT_ENABLE;
920 	u32 val = readl(sge->adapter->regs + A_PL_ENABLE);
921 
922 	if (sge->adapter->port[0].dev->hw_features & NETIF_F_TSO)
923 		en &= ~F_PACKET_TOO_BIG;
924 	writel(en, sge->adapter->regs + A_SG_INT_ENABLE);
925 	writel(val | SGE_PL_INTR_MASK, sge->adapter->regs + A_PL_ENABLE);
926 }
927 
928 /*
929  * Clear SGE interrupts.
930  */
931 void t1_sge_intr_clear(struct sge *sge)
932 {
933 	writel(SGE_PL_INTR_MASK, sge->adapter->regs + A_PL_CAUSE);
934 	writel(0xffffffff, sge->adapter->regs + A_SG_INT_CAUSE);
935 }
936 
937 /*
938  * SGE 'Error' interrupt handler
939  */
940 int t1_sge_intr_error_handler(struct sge *sge)
941 {
942 	struct adapter *adapter = sge->adapter;
943 	u32 cause = readl(adapter->regs + A_SG_INT_CAUSE);
944 
945 	if (adapter->port[0].dev->hw_features & NETIF_F_TSO)
946 		cause &= ~F_PACKET_TOO_BIG;
947 	if (cause & F_RESPQ_EXHAUSTED)
948 		sge->stats.respQ_empty++;
949 	if (cause & F_RESPQ_OVERFLOW) {
950 		sge->stats.respQ_overflow++;
951 		pr_alert("%s: SGE response queue overflow\n",
952 			 adapter->name);
953 	}
954 	if (cause & F_FL_EXHAUSTED) {
955 		sge->stats.freelistQ_empty++;
956 		freelQs_empty(sge);
957 	}
958 	if (cause & F_PACKET_TOO_BIG) {
959 		sge->stats.pkt_too_big++;
960 		pr_alert("%s: SGE max packet size exceeded\n",
961 			 adapter->name);
962 	}
963 	if (cause & F_PACKET_MISMATCH) {
964 		sge->stats.pkt_mismatch++;
965 		pr_alert("%s: SGE packet mismatch\n", adapter->name);
966 	}
967 	if (cause & SGE_INT_FATAL)
968 		t1_fatal_err(adapter);
969 
970 	writel(cause, adapter->regs + A_SG_INT_CAUSE);
971 	return 0;
972 }
973 
974 const struct sge_intr_counts *t1_sge_get_intr_counts(const struct sge *sge)
975 {
976 	return &sge->stats;
977 }
978 
979 void t1_sge_get_port_stats(const struct sge *sge, int port,
980 			   struct sge_port_stats *ss)
981 {
982 	int cpu;
983 
984 	memset(ss, 0, sizeof(*ss));
985 	for_each_possible_cpu(cpu) {
986 		struct sge_port_stats *st = per_cpu_ptr(sge->port_stats[port], cpu);
987 
988 		ss->rx_cso_good += st->rx_cso_good;
989 		ss->tx_cso += st->tx_cso;
990 		ss->tx_tso += st->tx_tso;
991 		ss->tx_need_hdrroom += st->tx_need_hdrroom;
992 		ss->vlan_xtract += st->vlan_xtract;
993 		ss->vlan_insert += st->vlan_insert;
994 	}
995 }
996 
997 /**
998  *	recycle_fl_buf - recycle a free list buffer
999  *	@fl: the free list
1000  *	@idx: index of buffer to recycle
1001  *
1002  *	Recycles the specified buffer on the given free list by adding it at
1003  *	the next available slot on the list.
1004  */
1005 static void recycle_fl_buf(struct freelQ *fl, int idx)
1006 {
1007 	struct freelQ_e *from = &fl->entries[idx];
1008 	struct freelQ_e *to = &fl->entries[fl->pidx];
1009 
1010 	fl->centries[fl->pidx] = fl->centries[idx];
1011 	to->addr_lo = from->addr_lo;
1012 	to->addr_hi = from->addr_hi;
1013 	to->len_gen = G_CMD_LEN(from->len_gen) | V_CMD_GEN1(fl->genbit);
1014 	wmb();
1015 	to->gen2 = V_CMD_GEN2(fl->genbit);
1016 	fl->credits++;
1017 
1018 	if (++fl->pidx == fl->size) {
1019 		fl->pidx = 0;
1020 		fl->genbit ^= 1;
1021 	}
1022 }
1023 
1024 static int copybreak __read_mostly = 256;
1025 module_param(copybreak, int, 0);
1026 MODULE_PARM_DESC(copybreak, "Receive copy threshold");
1027 
1028 /**
1029  *	get_packet - return the next ingress packet buffer
1030  *	@adapter: the adapter that received the packet
1031  *	@fl: the SGE free list holding the packet
1032  *	@len: the actual packet length, excluding any SGE padding
1033  *
1034  *	Get the next packet from a free list and complete setup of the
1035  *	sk_buff.  If the packet is small we make a copy and recycle the
1036  *	original buffer, otherwise we use the original buffer itself.  If a
1037  *	positive drop threshold is supplied packets are dropped and their
1038  *	buffers recycled if (a) the number of remaining buffers is under the
1039  *	threshold and the packet is too big to copy, or (b) the packet should
1040  *	be copied but there is no memory for the copy.
1041  */
1042 static inline struct sk_buff *get_packet(struct adapter *adapter,
1043 					 struct freelQ *fl, unsigned int len)
1044 {
1045 	const struct freelQ_ce *ce = &fl->centries[fl->cidx];
1046 	struct pci_dev *pdev = adapter->pdev;
1047 	struct sk_buff *skb;
1048 
1049 	if (len < copybreak) {
1050 		skb = napi_alloc_skb(&adapter->napi, len);
1051 		if (!skb)
1052 			goto use_orig_buf;
1053 
1054 		skb_put(skb, len);
1055 		dma_sync_single_for_cpu(&pdev->dev,
1056 					dma_unmap_addr(ce, dma_addr),
1057 					dma_unmap_len(ce, dma_len),
1058 					DMA_FROM_DEVICE);
1059 		skb_copy_from_linear_data(ce->skb, skb->data, len);
1060 		dma_sync_single_for_device(&pdev->dev,
1061 					   dma_unmap_addr(ce, dma_addr),
1062 					   dma_unmap_len(ce, dma_len),
1063 					   DMA_FROM_DEVICE);
1064 		recycle_fl_buf(fl, fl->cidx);
1065 		return skb;
1066 	}
1067 
1068 use_orig_buf:
1069 	if (fl->credits < 2) {
1070 		recycle_fl_buf(fl, fl->cidx);
1071 		return NULL;
1072 	}
1073 
1074 	dma_unmap_single(&pdev->dev, dma_unmap_addr(ce, dma_addr),
1075 			 dma_unmap_len(ce, dma_len), DMA_FROM_DEVICE);
1076 	skb = ce->skb;
1077 	prefetch(skb->data);
1078 
1079 	skb_put(skb, len);
1080 	return skb;
1081 }
1082 
1083 /**
1084  *	unexpected_offload - handle an unexpected offload packet
1085  *	@adapter: the adapter
1086  *	@fl: the free list that received the packet
1087  *
1088  *	Called when we receive an unexpected offload packet (e.g., the TOE
1089  *	function is disabled or the card is a NIC).  Prints a message and
1090  *	recycles the buffer.
1091  */
1092 static void unexpected_offload(struct adapter *adapter, struct freelQ *fl)
1093 {
1094 	struct freelQ_ce *ce = &fl->centries[fl->cidx];
1095 	struct sk_buff *skb = ce->skb;
1096 
1097 	dma_sync_single_for_cpu(&adapter->pdev->dev,
1098 				dma_unmap_addr(ce, dma_addr),
1099 				dma_unmap_len(ce, dma_len), DMA_FROM_DEVICE);
1100 	pr_err("%s: unexpected offload packet, cmd %u\n",
1101 	       adapter->name, *skb->data);
1102 	recycle_fl_buf(fl, fl->cidx);
1103 }
1104 
1105 /*
1106  * T1/T2 SGE limits the maximum DMA size per TX descriptor to
1107  * SGE_TX_DESC_MAX_PLEN (16KB). If the PAGE_SIZE is larger than 16KB, the
1108  * stack might send more than SGE_TX_DESC_MAX_PLEN in a contiguous manner.
1109  * Note that the *_large_page_tx_descs stuff will be optimized out when
1110  * PAGE_SIZE <= SGE_TX_DESC_MAX_PLEN.
1111  *
1112  * compute_large_page_descs() computes how many additional descriptors are
1113  * required to break down the stack's request.
1114  */
1115 static inline unsigned int compute_large_page_tx_descs(struct sk_buff *skb)
1116 {
1117 	unsigned int count = 0;
1118 
1119 	if (PAGE_SIZE > SGE_TX_DESC_MAX_PLEN) {
1120 		unsigned int nfrags = skb_shinfo(skb)->nr_frags;
1121 		unsigned int i, len = skb_headlen(skb);
1122 		while (len > SGE_TX_DESC_MAX_PLEN) {
1123 			count++;
1124 			len -= SGE_TX_DESC_MAX_PLEN;
1125 		}
1126 		for (i = 0; nfrags--; i++) {
1127 			const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1128 			len = skb_frag_size(frag);
1129 			while (len > SGE_TX_DESC_MAX_PLEN) {
1130 				count++;
1131 				len -= SGE_TX_DESC_MAX_PLEN;
1132 			}
1133 		}
1134 	}
1135 	return count;
1136 }
1137 
1138 /*
1139  * Write a cmdQ entry.
1140  *
1141  * Since this function writes the 'flags' field, it must not be used to
1142  * write the first cmdQ entry.
1143  */
1144 static inline void write_tx_desc(struct cmdQ_e *e, dma_addr_t mapping,
1145 				 unsigned int len, unsigned int gen,
1146 				 unsigned int eop)
1147 {
1148 	BUG_ON(len > SGE_TX_DESC_MAX_PLEN);
1149 
1150 	e->addr_lo = (u32)mapping;
1151 	e->addr_hi = (u64)mapping >> 32;
1152 	e->len_gen = V_CMD_LEN(len) | V_CMD_GEN1(gen);
1153 	e->flags = F_CMD_DATAVALID | V_CMD_EOP(eop) | V_CMD_GEN2(gen);
1154 }
1155 
1156 /*
1157  * See comment for previous function.
1158  *
1159  * write_tx_descs_large_page() writes additional SGE tx descriptors if
1160  * *desc_len exceeds HW's capability.
1161  */
1162 static inline unsigned int write_large_page_tx_descs(unsigned int pidx,
1163 						     struct cmdQ_e **e,
1164 						     struct cmdQ_ce **ce,
1165 						     unsigned int *gen,
1166 						     dma_addr_t *desc_mapping,
1167 						     unsigned int *desc_len,
1168 						     unsigned int nfrags,
1169 						     struct cmdQ *q)
1170 {
1171 	if (PAGE_SIZE > SGE_TX_DESC_MAX_PLEN) {
1172 		struct cmdQ_e *e1 = *e;
1173 		struct cmdQ_ce *ce1 = *ce;
1174 
1175 		while (*desc_len > SGE_TX_DESC_MAX_PLEN) {
1176 			*desc_len -= SGE_TX_DESC_MAX_PLEN;
1177 			write_tx_desc(e1, *desc_mapping, SGE_TX_DESC_MAX_PLEN,
1178 				      *gen, nfrags == 0 && *desc_len == 0);
1179 			ce1->skb = NULL;
1180 			dma_unmap_len_set(ce1, dma_len, 0);
1181 			*desc_mapping += SGE_TX_DESC_MAX_PLEN;
1182 			if (*desc_len) {
1183 				ce1++;
1184 				e1++;
1185 				if (++pidx == q->size) {
1186 					pidx = 0;
1187 					*gen ^= 1;
1188 					ce1 = q->centries;
1189 					e1 = q->entries;
1190 				}
1191 			}
1192 		}
1193 		*e = e1;
1194 		*ce = ce1;
1195 	}
1196 	return pidx;
1197 }
1198 
1199 /*
1200  * Write the command descriptors to transmit the given skb starting at
1201  * descriptor pidx with the given generation.
1202  */
1203 static inline void write_tx_descs(struct adapter *adapter, struct sk_buff *skb,
1204 				  unsigned int pidx, unsigned int gen,
1205 				  struct cmdQ *q)
1206 {
1207 	dma_addr_t mapping, desc_mapping;
1208 	struct cmdQ_e *e, *e1;
1209 	struct cmdQ_ce *ce;
1210 	unsigned int i, flags, first_desc_len, desc_len,
1211 	    nfrags = skb_shinfo(skb)->nr_frags;
1212 
1213 	e = e1 = &q->entries[pidx];
1214 	ce = &q->centries[pidx];
1215 
1216 	mapping = dma_map_single(&adapter->pdev->dev, skb->data,
1217 				 skb_headlen(skb), DMA_TO_DEVICE);
1218 
1219 	desc_mapping = mapping;
1220 	desc_len = skb_headlen(skb);
1221 
1222 	flags = F_CMD_DATAVALID | F_CMD_SOP |
1223 	    V_CMD_EOP(nfrags == 0 && desc_len <= SGE_TX_DESC_MAX_PLEN) |
1224 	    V_CMD_GEN2(gen);
1225 	first_desc_len = (desc_len <= SGE_TX_DESC_MAX_PLEN) ?
1226 	    desc_len : SGE_TX_DESC_MAX_PLEN;
1227 	e->addr_lo = (u32)desc_mapping;
1228 	e->addr_hi = (u64)desc_mapping >> 32;
1229 	e->len_gen = V_CMD_LEN(first_desc_len) | V_CMD_GEN1(gen);
1230 	ce->skb = NULL;
1231 	dma_unmap_len_set(ce, dma_len, 0);
1232 
1233 	if (PAGE_SIZE > SGE_TX_DESC_MAX_PLEN &&
1234 	    desc_len > SGE_TX_DESC_MAX_PLEN) {
1235 		desc_mapping += first_desc_len;
1236 		desc_len -= first_desc_len;
1237 		e1++;
1238 		ce++;
1239 		if (++pidx == q->size) {
1240 			pidx = 0;
1241 			gen ^= 1;
1242 			e1 = q->entries;
1243 			ce = q->centries;
1244 		}
1245 		pidx = write_large_page_tx_descs(pidx, &e1, &ce, &gen,
1246 						 &desc_mapping, &desc_len,
1247 						 nfrags, q);
1248 
1249 		if (likely(desc_len))
1250 			write_tx_desc(e1, desc_mapping, desc_len, gen,
1251 				      nfrags == 0);
1252 	}
1253 
1254 	ce->skb = NULL;
1255 	dma_unmap_addr_set(ce, dma_addr, mapping);
1256 	dma_unmap_len_set(ce, dma_len, skb_headlen(skb));
1257 
1258 	for (i = 0; nfrags--; i++) {
1259 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1260 		e1++;
1261 		ce++;
1262 		if (++pidx == q->size) {
1263 			pidx = 0;
1264 			gen ^= 1;
1265 			e1 = q->entries;
1266 			ce = q->centries;
1267 		}
1268 
1269 		mapping = skb_frag_dma_map(&adapter->pdev->dev, frag, 0,
1270 					   skb_frag_size(frag), DMA_TO_DEVICE);
1271 		desc_mapping = mapping;
1272 		desc_len = skb_frag_size(frag);
1273 
1274 		pidx = write_large_page_tx_descs(pidx, &e1, &ce, &gen,
1275 						 &desc_mapping, &desc_len,
1276 						 nfrags, q);
1277 		if (likely(desc_len))
1278 			write_tx_desc(e1, desc_mapping, desc_len, gen,
1279 				      nfrags == 0);
1280 		ce->skb = NULL;
1281 		dma_unmap_addr_set(ce, dma_addr, mapping);
1282 		dma_unmap_len_set(ce, dma_len, skb_frag_size(frag));
1283 	}
1284 	ce->skb = skb;
1285 	wmb();
1286 	e->flags = flags;
1287 }
1288 
1289 /*
1290  * Clean up completed Tx buffers.
1291  */
1292 static inline void reclaim_completed_tx(struct sge *sge, struct cmdQ *q)
1293 {
1294 	unsigned int reclaim = q->processed - q->cleaned;
1295 
1296 	if (reclaim) {
1297 		pr_debug("reclaim_completed_tx processed:%d cleaned:%d\n",
1298 			 q->processed, q->cleaned);
1299 		free_cmdQ_buffers(sge, q, reclaim);
1300 		q->cleaned += reclaim;
1301 	}
1302 }
1303 
1304 /*
1305  * Called from tasklet. Checks the scheduler for any
1306  * pending skbs that can be sent.
1307  */
1308 static void restart_sched(unsigned long arg)
1309 {
1310 	struct sge *sge = (struct sge *) arg;
1311 	struct adapter *adapter = sge->adapter;
1312 	struct cmdQ *q = &sge->cmdQ[0];
1313 	struct sk_buff *skb;
1314 	unsigned int credits, queued_skb = 0;
1315 
1316 	spin_lock(&q->lock);
1317 	reclaim_completed_tx(sge, q);
1318 
1319 	credits = q->size - q->in_use;
1320 	pr_debug("restart_sched credits=%d\n", credits);
1321 	while ((skb = sched_skb(sge, NULL, credits)) != NULL) {
1322 		unsigned int genbit, pidx, count;
1323 	        count = 1 + skb_shinfo(skb)->nr_frags;
1324 		count += compute_large_page_tx_descs(skb);
1325 		q->in_use += count;
1326 		genbit = q->genbit;
1327 		pidx = q->pidx;
1328 		q->pidx += count;
1329 		if (q->pidx >= q->size) {
1330 			q->pidx -= q->size;
1331 			q->genbit ^= 1;
1332 		}
1333 		write_tx_descs(adapter, skb, pidx, genbit, q);
1334 	        credits = q->size - q->in_use;
1335 		queued_skb = 1;
1336 	}
1337 
1338 	if (queued_skb) {
1339 		clear_bit(CMDQ_STAT_LAST_PKT_DB, &q->status);
1340 		if (test_and_set_bit(CMDQ_STAT_RUNNING, &q->status) == 0) {
1341 			set_bit(CMDQ_STAT_LAST_PKT_DB, &q->status);
1342 			writel(F_CMDQ0_ENABLE, adapter->regs + A_SG_DOORBELL);
1343 		}
1344 	}
1345 	spin_unlock(&q->lock);
1346 }
1347 
1348 /**
1349  *	sge_rx - process an ingress ethernet packet
1350  *	@sge: the sge structure
1351  *	@fl: the free list that contains the packet buffer
1352  *	@len: the packet length
1353  *
1354  *	Process an ingress ethernet pakcet and deliver it to the stack.
1355  */
1356 static void sge_rx(struct sge *sge, struct freelQ *fl, unsigned int len)
1357 {
1358 	struct sk_buff *skb;
1359 	const struct cpl_rx_pkt *p;
1360 	struct adapter *adapter = sge->adapter;
1361 	struct sge_port_stats *st;
1362 	struct net_device *dev;
1363 
1364 	skb = get_packet(adapter, fl, len - sge->rx_pkt_pad);
1365 	if (unlikely(!skb)) {
1366 		sge->stats.rx_drops++;
1367 		return;
1368 	}
1369 
1370 	p = (const struct cpl_rx_pkt *) skb->data;
1371 	if (p->iff >= adapter->params.nports) {
1372 		kfree_skb(skb);
1373 		return;
1374 	}
1375 	__skb_pull(skb, sizeof(*p));
1376 
1377 	st = this_cpu_ptr(sge->port_stats[p->iff]);
1378 	dev = adapter->port[p->iff].dev;
1379 
1380 	skb->protocol = eth_type_trans(skb, dev);
1381 	if ((dev->features & NETIF_F_RXCSUM) && p->csum == 0xffff &&
1382 	    skb->protocol == htons(ETH_P_IP) &&
1383 	    (skb->data[9] == IPPROTO_TCP || skb->data[9] == IPPROTO_UDP)) {
1384 		++st->rx_cso_good;
1385 		skb->ip_summed = CHECKSUM_UNNECESSARY;
1386 	} else
1387 		skb_checksum_none_assert(skb);
1388 
1389 	if (p->vlan_valid) {
1390 		st->vlan_xtract++;
1391 		__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(p->vlan));
1392 	}
1393 	netif_receive_skb(skb);
1394 }
1395 
1396 /*
1397  * Returns true if a command queue has enough available descriptors that
1398  * we can resume Tx operation after temporarily disabling its packet queue.
1399  */
1400 static inline int enough_free_Tx_descs(const struct cmdQ *q)
1401 {
1402 	unsigned int r = q->processed - q->cleaned;
1403 
1404 	return q->in_use - r < (q->size >> 1);
1405 }
1406 
1407 /*
1408  * Called when sufficient space has become available in the SGE command queues
1409  * after the Tx packet schedulers have been suspended to restart the Tx path.
1410  */
1411 static void restart_tx_queues(struct sge *sge)
1412 {
1413 	struct adapter *adap = sge->adapter;
1414 	int i;
1415 
1416 	if (!enough_free_Tx_descs(&sge->cmdQ[0]))
1417 		return;
1418 
1419 	for_each_port(adap, i) {
1420 		struct net_device *nd = adap->port[i].dev;
1421 
1422 		if (test_and_clear_bit(nd->if_port, &sge->stopped_tx_queues) &&
1423 		    netif_running(nd)) {
1424 			sge->stats.cmdQ_restarted[2]++;
1425 			netif_wake_queue(nd);
1426 		}
1427 	}
1428 }
1429 
1430 /*
1431  * update_tx_info is called from the interrupt handler/NAPI to return cmdQ0
1432  * information.
1433  */
1434 static unsigned int update_tx_info(struct adapter *adapter,
1435 					  unsigned int flags,
1436 					  unsigned int pr0)
1437 {
1438 	struct sge *sge = adapter->sge;
1439 	struct cmdQ *cmdq = &sge->cmdQ[0];
1440 
1441 	cmdq->processed += pr0;
1442 	if (flags & (F_FL0_ENABLE | F_FL1_ENABLE)) {
1443 		freelQs_empty(sge);
1444 		flags &= ~(F_FL0_ENABLE | F_FL1_ENABLE);
1445 	}
1446 	if (flags & F_CMDQ0_ENABLE) {
1447 		clear_bit(CMDQ_STAT_RUNNING, &cmdq->status);
1448 
1449 		if (cmdq->cleaned + cmdq->in_use != cmdq->processed &&
1450 		    !test_and_set_bit(CMDQ_STAT_LAST_PKT_DB, &cmdq->status)) {
1451 			set_bit(CMDQ_STAT_RUNNING, &cmdq->status);
1452 			writel(F_CMDQ0_ENABLE, adapter->regs + A_SG_DOORBELL);
1453 		}
1454 		if (sge->tx_sched)
1455 			tasklet_hi_schedule(&sge->tx_sched->sched_tsk);
1456 
1457 		flags &= ~F_CMDQ0_ENABLE;
1458 	}
1459 
1460 	if (unlikely(sge->stopped_tx_queues != 0))
1461 		restart_tx_queues(sge);
1462 
1463 	return flags;
1464 }
1465 
1466 /*
1467  * Process SGE responses, up to the supplied budget.  Returns the number of
1468  * responses processed.  A negative budget is effectively unlimited.
1469  */
1470 static int process_responses(struct adapter *adapter, int budget)
1471 {
1472 	struct sge *sge = adapter->sge;
1473 	struct respQ *q = &sge->respQ;
1474 	struct respQ_e *e = &q->entries[q->cidx];
1475 	int done = 0;
1476 	unsigned int flags = 0;
1477 	unsigned int cmdq_processed[SGE_CMDQ_N] = {0, 0};
1478 
1479 	while (done < budget && e->GenerationBit == q->genbit) {
1480 		flags |= e->Qsleeping;
1481 
1482 		cmdq_processed[0] += e->Cmdq0CreditReturn;
1483 		cmdq_processed[1] += e->Cmdq1CreditReturn;
1484 
1485 		/* We batch updates to the TX side to avoid cacheline
1486 		 * ping-pong of TX state information on MP where the sender
1487 		 * might run on a different CPU than this function...
1488 		 */
1489 		if (unlikely((flags & F_CMDQ0_ENABLE) || cmdq_processed[0] > 64)) {
1490 			flags = update_tx_info(adapter, flags, cmdq_processed[0]);
1491 			cmdq_processed[0] = 0;
1492 		}
1493 
1494 		if (unlikely(cmdq_processed[1] > 16)) {
1495 			sge->cmdQ[1].processed += cmdq_processed[1];
1496 			cmdq_processed[1] = 0;
1497 		}
1498 
1499 		if (likely(e->DataValid)) {
1500 			struct freelQ *fl = &sge->freelQ[e->FreelistQid];
1501 
1502 			BUG_ON(!e->Sop || !e->Eop);
1503 			if (unlikely(e->Offload))
1504 				unexpected_offload(adapter, fl);
1505 			else
1506 				sge_rx(sge, fl, e->BufferLength);
1507 
1508 			++done;
1509 
1510 			/*
1511 			 * Note: this depends on each packet consuming a
1512 			 * single free-list buffer; cf. the BUG above.
1513 			 */
1514 			if (++fl->cidx == fl->size)
1515 				fl->cidx = 0;
1516 			prefetch(fl->centries[fl->cidx].skb);
1517 
1518 			if (unlikely(--fl->credits <
1519 				     fl->size - SGE_FREEL_REFILL_THRESH))
1520 				refill_free_list(sge, fl);
1521 		} else
1522 			sge->stats.pure_rsps++;
1523 
1524 		e++;
1525 		if (unlikely(++q->cidx == q->size)) {
1526 			q->cidx = 0;
1527 			q->genbit ^= 1;
1528 			e = q->entries;
1529 		}
1530 		prefetch(e);
1531 
1532 		if (++q->credits > SGE_RESPQ_REPLENISH_THRES) {
1533 			writel(q->credits, adapter->regs + A_SG_RSPQUEUECREDIT);
1534 			q->credits = 0;
1535 		}
1536 	}
1537 
1538 	flags = update_tx_info(adapter, flags, cmdq_processed[0]);
1539 	sge->cmdQ[1].processed += cmdq_processed[1];
1540 
1541 	return done;
1542 }
1543 
1544 static inline int responses_pending(const struct adapter *adapter)
1545 {
1546 	const struct respQ *Q = &adapter->sge->respQ;
1547 	const struct respQ_e *e = &Q->entries[Q->cidx];
1548 
1549 	return e->GenerationBit == Q->genbit;
1550 }
1551 
1552 /*
1553  * A simpler version of process_responses() that handles only pure (i.e.,
1554  * non data-carrying) responses.  Such respones are too light-weight to justify
1555  * calling a softirq when using NAPI, so we handle them specially in hard
1556  * interrupt context.  The function is called with a pointer to a response,
1557  * which the caller must ensure is a valid pure response.  Returns 1 if it
1558  * encounters a valid data-carrying response, 0 otherwise.
1559  */
1560 static int process_pure_responses(struct adapter *adapter)
1561 {
1562 	struct sge *sge = adapter->sge;
1563 	struct respQ *q = &sge->respQ;
1564 	struct respQ_e *e = &q->entries[q->cidx];
1565 	const struct freelQ *fl = &sge->freelQ[e->FreelistQid];
1566 	unsigned int flags = 0;
1567 	unsigned int cmdq_processed[SGE_CMDQ_N] = {0, 0};
1568 
1569 	prefetch(fl->centries[fl->cidx].skb);
1570 	if (e->DataValid)
1571 		return 1;
1572 
1573 	do {
1574 		flags |= e->Qsleeping;
1575 
1576 		cmdq_processed[0] += e->Cmdq0CreditReturn;
1577 		cmdq_processed[1] += e->Cmdq1CreditReturn;
1578 
1579 		e++;
1580 		if (unlikely(++q->cidx == q->size)) {
1581 			q->cidx = 0;
1582 			q->genbit ^= 1;
1583 			e = q->entries;
1584 		}
1585 		prefetch(e);
1586 
1587 		if (++q->credits > SGE_RESPQ_REPLENISH_THRES) {
1588 			writel(q->credits, adapter->regs + A_SG_RSPQUEUECREDIT);
1589 			q->credits = 0;
1590 		}
1591 		sge->stats.pure_rsps++;
1592 	} while (e->GenerationBit == q->genbit && !e->DataValid);
1593 
1594 	flags = update_tx_info(adapter, flags, cmdq_processed[0]);
1595 	sge->cmdQ[1].processed += cmdq_processed[1];
1596 
1597 	return e->GenerationBit == q->genbit;
1598 }
1599 
1600 /*
1601  * Handler for new data events when using NAPI.  This does not need any locking
1602  * or protection from interrupts as data interrupts are off at this point and
1603  * other adapter interrupts do not interfere.
1604  */
1605 int t1_poll(struct napi_struct *napi, int budget)
1606 {
1607 	struct adapter *adapter = container_of(napi, struct adapter, napi);
1608 	int work_done = process_responses(adapter, budget);
1609 
1610 	if (likely(work_done < budget)) {
1611 		napi_complete_done(napi, work_done);
1612 		writel(adapter->sge->respQ.cidx,
1613 		       adapter->regs + A_SG_SLEEPING);
1614 	}
1615 	return work_done;
1616 }
1617 
1618 irqreturn_t t1_interrupt(int irq, void *data)
1619 {
1620 	struct adapter *adapter = data;
1621 	struct sge *sge = adapter->sge;
1622 	int handled;
1623 
1624 	if (likely(responses_pending(adapter))) {
1625 		writel(F_PL_INTR_SGE_DATA, adapter->regs + A_PL_CAUSE);
1626 
1627 		if (napi_schedule_prep(&adapter->napi)) {
1628 			if (process_pure_responses(adapter))
1629 				__napi_schedule(&adapter->napi);
1630 			else {
1631 				/* no data, no NAPI needed */
1632 				writel(sge->respQ.cidx, adapter->regs + A_SG_SLEEPING);
1633 				/* undo schedule_prep */
1634 				napi_enable(&adapter->napi);
1635 			}
1636 		}
1637 		return IRQ_HANDLED;
1638 	}
1639 
1640 	spin_lock(&adapter->async_lock);
1641 	handled = t1_slow_intr_handler(adapter);
1642 	spin_unlock(&adapter->async_lock);
1643 
1644 	if (!handled)
1645 		sge->stats.unhandled_irqs++;
1646 
1647 	return IRQ_RETVAL(handled != 0);
1648 }
1649 
1650 /*
1651  * Enqueues the sk_buff onto the cmdQ[qid] and has hardware fetch it.
1652  *
1653  * The code figures out how many entries the sk_buff will require in the
1654  * cmdQ and updates the cmdQ data structure with the state once the enqueue
1655  * has complete. Then, it doesn't access the global structure anymore, but
1656  * uses the corresponding fields on the stack. In conjunction with a spinlock
1657  * around that code, we can make the function reentrant without holding the
1658  * lock when we actually enqueue (which might be expensive, especially on
1659  * architectures with IO MMUs).
1660  *
1661  * This runs with softirqs disabled.
1662  */
1663 static int t1_sge_tx(struct sk_buff *skb, struct adapter *adapter,
1664 		     unsigned int qid, struct net_device *dev)
1665 {
1666 	struct sge *sge = adapter->sge;
1667 	struct cmdQ *q = &sge->cmdQ[qid];
1668 	unsigned int credits, pidx, genbit, count, use_sched_skb = 0;
1669 
1670 	spin_lock(&q->lock);
1671 
1672 	reclaim_completed_tx(sge, q);
1673 
1674 	pidx = q->pidx;
1675 	credits = q->size - q->in_use;
1676 	count = 1 + skb_shinfo(skb)->nr_frags;
1677 	count += compute_large_page_tx_descs(skb);
1678 
1679 	/* Ethernet packet */
1680 	if (unlikely(credits < count)) {
1681 		if (!netif_queue_stopped(dev)) {
1682 			netif_stop_queue(dev);
1683 			set_bit(dev->if_port, &sge->stopped_tx_queues);
1684 			sge->stats.cmdQ_full[2]++;
1685 			pr_err("%s: Tx ring full while queue awake!\n",
1686 			       adapter->name);
1687 		}
1688 		spin_unlock(&q->lock);
1689 		return NETDEV_TX_BUSY;
1690 	}
1691 
1692 	if (unlikely(credits - count < q->stop_thres)) {
1693 		netif_stop_queue(dev);
1694 		set_bit(dev->if_port, &sge->stopped_tx_queues);
1695 		sge->stats.cmdQ_full[2]++;
1696 	}
1697 
1698 	/* T204 cmdQ0 skbs that are destined for a certain port have to go
1699 	 * through the scheduler.
1700 	 */
1701 	if (sge->tx_sched && !qid && skb->dev) {
1702 use_sched:
1703 		use_sched_skb = 1;
1704 		/* Note that the scheduler might return a different skb than
1705 		 * the one passed in.
1706 		 */
1707 		skb = sched_skb(sge, skb, credits);
1708 		if (!skb) {
1709 			spin_unlock(&q->lock);
1710 			return NETDEV_TX_OK;
1711 		}
1712 		pidx = q->pidx;
1713 		count = 1 + skb_shinfo(skb)->nr_frags;
1714 		count += compute_large_page_tx_descs(skb);
1715 	}
1716 
1717 	q->in_use += count;
1718 	genbit = q->genbit;
1719 	pidx = q->pidx;
1720 	q->pidx += count;
1721 	if (q->pidx >= q->size) {
1722 		q->pidx -= q->size;
1723 		q->genbit ^= 1;
1724 	}
1725 	spin_unlock(&q->lock);
1726 
1727 	write_tx_descs(adapter, skb, pidx, genbit, q);
1728 
1729 	/*
1730 	 * We always ring the doorbell for cmdQ1.  For cmdQ0, we only ring
1731 	 * the doorbell if the Q is asleep. There is a natural race, where
1732 	 * the hardware is going to sleep just after we checked, however,
1733 	 * then the interrupt handler will detect the outstanding TX packet
1734 	 * and ring the doorbell for us.
1735 	 */
1736 	if (qid)
1737 		doorbell_pio(adapter, F_CMDQ1_ENABLE);
1738 	else {
1739 		clear_bit(CMDQ_STAT_LAST_PKT_DB, &q->status);
1740 		if (test_and_set_bit(CMDQ_STAT_RUNNING, &q->status) == 0) {
1741 			set_bit(CMDQ_STAT_LAST_PKT_DB, &q->status);
1742 			writel(F_CMDQ0_ENABLE, adapter->regs + A_SG_DOORBELL);
1743 		}
1744 	}
1745 
1746 	if (use_sched_skb) {
1747 		if (spin_trylock(&q->lock)) {
1748 			credits = q->size - q->in_use;
1749 			skb = NULL;
1750 			goto use_sched;
1751 		}
1752 	}
1753 	return NETDEV_TX_OK;
1754 }
1755 
1756 #define MK_ETH_TYPE_MSS(type, mss) (((mss) & 0x3FFF) | ((type) << 14))
1757 
1758 /*
1759  *	eth_hdr_len - return the length of an Ethernet header
1760  *	@data: pointer to the start of the Ethernet header
1761  *
1762  *	Returns the length of an Ethernet header, including optional VLAN tag.
1763  */
1764 static inline int eth_hdr_len(const void *data)
1765 {
1766 	const struct ethhdr *e = data;
1767 
1768 	return e->h_proto == htons(ETH_P_8021Q) ? VLAN_ETH_HLEN : ETH_HLEN;
1769 }
1770 
1771 /*
1772  * Adds the CPL header to the sk_buff and passes it to t1_sge_tx.
1773  */
1774 netdev_tx_t t1_start_xmit(struct sk_buff *skb, struct net_device *dev)
1775 {
1776 	struct adapter *adapter = dev->ml_priv;
1777 	struct sge *sge = adapter->sge;
1778 	struct sge_port_stats *st = this_cpu_ptr(sge->port_stats[dev->if_port]);
1779 	struct cpl_tx_pkt *cpl;
1780 	struct sk_buff *orig_skb = skb;
1781 	int ret;
1782 
1783 	if (skb->protocol == htons(ETH_P_CPL5))
1784 		goto send;
1785 
1786 	/*
1787 	 * We are using a non-standard hard_header_len.
1788 	 * Allocate more header room in the rare cases it is not big enough.
1789 	 */
1790 	if (unlikely(skb_headroom(skb) < dev->hard_header_len - ETH_HLEN)) {
1791 		skb = skb_realloc_headroom(skb, sizeof(struct cpl_tx_pkt_lso));
1792 		++st->tx_need_hdrroom;
1793 		dev_kfree_skb_any(orig_skb);
1794 		if (!skb)
1795 			return NETDEV_TX_OK;
1796 	}
1797 
1798 	if (skb_shinfo(skb)->gso_size) {
1799 		int eth_type;
1800 		struct cpl_tx_pkt_lso *hdr;
1801 
1802 		++st->tx_tso;
1803 
1804 		eth_type = skb_network_offset(skb) == ETH_HLEN ?
1805 			CPL_ETH_II : CPL_ETH_II_VLAN;
1806 
1807 		hdr = skb_push(skb, sizeof(*hdr));
1808 		hdr->opcode = CPL_TX_PKT_LSO;
1809 		hdr->ip_csum_dis = hdr->l4_csum_dis = 0;
1810 		hdr->ip_hdr_words = ip_hdr(skb)->ihl;
1811 		hdr->tcp_hdr_words = tcp_hdr(skb)->doff;
1812 		hdr->eth_type_mss = htons(MK_ETH_TYPE_MSS(eth_type,
1813 							  skb_shinfo(skb)->gso_size));
1814 		hdr->len = htonl(skb->len - sizeof(*hdr));
1815 		cpl = (struct cpl_tx_pkt *)hdr;
1816 	} else {
1817 		/*
1818 		 * Packets shorter than ETH_HLEN can break the MAC, drop them
1819 		 * early.  Also, we may get oversized packets because some
1820 		 * parts of the kernel don't handle our unusual hard_header_len
1821 		 * right, drop those too.
1822 		 */
1823 		if (unlikely(skb->len < ETH_HLEN ||
1824 			     skb->len > dev->mtu + eth_hdr_len(skb->data))) {
1825 			netdev_dbg(dev, "packet size %d hdr %d mtu%d\n",
1826 				   skb->len, eth_hdr_len(skb->data), dev->mtu);
1827 			dev_kfree_skb_any(skb);
1828 			return NETDEV_TX_OK;
1829 		}
1830 
1831 		if (skb->ip_summed == CHECKSUM_PARTIAL &&
1832 		    ip_hdr(skb)->protocol == IPPROTO_UDP) {
1833 			if (unlikely(skb_checksum_help(skb))) {
1834 				netdev_dbg(dev, "unable to do udp checksum\n");
1835 				dev_kfree_skb_any(skb);
1836 				return NETDEV_TX_OK;
1837 			}
1838 		}
1839 
1840 		/* Hmmm, assuming to catch the gratious arp... and we'll use
1841 		 * it to flush out stuck espi packets...
1842 		 */
1843 		if ((unlikely(!adapter->sge->espibug_skb[dev->if_port]))) {
1844 			if (skb->protocol == htons(ETH_P_ARP) &&
1845 			    arp_hdr(skb)->ar_op == htons(ARPOP_REQUEST)) {
1846 				adapter->sge->espibug_skb[dev->if_port] = skb;
1847 				/* We want to re-use this skb later. We
1848 				 * simply bump the reference count and it
1849 				 * will not be freed...
1850 				 */
1851 				skb = skb_get(skb);
1852 			}
1853 		}
1854 
1855 		cpl = __skb_push(skb, sizeof(*cpl));
1856 		cpl->opcode = CPL_TX_PKT;
1857 		cpl->ip_csum_dis = 1;    /* SW calculates IP csum */
1858 		cpl->l4_csum_dis = skb->ip_summed == CHECKSUM_PARTIAL ? 0 : 1;
1859 		/* the length field isn't used so don't bother setting it */
1860 
1861 		st->tx_cso += (skb->ip_summed == CHECKSUM_PARTIAL);
1862 	}
1863 	cpl->iff = dev->if_port;
1864 
1865 	if (skb_vlan_tag_present(skb)) {
1866 		cpl->vlan_valid = 1;
1867 		cpl->vlan = htons(skb_vlan_tag_get(skb));
1868 		st->vlan_insert++;
1869 	} else
1870 		cpl->vlan_valid = 0;
1871 
1872 send:
1873 	ret = t1_sge_tx(skb, adapter, 0, dev);
1874 
1875 	/* If transmit busy, and we reallocated skb's due to headroom limit,
1876 	 * then silently discard to avoid leak.
1877 	 */
1878 	if (unlikely(ret != NETDEV_TX_OK && skb != orig_skb)) {
1879 		dev_kfree_skb_any(skb);
1880 		ret = NETDEV_TX_OK;
1881 	}
1882 	return ret;
1883 }
1884 
1885 /*
1886  * Callback for the Tx buffer reclaim timer.  Runs with softirqs disabled.
1887  */
1888 static void sge_tx_reclaim_cb(struct timer_list *t)
1889 {
1890 	int i;
1891 	struct sge *sge = from_timer(sge, t, tx_reclaim_timer);
1892 
1893 	for (i = 0; i < SGE_CMDQ_N; ++i) {
1894 		struct cmdQ *q = &sge->cmdQ[i];
1895 
1896 		if (!spin_trylock(&q->lock))
1897 			continue;
1898 
1899 		reclaim_completed_tx(sge, q);
1900 		if (i == 0 && q->in_use) {    /* flush pending credits */
1901 			writel(F_CMDQ0_ENABLE, sge->adapter->regs + A_SG_DOORBELL);
1902 		}
1903 		spin_unlock(&q->lock);
1904 	}
1905 	mod_timer(&sge->tx_reclaim_timer, jiffies + TX_RECLAIM_PERIOD);
1906 }
1907 
1908 /*
1909  * Propagate changes of the SGE coalescing parameters to the HW.
1910  */
1911 int t1_sge_set_coalesce_params(struct sge *sge, struct sge_params *p)
1912 {
1913 	sge->fixed_intrtimer = p->rx_coalesce_usecs *
1914 		core_ticks_per_usec(sge->adapter);
1915 	writel(sge->fixed_intrtimer, sge->adapter->regs + A_SG_INTRTIMER);
1916 	return 0;
1917 }
1918 
1919 /*
1920  * Allocates both RX and TX resources and configures the SGE. However,
1921  * the hardware is not enabled yet.
1922  */
1923 int t1_sge_configure(struct sge *sge, struct sge_params *p)
1924 {
1925 	if (alloc_rx_resources(sge, p))
1926 		return -ENOMEM;
1927 	if (alloc_tx_resources(sge, p)) {
1928 		free_rx_resources(sge);
1929 		return -ENOMEM;
1930 	}
1931 	configure_sge(sge, p);
1932 
1933 	/*
1934 	 * Now that we have sized the free lists calculate the payload
1935 	 * capacity of the large buffers.  Other parts of the driver use
1936 	 * this to set the max offload coalescing size so that RX packets
1937 	 * do not overflow our large buffers.
1938 	 */
1939 	p->large_buf_capacity = jumbo_payload_capacity(sge);
1940 	return 0;
1941 }
1942 
1943 /*
1944  * Disables the DMA engine.
1945  */
1946 void t1_sge_stop(struct sge *sge)
1947 {
1948 	int i;
1949 	writel(0, sge->adapter->regs + A_SG_CONTROL);
1950 	readl(sge->adapter->regs + A_SG_CONTROL); /* flush */
1951 
1952 	if (is_T2(sge->adapter))
1953 		del_timer_sync(&sge->espibug_timer);
1954 
1955 	del_timer_sync(&sge->tx_reclaim_timer);
1956 	if (sge->tx_sched)
1957 		tx_sched_stop(sge);
1958 
1959 	for (i = 0; i < MAX_NPORTS; i++)
1960 		kfree_skb(sge->espibug_skb[i]);
1961 }
1962 
1963 /*
1964  * Enables the DMA engine.
1965  */
1966 void t1_sge_start(struct sge *sge)
1967 {
1968 	refill_free_list(sge, &sge->freelQ[0]);
1969 	refill_free_list(sge, &sge->freelQ[1]);
1970 
1971 	writel(sge->sge_control, sge->adapter->regs + A_SG_CONTROL);
1972 	doorbell_pio(sge->adapter, F_FL0_ENABLE | F_FL1_ENABLE);
1973 	readl(sge->adapter->regs + A_SG_CONTROL); /* flush */
1974 
1975 	mod_timer(&sge->tx_reclaim_timer, jiffies + TX_RECLAIM_PERIOD);
1976 
1977 	if (is_T2(sge->adapter))
1978 		mod_timer(&sge->espibug_timer, jiffies + sge->espibug_timeout);
1979 }
1980 
1981 /*
1982  * Callback for the T2 ESPI 'stuck packet feature' workaorund
1983  */
1984 static void espibug_workaround_t204(struct timer_list *t)
1985 {
1986 	struct sge *sge = from_timer(sge, t, espibug_timer);
1987 	struct adapter *adapter = sge->adapter;
1988 	unsigned int nports = adapter->params.nports;
1989 	u32 seop[MAX_NPORTS];
1990 
1991 	if (adapter->open_device_map & PORT_MASK) {
1992 		int i;
1993 
1994 		if (t1_espi_get_mon_t204(adapter, &(seop[0]), 0) < 0)
1995 			return;
1996 
1997 		for (i = 0; i < nports; i++) {
1998 			struct sk_buff *skb = sge->espibug_skb[i];
1999 
2000 			if (!netif_running(adapter->port[i].dev) ||
2001 			    netif_queue_stopped(adapter->port[i].dev) ||
2002 			    !seop[i] || ((seop[i] & 0xfff) != 0) || !skb)
2003 				continue;
2004 
2005 			if (!skb->cb[0]) {
2006 				skb_copy_to_linear_data_offset(skb,
2007 						    sizeof(struct cpl_tx_pkt),
2008 							       ch_mac_addr,
2009 							       ETH_ALEN);
2010 				skb_copy_to_linear_data_offset(skb,
2011 							       skb->len - 10,
2012 							       ch_mac_addr,
2013 							       ETH_ALEN);
2014 				skb->cb[0] = 0xff;
2015 			}
2016 
2017 			/* bump the reference count to avoid freeing of
2018 			 * the skb once the DMA has completed.
2019 			 */
2020 			skb = skb_get(skb);
2021 			t1_sge_tx(skb, adapter, 0, adapter->port[i].dev);
2022 		}
2023 	}
2024 	mod_timer(&sge->espibug_timer, jiffies + sge->espibug_timeout);
2025 }
2026 
2027 static void espibug_workaround(struct timer_list *t)
2028 {
2029 	struct sge *sge = from_timer(sge, t, espibug_timer);
2030 	struct adapter *adapter = sge->adapter;
2031 
2032 	if (netif_running(adapter->port[0].dev)) {
2033 	        struct sk_buff *skb = sge->espibug_skb[0];
2034 	        u32 seop = t1_espi_get_mon(adapter, 0x930, 0);
2035 
2036 	        if ((seop & 0xfff0fff) == 0xfff && skb) {
2037 	                if (!skb->cb[0]) {
2038 	                        skb_copy_to_linear_data_offset(skb,
2039 						     sizeof(struct cpl_tx_pkt),
2040 							       ch_mac_addr,
2041 							       ETH_ALEN);
2042 	                        skb_copy_to_linear_data_offset(skb,
2043 							       skb->len - 10,
2044 							       ch_mac_addr,
2045 							       ETH_ALEN);
2046 	                        skb->cb[0] = 0xff;
2047 	                }
2048 
2049 	                /* bump the reference count to avoid freeing of the
2050 	                 * skb once the DMA has completed.
2051 	                 */
2052 	                skb = skb_get(skb);
2053 	                t1_sge_tx(skb, adapter, 0, adapter->port[0].dev);
2054 	        }
2055 	}
2056 	mod_timer(&sge->espibug_timer, jiffies + sge->espibug_timeout);
2057 }
2058 
2059 /*
2060  * Creates a t1_sge structure and returns suggested resource parameters.
2061  */
2062 struct sge *t1_sge_create(struct adapter *adapter, struct sge_params *p)
2063 {
2064 	struct sge *sge = kzalloc(sizeof(*sge), GFP_KERNEL);
2065 	int i;
2066 
2067 	if (!sge)
2068 		return NULL;
2069 
2070 	sge->adapter = adapter;
2071 	sge->netdev = adapter->port[0].dev;
2072 	sge->rx_pkt_pad = t1_is_T1B(adapter) ? 0 : 2;
2073 	sge->jumbo_fl = t1_is_T1B(adapter) ? 1 : 0;
2074 
2075 	for_each_port(adapter, i) {
2076 		sge->port_stats[i] = alloc_percpu(struct sge_port_stats);
2077 		if (!sge->port_stats[i])
2078 			goto nomem_port;
2079 	}
2080 
2081 	timer_setup(&sge->tx_reclaim_timer, sge_tx_reclaim_cb, 0);
2082 
2083 	if (is_T2(sge->adapter)) {
2084 		timer_setup(&sge->espibug_timer,
2085 			    adapter->params.nports > 1 ? espibug_workaround_t204 : espibug_workaround,
2086 			    0);
2087 
2088 		if (adapter->params.nports > 1)
2089 			tx_sched_init(sge);
2090 
2091 		sge->espibug_timeout = 1;
2092 		/* for T204, every 10ms */
2093 		if (adapter->params.nports > 1)
2094 			sge->espibug_timeout = HZ/100;
2095 	}
2096 
2097 
2098 	p->cmdQ_size[0] = SGE_CMDQ0_E_N;
2099 	p->cmdQ_size[1] = SGE_CMDQ1_E_N;
2100 	p->freelQ_size[!sge->jumbo_fl] = SGE_FREEL_SIZE;
2101 	p->freelQ_size[sge->jumbo_fl] = SGE_JUMBO_FREEL_SIZE;
2102 	if (sge->tx_sched) {
2103 		if (board_info(sge->adapter)->board == CHBT_BOARD_CHT204)
2104 			p->rx_coalesce_usecs = 15;
2105 		else
2106 			p->rx_coalesce_usecs = 50;
2107 	} else
2108 		p->rx_coalesce_usecs = 50;
2109 
2110 	p->coalesce_enable = 0;
2111 	p->sample_interval_usecs = 0;
2112 
2113 	return sge;
2114 nomem_port:
2115 	while (i >= 0) {
2116 		free_percpu(sge->port_stats[i]);
2117 		--i;
2118 	}
2119 	kfree(sge);
2120 	return NULL;
2121 
2122 }
2123