1 /*
2  * This file is part of the Chelsio T4 Ethernet driver for Linux.
3  *
4  * Copyright (c) 2003-2014 Chelsio Communications, Inc. All rights reserved.
5  *
6  * This software is available to you under a choice of one of two
7  * licenses.  You may choose to be licensed under the terms of the GNU
8  * General Public License (GPL) Version 2, available from the file
9  * COPYING in the main directory of this source tree, or the
10  * OpenIB.org BSD license below:
11  *
12  *     Redistribution and use in source and binary forms, with or
13  *     without modification, are permitted provided that the following
14  *     conditions are met:
15  *
16  *      - Redistributions of source code must retain the above
17  *        copyright notice, this list of conditions and the following
18  *        disclaimer.
19  *
20  *      - Redistributions in binary form must reproduce the above
21  *        copyright notice, this list of conditions and the following
22  *        disclaimer in the documentation and/or other materials
23  *        provided with the distribution.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
29  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
30  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  */
34 
35 #include <linux/skbuff.h>
36 #include <linux/netdevice.h>
37 #include <linux/etherdevice.h>
38 #include <linux/if_vlan.h>
39 #include <linux/ip.h>
40 #include <linux/dma-mapping.h>
41 #include <linux/jiffies.h>
42 #include <linux/prefetch.h>
43 #include <linux/export.h>
44 #include <net/xfrm.h>
45 #include <net/ipv6.h>
46 #include <net/tcp.h>
47 #include <net/busy_poll.h>
48 #ifdef CONFIG_CHELSIO_T4_FCOE
49 #include <scsi/fc/fc_fcoe.h>
50 #endif /* CONFIG_CHELSIO_T4_FCOE */
51 #include "cxgb4.h"
52 #include "t4_regs.h"
53 #include "t4_values.h"
54 #include "t4_msg.h"
55 #include "t4fw_api.h"
56 #include "cxgb4_ptp.h"
57 #include "cxgb4_uld.h"
58 
59 /*
60  * Rx buffer size.  We use largish buffers if possible but settle for single
61  * pages under memory shortage.
62  */
63 #if PAGE_SHIFT >= 16
64 # define FL_PG_ORDER 0
65 #else
66 # define FL_PG_ORDER (16 - PAGE_SHIFT)
67 #endif
68 
69 /* RX_PULL_LEN should be <= RX_COPY_THRES */
70 #define RX_COPY_THRES    256
71 #define RX_PULL_LEN      128
72 
73 /*
74  * Main body length for sk_buffs used for Rx Ethernet packets with fragments.
75  * Should be >= RX_PULL_LEN but possibly bigger to give pskb_may_pull some room.
76  */
77 #define RX_PKT_SKB_LEN   512
78 
79 /*
80  * Max number of Tx descriptors we clean up at a time.  Should be modest as
81  * freeing skbs isn't cheap and it happens while holding locks.  We just need
82  * to free packets faster than they arrive, we eventually catch up and keep
83  * the amortized cost reasonable.  Must be >= 2 * TXQ_STOP_THRES.
84  */
85 #define MAX_TX_RECLAIM 16
86 
87 /*
88  * Max number of Rx buffers we replenish at a time.  Again keep this modest,
89  * allocating buffers isn't cheap either.
90  */
91 #define MAX_RX_REFILL 16U
92 
93 /*
94  * Period of the Rx queue check timer.  This timer is infrequent as it has
95  * something to do only when the system experiences severe memory shortage.
96  */
97 #define RX_QCHECK_PERIOD (HZ / 2)
98 
99 /*
100  * Period of the Tx queue check timer.
101  */
102 #define TX_QCHECK_PERIOD (HZ / 2)
103 
104 /*
105  * Max number of Tx descriptors to be reclaimed by the Tx timer.
106  */
107 #define MAX_TIMER_TX_RECLAIM 100
108 
109 /*
110  * Timer index used when backing off due to memory shortage.
111  */
112 #define NOMEM_TMR_IDX (SGE_NTIMERS - 1)
113 
114 /*
115  * Suspension threshold for non-Ethernet Tx queues.  We require enough room
116  * for a full sized WR.
117  */
118 #define TXQ_STOP_THRES (SGE_MAX_WR_LEN / sizeof(struct tx_desc))
119 
120 /*
121  * Max Tx descriptor space we allow for an Ethernet packet to be inlined
122  * into a WR.
123  */
124 #define MAX_IMM_TX_PKT_LEN 256
125 
126 /*
127  * Max size of a WR sent through a control Tx queue.
128  */
129 #define MAX_CTRL_WR_LEN SGE_MAX_WR_LEN
130 
131 struct rx_sw_desc {                /* SW state per Rx descriptor */
132 	struct page *page;
133 	dma_addr_t dma_addr;
134 };
135 
136 /*
137  * Rx buffer sizes for "useskbs" Free List buffers (one ingress packet pe skb
138  * buffer).  We currently only support two sizes for 1500- and 9000-byte MTUs.
139  * We could easily support more but there doesn't seem to be much need for
140  * that ...
141  */
142 #define FL_MTU_SMALL 1500
143 #define FL_MTU_LARGE 9000
144 
145 static inline unsigned int fl_mtu_bufsize(struct adapter *adapter,
146 					  unsigned int mtu)
147 {
148 	struct sge *s = &adapter->sge;
149 
150 	return ALIGN(s->pktshift + ETH_HLEN + VLAN_HLEN + mtu, s->fl_align);
151 }
152 
153 #define FL_MTU_SMALL_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_SMALL)
154 #define FL_MTU_LARGE_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_LARGE)
155 
156 /*
157  * Bits 0..3 of rx_sw_desc.dma_addr have special meaning.  The hardware uses
158  * these to specify the buffer size as an index into the SGE Free List Buffer
159  * Size register array.  We also use bit 4, when the buffer has been unmapped
160  * for DMA, but this is of course never sent to the hardware and is only used
161  * to prevent double unmappings.  All of the above requires that the Free List
162  * Buffers which we allocate have the bottom 5 bits free (0) -- i.e. are
163  * 32-byte or or a power of 2 greater in alignment.  Since the SGE's minimal
164  * Free List Buffer alignment is 32 bytes, this works out for us ...
165  */
166 enum {
167 	RX_BUF_FLAGS     = 0x1f,   /* bottom five bits are special */
168 	RX_BUF_SIZE      = 0x0f,   /* bottom three bits are for buf sizes */
169 	RX_UNMAPPED_BUF  = 0x10,   /* buffer is not mapped */
170 
171 	/*
172 	 * XXX We shouldn't depend on being able to use these indices.
173 	 * XXX Especially when some other Master PF has initialized the
174 	 * XXX adapter or we use the Firmware Configuration File.  We
175 	 * XXX should really search through the Host Buffer Size register
176 	 * XXX array for the appropriately sized buffer indices.
177 	 */
178 	RX_SMALL_PG_BUF  = 0x0,   /* small (PAGE_SIZE) page buffer */
179 	RX_LARGE_PG_BUF  = 0x1,   /* buffer large (FL_PG_ORDER) page buffer */
180 
181 	RX_SMALL_MTU_BUF = 0x2,   /* small MTU buffer */
182 	RX_LARGE_MTU_BUF = 0x3,   /* large MTU buffer */
183 };
184 
185 static int timer_pkt_quota[] = {1, 1, 2, 3, 4, 5};
186 #define MIN_NAPI_WORK  1
187 
188 static inline dma_addr_t get_buf_addr(const struct rx_sw_desc *d)
189 {
190 	return d->dma_addr & ~(dma_addr_t)RX_BUF_FLAGS;
191 }
192 
193 static inline bool is_buf_mapped(const struct rx_sw_desc *d)
194 {
195 	return !(d->dma_addr & RX_UNMAPPED_BUF);
196 }
197 
198 /**
199  *	txq_avail - return the number of available slots in a Tx queue
200  *	@q: the Tx queue
201  *
202  *	Returns the number of descriptors in a Tx queue available to write new
203  *	packets.
204  */
205 static inline unsigned int txq_avail(const struct sge_txq *q)
206 {
207 	return q->size - 1 - q->in_use;
208 }
209 
210 /**
211  *	fl_cap - return the capacity of a free-buffer list
212  *	@fl: the FL
213  *
214  *	Returns the capacity of a free-buffer list.  The capacity is less than
215  *	the size because one descriptor needs to be left unpopulated, otherwise
216  *	HW will think the FL is empty.
217  */
218 static inline unsigned int fl_cap(const struct sge_fl *fl)
219 {
220 	return fl->size - 8;   /* 1 descriptor = 8 buffers */
221 }
222 
223 /**
224  *	fl_starving - return whether a Free List is starving.
225  *	@adapter: pointer to the adapter
226  *	@fl: the Free List
227  *
228  *	Tests specified Free List to see whether the number of buffers
229  *	available to the hardware has falled below our "starvation"
230  *	threshold.
231  */
232 static inline bool fl_starving(const struct adapter *adapter,
233 			       const struct sge_fl *fl)
234 {
235 	const struct sge *s = &adapter->sge;
236 
237 	return fl->avail - fl->pend_cred <= s->fl_starve_thres;
238 }
239 
240 int cxgb4_map_skb(struct device *dev, const struct sk_buff *skb,
241 		  dma_addr_t *addr)
242 {
243 	const skb_frag_t *fp, *end;
244 	const struct skb_shared_info *si;
245 
246 	*addr = dma_map_single(dev, skb->data, skb_headlen(skb), DMA_TO_DEVICE);
247 	if (dma_mapping_error(dev, *addr))
248 		goto out_err;
249 
250 	si = skb_shinfo(skb);
251 	end = &si->frags[si->nr_frags];
252 
253 	for (fp = si->frags; fp < end; fp++) {
254 		*++addr = skb_frag_dma_map(dev, fp, 0, skb_frag_size(fp),
255 					   DMA_TO_DEVICE);
256 		if (dma_mapping_error(dev, *addr))
257 			goto unwind;
258 	}
259 	return 0;
260 
261 unwind:
262 	while (fp-- > si->frags)
263 		dma_unmap_page(dev, *--addr, skb_frag_size(fp), DMA_TO_DEVICE);
264 
265 	dma_unmap_single(dev, addr[-1], skb_headlen(skb), DMA_TO_DEVICE);
266 out_err:
267 	return -ENOMEM;
268 }
269 EXPORT_SYMBOL(cxgb4_map_skb);
270 
271 #ifdef CONFIG_NEED_DMA_MAP_STATE
272 static void unmap_skb(struct device *dev, const struct sk_buff *skb,
273 		      const dma_addr_t *addr)
274 {
275 	const skb_frag_t *fp, *end;
276 	const struct skb_shared_info *si;
277 
278 	dma_unmap_single(dev, *addr++, skb_headlen(skb), DMA_TO_DEVICE);
279 
280 	si = skb_shinfo(skb);
281 	end = &si->frags[si->nr_frags];
282 	for (fp = si->frags; fp < end; fp++)
283 		dma_unmap_page(dev, *addr++, skb_frag_size(fp), DMA_TO_DEVICE);
284 }
285 
286 /**
287  *	deferred_unmap_destructor - unmap a packet when it is freed
288  *	@skb: the packet
289  *
290  *	This is the packet destructor used for Tx packets that need to remain
291  *	mapped until they are freed rather than until their Tx descriptors are
292  *	freed.
293  */
294 static void deferred_unmap_destructor(struct sk_buff *skb)
295 {
296 	unmap_skb(skb->dev->dev.parent, skb, (dma_addr_t *)skb->head);
297 }
298 #endif
299 
300 static void unmap_sgl(struct device *dev, const struct sk_buff *skb,
301 		      const struct ulptx_sgl *sgl, const struct sge_txq *q)
302 {
303 	const struct ulptx_sge_pair *p;
304 	unsigned int nfrags = skb_shinfo(skb)->nr_frags;
305 
306 	if (likely(skb_headlen(skb)))
307 		dma_unmap_single(dev, be64_to_cpu(sgl->addr0), ntohl(sgl->len0),
308 				 DMA_TO_DEVICE);
309 	else {
310 		dma_unmap_page(dev, be64_to_cpu(sgl->addr0), ntohl(sgl->len0),
311 			       DMA_TO_DEVICE);
312 		nfrags--;
313 	}
314 
315 	/*
316 	 * the complexity below is because of the possibility of a wrap-around
317 	 * in the middle of an SGL
318 	 */
319 	for (p = sgl->sge; nfrags >= 2; nfrags -= 2) {
320 		if (likely((u8 *)(p + 1) <= (u8 *)q->stat)) {
321 unmap:			dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
322 				       ntohl(p->len[0]), DMA_TO_DEVICE);
323 			dma_unmap_page(dev, be64_to_cpu(p->addr[1]),
324 				       ntohl(p->len[1]), DMA_TO_DEVICE);
325 			p++;
326 		} else if ((u8 *)p == (u8 *)q->stat) {
327 			p = (const struct ulptx_sge_pair *)q->desc;
328 			goto unmap;
329 		} else if ((u8 *)p + 8 == (u8 *)q->stat) {
330 			const __be64 *addr = (const __be64 *)q->desc;
331 
332 			dma_unmap_page(dev, be64_to_cpu(addr[0]),
333 				       ntohl(p->len[0]), DMA_TO_DEVICE);
334 			dma_unmap_page(dev, be64_to_cpu(addr[1]),
335 				       ntohl(p->len[1]), DMA_TO_DEVICE);
336 			p = (const struct ulptx_sge_pair *)&addr[2];
337 		} else {
338 			const __be64 *addr = (const __be64 *)q->desc;
339 
340 			dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
341 				       ntohl(p->len[0]), DMA_TO_DEVICE);
342 			dma_unmap_page(dev, be64_to_cpu(addr[0]),
343 				       ntohl(p->len[1]), DMA_TO_DEVICE);
344 			p = (const struct ulptx_sge_pair *)&addr[1];
345 		}
346 	}
347 	if (nfrags) {
348 		__be64 addr;
349 
350 		if ((u8 *)p == (u8 *)q->stat)
351 			p = (const struct ulptx_sge_pair *)q->desc;
352 		addr = (u8 *)p + 16 <= (u8 *)q->stat ? p->addr[0] :
353 						       *(const __be64 *)q->desc;
354 		dma_unmap_page(dev, be64_to_cpu(addr), ntohl(p->len[0]),
355 			       DMA_TO_DEVICE);
356 	}
357 }
358 
359 /**
360  *	free_tx_desc - reclaims Tx descriptors and their buffers
361  *	@adapter: the adapter
362  *	@q: the Tx queue to reclaim descriptors from
363  *	@n: the number of descriptors to reclaim
364  *	@unmap: whether the buffers should be unmapped for DMA
365  *
366  *	Reclaims Tx descriptors from an SGE Tx queue and frees the associated
367  *	Tx buffers.  Called with the Tx queue lock held.
368  */
369 void free_tx_desc(struct adapter *adap, struct sge_txq *q,
370 		  unsigned int n, bool unmap)
371 {
372 	struct tx_sw_desc *d;
373 	unsigned int cidx = q->cidx;
374 	struct device *dev = adap->pdev_dev;
375 
376 	d = &q->sdesc[cidx];
377 	while (n--) {
378 		if (d->skb) {                       /* an SGL is present */
379 			if (unmap)
380 				unmap_sgl(dev, d->skb, d->sgl, q);
381 			dev_consume_skb_any(d->skb);
382 			d->skb = NULL;
383 		}
384 		++d;
385 		if (++cidx == q->size) {
386 			cidx = 0;
387 			d = q->sdesc;
388 		}
389 	}
390 	q->cidx = cidx;
391 }
392 
393 /*
394  * Return the number of reclaimable descriptors in a Tx queue.
395  */
396 static inline int reclaimable(const struct sge_txq *q)
397 {
398 	int hw_cidx = ntohs(READ_ONCE(q->stat->cidx));
399 	hw_cidx -= q->cidx;
400 	return hw_cidx < 0 ? hw_cidx + q->size : hw_cidx;
401 }
402 
403 /**
404  *	cxgb4_reclaim_completed_tx - reclaims completed Tx descriptors
405  *	@adap: the adapter
406  *	@q: the Tx queue to reclaim completed descriptors from
407  *	@unmap: whether the buffers should be unmapped for DMA
408  *
409  *	Reclaims Tx descriptors that the SGE has indicated it has processed,
410  *	and frees the associated buffers if possible.  Called with the Tx
411  *	queue locked.
412  */
413 inline void cxgb4_reclaim_completed_tx(struct adapter *adap, struct sge_txq *q,
414 					bool unmap)
415 {
416 	int avail = reclaimable(q);
417 
418 	if (avail) {
419 		/*
420 		 * Limit the amount of clean up work we do at a time to keep
421 		 * the Tx lock hold time O(1).
422 		 */
423 		if (avail > MAX_TX_RECLAIM)
424 			avail = MAX_TX_RECLAIM;
425 
426 		free_tx_desc(adap, q, avail, unmap);
427 		q->in_use -= avail;
428 	}
429 }
430 EXPORT_SYMBOL(cxgb4_reclaim_completed_tx);
431 
432 static inline int get_buf_size(struct adapter *adapter,
433 			       const struct rx_sw_desc *d)
434 {
435 	struct sge *s = &adapter->sge;
436 	unsigned int rx_buf_size_idx = d->dma_addr & RX_BUF_SIZE;
437 	int buf_size;
438 
439 	switch (rx_buf_size_idx) {
440 	case RX_SMALL_PG_BUF:
441 		buf_size = PAGE_SIZE;
442 		break;
443 
444 	case RX_LARGE_PG_BUF:
445 		buf_size = PAGE_SIZE << s->fl_pg_order;
446 		break;
447 
448 	case RX_SMALL_MTU_BUF:
449 		buf_size = FL_MTU_SMALL_BUFSIZE(adapter);
450 		break;
451 
452 	case RX_LARGE_MTU_BUF:
453 		buf_size = FL_MTU_LARGE_BUFSIZE(adapter);
454 		break;
455 
456 	default:
457 		BUG_ON(1);
458 	}
459 
460 	return buf_size;
461 }
462 
463 /**
464  *	free_rx_bufs - free the Rx buffers on an SGE free list
465  *	@adap: the adapter
466  *	@q: the SGE free list to free buffers from
467  *	@n: how many buffers to free
468  *
469  *	Release the next @n buffers on an SGE free-buffer Rx queue.   The
470  *	buffers must be made inaccessible to HW before calling this function.
471  */
472 static void free_rx_bufs(struct adapter *adap, struct sge_fl *q, int n)
473 {
474 	while (n--) {
475 		struct rx_sw_desc *d = &q->sdesc[q->cidx];
476 
477 		if (is_buf_mapped(d))
478 			dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
479 				       get_buf_size(adap, d),
480 				       PCI_DMA_FROMDEVICE);
481 		put_page(d->page);
482 		d->page = NULL;
483 		if (++q->cidx == q->size)
484 			q->cidx = 0;
485 		q->avail--;
486 	}
487 }
488 
489 /**
490  *	unmap_rx_buf - unmap the current Rx buffer on an SGE free list
491  *	@adap: the adapter
492  *	@q: the SGE free list
493  *
494  *	Unmap the current buffer on an SGE free-buffer Rx queue.   The
495  *	buffer must be made inaccessible to HW before calling this function.
496  *
497  *	This is similar to @free_rx_bufs above but does not free the buffer.
498  *	Do note that the FL still loses any further access to the buffer.
499  */
500 static void unmap_rx_buf(struct adapter *adap, struct sge_fl *q)
501 {
502 	struct rx_sw_desc *d = &q->sdesc[q->cidx];
503 
504 	if (is_buf_mapped(d))
505 		dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
506 			       get_buf_size(adap, d), PCI_DMA_FROMDEVICE);
507 	d->page = NULL;
508 	if (++q->cidx == q->size)
509 		q->cidx = 0;
510 	q->avail--;
511 }
512 
513 static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q)
514 {
515 	if (q->pend_cred >= 8) {
516 		u32 val = adap->params.arch.sge_fl_db;
517 
518 		if (is_t4(adap->params.chip))
519 			val |= PIDX_V(q->pend_cred / 8);
520 		else
521 			val |= PIDX_T5_V(q->pend_cred / 8);
522 
523 		/* Make sure all memory writes to the Free List queue are
524 		 * committed before we tell the hardware about them.
525 		 */
526 		wmb();
527 
528 		/* If we don't have access to the new User Doorbell (T5+), use
529 		 * the old doorbell mechanism; otherwise use the new BAR2
530 		 * mechanism.
531 		 */
532 		if (unlikely(q->bar2_addr == NULL)) {
533 			t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
534 				     val | QID_V(q->cntxt_id));
535 		} else {
536 			writel(val | QID_V(q->bar2_qid),
537 			       q->bar2_addr + SGE_UDB_KDOORBELL);
538 
539 			/* This Write memory Barrier will force the write to
540 			 * the User Doorbell area to be flushed.
541 			 */
542 			wmb();
543 		}
544 		q->pend_cred &= 7;
545 	}
546 }
547 
548 static inline void set_rx_sw_desc(struct rx_sw_desc *sd, struct page *pg,
549 				  dma_addr_t mapping)
550 {
551 	sd->page = pg;
552 	sd->dma_addr = mapping;      /* includes size low bits */
553 }
554 
555 /**
556  *	refill_fl - refill an SGE Rx buffer ring
557  *	@adap: the adapter
558  *	@q: the ring to refill
559  *	@n: the number of new buffers to allocate
560  *	@gfp: the gfp flags for the allocations
561  *
562  *	(Re)populate an SGE free-buffer queue with up to @n new packet buffers,
563  *	allocated with the supplied gfp flags.  The caller must assure that
564  *	@n does not exceed the queue's capacity.  If afterwards the queue is
565  *	found critically low mark it as starving in the bitmap of starving FLs.
566  *
567  *	Returns the number of buffers allocated.
568  */
569 static unsigned int refill_fl(struct adapter *adap, struct sge_fl *q, int n,
570 			      gfp_t gfp)
571 {
572 	struct sge *s = &adap->sge;
573 	struct page *pg;
574 	dma_addr_t mapping;
575 	unsigned int cred = q->avail;
576 	__be64 *d = &q->desc[q->pidx];
577 	struct rx_sw_desc *sd = &q->sdesc[q->pidx];
578 	int node;
579 
580 #ifdef CONFIG_DEBUG_FS
581 	if (test_bit(q->cntxt_id - adap->sge.egr_start, adap->sge.blocked_fl))
582 		goto out;
583 #endif
584 
585 	gfp |= __GFP_NOWARN;
586 	node = dev_to_node(adap->pdev_dev);
587 
588 	if (s->fl_pg_order == 0)
589 		goto alloc_small_pages;
590 
591 	/*
592 	 * Prefer large buffers
593 	 */
594 	while (n) {
595 		pg = alloc_pages_node(node, gfp | __GFP_COMP, s->fl_pg_order);
596 		if (unlikely(!pg)) {
597 			q->large_alloc_failed++;
598 			break;       /* fall back to single pages */
599 		}
600 
601 		mapping = dma_map_page(adap->pdev_dev, pg, 0,
602 				       PAGE_SIZE << s->fl_pg_order,
603 				       PCI_DMA_FROMDEVICE);
604 		if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
605 			__free_pages(pg, s->fl_pg_order);
606 			q->mapping_err++;
607 			goto out;   /* do not try small pages for this error */
608 		}
609 		mapping |= RX_LARGE_PG_BUF;
610 		*d++ = cpu_to_be64(mapping);
611 
612 		set_rx_sw_desc(sd, pg, mapping);
613 		sd++;
614 
615 		q->avail++;
616 		if (++q->pidx == q->size) {
617 			q->pidx = 0;
618 			sd = q->sdesc;
619 			d = q->desc;
620 		}
621 		n--;
622 	}
623 
624 alloc_small_pages:
625 	while (n--) {
626 		pg = alloc_pages_node(node, gfp, 0);
627 		if (unlikely(!pg)) {
628 			q->alloc_failed++;
629 			break;
630 		}
631 
632 		mapping = dma_map_page(adap->pdev_dev, pg, 0, PAGE_SIZE,
633 				       PCI_DMA_FROMDEVICE);
634 		if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
635 			put_page(pg);
636 			q->mapping_err++;
637 			goto out;
638 		}
639 		*d++ = cpu_to_be64(mapping);
640 
641 		set_rx_sw_desc(sd, pg, mapping);
642 		sd++;
643 
644 		q->avail++;
645 		if (++q->pidx == q->size) {
646 			q->pidx = 0;
647 			sd = q->sdesc;
648 			d = q->desc;
649 		}
650 	}
651 
652 out:	cred = q->avail - cred;
653 	q->pend_cred += cred;
654 	ring_fl_db(adap, q);
655 
656 	if (unlikely(fl_starving(adap, q))) {
657 		smp_wmb();
658 		q->low++;
659 		set_bit(q->cntxt_id - adap->sge.egr_start,
660 			adap->sge.starving_fl);
661 	}
662 
663 	return cred;
664 }
665 
666 static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl)
667 {
668 	refill_fl(adap, fl, min(MAX_RX_REFILL, fl_cap(fl) - fl->avail),
669 		  GFP_ATOMIC);
670 }
671 
672 /**
673  *	alloc_ring - allocate resources for an SGE descriptor ring
674  *	@dev: the PCI device's core device
675  *	@nelem: the number of descriptors
676  *	@elem_size: the size of each descriptor
677  *	@sw_size: the size of the SW state associated with each ring element
678  *	@phys: the physical address of the allocated ring
679  *	@metadata: address of the array holding the SW state for the ring
680  *	@stat_size: extra space in HW ring for status information
681  *	@node: preferred node for memory allocations
682  *
683  *	Allocates resources for an SGE descriptor ring, such as Tx queues,
684  *	free buffer lists, or response queues.  Each SGE ring requires
685  *	space for its HW descriptors plus, optionally, space for the SW state
686  *	associated with each HW entry (the metadata).  The function returns
687  *	three values: the virtual address for the HW ring (the return value
688  *	of the function), the bus address of the HW ring, and the address
689  *	of the SW ring.
690  */
691 static void *alloc_ring(struct device *dev, size_t nelem, size_t elem_size,
692 			size_t sw_size, dma_addr_t *phys, void *metadata,
693 			size_t stat_size, int node)
694 {
695 	size_t len = nelem * elem_size + stat_size;
696 	void *s = NULL;
697 	void *p = dma_alloc_coherent(dev, len, phys, GFP_KERNEL);
698 
699 	if (!p)
700 		return NULL;
701 	if (sw_size) {
702 		s = kzalloc_node(nelem * sw_size, GFP_KERNEL, node);
703 
704 		if (!s) {
705 			dma_free_coherent(dev, len, p, *phys);
706 			return NULL;
707 		}
708 	}
709 	if (metadata)
710 		*(void **)metadata = s;
711 	memset(p, 0, len);
712 	return p;
713 }
714 
715 /**
716  *	sgl_len - calculates the size of an SGL of the given capacity
717  *	@n: the number of SGL entries
718  *
719  *	Calculates the number of flits needed for a scatter/gather list that
720  *	can hold the given number of entries.
721  */
722 static inline unsigned int sgl_len(unsigned int n)
723 {
724 	/* A Direct Scatter Gather List uses 32-bit lengths and 64-bit PCI DMA
725 	 * addresses.  The DSGL Work Request starts off with a 32-bit DSGL
726 	 * ULPTX header, then Length0, then Address0, then, for 1 <= i <= N,
727 	 * repeated sequences of { Length[i], Length[i+1], Address[i],
728 	 * Address[i+1] } (this ensures that all addresses are on 64-bit
729 	 * boundaries).  If N is even, then Length[N+1] should be set to 0 and
730 	 * Address[N+1] is omitted.
731 	 *
732 	 * The following calculation incorporates all of the above.  It's
733 	 * somewhat hard to follow but, briefly: the "+2" accounts for the
734 	 * first two flits which include the DSGL header, Length0 and
735 	 * Address0; the "(3*(n-1))/2" covers the main body of list entries (3
736 	 * flits for every pair of the remaining N) +1 if (n-1) is odd; and
737 	 * finally the "+((n-1)&1)" adds the one remaining flit needed if
738 	 * (n-1) is odd ...
739 	 */
740 	n--;
741 	return (3 * n) / 2 + (n & 1) + 2;
742 }
743 
744 /**
745  *	flits_to_desc - returns the num of Tx descriptors for the given flits
746  *	@n: the number of flits
747  *
748  *	Returns the number of Tx descriptors needed for the supplied number
749  *	of flits.
750  */
751 static inline unsigned int flits_to_desc(unsigned int n)
752 {
753 	BUG_ON(n > SGE_MAX_WR_LEN / 8);
754 	return DIV_ROUND_UP(n, 8);
755 }
756 
757 /**
758  *	is_eth_imm - can an Ethernet packet be sent as immediate data?
759  *	@skb: the packet
760  *
761  *	Returns whether an Ethernet packet is small enough to fit as
762  *	immediate data. Return value corresponds to headroom required.
763  */
764 static inline int is_eth_imm(const struct sk_buff *skb, unsigned int chip_ver)
765 {
766 	int hdrlen = 0;
767 
768 	if (skb->encapsulation && skb_shinfo(skb)->gso_size &&
769 	    chip_ver > CHELSIO_T5) {
770 		hdrlen = sizeof(struct cpl_tx_tnl_lso);
771 		hdrlen += sizeof(struct cpl_tx_pkt_core);
772 	} else {
773 		hdrlen = skb_shinfo(skb)->gso_size ?
774 			 sizeof(struct cpl_tx_pkt_lso_core) : 0;
775 		hdrlen += sizeof(struct cpl_tx_pkt);
776 	}
777 	if (skb->len <= MAX_IMM_TX_PKT_LEN - hdrlen)
778 		return hdrlen;
779 	return 0;
780 }
781 
782 /**
783  *	calc_tx_flits - calculate the number of flits for a packet Tx WR
784  *	@skb: the packet
785  *
786  *	Returns the number of flits needed for a Tx WR for the given Ethernet
787  *	packet, including the needed WR and CPL headers.
788  */
789 static inline unsigned int calc_tx_flits(const struct sk_buff *skb,
790 					 unsigned int chip_ver)
791 {
792 	unsigned int flits;
793 	int hdrlen = is_eth_imm(skb, chip_ver);
794 
795 	/* If the skb is small enough, we can pump it out as a work request
796 	 * with only immediate data.  In that case we just have to have the
797 	 * TX Packet header plus the skb data in the Work Request.
798 	 */
799 
800 	if (hdrlen)
801 		return DIV_ROUND_UP(skb->len + hdrlen, sizeof(__be64));
802 
803 	/* Otherwise, we're going to have to construct a Scatter gather list
804 	 * of the skb body and fragments.  We also include the flits necessary
805 	 * for the TX Packet Work Request and CPL.  We always have a firmware
806 	 * Write Header (incorporated as part of the cpl_tx_pkt_lso and
807 	 * cpl_tx_pkt structures), followed by either a TX Packet Write CPL
808 	 * message or, if we're doing a Large Send Offload, an LSO CPL message
809 	 * with an embedded TX Packet Write CPL message.
810 	 */
811 	flits = sgl_len(skb_shinfo(skb)->nr_frags + 1);
812 	if (skb_shinfo(skb)->gso_size) {
813 		if (skb->encapsulation && chip_ver > CHELSIO_T5)
814 			hdrlen = sizeof(struct fw_eth_tx_pkt_wr) +
815 				 sizeof(struct cpl_tx_tnl_lso);
816 		else
817 			hdrlen = sizeof(struct fw_eth_tx_pkt_wr) +
818 				 sizeof(struct cpl_tx_pkt_lso_core);
819 
820 		hdrlen += sizeof(struct cpl_tx_pkt_core);
821 		flits += (hdrlen / sizeof(__be64));
822 	} else {
823 		flits += (sizeof(struct fw_eth_tx_pkt_wr) +
824 			  sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
825 	}
826 	return flits;
827 }
828 
829 /**
830  *	calc_tx_descs - calculate the number of Tx descriptors for a packet
831  *	@skb: the packet
832  *
833  *	Returns the number of Tx descriptors needed for the given Ethernet
834  *	packet, including the needed WR and CPL headers.
835  */
836 static inline unsigned int calc_tx_descs(const struct sk_buff *skb,
837 					 unsigned int chip_ver)
838 {
839 	return flits_to_desc(calc_tx_flits(skb, chip_ver));
840 }
841 
842 /**
843  *	cxgb4_write_sgl - populate a scatter/gather list for a packet
844  *	@skb: the packet
845  *	@q: the Tx queue we are writing into
846  *	@sgl: starting location for writing the SGL
847  *	@end: points right after the end of the SGL
848  *	@start: start offset into skb main-body data to include in the SGL
849  *	@addr: the list of bus addresses for the SGL elements
850  *
851  *	Generates a gather list for the buffers that make up a packet.
852  *	The caller must provide adequate space for the SGL that will be written.
853  *	The SGL includes all of the packet's page fragments and the data in its
854  *	main body except for the first @start bytes.  @sgl must be 16-byte
855  *	aligned and within a Tx descriptor with available space.  @end points
856  *	right after the end of the SGL but does not account for any potential
857  *	wrap around, i.e., @end > @sgl.
858  */
859 void cxgb4_write_sgl(const struct sk_buff *skb, struct sge_txq *q,
860 		     struct ulptx_sgl *sgl, u64 *end, unsigned int start,
861 		     const dma_addr_t *addr)
862 {
863 	unsigned int i, len;
864 	struct ulptx_sge_pair *to;
865 	const struct skb_shared_info *si = skb_shinfo(skb);
866 	unsigned int nfrags = si->nr_frags;
867 	struct ulptx_sge_pair buf[MAX_SKB_FRAGS / 2 + 1];
868 
869 	len = skb_headlen(skb) - start;
870 	if (likely(len)) {
871 		sgl->len0 = htonl(len);
872 		sgl->addr0 = cpu_to_be64(addr[0] + start);
873 		nfrags++;
874 	} else {
875 		sgl->len0 = htonl(skb_frag_size(&si->frags[0]));
876 		sgl->addr0 = cpu_to_be64(addr[1]);
877 	}
878 
879 	sgl->cmd_nsge = htonl(ULPTX_CMD_V(ULP_TX_SC_DSGL) |
880 			      ULPTX_NSGE_V(nfrags));
881 	if (likely(--nfrags == 0))
882 		return;
883 	/*
884 	 * Most of the complexity below deals with the possibility we hit the
885 	 * end of the queue in the middle of writing the SGL.  For this case
886 	 * only we create the SGL in a temporary buffer and then copy it.
887 	 */
888 	to = (u8 *)end > (u8 *)q->stat ? buf : sgl->sge;
889 
890 	for (i = (nfrags != si->nr_frags); nfrags >= 2; nfrags -= 2, to++) {
891 		to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
892 		to->len[1] = cpu_to_be32(skb_frag_size(&si->frags[++i]));
893 		to->addr[0] = cpu_to_be64(addr[i]);
894 		to->addr[1] = cpu_to_be64(addr[++i]);
895 	}
896 	if (nfrags) {
897 		to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
898 		to->len[1] = cpu_to_be32(0);
899 		to->addr[0] = cpu_to_be64(addr[i + 1]);
900 	}
901 	if (unlikely((u8 *)end > (u8 *)q->stat)) {
902 		unsigned int part0 = (u8 *)q->stat - (u8 *)sgl->sge, part1;
903 
904 		if (likely(part0))
905 			memcpy(sgl->sge, buf, part0);
906 		part1 = (u8 *)end - (u8 *)q->stat;
907 		memcpy(q->desc, (u8 *)buf + part0, part1);
908 		end = (void *)q->desc + part1;
909 	}
910 	if ((uintptr_t)end & 8)           /* 0-pad to multiple of 16 */
911 		*end = 0;
912 }
913 EXPORT_SYMBOL(cxgb4_write_sgl);
914 
915 /* This function copies 64 byte coalesced work request to
916  * memory mapped BAR2 space. For coalesced WR SGE fetches
917  * data from the FIFO instead of from Host.
918  */
919 static void cxgb_pio_copy(u64 __iomem *dst, u64 *src)
920 {
921 	int count = 8;
922 
923 	while (count) {
924 		writeq(*src, dst);
925 		src++;
926 		dst++;
927 		count--;
928 	}
929 }
930 
931 /**
932  *	cxgb4_ring_tx_db - check and potentially ring a Tx queue's doorbell
933  *	@adap: the adapter
934  *	@q: the Tx queue
935  *	@n: number of new descriptors to give to HW
936  *
937  *	Ring the doorbel for a Tx queue.
938  */
939 inline void cxgb4_ring_tx_db(struct adapter *adap, struct sge_txq *q, int n)
940 {
941 	/* Make sure that all writes to the TX Descriptors are committed
942 	 * before we tell the hardware about them.
943 	 */
944 	wmb();
945 
946 	/* If we don't have access to the new User Doorbell (T5+), use the old
947 	 * doorbell mechanism; otherwise use the new BAR2 mechanism.
948 	 */
949 	if (unlikely(q->bar2_addr == NULL)) {
950 		u32 val = PIDX_V(n);
951 		unsigned long flags;
952 
953 		/* For T4 we need to participate in the Doorbell Recovery
954 		 * mechanism.
955 		 */
956 		spin_lock_irqsave(&q->db_lock, flags);
957 		if (!q->db_disabled)
958 			t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
959 				     QID_V(q->cntxt_id) | val);
960 		else
961 			q->db_pidx_inc += n;
962 		q->db_pidx = q->pidx;
963 		spin_unlock_irqrestore(&q->db_lock, flags);
964 	} else {
965 		u32 val = PIDX_T5_V(n);
966 
967 		/* T4 and later chips share the same PIDX field offset within
968 		 * the doorbell, but T5 and later shrank the field in order to
969 		 * gain a bit for Doorbell Priority.  The field was absurdly
970 		 * large in the first place (14 bits) so we just use the T5
971 		 * and later limits and warn if a Queue ID is too large.
972 		 */
973 		WARN_ON(val & DBPRIO_F);
974 
975 		/* If we're only writing a single TX Descriptor and we can use
976 		 * Inferred QID registers, we can use the Write Combining
977 		 * Gather Buffer; otherwise we use the simple doorbell.
978 		 */
979 		if (n == 1 && q->bar2_qid == 0) {
980 			int index = (q->pidx
981 				     ? (q->pidx - 1)
982 				     : (q->size - 1));
983 			u64 *wr = (u64 *)&q->desc[index];
984 
985 			cxgb_pio_copy((u64 __iomem *)
986 				      (q->bar2_addr + SGE_UDB_WCDOORBELL),
987 				      wr);
988 		} else {
989 			writel(val | QID_V(q->bar2_qid),
990 			       q->bar2_addr + SGE_UDB_KDOORBELL);
991 		}
992 
993 		/* This Write Memory Barrier will force the write to the User
994 		 * Doorbell area to be flushed.  This is needed to prevent
995 		 * writes on different CPUs for the same queue from hitting
996 		 * the adapter out of order.  This is required when some Work
997 		 * Requests take the Write Combine Gather Buffer path (user
998 		 * doorbell area offset [SGE_UDB_WCDOORBELL..+63]) and some
999 		 * take the traditional path where we simply increment the
1000 		 * PIDX (User Doorbell area SGE_UDB_KDOORBELL) and have the
1001 		 * hardware DMA read the actual Work Request.
1002 		 */
1003 		wmb();
1004 	}
1005 }
1006 EXPORT_SYMBOL(cxgb4_ring_tx_db);
1007 
1008 /**
1009  *	cxgb4_inline_tx_skb - inline a packet's data into Tx descriptors
1010  *	@skb: the packet
1011  *	@q: the Tx queue where the packet will be inlined
1012  *	@pos: starting position in the Tx queue where to inline the packet
1013  *
1014  *	Inline a packet's contents directly into Tx descriptors, starting at
1015  *	the given position within the Tx DMA ring.
1016  *	Most of the complexity of this operation is dealing with wrap arounds
1017  *	in the middle of the packet we want to inline.
1018  */
1019 void cxgb4_inline_tx_skb(const struct sk_buff *skb,
1020 			 const struct sge_txq *q, void *pos)
1021 {
1022 	int left = (void *)q->stat - pos;
1023 	u64 *p;
1024 
1025 	if (likely(skb->len <= left)) {
1026 		if (likely(!skb->data_len))
1027 			skb_copy_from_linear_data(skb, pos, skb->len);
1028 		else
1029 			skb_copy_bits(skb, 0, pos, skb->len);
1030 		pos += skb->len;
1031 	} else {
1032 		skb_copy_bits(skb, 0, pos, left);
1033 		skb_copy_bits(skb, left, q->desc, skb->len - left);
1034 		pos = (void *)q->desc + (skb->len - left);
1035 	}
1036 
1037 	/* 0-pad to multiple of 16 */
1038 	p = PTR_ALIGN(pos, 8);
1039 	if ((uintptr_t)p & 8)
1040 		*p = 0;
1041 }
1042 EXPORT_SYMBOL(cxgb4_inline_tx_skb);
1043 
1044 static void *inline_tx_skb_header(const struct sk_buff *skb,
1045 				  const struct sge_txq *q,  void *pos,
1046 				  int length)
1047 {
1048 	u64 *p;
1049 	int left = (void *)q->stat - pos;
1050 
1051 	if (likely(length <= left)) {
1052 		memcpy(pos, skb->data, length);
1053 		pos += length;
1054 	} else {
1055 		memcpy(pos, skb->data, left);
1056 		memcpy(q->desc, skb->data + left, length - left);
1057 		pos = (void *)q->desc + (length - left);
1058 	}
1059 	/* 0-pad to multiple of 16 */
1060 	p = PTR_ALIGN(pos, 8);
1061 	if ((uintptr_t)p & 8) {
1062 		*p = 0;
1063 		return p + 1;
1064 	}
1065 	return p;
1066 }
1067 
1068 /*
1069  * Figure out what HW csum a packet wants and return the appropriate control
1070  * bits.
1071  */
1072 static u64 hwcsum(enum chip_type chip, const struct sk_buff *skb)
1073 {
1074 	int csum_type;
1075 	const struct iphdr *iph = ip_hdr(skb);
1076 
1077 	if (iph->version == 4) {
1078 		if (iph->protocol == IPPROTO_TCP)
1079 			csum_type = TX_CSUM_TCPIP;
1080 		else if (iph->protocol == IPPROTO_UDP)
1081 			csum_type = TX_CSUM_UDPIP;
1082 		else {
1083 nocsum:			/*
1084 			 * unknown protocol, disable HW csum
1085 			 * and hope a bad packet is detected
1086 			 */
1087 			return TXPKT_L4CSUM_DIS_F;
1088 		}
1089 	} else {
1090 		/*
1091 		 * this doesn't work with extension headers
1092 		 */
1093 		const struct ipv6hdr *ip6h = (const struct ipv6hdr *)iph;
1094 
1095 		if (ip6h->nexthdr == IPPROTO_TCP)
1096 			csum_type = TX_CSUM_TCPIP6;
1097 		else if (ip6h->nexthdr == IPPROTO_UDP)
1098 			csum_type = TX_CSUM_UDPIP6;
1099 		else
1100 			goto nocsum;
1101 	}
1102 
1103 	if (likely(csum_type >= TX_CSUM_TCPIP)) {
1104 		u64 hdr_len = TXPKT_IPHDR_LEN_V(skb_network_header_len(skb));
1105 		int eth_hdr_len = skb_network_offset(skb) - ETH_HLEN;
1106 
1107 		if (CHELSIO_CHIP_VERSION(chip) <= CHELSIO_T5)
1108 			hdr_len |= TXPKT_ETHHDR_LEN_V(eth_hdr_len);
1109 		else
1110 			hdr_len |= T6_TXPKT_ETHHDR_LEN_V(eth_hdr_len);
1111 		return TXPKT_CSUM_TYPE_V(csum_type) | hdr_len;
1112 	} else {
1113 		int start = skb_transport_offset(skb);
1114 
1115 		return TXPKT_CSUM_TYPE_V(csum_type) |
1116 			TXPKT_CSUM_START_V(start) |
1117 			TXPKT_CSUM_LOC_V(start + skb->csum_offset);
1118 	}
1119 }
1120 
1121 static void eth_txq_stop(struct sge_eth_txq *q)
1122 {
1123 	netif_tx_stop_queue(q->txq);
1124 	q->q.stops++;
1125 }
1126 
1127 static inline void txq_advance(struct sge_txq *q, unsigned int n)
1128 {
1129 	q->in_use += n;
1130 	q->pidx += n;
1131 	if (q->pidx >= q->size)
1132 		q->pidx -= q->size;
1133 }
1134 
1135 #ifdef CONFIG_CHELSIO_T4_FCOE
1136 static inline int
1137 cxgb_fcoe_offload(struct sk_buff *skb, struct adapter *adap,
1138 		  const struct port_info *pi, u64 *cntrl)
1139 {
1140 	const struct cxgb_fcoe *fcoe = &pi->fcoe;
1141 
1142 	if (!(fcoe->flags & CXGB_FCOE_ENABLED))
1143 		return 0;
1144 
1145 	if (skb->protocol != htons(ETH_P_FCOE))
1146 		return 0;
1147 
1148 	skb_reset_mac_header(skb);
1149 	skb->mac_len = sizeof(struct ethhdr);
1150 
1151 	skb_set_network_header(skb, skb->mac_len);
1152 	skb_set_transport_header(skb, skb->mac_len + sizeof(struct fcoe_hdr));
1153 
1154 	if (!cxgb_fcoe_sof_eof_supported(adap, skb))
1155 		return -ENOTSUPP;
1156 
1157 	/* FC CRC offload */
1158 	*cntrl = TXPKT_CSUM_TYPE_V(TX_CSUM_FCOE) |
1159 		     TXPKT_L4CSUM_DIS_F | TXPKT_IPCSUM_DIS_F |
1160 		     TXPKT_CSUM_START_V(CXGB_FCOE_TXPKT_CSUM_START) |
1161 		     TXPKT_CSUM_END_V(CXGB_FCOE_TXPKT_CSUM_END) |
1162 		     TXPKT_CSUM_LOC_V(CXGB_FCOE_TXPKT_CSUM_END);
1163 	return 0;
1164 }
1165 #endif /* CONFIG_CHELSIO_T4_FCOE */
1166 
1167 /* Returns tunnel type if hardware supports offloading of the same.
1168  * It is called only for T5 and onwards.
1169  */
1170 enum cpl_tx_tnl_lso_type cxgb_encap_offload_supported(struct sk_buff *skb)
1171 {
1172 	u8 l4_hdr = 0;
1173 	enum cpl_tx_tnl_lso_type tnl_type = TX_TNL_TYPE_OPAQUE;
1174 	struct port_info *pi = netdev_priv(skb->dev);
1175 	struct adapter *adapter = pi->adapter;
1176 
1177 	if (skb->inner_protocol_type != ENCAP_TYPE_ETHER ||
1178 	    skb->inner_protocol != htons(ETH_P_TEB))
1179 		return tnl_type;
1180 
1181 	switch (vlan_get_protocol(skb)) {
1182 	case htons(ETH_P_IP):
1183 		l4_hdr = ip_hdr(skb)->protocol;
1184 		break;
1185 	case htons(ETH_P_IPV6):
1186 		l4_hdr = ipv6_hdr(skb)->nexthdr;
1187 		break;
1188 	default:
1189 		return tnl_type;
1190 	}
1191 
1192 	switch (l4_hdr) {
1193 	case IPPROTO_UDP:
1194 		if (adapter->vxlan_port == udp_hdr(skb)->dest)
1195 			tnl_type = TX_TNL_TYPE_VXLAN;
1196 		else if (adapter->geneve_port == udp_hdr(skb)->dest)
1197 			tnl_type = TX_TNL_TYPE_GENEVE;
1198 		break;
1199 	default:
1200 		return tnl_type;
1201 	}
1202 
1203 	return tnl_type;
1204 }
1205 
1206 static inline void t6_fill_tnl_lso(struct sk_buff *skb,
1207 				   struct cpl_tx_tnl_lso *tnl_lso,
1208 				   enum cpl_tx_tnl_lso_type tnl_type)
1209 {
1210 	u32 val;
1211 	int in_eth_xtra_len;
1212 	int l3hdr_len = skb_network_header_len(skb);
1213 	int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
1214 	const struct skb_shared_info *ssi = skb_shinfo(skb);
1215 	bool v6 = (ip_hdr(skb)->version == 6);
1216 
1217 	val = CPL_TX_TNL_LSO_OPCODE_V(CPL_TX_TNL_LSO) |
1218 	      CPL_TX_TNL_LSO_FIRST_F |
1219 	      CPL_TX_TNL_LSO_LAST_F |
1220 	      (v6 ? CPL_TX_TNL_LSO_IPV6OUT_F : 0) |
1221 	      CPL_TX_TNL_LSO_ETHHDRLENOUT_V(eth_xtra_len / 4) |
1222 	      CPL_TX_TNL_LSO_IPHDRLENOUT_V(l3hdr_len / 4) |
1223 	      (v6 ? 0 : CPL_TX_TNL_LSO_IPHDRCHKOUT_F) |
1224 	      CPL_TX_TNL_LSO_IPLENSETOUT_F |
1225 	      (v6 ? 0 : CPL_TX_TNL_LSO_IPIDINCOUT_F);
1226 	tnl_lso->op_to_IpIdSplitOut = htonl(val);
1227 
1228 	tnl_lso->IpIdOffsetOut = 0;
1229 
1230 	/* Get the tunnel header length */
1231 	val = skb_inner_mac_header(skb) - skb_mac_header(skb);
1232 	in_eth_xtra_len = skb_inner_network_header(skb) -
1233 			  skb_inner_mac_header(skb) - ETH_HLEN;
1234 
1235 	switch (tnl_type) {
1236 	case TX_TNL_TYPE_VXLAN:
1237 	case TX_TNL_TYPE_GENEVE:
1238 		tnl_lso->UdpLenSetOut_to_TnlHdrLen =
1239 			htons(CPL_TX_TNL_LSO_UDPCHKCLROUT_F |
1240 			CPL_TX_TNL_LSO_UDPLENSETOUT_F);
1241 		break;
1242 	default:
1243 		tnl_lso->UdpLenSetOut_to_TnlHdrLen = 0;
1244 		break;
1245 	}
1246 
1247 	tnl_lso->UdpLenSetOut_to_TnlHdrLen |=
1248 		 htons(CPL_TX_TNL_LSO_TNLHDRLEN_V(val) |
1249 		       CPL_TX_TNL_LSO_TNLTYPE_V(tnl_type));
1250 
1251 	tnl_lso->r1 = 0;
1252 
1253 	val = CPL_TX_TNL_LSO_ETHHDRLEN_V(in_eth_xtra_len / 4) |
1254 	      CPL_TX_TNL_LSO_IPV6_V(inner_ip_hdr(skb)->version == 6) |
1255 	      CPL_TX_TNL_LSO_IPHDRLEN_V(skb_inner_network_header_len(skb) / 4) |
1256 	      CPL_TX_TNL_LSO_TCPHDRLEN_V(inner_tcp_hdrlen(skb) / 4);
1257 	tnl_lso->Flow_to_TcpHdrLen = htonl(val);
1258 
1259 	tnl_lso->IpIdOffset = htons(0);
1260 
1261 	tnl_lso->IpIdSplit_to_Mss = htons(CPL_TX_TNL_LSO_MSS_V(ssi->gso_size));
1262 	tnl_lso->TCPSeqOffset = htonl(0);
1263 	tnl_lso->EthLenOffset_Size = htonl(CPL_TX_TNL_LSO_SIZE_V(skb->len));
1264 }
1265 
1266 /**
1267  *	t4_eth_xmit - add a packet to an Ethernet Tx queue
1268  *	@skb: the packet
1269  *	@dev: the egress net device
1270  *
1271  *	Add a packet to an SGE Ethernet Tx queue.  Runs with softirqs disabled.
1272  */
1273 netdev_tx_t t4_eth_xmit(struct sk_buff *skb, struct net_device *dev)
1274 {
1275 	u32 wr_mid, ctrl0, op;
1276 	u64 cntrl, *end;
1277 	int qidx, credits;
1278 	unsigned int flits, ndesc;
1279 	struct adapter *adap;
1280 	struct sge_eth_txq *q;
1281 	const struct port_info *pi;
1282 	struct fw_eth_tx_pkt_wr *wr;
1283 	struct cpl_tx_pkt_core *cpl;
1284 	const struct skb_shared_info *ssi;
1285 	dma_addr_t addr[MAX_SKB_FRAGS + 1];
1286 	bool immediate = false;
1287 	int len, max_pkt_len;
1288 	bool ptp_enabled = is_ptp_enabled(skb, dev);
1289 	unsigned int chip_ver;
1290 	enum cpl_tx_tnl_lso_type tnl_type = TX_TNL_TYPE_OPAQUE;
1291 
1292 #ifdef CONFIG_CHELSIO_T4_FCOE
1293 	int err;
1294 #endif /* CONFIG_CHELSIO_T4_FCOE */
1295 
1296 	/*
1297 	 * The chip min packet length is 10 octets but play safe and reject
1298 	 * anything shorter than an Ethernet header.
1299 	 */
1300 	if (unlikely(skb->len < ETH_HLEN)) {
1301 out_free:	dev_kfree_skb_any(skb);
1302 		return NETDEV_TX_OK;
1303 	}
1304 
1305 	/* Discard the packet if the length is greater than mtu */
1306 	max_pkt_len = ETH_HLEN + dev->mtu;
1307 	if (skb_vlan_tagged(skb))
1308 		max_pkt_len += VLAN_HLEN;
1309 	if (!skb_shinfo(skb)->gso_size && (unlikely(skb->len > max_pkt_len)))
1310 		goto out_free;
1311 
1312 	pi = netdev_priv(dev);
1313 	adap = pi->adapter;
1314 	ssi = skb_shinfo(skb);
1315 #ifdef CONFIG_CHELSIO_IPSEC_INLINE
1316 	if (xfrm_offload(skb) && !ssi->gso_size)
1317 		return adap->uld[CXGB4_ULD_CRYPTO].tx_handler(skb, dev);
1318 #endif /* CHELSIO_IPSEC_INLINE */
1319 
1320 	qidx = skb_get_queue_mapping(skb);
1321 	if (ptp_enabled) {
1322 		spin_lock(&adap->ptp_lock);
1323 		if (!(adap->ptp_tx_skb)) {
1324 			skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
1325 			adap->ptp_tx_skb = skb_get(skb);
1326 		} else {
1327 			spin_unlock(&adap->ptp_lock);
1328 			goto out_free;
1329 		}
1330 		q = &adap->sge.ptptxq;
1331 	} else {
1332 		q = &adap->sge.ethtxq[qidx + pi->first_qset];
1333 	}
1334 	skb_tx_timestamp(skb);
1335 
1336 	cxgb4_reclaim_completed_tx(adap, &q->q, true);
1337 	cntrl = TXPKT_L4CSUM_DIS_F | TXPKT_IPCSUM_DIS_F;
1338 
1339 #ifdef CONFIG_CHELSIO_T4_FCOE
1340 	err = cxgb_fcoe_offload(skb, adap, pi, &cntrl);
1341 	if (unlikely(err == -ENOTSUPP)) {
1342 		if (ptp_enabled)
1343 			spin_unlock(&adap->ptp_lock);
1344 		goto out_free;
1345 	}
1346 #endif /* CONFIG_CHELSIO_T4_FCOE */
1347 
1348 	chip_ver = CHELSIO_CHIP_VERSION(adap->params.chip);
1349 	flits = calc_tx_flits(skb, chip_ver);
1350 	ndesc = flits_to_desc(flits);
1351 	credits = txq_avail(&q->q) - ndesc;
1352 
1353 	if (unlikely(credits < 0)) {
1354 		eth_txq_stop(q);
1355 		dev_err(adap->pdev_dev,
1356 			"%s: Tx ring %u full while queue awake!\n",
1357 			dev->name, qidx);
1358 		if (ptp_enabled)
1359 			spin_unlock(&adap->ptp_lock);
1360 		return NETDEV_TX_BUSY;
1361 	}
1362 
1363 	if (is_eth_imm(skb, chip_ver))
1364 		immediate = true;
1365 
1366 	if (skb->encapsulation && chip_ver > CHELSIO_T5)
1367 		tnl_type = cxgb_encap_offload_supported(skb);
1368 
1369 	if (!immediate &&
1370 	    unlikely(cxgb4_map_skb(adap->pdev_dev, skb, addr) < 0)) {
1371 		q->mapping_err++;
1372 		if (ptp_enabled)
1373 			spin_unlock(&adap->ptp_lock);
1374 		goto out_free;
1375 	}
1376 
1377 	wr_mid = FW_WR_LEN16_V(DIV_ROUND_UP(flits, 2));
1378 	if (unlikely(credits < ETHTXQ_STOP_THRES)) {
1379 		eth_txq_stop(q);
1380 		wr_mid |= FW_WR_EQUEQ_F | FW_WR_EQUIQ_F;
1381 	}
1382 
1383 	wr = (void *)&q->q.desc[q->q.pidx];
1384 	wr->equiq_to_len16 = htonl(wr_mid);
1385 	wr->r3 = cpu_to_be64(0);
1386 	end = (u64 *)wr + flits;
1387 
1388 	len = immediate ? skb->len : 0;
1389 	if (ssi->gso_size) {
1390 		struct cpl_tx_pkt_lso *lso = (void *)wr;
1391 		bool v6 = (ssi->gso_type & SKB_GSO_TCPV6) != 0;
1392 		int l3hdr_len = skb_network_header_len(skb);
1393 		int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
1394 		struct cpl_tx_tnl_lso *tnl_lso = (void *)(wr + 1);
1395 
1396 		if (tnl_type)
1397 			len += sizeof(*tnl_lso);
1398 		else
1399 			len += sizeof(*lso);
1400 
1401 		wr->op_immdlen = htonl(FW_WR_OP_V(FW_ETH_TX_PKT_WR) |
1402 				       FW_WR_IMMDLEN_V(len));
1403 		if (tnl_type) {
1404 			struct iphdr *iph = ip_hdr(skb);
1405 
1406 			t6_fill_tnl_lso(skb, tnl_lso, tnl_type);
1407 			cpl = (void *)(tnl_lso + 1);
1408 			/* Driver is expected to compute partial checksum that
1409 			 * does not include the IP Total Length.
1410 			 */
1411 			if (iph->version == 4) {
1412 				iph->check = 0;
1413 				iph->tot_len = 0;
1414 				iph->check = (u16)(~ip_fast_csum((u8 *)iph,
1415 								 iph->ihl));
1416 			}
1417 			if (skb->ip_summed == CHECKSUM_PARTIAL)
1418 				cntrl = hwcsum(adap->params.chip, skb);
1419 		} else {
1420 			lso->c.lso_ctrl = htonl(LSO_OPCODE_V(CPL_TX_PKT_LSO) |
1421 					  LSO_FIRST_SLICE_F | LSO_LAST_SLICE_F |
1422 					  LSO_IPV6_V(v6) |
1423 					  LSO_ETHHDR_LEN_V(eth_xtra_len / 4) |
1424 					  LSO_IPHDR_LEN_V(l3hdr_len / 4) |
1425 					  LSO_TCPHDR_LEN_V(tcp_hdr(skb)->doff));
1426 			lso->c.ipid_ofst = htons(0);
1427 			lso->c.mss = htons(ssi->gso_size);
1428 			lso->c.seqno_offset = htonl(0);
1429 			if (is_t4(adap->params.chip))
1430 				lso->c.len = htonl(skb->len);
1431 			else
1432 				lso->c.len =
1433 					htonl(LSO_T5_XFER_SIZE_V(skb->len));
1434 			cpl = (void *)(lso + 1);
1435 
1436 			if (CHELSIO_CHIP_VERSION(adap->params.chip)
1437 			    <= CHELSIO_T5)
1438 				cntrl =	TXPKT_ETHHDR_LEN_V(eth_xtra_len);
1439 			else
1440 				cntrl = T6_TXPKT_ETHHDR_LEN_V(eth_xtra_len);
1441 
1442 			cntrl |= TXPKT_CSUM_TYPE_V(v6 ?
1443 				 TX_CSUM_TCPIP6 : TX_CSUM_TCPIP) |
1444 				 TXPKT_IPHDR_LEN_V(l3hdr_len);
1445 		}
1446 		q->tso++;
1447 		q->tx_cso += ssi->gso_segs;
1448 	} else {
1449 		len += sizeof(*cpl);
1450 		if (ptp_enabled)
1451 			op = FW_PTP_TX_PKT_WR;
1452 		else
1453 			op = FW_ETH_TX_PKT_WR;
1454 		wr->op_immdlen = htonl(FW_WR_OP_V(op) |
1455 				       FW_WR_IMMDLEN_V(len));
1456 		cpl = (void *)(wr + 1);
1457 		if (skb->ip_summed == CHECKSUM_PARTIAL) {
1458 			cntrl = hwcsum(adap->params.chip, skb) |
1459 				TXPKT_IPCSUM_DIS_F;
1460 			q->tx_cso++;
1461 		}
1462 	}
1463 
1464 	if (skb_vlan_tag_present(skb)) {
1465 		q->vlan_ins++;
1466 		cntrl |= TXPKT_VLAN_VLD_F | TXPKT_VLAN_V(skb_vlan_tag_get(skb));
1467 #ifdef CONFIG_CHELSIO_T4_FCOE
1468 		if (skb->protocol == htons(ETH_P_FCOE))
1469 			cntrl |= TXPKT_VLAN_V(
1470 				 ((skb->priority & 0x7) << VLAN_PRIO_SHIFT));
1471 #endif /* CONFIG_CHELSIO_T4_FCOE */
1472 	}
1473 
1474 	ctrl0 = TXPKT_OPCODE_V(CPL_TX_PKT_XT) | TXPKT_INTF_V(pi->tx_chan) |
1475 		TXPKT_PF_V(adap->pf);
1476 	if (ptp_enabled)
1477 		ctrl0 |= TXPKT_TSTAMP_F;
1478 #ifdef CONFIG_CHELSIO_T4_DCB
1479 	if (is_t4(adap->params.chip))
1480 		ctrl0 |= TXPKT_OVLAN_IDX_V(q->dcb_prio);
1481 	else
1482 		ctrl0 |= TXPKT_T5_OVLAN_IDX_V(q->dcb_prio);
1483 #endif
1484 	cpl->ctrl0 = htonl(ctrl0);
1485 	cpl->pack = htons(0);
1486 	cpl->len = htons(skb->len);
1487 	cpl->ctrl1 = cpu_to_be64(cntrl);
1488 
1489 	if (immediate) {
1490 		cxgb4_inline_tx_skb(skb, &q->q, cpl + 1);
1491 		dev_consume_skb_any(skb);
1492 	} else {
1493 		int last_desc;
1494 
1495 		cxgb4_write_sgl(skb, &q->q, (struct ulptx_sgl *)(cpl + 1),
1496 				end, 0, addr);
1497 		skb_orphan(skb);
1498 
1499 		last_desc = q->q.pidx + ndesc - 1;
1500 		if (last_desc >= q->q.size)
1501 			last_desc -= q->q.size;
1502 		q->q.sdesc[last_desc].skb = skb;
1503 		q->q.sdesc[last_desc].sgl = (struct ulptx_sgl *)(cpl + 1);
1504 	}
1505 
1506 	txq_advance(&q->q, ndesc);
1507 
1508 	cxgb4_ring_tx_db(adap, &q->q, ndesc);
1509 	if (ptp_enabled)
1510 		spin_unlock(&adap->ptp_lock);
1511 	return NETDEV_TX_OK;
1512 }
1513 
1514 /**
1515  *	reclaim_completed_tx_imm - reclaim completed control-queue Tx descs
1516  *	@q: the SGE control Tx queue
1517  *
1518  *	This is a variant of cxgb4_reclaim_completed_tx() that is used
1519  *	for Tx queues that send only immediate data (presently just
1520  *	the control queues) and	thus do not have any sk_buffs to release.
1521  */
1522 static inline void reclaim_completed_tx_imm(struct sge_txq *q)
1523 {
1524 	int hw_cidx = ntohs(READ_ONCE(q->stat->cidx));
1525 	int reclaim = hw_cidx - q->cidx;
1526 
1527 	if (reclaim < 0)
1528 		reclaim += q->size;
1529 
1530 	q->in_use -= reclaim;
1531 	q->cidx = hw_cidx;
1532 }
1533 
1534 /**
1535  *	is_imm - check whether a packet can be sent as immediate data
1536  *	@skb: the packet
1537  *
1538  *	Returns true if a packet can be sent as a WR with immediate data.
1539  */
1540 static inline int is_imm(const struct sk_buff *skb)
1541 {
1542 	return skb->len <= MAX_CTRL_WR_LEN;
1543 }
1544 
1545 /**
1546  *	ctrlq_check_stop - check if a control queue is full and should stop
1547  *	@q: the queue
1548  *	@wr: most recent WR written to the queue
1549  *
1550  *	Check if a control queue has become full and should be stopped.
1551  *	We clean up control queue descriptors very lazily, only when we are out.
1552  *	If the queue is still full after reclaiming any completed descriptors
1553  *	we suspend it and have the last WR wake it up.
1554  */
1555 static void ctrlq_check_stop(struct sge_ctrl_txq *q, struct fw_wr_hdr *wr)
1556 {
1557 	reclaim_completed_tx_imm(&q->q);
1558 	if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
1559 		wr->lo |= htonl(FW_WR_EQUEQ_F | FW_WR_EQUIQ_F);
1560 		q->q.stops++;
1561 		q->full = 1;
1562 	}
1563 }
1564 
1565 /**
1566  *	ctrl_xmit - send a packet through an SGE control Tx queue
1567  *	@q: the control queue
1568  *	@skb: the packet
1569  *
1570  *	Send a packet through an SGE control Tx queue.  Packets sent through
1571  *	a control queue must fit entirely as immediate data.
1572  */
1573 static int ctrl_xmit(struct sge_ctrl_txq *q, struct sk_buff *skb)
1574 {
1575 	unsigned int ndesc;
1576 	struct fw_wr_hdr *wr;
1577 
1578 	if (unlikely(!is_imm(skb))) {
1579 		WARN_ON(1);
1580 		dev_kfree_skb(skb);
1581 		return NET_XMIT_DROP;
1582 	}
1583 
1584 	ndesc = DIV_ROUND_UP(skb->len, sizeof(struct tx_desc));
1585 	spin_lock(&q->sendq.lock);
1586 
1587 	if (unlikely(q->full)) {
1588 		skb->priority = ndesc;                  /* save for restart */
1589 		__skb_queue_tail(&q->sendq, skb);
1590 		spin_unlock(&q->sendq.lock);
1591 		return NET_XMIT_CN;
1592 	}
1593 
1594 	wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
1595 	cxgb4_inline_tx_skb(skb, &q->q, wr);
1596 
1597 	txq_advance(&q->q, ndesc);
1598 	if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES))
1599 		ctrlq_check_stop(q, wr);
1600 
1601 	cxgb4_ring_tx_db(q->adap, &q->q, ndesc);
1602 	spin_unlock(&q->sendq.lock);
1603 
1604 	kfree_skb(skb);
1605 	return NET_XMIT_SUCCESS;
1606 }
1607 
1608 /**
1609  *	restart_ctrlq - restart a suspended control queue
1610  *	@data: the control queue to restart
1611  *
1612  *	Resumes transmission on a suspended Tx control queue.
1613  */
1614 static void restart_ctrlq(unsigned long data)
1615 {
1616 	struct sk_buff *skb;
1617 	unsigned int written = 0;
1618 	struct sge_ctrl_txq *q = (struct sge_ctrl_txq *)data;
1619 
1620 	spin_lock(&q->sendq.lock);
1621 	reclaim_completed_tx_imm(&q->q);
1622 	BUG_ON(txq_avail(&q->q) < TXQ_STOP_THRES);  /* q should be empty */
1623 
1624 	while ((skb = __skb_dequeue(&q->sendq)) != NULL) {
1625 		struct fw_wr_hdr *wr;
1626 		unsigned int ndesc = skb->priority;     /* previously saved */
1627 
1628 		written += ndesc;
1629 		/* Write descriptors and free skbs outside the lock to limit
1630 		 * wait times.  q->full is still set so new skbs will be queued.
1631 		 */
1632 		wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
1633 		txq_advance(&q->q, ndesc);
1634 		spin_unlock(&q->sendq.lock);
1635 
1636 		cxgb4_inline_tx_skb(skb, &q->q, wr);
1637 		kfree_skb(skb);
1638 
1639 		if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
1640 			unsigned long old = q->q.stops;
1641 
1642 			ctrlq_check_stop(q, wr);
1643 			if (q->q.stops != old) {          /* suspended anew */
1644 				spin_lock(&q->sendq.lock);
1645 				goto ringdb;
1646 			}
1647 		}
1648 		if (written > 16) {
1649 			cxgb4_ring_tx_db(q->adap, &q->q, written);
1650 			written = 0;
1651 		}
1652 		spin_lock(&q->sendq.lock);
1653 	}
1654 	q->full = 0;
1655 ringdb:
1656 	if (written)
1657 		cxgb4_ring_tx_db(q->adap, &q->q, written);
1658 	spin_unlock(&q->sendq.lock);
1659 }
1660 
1661 /**
1662  *	t4_mgmt_tx - send a management message
1663  *	@adap: the adapter
1664  *	@skb: the packet containing the management message
1665  *
1666  *	Send a management message through control queue 0.
1667  */
1668 int t4_mgmt_tx(struct adapter *adap, struct sk_buff *skb)
1669 {
1670 	int ret;
1671 
1672 	local_bh_disable();
1673 	ret = ctrl_xmit(&adap->sge.ctrlq[0], skb);
1674 	local_bh_enable();
1675 	return ret;
1676 }
1677 
1678 /**
1679  *	is_ofld_imm - check whether a packet can be sent as immediate data
1680  *	@skb: the packet
1681  *
1682  *	Returns true if a packet can be sent as an offload WR with immediate
1683  *	data.  We currently use the same limit as for Ethernet packets.
1684  */
1685 static inline int is_ofld_imm(const struct sk_buff *skb)
1686 {
1687 	struct work_request_hdr *req = (struct work_request_hdr *)skb->data;
1688 	unsigned long opcode = FW_WR_OP_G(ntohl(req->wr_hi));
1689 
1690 	if (opcode == FW_CRYPTO_LOOKASIDE_WR)
1691 		return skb->len <= SGE_MAX_WR_LEN;
1692 	else
1693 		return skb->len <= MAX_IMM_TX_PKT_LEN;
1694 }
1695 
1696 /**
1697  *	calc_tx_flits_ofld - calculate # of flits for an offload packet
1698  *	@skb: the packet
1699  *
1700  *	Returns the number of flits needed for the given offload packet.
1701  *	These packets are already fully constructed and no additional headers
1702  *	will be added.
1703  */
1704 static inline unsigned int calc_tx_flits_ofld(const struct sk_buff *skb)
1705 {
1706 	unsigned int flits, cnt;
1707 
1708 	if (is_ofld_imm(skb))
1709 		return DIV_ROUND_UP(skb->len, 8);
1710 
1711 	flits = skb_transport_offset(skb) / 8U;   /* headers */
1712 	cnt = skb_shinfo(skb)->nr_frags;
1713 	if (skb_tail_pointer(skb) != skb_transport_header(skb))
1714 		cnt++;
1715 	return flits + sgl_len(cnt);
1716 }
1717 
1718 /**
1719  *	txq_stop_maperr - stop a Tx queue due to I/O MMU exhaustion
1720  *	@adap: the adapter
1721  *	@q: the queue to stop
1722  *
1723  *	Mark a Tx queue stopped due to I/O MMU exhaustion and resulting
1724  *	inability to map packets.  A periodic timer attempts to restart
1725  *	queues so marked.
1726  */
1727 static void txq_stop_maperr(struct sge_uld_txq *q)
1728 {
1729 	q->mapping_err++;
1730 	q->q.stops++;
1731 	set_bit(q->q.cntxt_id - q->adap->sge.egr_start,
1732 		q->adap->sge.txq_maperr);
1733 }
1734 
1735 /**
1736  *	ofldtxq_stop - stop an offload Tx queue that has become full
1737  *	@q: the queue to stop
1738  *	@wr: the Work Request causing the queue to become full
1739  *
1740  *	Stops an offload Tx queue that has become full and modifies the packet
1741  *	being written to request a wakeup.
1742  */
1743 static void ofldtxq_stop(struct sge_uld_txq *q, struct fw_wr_hdr *wr)
1744 {
1745 	wr->lo |= htonl(FW_WR_EQUEQ_F | FW_WR_EQUIQ_F);
1746 	q->q.stops++;
1747 	q->full = 1;
1748 }
1749 
1750 /**
1751  *	service_ofldq - service/restart a suspended offload queue
1752  *	@q: the offload queue
1753  *
1754  *	Services an offload Tx queue by moving packets from its Pending Send
1755  *	Queue to the Hardware TX ring.  The function starts and ends with the
1756  *	Send Queue locked, but drops the lock while putting the skb at the
1757  *	head of the Send Queue onto the Hardware TX Ring.  Dropping the lock
1758  *	allows more skbs to be added to the Send Queue by other threads.
1759  *	The packet being processed at the head of the Pending Send Queue is
1760  *	left on the queue in case we experience DMA Mapping errors, etc.
1761  *	and need to give up and restart later.
1762  *
1763  *	service_ofldq() can be thought of as a task which opportunistically
1764  *	uses other threads execution contexts.  We use the Offload Queue
1765  *	boolean "service_ofldq_running" to make sure that only one instance
1766  *	is ever running at a time ...
1767  */
1768 static void service_ofldq(struct sge_uld_txq *q)
1769 {
1770 	u64 *pos, *before, *end;
1771 	int credits;
1772 	struct sk_buff *skb;
1773 	struct sge_txq *txq;
1774 	unsigned int left;
1775 	unsigned int written = 0;
1776 	unsigned int flits, ndesc;
1777 
1778 	/* If another thread is currently in service_ofldq() processing the
1779 	 * Pending Send Queue then there's nothing to do. Otherwise, flag
1780 	 * that we're doing the work and continue.  Examining/modifying
1781 	 * the Offload Queue boolean "service_ofldq_running" must be done
1782 	 * while holding the Pending Send Queue Lock.
1783 	 */
1784 	if (q->service_ofldq_running)
1785 		return;
1786 	q->service_ofldq_running = true;
1787 
1788 	while ((skb = skb_peek(&q->sendq)) != NULL && !q->full) {
1789 		/* We drop the lock while we're working with the skb at the
1790 		 * head of the Pending Send Queue.  This allows more skbs to
1791 		 * be added to the Pending Send Queue while we're working on
1792 		 * this one.  We don't need to lock to guard the TX Ring
1793 		 * updates because only one thread of execution is ever
1794 		 * allowed into service_ofldq() at a time.
1795 		 */
1796 		spin_unlock(&q->sendq.lock);
1797 
1798 		cxgb4_reclaim_completed_tx(q->adap, &q->q, false);
1799 
1800 		flits = skb->priority;                /* previously saved */
1801 		ndesc = flits_to_desc(flits);
1802 		credits = txq_avail(&q->q) - ndesc;
1803 		BUG_ON(credits < 0);
1804 		if (unlikely(credits < TXQ_STOP_THRES))
1805 			ofldtxq_stop(q, (struct fw_wr_hdr *)skb->data);
1806 
1807 		pos = (u64 *)&q->q.desc[q->q.pidx];
1808 		if (is_ofld_imm(skb))
1809 			cxgb4_inline_tx_skb(skb, &q->q, pos);
1810 		else if (cxgb4_map_skb(q->adap->pdev_dev, skb,
1811 				       (dma_addr_t *)skb->head)) {
1812 			txq_stop_maperr(q);
1813 			spin_lock(&q->sendq.lock);
1814 			break;
1815 		} else {
1816 			int last_desc, hdr_len = skb_transport_offset(skb);
1817 
1818 			/* The WR headers  may not fit within one descriptor.
1819 			 * So we need to deal with wrap-around here.
1820 			 */
1821 			before = (u64 *)pos;
1822 			end = (u64 *)pos + flits;
1823 			txq = &q->q;
1824 			pos = (void *)inline_tx_skb_header(skb, &q->q,
1825 							   (void *)pos,
1826 							   hdr_len);
1827 			if (before > (u64 *)pos) {
1828 				left = (u8 *)end - (u8 *)txq->stat;
1829 				end = (void *)txq->desc + left;
1830 			}
1831 
1832 			/* If current position is already at the end of the
1833 			 * ofld queue, reset the current to point to
1834 			 * start of the queue and update the end ptr as well.
1835 			 */
1836 			if (pos == (u64 *)txq->stat) {
1837 				left = (u8 *)end - (u8 *)txq->stat;
1838 				end = (void *)txq->desc + left;
1839 				pos = (void *)txq->desc;
1840 			}
1841 
1842 			cxgb4_write_sgl(skb, &q->q, (void *)pos,
1843 					end, hdr_len,
1844 					(dma_addr_t *)skb->head);
1845 #ifdef CONFIG_NEED_DMA_MAP_STATE
1846 			skb->dev = q->adap->port[0];
1847 			skb->destructor = deferred_unmap_destructor;
1848 #endif
1849 			last_desc = q->q.pidx + ndesc - 1;
1850 			if (last_desc >= q->q.size)
1851 				last_desc -= q->q.size;
1852 			q->q.sdesc[last_desc].skb = skb;
1853 		}
1854 
1855 		txq_advance(&q->q, ndesc);
1856 		written += ndesc;
1857 		if (unlikely(written > 32)) {
1858 			cxgb4_ring_tx_db(q->adap, &q->q, written);
1859 			written = 0;
1860 		}
1861 
1862 		/* Reacquire the Pending Send Queue Lock so we can unlink the
1863 		 * skb we've just successfully transferred to the TX Ring and
1864 		 * loop for the next skb which may be at the head of the
1865 		 * Pending Send Queue.
1866 		 */
1867 		spin_lock(&q->sendq.lock);
1868 		__skb_unlink(skb, &q->sendq);
1869 		if (is_ofld_imm(skb))
1870 			kfree_skb(skb);
1871 	}
1872 	if (likely(written))
1873 		cxgb4_ring_tx_db(q->adap, &q->q, written);
1874 
1875 	/*Indicate that no thread is processing the Pending Send Queue
1876 	 * currently.
1877 	 */
1878 	q->service_ofldq_running = false;
1879 }
1880 
1881 /**
1882  *	ofld_xmit - send a packet through an offload queue
1883  *	@q: the Tx offload queue
1884  *	@skb: the packet
1885  *
1886  *	Send an offload packet through an SGE offload queue.
1887  */
1888 static int ofld_xmit(struct sge_uld_txq *q, struct sk_buff *skb)
1889 {
1890 	skb->priority = calc_tx_flits_ofld(skb);       /* save for restart */
1891 	spin_lock(&q->sendq.lock);
1892 
1893 	/* Queue the new skb onto the Offload Queue's Pending Send Queue.  If
1894 	 * that results in this new skb being the only one on the queue, start
1895 	 * servicing it.  If there are other skbs already on the list, then
1896 	 * either the queue is currently being processed or it's been stopped
1897 	 * for some reason and it'll be restarted at a later time.  Restart
1898 	 * paths are triggered by events like experiencing a DMA Mapping Error
1899 	 * or filling the Hardware TX Ring.
1900 	 */
1901 	__skb_queue_tail(&q->sendq, skb);
1902 	if (q->sendq.qlen == 1)
1903 		service_ofldq(q);
1904 
1905 	spin_unlock(&q->sendq.lock);
1906 	return NET_XMIT_SUCCESS;
1907 }
1908 
1909 /**
1910  *	restart_ofldq - restart a suspended offload queue
1911  *	@data: the offload queue to restart
1912  *
1913  *	Resumes transmission on a suspended Tx offload queue.
1914  */
1915 static void restart_ofldq(unsigned long data)
1916 {
1917 	struct sge_uld_txq *q = (struct sge_uld_txq *)data;
1918 
1919 	spin_lock(&q->sendq.lock);
1920 	q->full = 0;            /* the queue actually is completely empty now */
1921 	service_ofldq(q);
1922 	spin_unlock(&q->sendq.lock);
1923 }
1924 
1925 /**
1926  *	skb_txq - return the Tx queue an offload packet should use
1927  *	@skb: the packet
1928  *
1929  *	Returns the Tx queue an offload packet should use as indicated by bits
1930  *	1-15 in the packet's queue_mapping.
1931  */
1932 static inline unsigned int skb_txq(const struct sk_buff *skb)
1933 {
1934 	return skb->queue_mapping >> 1;
1935 }
1936 
1937 /**
1938  *	is_ctrl_pkt - return whether an offload packet is a control packet
1939  *	@skb: the packet
1940  *
1941  *	Returns whether an offload packet should use an OFLD or a CTRL
1942  *	Tx queue as indicated by bit 0 in the packet's queue_mapping.
1943  */
1944 static inline unsigned int is_ctrl_pkt(const struct sk_buff *skb)
1945 {
1946 	return skb->queue_mapping & 1;
1947 }
1948 
1949 static inline int uld_send(struct adapter *adap, struct sk_buff *skb,
1950 			   unsigned int tx_uld_type)
1951 {
1952 	struct sge_uld_txq_info *txq_info;
1953 	struct sge_uld_txq *txq;
1954 	unsigned int idx = skb_txq(skb);
1955 
1956 	if (unlikely(is_ctrl_pkt(skb))) {
1957 		/* Single ctrl queue is a requirement for LE workaround path */
1958 		if (adap->tids.nsftids)
1959 			idx = 0;
1960 		return ctrl_xmit(&adap->sge.ctrlq[idx], skb);
1961 	}
1962 
1963 	txq_info = adap->sge.uld_txq_info[tx_uld_type];
1964 	if (unlikely(!txq_info)) {
1965 		WARN_ON(true);
1966 		return NET_XMIT_DROP;
1967 	}
1968 
1969 	txq = &txq_info->uldtxq[idx];
1970 	return ofld_xmit(txq, skb);
1971 }
1972 
1973 /**
1974  *	t4_ofld_send - send an offload packet
1975  *	@adap: the adapter
1976  *	@skb: the packet
1977  *
1978  *	Sends an offload packet.  We use the packet queue_mapping to select the
1979  *	appropriate Tx queue as follows: bit 0 indicates whether the packet
1980  *	should be sent as regular or control, bits 1-15 select the queue.
1981  */
1982 int t4_ofld_send(struct adapter *adap, struct sk_buff *skb)
1983 {
1984 	int ret;
1985 
1986 	local_bh_disable();
1987 	ret = uld_send(adap, skb, CXGB4_TX_OFLD);
1988 	local_bh_enable();
1989 	return ret;
1990 }
1991 
1992 /**
1993  *	cxgb4_ofld_send - send an offload packet
1994  *	@dev: the net device
1995  *	@skb: the packet
1996  *
1997  *	Sends an offload packet.  This is an exported version of @t4_ofld_send,
1998  *	intended for ULDs.
1999  */
2000 int cxgb4_ofld_send(struct net_device *dev, struct sk_buff *skb)
2001 {
2002 	return t4_ofld_send(netdev2adap(dev), skb);
2003 }
2004 EXPORT_SYMBOL(cxgb4_ofld_send);
2005 
2006 static void *inline_tx_header(const void *src,
2007 			      const struct sge_txq *q,
2008 			      void *pos, int length)
2009 {
2010 	int left = (void *)q->stat - pos;
2011 	u64 *p;
2012 
2013 	if (likely(length <= left)) {
2014 		memcpy(pos, src, length);
2015 		pos += length;
2016 	} else {
2017 		memcpy(pos, src, left);
2018 		memcpy(q->desc, src + left, length - left);
2019 		pos = (void *)q->desc + (length - left);
2020 	}
2021 	/* 0-pad to multiple of 16 */
2022 	p = PTR_ALIGN(pos, 8);
2023 	if ((uintptr_t)p & 8) {
2024 		*p = 0;
2025 		return p + 1;
2026 	}
2027 	return p;
2028 }
2029 
2030 /**
2031  *      ofld_xmit_direct - copy a WR into offload queue
2032  *      @q: the Tx offload queue
2033  *      @src: location of WR
2034  *      @len: WR length
2035  *
2036  *      Copy an immediate WR into an uncontended SGE offload queue.
2037  */
2038 static int ofld_xmit_direct(struct sge_uld_txq *q, const void *src,
2039 			    unsigned int len)
2040 {
2041 	unsigned int ndesc;
2042 	int credits;
2043 	u64 *pos;
2044 
2045 	/* Use the lower limit as the cut-off */
2046 	if (len > MAX_IMM_OFLD_TX_DATA_WR_LEN) {
2047 		WARN_ON(1);
2048 		return NET_XMIT_DROP;
2049 	}
2050 
2051 	/* Don't return NET_XMIT_CN here as the current
2052 	 * implementation doesn't queue the request
2053 	 * using an skb when the following conditions not met
2054 	 */
2055 	if (!spin_trylock(&q->sendq.lock))
2056 		return NET_XMIT_DROP;
2057 
2058 	if (q->full || !skb_queue_empty(&q->sendq) ||
2059 	    q->service_ofldq_running) {
2060 		spin_unlock(&q->sendq.lock);
2061 		return NET_XMIT_DROP;
2062 	}
2063 	ndesc = flits_to_desc(DIV_ROUND_UP(len, 8));
2064 	credits = txq_avail(&q->q) - ndesc;
2065 	pos = (u64 *)&q->q.desc[q->q.pidx];
2066 
2067 	/* ofldtxq_stop modifies WR header in-situ */
2068 	inline_tx_header(src, &q->q, pos, len);
2069 	if (unlikely(credits < TXQ_STOP_THRES))
2070 		ofldtxq_stop(q, (struct fw_wr_hdr *)pos);
2071 	txq_advance(&q->q, ndesc);
2072 	cxgb4_ring_tx_db(q->adap, &q->q, ndesc);
2073 
2074 	spin_unlock(&q->sendq.lock);
2075 	return NET_XMIT_SUCCESS;
2076 }
2077 
2078 int cxgb4_immdata_send(struct net_device *dev, unsigned int idx,
2079 		       const void *src, unsigned int len)
2080 {
2081 	struct sge_uld_txq_info *txq_info;
2082 	struct sge_uld_txq *txq;
2083 	struct adapter *adap;
2084 	int ret;
2085 
2086 	adap = netdev2adap(dev);
2087 
2088 	local_bh_disable();
2089 	txq_info = adap->sge.uld_txq_info[CXGB4_TX_OFLD];
2090 	if (unlikely(!txq_info)) {
2091 		WARN_ON(true);
2092 		local_bh_enable();
2093 		return NET_XMIT_DROP;
2094 	}
2095 	txq = &txq_info->uldtxq[idx];
2096 
2097 	ret = ofld_xmit_direct(txq, src, len);
2098 	local_bh_enable();
2099 	return net_xmit_eval(ret);
2100 }
2101 EXPORT_SYMBOL(cxgb4_immdata_send);
2102 
2103 /**
2104  *	t4_crypto_send - send crypto packet
2105  *	@adap: the adapter
2106  *	@skb: the packet
2107  *
2108  *	Sends crypto packet.  We use the packet queue_mapping to select the
2109  *	appropriate Tx queue as follows: bit 0 indicates whether the packet
2110  *	should be sent as regular or control, bits 1-15 select the queue.
2111  */
2112 static int t4_crypto_send(struct adapter *adap, struct sk_buff *skb)
2113 {
2114 	int ret;
2115 
2116 	local_bh_disable();
2117 	ret = uld_send(adap, skb, CXGB4_TX_CRYPTO);
2118 	local_bh_enable();
2119 	return ret;
2120 }
2121 
2122 /**
2123  *	cxgb4_crypto_send - send crypto packet
2124  *	@dev: the net device
2125  *	@skb: the packet
2126  *
2127  *	Sends crypto packet.  This is an exported version of @t4_crypto_send,
2128  *	intended for ULDs.
2129  */
2130 int cxgb4_crypto_send(struct net_device *dev, struct sk_buff *skb)
2131 {
2132 	return t4_crypto_send(netdev2adap(dev), skb);
2133 }
2134 EXPORT_SYMBOL(cxgb4_crypto_send);
2135 
2136 static inline void copy_frags(struct sk_buff *skb,
2137 			      const struct pkt_gl *gl, unsigned int offset)
2138 {
2139 	int i;
2140 
2141 	/* usually there's just one frag */
2142 	__skb_fill_page_desc(skb, 0, gl->frags[0].page,
2143 			     gl->frags[0].offset + offset,
2144 			     gl->frags[0].size - offset);
2145 	skb_shinfo(skb)->nr_frags = gl->nfrags;
2146 	for (i = 1; i < gl->nfrags; i++)
2147 		__skb_fill_page_desc(skb, i, gl->frags[i].page,
2148 				     gl->frags[i].offset,
2149 				     gl->frags[i].size);
2150 
2151 	/* get a reference to the last page, we don't own it */
2152 	get_page(gl->frags[gl->nfrags - 1].page);
2153 }
2154 
2155 /**
2156  *	cxgb4_pktgl_to_skb - build an sk_buff from a packet gather list
2157  *	@gl: the gather list
2158  *	@skb_len: size of sk_buff main body if it carries fragments
2159  *	@pull_len: amount of data to move to the sk_buff's main body
2160  *
2161  *	Builds an sk_buff from the given packet gather list.  Returns the
2162  *	sk_buff or %NULL if sk_buff allocation failed.
2163  */
2164 struct sk_buff *cxgb4_pktgl_to_skb(const struct pkt_gl *gl,
2165 				   unsigned int skb_len, unsigned int pull_len)
2166 {
2167 	struct sk_buff *skb;
2168 
2169 	/*
2170 	 * Below we rely on RX_COPY_THRES being less than the smallest Rx buffer
2171 	 * size, which is expected since buffers are at least PAGE_SIZEd.
2172 	 * In this case packets up to RX_COPY_THRES have only one fragment.
2173 	 */
2174 	if (gl->tot_len <= RX_COPY_THRES) {
2175 		skb = dev_alloc_skb(gl->tot_len);
2176 		if (unlikely(!skb))
2177 			goto out;
2178 		__skb_put(skb, gl->tot_len);
2179 		skb_copy_to_linear_data(skb, gl->va, gl->tot_len);
2180 	} else {
2181 		skb = dev_alloc_skb(skb_len);
2182 		if (unlikely(!skb))
2183 			goto out;
2184 		__skb_put(skb, pull_len);
2185 		skb_copy_to_linear_data(skb, gl->va, pull_len);
2186 
2187 		copy_frags(skb, gl, pull_len);
2188 		skb->len = gl->tot_len;
2189 		skb->data_len = skb->len - pull_len;
2190 		skb->truesize += skb->data_len;
2191 	}
2192 out:	return skb;
2193 }
2194 EXPORT_SYMBOL(cxgb4_pktgl_to_skb);
2195 
2196 /**
2197  *	t4_pktgl_free - free a packet gather list
2198  *	@gl: the gather list
2199  *
2200  *	Releases the pages of a packet gather list.  We do not own the last
2201  *	page on the list and do not free it.
2202  */
2203 static void t4_pktgl_free(const struct pkt_gl *gl)
2204 {
2205 	int n;
2206 	const struct page_frag *p;
2207 
2208 	for (p = gl->frags, n = gl->nfrags - 1; n--; p++)
2209 		put_page(p->page);
2210 }
2211 
2212 /*
2213  * Process an MPS trace packet.  Give it an unused protocol number so it won't
2214  * be delivered to anyone and send it to the stack for capture.
2215  */
2216 static noinline int handle_trace_pkt(struct adapter *adap,
2217 				     const struct pkt_gl *gl)
2218 {
2219 	struct sk_buff *skb;
2220 
2221 	skb = cxgb4_pktgl_to_skb(gl, RX_PULL_LEN, RX_PULL_LEN);
2222 	if (unlikely(!skb)) {
2223 		t4_pktgl_free(gl);
2224 		return 0;
2225 	}
2226 
2227 	if (is_t4(adap->params.chip))
2228 		__skb_pull(skb, sizeof(struct cpl_trace_pkt));
2229 	else
2230 		__skb_pull(skb, sizeof(struct cpl_t5_trace_pkt));
2231 
2232 	skb_reset_mac_header(skb);
2233 	skb->protocol = htons(0xffff);
2234 	skb->dev = adap->port[0];
2235 	netif_receive_skb(skb);
2236 	return 0;
2237 }
2238 
2239 /**
2240  * cxgb4_sgetim_to_hwtstamp - convert sge time stamp to hw time stamp
2241  * @adap: the adapter
2242  * @hwtstamps: time stamp structure to update
2243  * @sgetstamp: 60bit iqe timestamp
2244  *
2245  * Every ingress queue entry has the 60-bit timestamp, convert that timestamp
2246  * which is in Core Clock ticks into ktime_t and assign it
2247  **/
2248 static void cxgb4_sgetim_to_hwtstamp(struct adapter *adap,
2249 				     struct skb_shared_hwtstamps *hwtstamps,
2250 				     u64 sgetstamp)
2251 {
2252 	u64 ns;
2253 	u64 tmp = (sgetstamp * 1000 * 1000 + adap->params.vpd.cclk / 2);
2254 
2255 	ns = div_u64(tmp, adap->params.vpd.cclk);
2256 
2257 	memset(hwtstamps, 0, sizeof(*hwtstamps));
2258 	hwtstamps->hwtstamp = ns_to_ktime(ns);
2259 }
2260 
2261 static void do_gro(struct sge_eth_rxq *rxq, const struct pkt_gl *gl,
2262 		   const struct cpl_rx_pkt *pkt)
2263 {
2264 	struct adapter *adapter = rxq->rspq.adap;
2265 	struct sge *s = &adapter->sge;
2266 	struct port_info *pi;
2267 	int ret;
2268 	struct sk_buff *skb;
2269 
2270 	skb = napi_get_frags(&rxq->rspq.napi);
2271 	if (unlikely(!skb)) {
2272 		t4_pktgl_free(gl);
2273 		rxq->stats.rx_drops++;
2274 		return;
2275 	}
2276 
2277 	copy_frags(skb, gl, s->pktshift);
2278 	skb->len = gl->tot_len - s->pktshift;
2279 	skb->data_len = skb->len;
2280 	skb->truesize += skb->data_len;
2281 	skb->ip_summed = CHECKSUM_UNNECESSARY;
2282 	skb_record_rx_queue(skb, rxq->rspq.idx);
2283 	pi = netdev_priv(skb->dev);
2284 	if (pi->rxtstamp)
2285 		cxgb4_sgetim_to_hwtstamp(adapter, skb_hwtstamps(skb),
2286 					 gl->sgetstamp);
2287 	if (rxq->rspq.netdev->features & NETIF_F_RXHASH)
2288 		skb_set_hash(skb, (__force u32)pkt->rsshdr.hash_val,
2289 			     PKT_HASH_TYPE_L3);
2290 
2291 	if (unlikely(pkt->vlan_ex)) {
2292 		__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(pkt->vlan));
2293 		rxq->stats.vlan_ex++;
2294 	}
2295 	ret = napi_gro_frags(&rxq->rspq.napi);
2296 	if (ret == GRO_HELD)
2297 		rxq->stats.lro_pkts++;
2298 	else if (ret == GRO_MERGED || ret == GRO_MERGED_FREE)
2299 		rxq->stats.lro_merged++;
2300 	rxq->stats.pkts++;
2301 	rxq->stats.rx_cso++;
2302 }
2303 
2304 enum {
2305 	RX_NON_PTP_PKT = 0,
2306 	RX_PTP_PKT_SUC = 1,
2307 	RX_PTP_PKT_ERR = 2
2308 };
2309 
2310 /**
2311  *     t4_systim_to_hwstamp - read hardware time stamp
2312  *     @adap: the adapter
2313  *     @skb: the packet
2314  *
2315  *     Read Time Stamp from MPS packet and insert in skb which
2316  *     is forwarded to PTP application
2317  */
2318 static noinline int t4_systim_to_hwstamp(struct adapter *adapter,
2319 					 struct sk_buff *skb)
2320 {
2321 	struct skb_shared_hwtstamps *hwtstamps;
2322 	struct cpl_rx_mps_pkt *cpl = NULL;
2323 	unsigned char *data;
2324 	int offset;
2325 
2326 	cpl = (struct cpl_rx_mps_pkt *)skb->data;
2327 	if (!(CPL_RX_MPS_PKT_TYPE_G(ntohl(cpl->op_to_r1_hi)) &
2328 	     X_CPL_RX_MPS_PKT_TYPE_PTP))
2329 		return RX_PTP_PKT_ERR;
2330 
2331 	data = skb->data + sizeof(*cpl);
2332 	skb_pull(skb, 2 * sizeof(u64) + sizeof(struct cpl_rx_mps_pkt));
2333 	offset = ETH_HLEN + IPV4_HLEN(skb->data) + UDP_HLEN;
2334 	if (skb->len < offset + OFF_PTP_SEQUENCE_ID + sizeof(short))
2335 		return RX_PTP_PKT_ERR;
2336 
2337 	hwtstamps = skb_hwtstamps(skb);
2338 	memset(hwtstamps, 0, sizeof(*hwtstamps));
2339 	hwtstamps->hwtstamp = ns_to_ktime(be64_to_cpu(*((u64 *)data)));
2340 
2341 	return RX_PTP_PKT_SUC;
2342 }
2343 
2344 /**
2345  *     t4_rx_hststamp - Recv PTP Event Message
2346  *     @adap: the adapter
2347  *     @rsp: the response queue descriptor holding the RX_PKT message
2348  *     @skb: the packet
2349  *
2350  *     PTP enabled and MPS packet, read HW timestamp
2351  */
2352 static int t4_rx_hststamp(struct adapter *adapter, const __be64 *rsp,
2353 			  struct sge_eth_rxq *rxq, struct sk_buff *skb)
2354 {
2355 	int ret;
2356 
2357 	if (unlikely((*(u8 *)rsp == CPL_RX_MPS_PKT) &&
2358 		     !is_t4(adapter->params.chip))) {
2359 		ret = t4_systim_to_hwstamp(adapter, skb);
2360 		if (ret == RX_PTP_PKT_ERR) {
2361 			kfree_skb(skb);
2362 			rxq->stats.rx_drops++;
2363 		}
2364 		return ret;
2365 	}
2366 	return RX_NON_PTP_PKT;
2367 }
2368 
2369 /**
2370  *      t4_tx_hststamp - Loopback PTP Transmit Event Message
2371  *      @adap: the adapter
2372  *      @skb: the packet
2373  *      @dev: the ingress net device
2374  *
2375  *      Read hardware timestamp for the loopback PTP Tx event message
2376  */
2377 static int t4_tx_hststamp(struct adapter *adapter, struct sk_buff *skb,
2378 			  struct net_device *dev)
2379 {
2380 	struct port_info *pi = netdev_priv(dev);
2381 
2382 	if (!is_t4(adapter->params.chip) && adapter->ptp_tx_skb) {
2383 		cxgb4_ptp_read_hwstamp(adapter, pi);
2384 		kfree_skb(skb);
2385 		return 0;
2386 	}
2387 	return 1;
2388 }
2389 
2390 /**
2391  *	t4_ethrx_handler - process an ingress ethernet packet
2392  *	@q: the response queue that received the packet
2393  *	@rsp: the response queue descriptor holding the RX_PKT message
2394  *	@si: the gather list of packet fragments
2395  *
2396  *	Process an ingress ethernet packet and deliver it to the stack.
2397  */
2398 int t4_ethrx_handler(struct sge_rspq *q, const __be64 *rsp,
2399 		     const struct pkt_gl *si)
2400 {
2401 	bool csum_ok;
2402 	struct sk_buff *skb;
2403 	const struct cpl_rx_pkt *pkt;
2404 	struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
2405 	struct adapter *adapter = q->adap;
2406 	struct sge *s = &q->adap->sge;
2407 	int cpl_trace_pkt = is_t4(q->adap->params.chip) ?
2408 			    CPL_TRACE_PKT : CPL_TRACE_PKT_T5;
2409 	u16 err_vec;
2410 	struct port_info *pi;
2411 	int ret = 0;
2412 
2413 	if (unlikely(*(u8 *)rsp == cpl_trace_pkt))
2414 		return handle_trace_pkt(q->adap, si);
2415 
2416 	pkt = (const struct cpl_rx_pkt *)rsp;
2417 	/* Compressed error vector is enabled for T6 only */
2418 	if (q->adap->params.tp.rx_pkt_encap)
2419 		err_vec = T6_COMPR_RXERR_VEC_G(be16_to_cpu(pkt->err_vec));
2420 	else
2421 		err_vec = be16_to_cpu(pkt->err_vec);
2422 
2423 	csum_ok = pkt->csum_calc && !err_vec &&
2424 		  (q->netdev->features & NETIF_F_RXCSUM);
2425 	if ((pkt->l2info & htonl(RXF_TCP_F)) &&
2426 	    (q->netdev->features & NETIF_F_GRO) && csum_ok && !pkt->ip_frag) {
2427 		do_gro(rxq, si, pkt);
2428 		return 0;
2429 	}
2430 
2431 	skb = cxgb4_pktgl_to_skb(si, RX_PKT_SKB_LEN, RX_PULL_LEN);
2432 	if (unlikely(!skb)) {
2433 		t4_pktgl_free(si);
2434 		rxq->stats.rx_drops++;
2435 		return 0;
2436 	}
2437 	pi = netdev_priv(q->netdev);
2438 
2439 	/* Handle PTP Event Rx packet */
2440 	if (unlikely(pi->ptp_enable)) {
2441 		ret = t4_rx_hststamp(adapter, rsp, rxq, skb);
2442 		if (ret == RX_PTP_PKT_ERR)
2443 			return 0;
2444 	}
2445 	if (likely(!ret))
2446 		__skb_pull(skb, s->pktshift); /* remove ethernet header pad */
2447 
2448 	/* Handle the PTP Event Tx Loopback packet */
2449 	if (unlikely(pi->ptp_enable && !ret &&
2450 		     (pkt->l2info & htonl(RXF_UDP_F)) &&
2451 		     cxgb4_ptp_is_ptp_rx(skb))) {
2452 		if (!t4_tx_hststamp(adapter, skb, q->netdev))
2453 			return 0;
2454 	}
2455 
2456 	skb->protocol = eth_type_trans(skb, q->netdev);
2457 	skb_record_rx_queue(skb, q->idx);
2458 	if (skb->dev->features & NETIF_F_RXHASH)
2459 		skb_set_hash(skb, (__force u32)pkt->rsshdr.hash_val,
2460 			     PKT_HASH_TYPE_L3);
2461 
2462 	rxq->stats.pkts++;
2463 
2464 	if (pi->rxtstamp)
2465 		cxgb4_sgetim_to_hwtstamp(q->adap, skb_hwtstamps(skb),
2466 					 si->sgetstamp);
2467 	if (csum_ok && (pkt->l2info & htonl(RXF_UDP_F | RXF_TCP_F))) {
2468 		if (!pkt->ip_frag) {
2469 			skb->ip_summed = CHECKSUM_UNNECESSARY;
2470 			rxq->stats.rx_cso++;
2471 		} else if (pkt->l2info & htonl(RXF_IP_F)) {
2472 			__sum16 c = (__force __sum16)pkt->csum;
2473 			skb->csum = csum_unfold(c);
2474 			skb->ip_summed = CHECKSUM_COMPLETE;
2475 			rxq->stats.rx_cso++;
2476 		}
2477 	} else {
2478 		skb_checksum_none_assert(skb);
2479 #ifdef CONFIG_CHELSIO_T4_FCOE
2480 #define CPL_RX_PKT_FLAGS (RXF_PSH_F | RXF_SYN_F | RXF_UDP_F | \
2481 			  RXF_TCP_F | RXF_IP_F | RXF_IP6_F | RXF_LRO_F)
2482 
2483 		if (!(pkt->l2info & cpu_to_be32(CPL_RX_PKT_FLAGS))) {
2484 			if ((pkt->l2info & cpu_to_be32(RXF_FCOE_F)) &&
2485 			    (pi->fcoe.flags & CXGB_FCOE_ENABLED)) {
2486 				if (q->adap->params.tp.rx_pkt_encap)
2487 					csum_ok = err_vec &
2488 						  T6_COMPR_RXERR_SUM_F;
2489 				else
2490 					csum_ok = err_vec & RXERR_CSUM_F;
2491 				if (!csum_ok)
2492 					skb->ip_summed = CHECKSUM_UNNECESSARY;
2493 			}
2494 		}
2495 
2496 #undef CPL_RX_PKT_FLAGS
2497 #endif /* CONFIG_CHELSIO_T4_FCOE */
2498 	}
2499 
2500 	if (unlikely(pkt->vlan_ex)) {
2501 		__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(pkt->vlan));
2502 		rxq->stats.vlan_ex++;
2503 	}
2504 	skb_mark_napi_id(skb, &q->napi);
2505 	netif_receive_skb(skb);
2506 	return 0;
2507 }
2508 
2509 /**
2510  *	restore_rx_bufs - put back a packet's Rx buffers
2511  *	@si: the packet gather list
2512  *	@q: the SGE free list
2513  *	@frags: number of FL buffers to restore
2514  *
2515  *	Puts back on an FL the Rx buffers associated with @si.  The buffers
2516  *	have already been unmapped and are left unmapped, we mark them so to
2517  *	prevent further unmapping attempts.
2518  *
2519  *	This function undoes a series of @unmap_rx_buf calls when we find out
2520  *	that the current packet can't be processed right away afterall and we
2521  *	need to come back to it later.  This is a very rare event and there's
2522  *	no effort to make this particularly efficient.
2523  */
2524 static void restore_rx_bufs(const struct pkt_gl *si, struct sge_fl *q,
2525 			    int frags)
2526 {
2527 	struct rx_sw_desc *d;
2528 
2529 	while (frags--) {
2530 		if (q->cidx == 0)
2531 			q->cidx = q->size - 1;
2532 		else
2533 			q->cidx--;
2534 		d = &q->sdesc[q->cidx];
2535 		d->page = si->frags[frags].page;
2536 		d->dma_addr |= RX_UNMAPPED_BUF;
2537 		q->avail++;
2538 	}
2539 }
2540 
2541 /**
2542  *	is_new_response - check if a response is newly written
2543  *	@r: the response descriptor
2544  *	@q: the response queue
2545  *
2546  *	Returns true if a response descriptor contains a yet unprocessed
2547  *	response.
2548  */
2549 static inline bool is_new_response(const struct rsp_ctrl *r,
2550 				   const struct sge_rspq *q)
2551 {
2552 	return (r->type_gen >> RSPD_GEN_S) == q->gen;
2553 }
2554 
2555 /**
2556  *	rspq_next - advance to the next entry in a response queue
2557  *	@q: the queue
2558  *
2559  *	Updates the state of a response queue to advance it to the next entry.
2560  */
2561 static inline void rspq_next(struct sge_rspq *q)
2562 {
2563 	q->cur_desc = (void *)q->cur_desc + q->iqe_len;
2564 	if (unlikely(++q->cidx == q->size)) {
2565 		q->cidx = 0;
2566 		q->gen ^= 1;
2567 		q->cur_desc = q->desc;
2568 	}
2569 }
2570 
2571 /**
2572  *	process_responses - process responses from an SGE response queue
2573  *	@q: the ingress queue to process
2574  *	@budget: how many responses can be processed in this round
2575  *
2576  *	Process responses from an SGE response queue up to the supplied budget.
2577  *	Responses include received packets as well as control messages from FW
2578  *	or HW.
2579  *
2580  *	Additionally choose the interrupt holdoff time for the next interrupt
2581  *	on this queue.  If the system is under memory shortage use a fairly
2582  *	long delay to help recovery.
2583  */
2584 static int process_responses(struct sge_rspq *q, int budget)
2585 {
2586 	int ret, rsp_type;
2587 	int budget_left = budget;
2588 	const struct rsp_ctrl *rc;
2589 	struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
2590 	struct adapter *adapter = q->adap;
2591 	struct sge *s = &adapter->sge;
2592 
2593 	while (likely(budget_left)) {
2594 		rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
2595 		if (!is_new_response(rc, q)) {
2596 			if (q->flush_handler)
2597 				q->flush_handler(q);
2598 			break;
2599 		}
2600 
2601 		dma_rmb();
2602 		rsp_type = RSPD_TYPE_G(rc->type_gen);
2603 		if (likely(rsp_type == RSPD_TYPE_FLBUF_X)) {
2604 			struct page_frag *fp;
2605 			struct pkt_gl si;
2606 			const struct rx_sw_desc *rsd;
2607 			u32 len = ntohl(rc->pldbuflen_qid), bufsz, frags;
2608 
2609 			if (len & RSPD_NEWBUF_F) {
2610 				if (likely(q->offset > 0)) {
2611 					free_rx_bufs(q->adap, &rxq->fl, 1);
2612 					q->offset = 0;
2613 				}
2614 				len = RSPD_LEN_G(len);
2615 			}
2616 			si.tot_len = len;
2617 
2618 			/* gather packet fragments */
2619 			for (frags = 0, fp = si.frags; ; frags++, fp++) {
2620 				rsd = &rxq->fl.sdesc[rxq->fl.cidx];
2621 				bufsz = get_buf_size(adapter, rsd);
2622 				fp->page = rsd->page;
2623 				fp->offset = q->offset;
2624 				fp->size = min(bufsz, len);
2625 				len -= fp->size;
2626 				if (!len)
2627 					break;
2628 				unmap_rx_buf(q->adap, &rxq->fl);
2629 			}
2630 
2631 			si.sgetstamp = SGE_TIMESTAMP_G(
2632 					be64_to_cpu(rc->last_flit));
2633 			/*
2634 			 * Last buffer remains mapped so explicitly make it
2635 			 * coherent for CPU access.
2636 			 */
2637 			dma_sync_single_for_cpu(q->adap->pdev_dev,
2638 						get_buf_addr(rsd),
2639 						fp->size, DMA_FROM_DEVICE);
2640 
2641 			si.va = page_address(si.frags[0].page) +
2642 				si.frags[0].offset;
2643 			prefetch(si.va);
2644 
2645 			si.nfrags = frags + 1;
2646 			ret = q->handler(q, q->cur_desc, &si);
2647 			if (likely(ret == 0))
2648 				q->offset += ALIGN(fp->size, s->fl_align);
2649 			else
2650 				restore_rx_bufs(&si, &rxq->fl, frags);
2651 		} else if (likely(rsp_type == RSPD_TYPE_CPL_X)) {
2652 			ret = q->handler(q, q->cur_desc, NULL);
2653 		} else {
2654 			ret = q->handler(q, (const __be64 *)rc, CXGB4_MSG_AN);
2655 		}
2656 
2657 		if (unlikely(ret)) {
2658 			/* couldn't process descriptor, back off for recovery */
2659 			q->next_intr_params = QINTR_TIMER_IDX_V(NOMEM_TMR_IDX);
2660 			break;
2661 		}
2662 
2663 		rspq_next(q);
2664 		budget_left--;
2665 	}
2666 
2667 	if (q->offset >= 0 && fl_cap(&rxq->fl) - rxq->fl.avail >= 16)
2668 		__refill_fl(q->adap, &rxq->fl);
2669 	return budget - budget_left;
2670 }
2671 
2672 /**
2673  *	napi_rx_handler - the NAPI handler for Rx processing
2674  *	@napi: the napi instance
2675  *	@budget: how many packets we can process in this round
2676  *
2677  *	Handler for new data events when using NAPI.  This does not need any
2678  *	locking or protection from interrupts as data interrupts are off at
2679  *	this point and other adapter interrupts do not interfere (the latter
2680  *	in not a concern at all with MSI-X as non-data interrupts then have
2681  *	a separate handler).
2682  */
2683 static int napi_rx_handler(struct napi_struct *napi, int budget)
2684 {
2685 	unsigned int params;
2686 	struct sge_rspq *q = container_of(napi, struct sge_rspq, napi);
2687 	int work_done;
2688 	u32 val;
2689 
2690 	work_done = process_responses(q, budget);
2691 	if (likely(work_done < budget)) {
2692 		int timer_index;
2693 
2694 		napi_complete_done(napi, work_done);
2695 		timer_index = QINTR_TIMER_IDX_G(q->next_intr_params);
2696 
2697 		if (q->adaptive_rx) {
2698 			if (work_done > max(timer_pkt_quota[timer_index],
2699 					    MIN_NAPI_WORK))
2700 				timer_index = (timer_index + 1);
2701 			else
2702 				timer_index = timer_index - 1;
2703 
2704 			timer_index = clamp(timer_index, 0, SGE_TIMERREGS - 1);
2705 			q->next_intr_params =
2706 					QINTR_TIMER_IDX_V(timer_index) |
2707 					QINTR_CNT_EN_V(0);
2708 			params = q->next_intr_params;
2709 		} else {
2710 			params = q->next_intr_params;
2711 			q->next_intr_params = q->intr_params;
2712 		}
2713 	} else
2714 		params = QINTR_TIMER_IDX_V(7);
2715 
2716 	val = CIDXINC_V(work_done) | SEINTARM_V(params);
2717 
2718 	/* If we don't have access to the new User GTS (T5+), use the old
2719 	 * doorbell mechanism; otherwise use the new BAR2 mechanism.
2720 	 */
2721 	if (unlikely(q->bar2_addr == NULL)) {
2722 		t4_write_reg(q->adap, MYPF_REG(SGE_PF_GTS_A),
2723 			     val | INGRESSQID_V((u32)q->cntxt_id));
2724 	} else {
2725 		writel(val | INGRESSQID_V(q->bar2_qid),
2726 		       q->bar2_addr + SGE_UDB_GTS);
2727 		wmb();
2728 	}
2729 	return work_done;
2730 }
2731 
2732 /*
2733  * The MSI-X interrupt handler for an SGE response queue.
2734  */
2735 irqreturn_t t4_sge_intr_msix(int irq, void *cookie)
2736 {
2737 	struct sge_rspq *q = cookie;
2738 
2739 	napi_schedule(&q->napi);
2740 	return IRQ_HANDLED;
2741 }
2742 
2743 /*
2744  * Process the indirect interrupt entries in the interrupt queue and kick off
2745  * NAPI for each queue that has generated an entry.
2746  */
2747 static unsigned int process_intrq(struct adapter *adap)
2748 {
2749 	unsigned int credits;
2750 	const struct rsp_ctrl *rc;
2751 	struct sge_rspq *q = &adap->sge.intrq;
2752 	u32 val;
2753 
2754 	spin_lock(&adap->sge.intrq_lock);
2755 	for (credits = 0; ; credits++) {
2756 		rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
2757 		if (!is_new_response(rc, q))
2758 			break;
2759 
2760 		dma_rmb();
2761 		if (RSPD_TYPE_G(rc->type_gen) == RSPD_TYPE_INTR_X) {
2762 			unsigned int qid = ntohl(rc->pldbuflen_qid);
2763 
2764 			qid -= adap->sge.ingr_start;
2765 			napi_schedule(&adap->sge.ingr_map[qid]->napi);
2766 		}
2767 
2768 		rspq_next(q);
2769 	}
2770 
2771 	val =  CIDXINC_V(credits) | SEINTARM_V(q->intr_params);
2772 
2773 	/* If we don't have access to the new User GTS (T5+), use the old
2774 	 * doorbell mechanism; otherwise use the new BAR2 mechanism.
2775 	 */
2776 	if (unlikely(q->bar2_addr == NULL)) {
2777 		t4_write_reg(adap, MYPF_REG(SGE_PF_GTS_A),
2778 			     val | INGRESSQID_V(q->cntxt_id));
2779 	} else {
2780 		writel(val | INGRESSQID_V(q->bar2_qid),
2781 		       q->bar2_addr + SGE_UDB_GTS);
2782 		wmb();
2783 	}
2784 	spin_unlock(&adap->sge.intrq_lock);
2785 	return credits;
2786 }
2787 
2788 /*
2789  * The MSI interrupt handler, which handles data events from SGE response queues
2790  * as well as error and other async events as they all use the same MSI vector.
2791  */
2792 static irqreturn_t t4_intr_msi(int irq, void *cookie)
2793 {
2794 	struct adapter *adap = cookie;
2795 
2796 	if (adap->flags & MASTER_PF)
2797 		t4_slow_intr_handler(adap);
2798 	process_intrq(adap);
2799 	return IRQ_HANDLED;
2800 }
2801 
2802 /*
2803  * Interrupt handler for legacy INTx interrupts.
2804  * Handles data events from SGE response queues as well as error and other
2805  * async events as they all use the same interrupt line.
2806  */
2807 static irqreturn_t t4_intr_intx(int irq, void *cookie)
2808 {
2809 	struct adapter *adap = cookie;
2810 
2811 	t4_write_reg(adap, MYPF_REG(PCIE_PF_CLI_A), 0);
2812 	if (((adap->flags & MASTER_PF) && t4_slow_intr_handler(adap)) |
2813 	    process_intrq(adap))
2814 		return IRQ_HANDLED;
2815 	return IRQ_NONE;             /* probably shared interrupt */
2816 }
2817 
2818 /**
2819  *	t4_intr_handler - select the top-level interrupt handler
2820  *	@adap: the adapter
2821  *
2822  *	Selects the top-level interrupt handler based on the type of interrupts
2823  *	(MSI-X, MSI, or INTx).
2824  */
2825 irq_handler_t t4_intr_handler(struct adapter *adap)
2826 {
2827 	if (adap->flags & USING_MSIX)
2828 		return t4_sge_intr_msix;
2829 	if (adap->flags & USING_MSI)
2830 		return t4_intr_msi;
2831 	return t4_intr_intx;
2832 }
2833 
2834 static void sge_rx_timer_cb(struct timer_list *t)
2835 {
2836 	unsigned long m;
2837 	unsigned int i;
2838 	struct adapter *adap = from_timer(adap, t, sge.rx_timer);
2839 	struct sge *s = &adap->sge;
2840 
2841 	for (i = 0; i < BITS_TO_LONGS(s->egr_sz); i++)
2842 		for (m = s->starving_fl[i]; m; m &= m - 1) {
2843 			struct sge_eth_rxq *rxq;
2844 			unsigned int id = __ffs(m) + i * BITS_PER_LONG;
2845 			struct sge_fl *fl = s->egr_map[id];
2846 
2847 			clear_bit(id, s->starving_fl);
2848 			smp_mb__after_atomic();
2849 
2850 			if (fl_starving(adap, fl)) {
2851 				rxq = container_of(fl, struct sge_eth_rxq, fl);
2852 				if (napi_reschedule(&rxq->rspq.napi))
2853 					fl->starving++;
2854 				else
2855 					set_bit(id, s->starving_fl);
2856 			}
2857 		}
2858 	/* The remainder of the SGE RX Timer Callback routine is dedicated to
2859 	 * global Master PF activities like checking for chip ingress stalls,
2860 	 * etc.
2861 	 */
2862 	if (!(adap->flags & MASTER_PF))
2863 		goto done;
2864 
2865 	t4_idma_monitor(adap, &s->idma_monitor, HZ, RX_QCHECK_PERIOD);
2866 
2867 done:
2868 	mod_timer(&s->rx_timer, jiffies + RX_QCHECK_PERIOD);
2869 }
2870 
2871 static void sge_tx_timer_cb(struct timer_list *t)
2872 {
2873 	unsigned long m;
2874 	unsigned int i, budget;
2875 	struct adapter *adap = from_timer(adap, t, sge.tx_timer);
2876 	struct sge *s = &adap->sge;
2877 
2878 	for (i = 0; i < BITS_TO_LONGS(s->egr_sz); i++)
2879 		for (m = s->txq_maperr[i]; m; m &= m - 1) {
2880 			unsigned long id = __ffs(m) + i * BITS_PER_LONG;
2881 			struct sge_uld_txq *txq = s->egr_map[id];
2882 
2883 			clear_bit(id, s->txq_maperr);
2884 			tasklet_schedule(&txq->qresume_tsk);
2885 		}
2886 
2887 	if (!is_t4(adap->params.chip)) {
2888 		struct sge_eth_txq *q = &s->ptptxq;
2889 		int avail;
2890 
2891 		spin_lock(&adap->ptp_lock);
2892 		avail = reclaimable(&q->q);
2893 
2894 		if (avail) {
2895 			free_tx_desc(adap, &q->q, avail, false);
2896 			q->q.in_use -= avail;
2897 		}
2898 		spin_unlock(&adap->ptp_lock);
2899 	}
2900 
2901 	budget = MAX_TIMER_TX_RECLAIM;
2902 	i = s->ethtxq_rover;
2903 	do {
2904 		struct sge_eth_txq *q = &s->ethtxq[i];
2905 
2906 		if (q->q.in_use &&
2907 		    time_after_eq(jiffies, q->txq->trans_start + HZ / 100) &&
2908 		    __netif_tx_trylock(q->txq)) {
2909 			int avail = reclaimable(&q->q);
2910 
2911 			if (avail) {
2912 				if (avail > budget)
2913 					avail = budget;
2914 
2915 				free_tx_desc(adap, &q->q, avail, true);
2916 				q->q.in_use -= avail;
2917 				budget -= avail;
2918 			}
2919 			__netif_tx_unlock(q->txq);
2920 		}
2921 
2922 		if (++i >= s->ethqsets)
2923 			i = 0;
2924 	} while (budget && i != s->ethtxq_rover);
2925 	s->ethtxq_rover = i;
2926 	mod_timer(&s->tx_timer, jiffies + (budget ? TX_QCHECK_PERIOD : 2));
2927 }
2928 
2929 /**
2930  *	bar2_address - return the BAR2 address for an SGE Queue's Registers
2931  *	@adapter: the adapter
2932  *	@qid: the SGE Queue ID
2933  *	@qtype: the SGE Queue Type (Egress or Ingress)
2934  *	@pbar2_qid: BAR2 Queue ID or 0 for Queue ID inferred SGE Queues
2935  *
2936  *	Returns the BAR2 address for the SGE Queue Registers associated with
2937  *	@qid.  If BAR2 SGE Registers aren't available, returns NULL.  Also
2938  *	returns the BAR2 Queue ID to be used with writes to the BAR2 SGE
2939  *	Queue Registers.  If the BAR2 Queue ID is 0, then "Inferred Queue ID"
2940  *	Registers are supported (e.g. the Write Combining Doorbell Buffer).
2941  */
2942 static void __iomem *bar2_address(struct adapter *adapter,
2943 				  unsigned int qid,
2944 				  enum t4_bar2_qtype qtype,
2945 				  unsigned int *pbar2_qid)
2946 {
2947 	u64 bar2_qoffset;
2948 	int ret;
2949 
2950 	ret = t4_bar2_sge_qregs(adapter, qid, qtype, 0,
2951 				&bar2_qoffset, pbar2_qid);
2952 	if (ret)
2953 		return NULL;
2954 
2955 	return adapter->bar2 + bar2_qoffset;
2956 }
2957 
2958 /* @intr_idx: MSI/MSI-X vector if >=0, -(absolute qid + 1) if < 0
2959  * @cong: < 0 -> no congestion feedback, >= 0 -> congestion channel map
2960  */
2961 int t4_sge_alloc_rxq(struct adapter *adap, struct sge_rspq *iq, bool fwevtq,
2962 		     struct net_device *dev, int intr_idx,
2963 		     struct sge_fl *fl, rspq_handler_t hnd,
2964 		     rspq_flush_handler_t flush_hnd, int cong)
2965 {
2966 	int ret, flsz = 0;
2967 	struct fw_iq_cmd c;
2968 	struct sge *s = &adap->sge;
2969 	struct port_info *pi = netdev_priv(dev);
2970 	int relaxed = !(adap->flags & ROOT_NO_RELAXED_ORDERING);
2971 
2972 	/* Size needs to be multiple of 16, including status entry. */
2973 	iq->size = roundup(iq->size, 16);
2974 
2975 	iq->desc = alloc_ring(adap->pdev_dev, iq->size, iq->iqe_len, 0,
2976 			      &iq->phys_addr, NULL, 0,
2977 			      dev_to_node(adap->pdev_dev));
2978 	if (!iq->desc)
2979 		return -ENOMEM;
2980 
2981 	memset(&c, 0, sizeof(c));
2982 	c.op_to_vfn = htonl(FW_CMD_OP_V(FW_IQ_CMD) | FW_CMD_REQUEST_F |
2983 			    FW_CMD_WRITE_F | FW_CMD_EXEC_F |
2984 			    FW_IQ_CMD_PFN_V(adap->pf) | FW_IQ_CMD_VFN_V(0));
2985 	c.alloc_to_len16 = htonl(FW_IQ_CMD_ALLOC_F | FW_IQ_CMD_IQSTART_F |
2986 				 FW_LEN16(c));
2987 	c.type_to_iqandstindex = htonl(FW_IQ_CMD_TYPE_V(FW_IQ_TYPE_FL_INT_CAP) |
2988 		FW_IQ_CMD_IQASYNCH_V(fwevtq) | FW_IQ_CMD_VIID_V(pi->viid) |
2989 		FW_IQ_CMD_IQANDST_V(intr_idx < 0) |
2990 		FW_IQ_CMD_IQANUD_V(UPDATEDELIVERY_INTERRUPT_X) |
2991 		FW_IQ_CMD_IQANDSTINDEX_V(intr_idx >= 0 ? intr_idx :
2992 							-intr_idx - 1));
2993 	c.iqdroprss_to_iqesize = htons(FW_IQ_CMD_IQPCIECH_V(pi->tx_chan) |
2994 		FW_IQ_CMD_IQGTSMODE_F |
2995 		FW_IQ_CMD_IQINTCNTTHRESH_V(iq->pktcnt_idx) |
2996 		FW_IQ_CMD_IQESIZE_V(ilog2(iq->iqe_len) - 4));
2997 	c.iqsize = htons(iq->size);
2998 	c.iqaddr = cpu_to_be64(iq->phys_addr);
2999 	if (cong >= 0)
3000 		c.iqns_to_fl0congen = htonl(FW_IQ_CMD_IQFLINTCONGEN_F);
3001 
3002 	if (fl) {
3003 		enum chip_type chip = CHELSIO_CHIP_VERSION(adap->params.chip);
3004 
3005 		/* Allocate the ring for the hardware free list (with space
3006 		 * for its status page) along with the associated software
3007 		 * descriptor ring.  The free list size needs to be a multiple
3008 		 * of the Egress Queue Unit and at least 2 Egress Units larger
3009 		 * than the SGE's Egress Congrestion Threshold
3010 		 * (fl_starve_thres - 1).
3011 		 */
3012 		if (fl->size < s->fl_starve_thres - 1 + 2 * 8)
3013 			fl->size = s->fl_starve_thres - 1 + 2 * 8;
3014 		fl->size = roundup(fl->size, 8);
3015 		fl->desc = alloc_ring(adap->pdev_dev, fl->size, sizeof(__be64),
3016 				      sizeof(struct rx_sw_desc), &fl->addr,
3017 				      &fl->sdesc, s->stat_len,
3018 				      dev_to_node(adap->pdev_dev));
3019 		if (!fl->desc)
3020 			goto fl_nomem;
3021 
3022 		flsz = fl->size / 8 + s->stat_len / sizeof(struct tx_desc);
3023 		c.iqns_to_fl0congen |= htonl(FW_IQ_CMD_FL0PACKEN_F |
3024 					     FW_IQ_CMD_FL0FETCHRO_V(relaxed) |
3025 					     FW_IQ_CMD_FL0DATARO_V(relaxed) |
3026 					     FW_IQ_CMD_FL0PADEN_F);
3027 		if (cong >= 0)
3028 			c.iqns_to_fl0congen |=
3029 				htonl(FW_IQ_CMD_FL0CNGCHMAP_V(cong) |
3030 				      FW_IQ_CMD_FL0CONGCIF_F |
3031 				      FW_IQ_CMD_FL0CONGEN_F);
3032 		/* In T6, for egress queue type FL there is internal overhead
3033 		 * of 16B for header going into FLM module.  Hence the maximum
3034 		 * allowed burst size is 448 bytes.  For T4/T5, the hardware
3035 		 * doesn't coalesce fetch requests if more than 64 bytes of
3036 		 * Free List pointers are provided, so we use a 128-byte Fetch
3037 		 * Burst Minimum there (T6 implements coalescing so we can use
3038 		 * the smaller 64-byte value there).
3039 		 */
3040 		c.fl0dcaen_to_fl0cidxfthresh =
3041 			htons(FW_IQ_CMD_FL0FBMIN_V(chip <= CHELSIO_T5 ?
3042 						   FETCHBURSTMIN_128B_X :
3043 						   FETCHBURSTMIN_64B_X) |
3044 			      FW_IQ_CMD_FL0FBMAX_V((chip <= CHELSIO_T5) ?
3045 						   FETCHBURSTMAX_512B_X :
3046 						   FETCHBURSTMAX_256B_X));
3047 		c.fl0size = htons(flsz);
3048 		c.fl0addr = cpu_to_be64(fl->addr);
3049 	}
3050 
3051 	ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
3052 	if (ret)
3053 		goto err;
3054 
3055 	netif_napi_add(dev, &iq->napi, napi_rx_handler, 64);
3056 	iq->cur_desc = iq->desc;
3057 	iq->cidx = 0;
3058 	iq->gen = 1;
3059 	iq->next_intr_params = iq->intr_params;
3060 	iq->cntxt_id = ntohs(c.iqid);
3061 	iq->abs_id = ntohs(c.physiqid);
3062 	iq->bar2_addr = bar2_address(adap,
3063 				     iq->cntxt_id,
3064 				     T4_BAR2_QTYPE_INGRESS,
3065 				     &iq->bar2_qid);
3066 	iq->size--;                           /* subtract status entry */
3067 	iq->netdev = dev;
3068 	iq->handler = hnd;
3069 	iq->flush_handler = flush_hnd;
3070 
3071 	memset(&iq->lro_mgr, 0, sizeof(struct t4_lro_mgr));
3072 	skb_queue_head_init(&iq->lro_mgr.lroq);
3073 
3074 	/* set offset to -1 to distinguish ingress queues without FL */
3075 	iq->offset = fl ? 0 : -1;
3076 
3077 	adap->sge.ingr_map[iq->cntxt_id - adap->sge.ingr_start] = iq;
3078 
3079 	if (fl) {
3080 		fl->cntxt_id = ntohs(c.fl0id);
3081 		fl->avail = fl->pend_cred = 0;
3082 		fl->pidx = fl->cidx = 0;
3083 		fl->alloc_failed = fl->large_alloc_failed = fl->starving = 0;
3084 		adap->sge.egr_map[fl->cntxt_id - adap->sge.egr_start] = fl;
3085 
3086 		/* Note, we must initialize the BAR2 Free List User Doorbell
3087 		 * information before refilling the Free List!
3088 		 */
3089 		fl->bar2_addr = bar2_address(adap,
3090 					     fl->cntxt_id,
3091 					     T4_BAR2_QTYPE_EGRESS,
3092 					     &fl->bar2_qid);
3093 		refill_fl(adap, fl, fl_cap(fl), GFP_KERNEL);
3094 	}
3095 
3096 	/* For T5 and later we attempt to set up the Congestion Manager values
3097 	 * of the new RX Ethernet Queue.  This should really be handled by
3098 	 * firmware because it's more complex than any host driver wants to
3099 	 * get involved with and it's different per chip and this is almost
3100 	 * certainly wrong.  Firmware would be wrong as well, but it would be
3101 	 * a lot easier to fix in one place ...  For now we do something very
3102 	 * simple (and hopefully less wrong).
3103 	 */
3104 	if (!is_t4(adap->params.chip) && cong >= 0) {
3105 		u32 param, val, ch_map = 0;
3106 		int i;
3107 		u16 cng_ch_bits_log = adap->params.arch.cng_ch_bits_log;
3108 
3109 		param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
3110 			 FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DMAQ_CONM_CTXT) |
3111 			 FW_PARAMS_PARAM_YZ_V(iq->cntxt_id));
3112 		if (cong == 0) {
3113 			val = CONMCTXT_CNGTPMODE_V(CONMCTXT_CNGTPMODE_QUEUE_X);
3114 		} else {
3115 			val =
3116 			    CONMCTXT_CNGTPMODE_V(CONMCTXT_CNGTPMODE_CHANNEL_X);
3117 			for (i = 0; i < 4; i++) {
3118 				if (cong & (1 << i))
3119 					ch_map |= 1 << (i << cng_ch_bits_log);
3120 			}
3121 			val |= CONMCTXT_CNGCHMAP_V(ch_map);
3122 		}
3123 		ret = t4_set_params(adap, adap->mbox, adap->pf, 0, 1,
3124 				    &param, &val);
3125 		if (ret)
3126 			dev_warn(adap->pdev_dev, "Failed to set Congestion"
3127 				 " Manager Context for Ingress Queue %d: %d\n",
3128 				 iq->cntxt_id, -ret);
3129 	}
3130 
3131 	return 0;
3132 
3133 fl_nomem:
3134 	ret = -ENOMEM;
3135 err:
3136 	if (iq->desc) {
3137 		dma_free_coherent(adap->pdev_dev, iq->size * iq->iqe_len,
3138 				  iq->desc, iq->phys_addr);
3139 		iq->desc = NULL;
3140 	}
3141 	if (fl && fl->desc) {
3142 		kfree(fl->sdesc);
3143 		fl->sdesc = NULL;
3144 		dma_free_coherent(adap->pdev_dev, flsz * sizeof(struct tx_desc),
3145 				  fl->desc, fl->addr);
3146 		fl->desc = NULL;
3147 	}
3148 	return ret;
3149 }
3150 
3151 static void init_txq(struct adapter *adap, struct sge_txq *q, unsigned int id)
3152 {
3153 	q->cntxt_id = id;
3154 	q->bar2_addr = bar2_address(adap,
3155 				    q->cntxt_id,
3156 				    T4_BAR2_QTYPE_EGRESS,
3157 				    &q->bar2_qid);
3158 	q->in_use = 0;
3159 	q->cidx = q->pidx = 0;
3160 	q->stops = q->restarts = 0;
3161 	q->stat = (void *)&q->desc[q->size];
3162 	spin_lock_init(&q->db_lock);
3163 	adap->sge.egr_map[id - adap->sge.egr_start] = q;
3164 }
3165 
3166 int t4_sge_alloc_eth_txq(struct adapter *adap, struct sge_eth_txq *txq,
3167 			 struct net_device *dev, struct netdev_queue *netdevq,
3168 			 unsigned int iqid)
3169 {
3170 	int ret, nentries;
3171 	struct fw_eq_eth_cmd c;
3172 	struct sge *s = &adap->sge;
3173 	struct port_info *pi = netdev_priv(dev);
3174 
3175 	/* Add status entries */
3176 	nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
3177 
3178 	txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
3179 			sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
3180 			&txq->q.phys_addr, &txq->q.sdesc, s->stat_len,
3181 			netdev_queue_numa_node_read(netdevq));
3182 	if (!txq->q.desc)
3183 		return -ENOMEM;
3184 
3185 	memset(&c, 0, sizeof(c));
3186 	c.op_to_vfn = htonl(FW_CMD_OP_V(FW_EQ_ETH_CMD) | FW_CMD_REQUEST_F |
3187 			    FW_CMD_WRITE_F | FW_CMD_EXEC_F |
3188 			    FW_EQ_ETH_CMD_PFN_V(adap->pf) |
3189 			    FW_EQ_ETH_CMD_VFN_V(0));
3190 	c.alloc_to_len16 = htonl(FW_EQ_ETH_CMD_ALLOC_F |
3191 				 FW_EQ_ETH_CMD_EQSTART_F | FW_LEN16(c));
3192 	c.viid_pkd = htonl(FW_EQ_ETH_CMD_AUTOEQUEQE_F |
3193 			   FW_EQ_ETH_CMD_VIID_V(pi->viid));
3194 	c.fetchszm_to_iqid =
3195 		htonl(FW_EQ_ETH_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
3196 		      FW_EQ_ETH_CMD_PCIECHN_V(pi->tx_chan) |
3197 		      FW_EQ_ETH_CMD_FETCHRO_F | FW_EQ_ETH_CMD_IQID_V(iqid));
3198 	c.dcaen_to_eqsize =
3199 		htonl(FW_EQ_ETH_CMD_FBMIN_V(FETCHBURSTMIN_64B_X) |
3200 		      FW_EQ_ETH_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
3201 		      FW_EQ_ETH_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
3202 		      FW_EQ_ETH_CMD_EQSIZE_V(nentries));
3203 	c.eqaddr = cpu_to_be64(txq->q.phys_addr);
3204 
3205 	ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
3206 	if (ret) {
3207 		kfree(txq->q.sdesc);
3208 		txq->q.sdesc = NULL;
3209 		dma_free_coherent(adap->pdev_dev,
3210 				  nentries * sizeof(struct tx_desc),
3211 				  txq->q.desc, txq->q.phys_addr);
3212 		txq->q.desc = NULL;
3213 		return ret;
3214 	}
3215 
3216 	txq->q.q_type = CXGB4_TXQ_ETH;
3217 	init_txq(adap, &txq->q, FW_EQ_ETH_CMD_EQID_G(ntohl(c.eqid_pkd)));
3218 	txq->txq = netdevq;
3219 	txq->tso = txq->tx_cso = txq->vlan_ins = 0;
3220 	txq->mapping_err = 0;
3221 	return 0;
3222 }
3223 
3224 int t4_sge_alloc_ctrl_txq(struct adapter *adap, struct sge_ctrl_txq *txq,
3225 			  struct net_device *dev, unsigned int iqid,
3226 			  unsigned int cmplqid)
3227 {
3228 	int ret, nentries;
3229 	struct fw_eq_ctrl_cmd c;
3230 	struct sge *s = &adap->sge;
3231 	struct port_info *pi = netdev_priv(dev);
3232 
3233 	/* Add status entries */
3234 	nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
3235 
3236 	txq->q.desc = alloc_ring(adap->pdev_dev, nentries,
3237 				 sizeof(struct tx_desc), 0, &txq->q.phys_addr,
3238 				 NULL, 0, dev_to_node(adap->pdev_dev));
3239 	if (!txq->q.desc)
3240 		return -ENOMEM;
3241 
3242 	c.op_to_vfn = htonl(FW_CMD_OP_V(FW_EQ_CTRL_CMD) | FW_CMD_REQUEST_F |
3243 			    FW_CMD_WRITE_F | FW_CMD_EXEC_F |
3244 			    FW_EQ_CTRL_CMD_PFN_V(adap->pf) |
3245 			    FW_EQ_CTRL_CMD_VFN_V(0));
3246 	c.alloc_to_len16 = htonl(FW_EQ_CTRL_CMD_ALLOC_F |
3247 				 FW_EQ_CTRL_CMD_EQSTART_F | FW_LEN16(c));
3248 	c.cmpliqid_eqid = htonl(FW_EQ_CTRL_CMD_CMPLIQID_V(cmplqid));
3249 	c.physeqid_pkd = htonl(0);
3250 	c.fetchszm_to_iqid =
3251 		htonl(FW_EQ_CTRL_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
3252 		      FW_EQ_CTRL_CMD_PCIECHN_V(pi->tx_chan) |
3253 		      FW_EQ_CTRL_CMD_FETCHRO_F | FW_EQ_CTRL_CMD_IQID_V(iqid));
3254 	c.dcaen_to_eqsize =
3255 		htonl(FW_EQ_CTRL_CMD_FBMIN_V(FETCHBURSTMIN_64B_X) |
3256 		      FW_EQ_CTRL_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
3257 		      FW_EQ_CTRL_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
3258 		      FW_EQ_CTRL_CMD_EQSIZE_V(nentries));
3259 	c.eqaddr = cpu_to_be64(txq->q.phys_addr);
3260 
3261 	ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
3262 	if (ret) {
3263 		dma_free_coherent(adap->pdev_dev,
3264 				  nentries * sizeof(struct tx_desc),
3265 				  txq->q.desc, txq->q.phys_addr);
3266 		txq->q.desc = NULL;
3267 		return ret;
3268 	}
3269 
3270 	txq->q.q_type = CXGB4_TXQ_CTRL;
3271 	init_txq(adap, &txq->q, FW_EQ_CTRL_CMD_EQID_G(ntohl(c.cmpliqid_eqid)));
3272 	txq->adap = adap;
3273 	skb_queue_head_init(&txq->sendq);
3274 	tasklet_init(&txq->qresume_tsk, restart_ctrlq, (unsigned long)txq);
3275 	txq->full = 0;
3276 	return 0;
3277 }
3278 
3279 int t4_sge_mod_ctrl_txq(struct adapter *adap, unsigned int eqid,
3280 			unsigned int cmplqid)
3281 {
3282 	u32 param, val;
3283 
3284 	param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
3285 		 FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DMAQ_EQ_CMPLIQID_CTRL) |
3286 		 FW_PARAMS_PARAM_YZ_V(eqid));
3287 	val = cmplqid;
3288 	return t4_set_params(adap, adap->mbox, adap->pf, 0, 1, &param, &val);
3289 }
3290 
3291 int t4_sge_alloc_uld_txq(struct adapter *adap, struct sge_uld_txq *txq,
3292 			 struct net_device *dev, unsigned int iqid,
3293 			 unsigned int uld_type)
3294 {
3295 	int ret, nentries;
3296 	struct fw_eq_ofld_cmd c;
3297 	struct sge *s = &adap->sge;
3298 	struct port_info *pi = netdev_priv(dev);
3299 	int cmd = FW_EQ_OFLD_CMD;
3300 
3301 	/* Add status entries */
3302 	nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
3303 
3304 	txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
3305 			sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
3306 			&txq->q.phys_addr, &txq->q.sdesc, s->stat_len,
3307 			NUMA_NO_NODE);
3308 	if (!txq->q.desc)
3309 		return -ENOMEM;
3310 
3311 	memset(&c, 0, sizeof(c));
3312 	if (unlikely(uld_type == CXGB4_TX_CRYPTO))
3313 		cmd = FW_EQ_CTRL_CMD;
3314 	c.op_to_vfn = htonl(FW_CMD_OP_V(cmd) | FW_CMD_REQUEST_F |
3315 			    FW_CMD_WRITE_F | FW_CMD_EXEC_F |
3316 			    FW_EQ_OFLD_CMD_PFN_V(adap->pf) |
3317 			    FW_EQ_OFLD_CMD_VFN_V(0));
3318 	c.alloc_to_len16 = htonl(FW_EQ_OFLD_CMD_ALLOC_F |
3319 				 FW_EQ_OFLD_CMD_EQSTART_F | FW_LEN16(c));
3320 	c.fetchszm_to_iqid =
3321 		htonl(FW_EQ_OFLD_CMD_HOSTFCMODE_V(HOSTFCMODE_STATUS_PAGE_X) |
3322 		      FW_EQ_OFLD_CMD_PCIECHN_V(pi->tx_chan) |
3323 		      FW_EQ_OFLD_CMD_FETCHRO_F | FW_EQ_OFLD_CMD_IQID_V(iqid));
3324 	c.dcaen_to_eqsize =
3325 		htonl(FW_EQ_OFLD_CMD_FBMIN_V(FETCHBURSTMIN_64B_X) |
3326 		      FW_EQ_OFLD_CMD_FBMAX_V(FETCHBURSTMAX_512B_X) |
3327 		      FW_EQ_OFLD_CMD_CIDXFTHRESH_V(CIDXFLUSHTHRESH_32_X) |
3328 		      FW_EQ_OFLD_CMD_EQSIZE_V(nentries));
3329 	c.eqaddr = cpu_to_be64(txq->q.phys_addr);
3330 
3331 	ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
3332 	if (ret) {
3333 		kfree(txq->q.sdesc);
3334 		txq->q.sdesc = NULL;
3335 		dma_free_coherent(adap->pdev_dev,
3336 				  nentries * sizeof(struct tx_desc),
3337 				  txq->q.desc, txq->q.phys_addr);
3338 		txq->q.desc = NULL;
3339 		return ret;
3340 	}
3341 
3342 	txq->q.q_type = CXGB4_TXQ_ULD;
3343 	init_txq(adap, &txq->q, FW_EQ_OFLD_CMD_EQID_G(ntohl(c.eqid_pkd)));
3344 	txq->adap = adap;
3345 	skb_queue_head_init(&txq->sendq);
3346 	tasklet_init(&txq->qresume_tsk, restart_ofldq, (unsigned long)txq);
3347 	txq->full = 0;
3348 	txq->mapping_err = 0;
3349 	return 0;
3350 }
3351 
3352 void free_txq(struct adapter *adap, struct sge_txq *q)
3353 {
3354 	struct sge *s = &adap->sge;
3355 
3356 	dma_free_coherent(adap->pdev_dev,
3357 			  q->size * sizeof(struct tx_desc) + s->stat_len,
3358 			  q->desc, q->phys_addr);
3359 	q->cntxt_id = 0;
3360 	q->sdesc = NULL;
3361 	q->desc = NULL;
3362 }
3363 
3364 void free_rspq_fl(struct adapter *adap, struct sge_rspq *rq,
3365 		  struct sge_fl *fl)
3366 {
3367 	struct sge *s = &adap->sge;
3368 	unsigned int fl_id = fl ? fl->cntxt_id : 0xffff;
3369 
3370 	adap->sge.ingr_map[rq->cntxt_id - adap->sge.ingr_start] = NULL;
3371 	t4_iq_free(adap, adap->mbox, adap->pf, 0, FW_IQ_TYPE_FL_INT_CAP,
3372 		   rq->cntxt_id, fl_id, 0xffff);
3373 	dma_free_coherent(adap->pdev_dev, (rq->size + 1) * rq->iqe_len,
3374 			  rq->desc, rq->phys_addr);
3375 	netif_napi_del(&rq->napi);
3376 	rq->netdev = NULL;
3377 	rq->cntxt_id = rq->abs_id = 0;
3378 	rq->desc = NULL;
3379 
3380 	if (fl) {
3381 		free_rx_bufs(adap, fl, fl->avail);
3382 		dma_free_coherent(adap->pdev_dev, fl->size * 8 + s->stat_len,
3383 				  fl->desc, fl->addr);
3384 		kfree(fl->sdesc);
3385 		fl->sdesc = NULL;
3386 		fl->cntxt_id = 0;
3387 		fl->desc = NULL;
3388 	}
3389 }
3390 
3391 /**
3392  *      t4_free_ofld_rxqs - free a block of consecutive Rx queues
3393  *      @adap: the adapter
3394  *      @n: number of queues
3395  *      @q: pointer to first queue
3396  *
3397  *      Release the resources of a consecutive block of offload Rx queues.
3398  */
3399 void t4_free_ofld_rxqs(struct adapter *adap, int n, struct sge_ofld_rxq *q)
3400 {
3401 	for ( ; n; n--, q++)
3402 		if (q->rspq.desc)
3403 			free_rspq_fl(adap, &q->rspq,
3404 				     q->fl.size ? &q->fl : NULL);
3405 }
3406 
3407 /**
3408  *	t4_free_sge_resources - free SGE resources
3409  *	@adap: the adapter
3410  *
3411  *	Frees resources used by the SGE queue sets.
3412  */
3413 void t4_free_sge_resources(struct adapter *adap)
3414 {
3415 	int i;
3416 	struct sge_eth_rxq *eq;
3417 	struct sge_eth_txq *etq;
3418 
3419 	/* stop all Rx queues in order to start them draining */
3420 	for (i = 0; i < adap->sge.ethqsets; i++) {
3421 		eq = &adap->sge.ethrxq[i];
3422 		if (eq->rspq.desc)
3423 			t4_iq_stop(adap, adap->mbox, adap->pf, 0,
3424 				   FW_IQ_TYPE_FL_INT_CAP,
3425 				   eq->rspq.cntxt_id,
3426 				   eq->fl.size ? eq->fl.cntxt_id : 0xffff,
3427 				   0xffff);
3428 	}
3429 
3430 	/* clean up Ethernet Tx/Rx queues */
3431 	for (i = 0; i < adap->sge.ethqsets; i++) {
3432 		eq = &adap->sge.ethrxq[i];
3433 		if (eq->rspq.desc)
3434 			free_rspq_fl(adap, &eq->rspq,
3435 				     eq->fl.size ? &eq->fl : NULL);
3436 
3437 		etq = &adap->sge.ethtxq[i];
3438 		if (etq->q.desc) {
3439 			t4_eth_eq_free(adap, adap->mbox, adap->pf, 0,
3440 				       etq->q.cntxt_id);
3441 			__netif_tx_lock_bh(etq->txq);
3442 			free_tx_desc(adap, &etq->q, etq->q.in_use, true);
3443 			__netif_tx_unlock_bh(etq->txq);
3444 			kfree(etq->q.sdesc);
3445 			free_txq(adap, &etq->q);
3446 		}
3447 	}
3448 
3449 	/* clean up control Tx queues */
3450 	for (i = 0; i < ARRAY_SIZE(adap->sge.ctrlq); i++) {
3451 		struct sge_ctrl_txq *cq = &adap->sge.ctrlq[i];
3452 
3453 		if (cq->q.desc) {
3454 			tasklet_kill(&cq->qresume_tsk);
3455 			t4_ctrl_eq_free(adap, adap->mbox, adap->pf, 0,
3456 					cq->q.cntxt_id);
3457 			__skb_queue_purge(&cq->sendq);
3458 			free_txq(adap, &cq->q);
3459 		}
3460 	}
3461 
3462 	if (adap->sge.fw_evtq.desc)
3463 		free_rspq_fl(adap, &adap->sge.fw_evtq, NULL);
3464 
3465 	if (adap->sge.intrq.desc)
3466 		free_rspq_fl(adap, &adap->sge.intrq, NULL);
3467 
3468 	if (!is_t4(adap->params.chip)) {
3469 		etq = &adap->sge.ptptxq;
3470 		if (etq->q.desc) {
3471 			t4_eth_eq_free(adap, adap->mbox, adap->pf, 0,
3472 				       etq->q.cntxt_id);
3473 			spin_lock_bh(&adap->ptp_lock);
3474 			free_tx_desc(adap, &etq->q, etq->q.in_use, true);
3475 			spin_unlock_bh(&adap->ptp_lock);
3476 			kfree(etq->q.sdesc);
3477 			free_txq(adap, &etq->q);
3478 		}
3479 	}
3480 
3481 	/* clear the reverse egress queue map */
3482 	memset(adap->sge.egr_map, 0,
3483 	       adap->sge.egr_sz * sizeof(*adap->sge.egr_map));
3484 }
3485 
3486 void t4_sge_start(struct adapter *adap)
3487 {
3488 	adap->sge.ethtxq_rover = 0;
3489 	mod_timer(&adap->sge.rx_timer, jiffies + RX_QCHECK_PERIOD);
3490 	mod_timer(&adap->sge.tx_timer, jiffies + TX_QCHECK_PERIOD);
3491 }
3492 
3493 /**
3494  *	t4_sge_stop - disable SGE operation
3495  *	@adap: the adapter
3496  *
3497  *	Stop tasklets and timers associated with the DMA engine.  Note that
3498  *	this is effective only if measures have been taken to disable any HW
3499  *	events that may restart them.
3500  */
3501 void t4_sge_stop(struct adapter *adap)
3502 {
3503 	int i;
3504 	struct sge *s = &adap->sge;
3505 
3506 	if (in_interrupt())  /* actions below require waiting */
3507 		return;
3508 
3509 	if (s->rx_timer.function)
3510 		del_timer_sync(&s->rx_timer);
3511 	if (s->tx_timer.function)
3512 		del_timer_sync(&s->tx_timer);
3513 
3514 	if (is_offload(adap)) {
3515 		struct sge_uld_txq_info *txq_info;
3516 
3517 		txq_info = adap->sge.uld_txq_info[CXGB4_TX_OFLD];
3518 		if (txq_info) {
3519 			struct sge_uld_txq *txq = txq_info->uldtxq;
3520 
3521 			for_each_ofldtxq(&adap->sge, i) {
3522 				if (txq->q.desc)
3523 					tasklet_kill(&txq->qresume_tsk);
3524 			}
3525 		}
3526 	}
3527 
3528 	if (is_pci_uld(adap)) {
3529 		struct sge_uld_txq_info *txq_info;
3530 
3531 		txq_info = adap->sge.uld_txq_info[CXGB4_TX_CRYPTO];
3532 		if (txq_info) {
3533 			struct sge_uld_txq *txq = txq_info->uldtxq;
3534 
3535 			for_each_ofldtxq(&adap->sge, i) {
3536 				if (txq->q.desc)
3537 					tasklet_kill(&txq->qresume_tsk);
3538 			}
3539 		}
3540 	}
3541 
3542 	for (i = 0; i < ARRAY_SIZE(s->ctrlq); i++) {
3543 		struct sge_ctrl_txq *cq = &s->ctrlq[i];
3544 
3545 		if (cq->q.desc)
3546 			tasklet_kill(&cq->qresume_tsk);
3547 	}
3548 }
3549 
3550 /**
3551  *	t4_sge_init_soft - grab core SGE values needed by SGE code
3552  *	@adap: the adapter
3553  *
3554  *	We need to grab the SGE operating parameters that we need to have
3555  *	in order to do our job and make sure we can live with them.
3556  */
3557 
3558 static int t4_sge_init_soft(struct adapter *adap)
3559 {
3560 	struct sge *s = &adap->sge;
3561 	u32 fl_small_pg, fl_large_pg, fl_small_mtu, fl_large_mtu;
3562 	u32 timer_value_0_and_1, timer_value_2_and_3, timer_value_4_and_5;
3563 	u32 ingress_rx_threshold;
3564 
3565 	/*
3566 	 * Verify that CPL messages are going to the Ingress Queue for
3567 	 * process_responses() and that only packet data is going to the
3568 	 * Free Lists.
3569 	 */
3570 	if ((t4_read_reg(adap, SGE_CONTROL_A) & RXPKTCPLMODE_F) !=
3571 	    RXPKTCPLMODE_V(RXPKTCPLMODE_SPLIT_X)) {
3572 		dev_err(adap->pdev_dev, "bad SGE CPL MODE\n");
3573 		return -EINVAL;
3574 	}
3575 
3576 	/*
3577 	 * Validate the Host Buffer Register Array indices that we want to
3578 	 * use ...
3579 	 *
3580 	 * XXX Note that we should really read through the Host Buffer Size
3581 	 * XXX register array and find the indices of the Buffer Sizes which
3582 	 * XXX meet our needs!
3583 	 */
3584 	#define READ_FL_BUF(x) \
3585 		t4_read_reg(adap, SGE_FL_BUFFER_SIZE0_A+(x)*sizeof(u32))
3586 
3587 	fl_small_pg = READ_FL_BUF(RX_SMALL_PG_BUF);
3588 	fl_large_pg = READ_FL_BUF(RX_LARGE_PG_BUF);
3589 	fl_small_mtu = READ_FL_BUF(RX_SMALL_MTU_BUF);
3590 	fl_large_mtu = READ_FL_BUF(RX_LARGE_MTU_BUF);
3591 
3592 	/* We only bother using the Large Page logic if the Large Page Buffer
3593 	 * is larger than our Page Size Buffer.
3594 	 */
3595 	if (fl_large_pg <= fl_small_pg)
3596 		fl_large_pg = 0;
3597 
3598 	#undef READ_FL_BUF
3599 
3600 	/* The Page Size Buffer must be exactly equal to our Page Size and the
3601 	 * Large Page Size Buffer should be 0 (per above) or a power of 2.
3602 	 */
3603 	if (fl_small_pg != PAGE_SIZE ||
3604 	    (fl_large_pg & (fl_large_pg-1)) != 0) {
3605 		dev_err(adap->pdev_dev, "bad SGE FL page buffer sizes [%d, %d]\n",
3606 			fl_small_pg, fl_large_pg);
3607 		return -EINVAL;
3608 	}
3609 	if (fl_large_pg)
3610 		s->fl_pg_order = ilog2(fl_large_pg) - PAGE_SHIFT;
3611 
3612 	if (fl_small_mtu < FL_MTU_SMALL_BUFSIZE(adap) ||
3613 	    fl_large_mtu < FL_MTU_LARGE_BUFSIZE(adap)) {
3614 		dev_err(adap->pdev_dev, "bad SGE FL MTU sizes [%d, %d]\n",
3615 			fl_small_mtu, fl_large_mtu);
3616 		return -EINVAL;
3617 	}
3618 
3619 	/*
3620 	 * Retrieve our RX interrupt holdoff timer values and counter
3621 	 * threshold values from the SGE parameters.
3622 	 */
3623 	timer_value_0_and_1 = t4_read_reg(adap, SGE_TIMER_VALUE_0_AND_1_A);
3624 	timer_value_2_and_3 = t4_read_reg(adap, SGE_TIMER_VALUE_2_AND_3_A);
3625 	timer_value_4_and_5 = t4_read_reg(adap, SGE_TIMER_VALUE_4_AND_5_A);
3626 	s->timer_val[0] = core_ticks_to_us(adap,
3627 		TIMERVALUE0_G(timer_value_0_and_1));
3628 	s->timer_val[1] = core_ticks_to_us(adap,
3629 		TIMERVALUE1_G(timer_value_0_and_1));
3630 	s->timer_val[2] = core_ticks_to_us(adap,
3631 		TIMERVALUE2_G(timer_value_2_and_3));
3632 	s->timer_val[3] = core_ticks_to_us(adap,
3633 		TIMERVALUE3_G(timer_value_2_and_3));
3634 	s->timer_val[4] = core_ticks_to_us(adap,
3635 		TIMERVALUE4_G(timer_value_4_and_5));
3636 	s->timer_val[5] = core_ticks_to_us(adap,
3637 		TIMERVALUE5_G(timer_value_4_and_5));
3638 
3639 	ingress_rx_threshold = t4_read_reg(adap, SGE_INGRESS_RX_THRESHOLD_A);
3640 	s->counter_val[0] = THRESHOLD_0_G(ingress_rx_threshold);
3641 	s->counter_val[1] = THRESHOLD_1_G(ingress_rx_threshold);
3642 	s->counter_val[2] = THRESHOLD_2_G(ingress_rx_threshold);
3643 	s->counter_val[3] = THRESHOLD_3_G(ingress_rx_threshold);
3644 
3645 	return 0;
3646 }
3647 
3648 /**
3649  *     t4_sge_init - initialize SGE
3650  *     @adap: the adapter
3651  *
3652  *     Perform low-level SGE code initialization needed every time after a
3653  *     chip reset.
3654  */
3655 int t4_sge_init(struct adapter *adap)
3656 {
3657 	struct sge *s = &adap->sge;
3658 	u32 sge_control, sge_conm_ctrl;
3659 	int ret, egress_threshold;
3660 
3661 	/*
3662 	 * Ingress Padding Boundary and Egress Status Page Size are set up by
3663 	 * t4_fixup_host_params().
3664 	 */
3665 	sge_control = t4_read_reg(adap, SGE_CONTROL_A);
3666 	s->pktshift = PKTSHIFT_G(sge_control);
3667 	s->stat_len = (sge_control & EGRSTATUSPAGESIZE_F) ? 128 : 64;
3668 
3669 	s->fl_align = t4_fl_pkt_align(adap);
3670 	ret = t4_sge_init_soft(adap);
3671 	if (ret < 0)
3672 		return ret;
3673 
3674 	/*
3675 	 * A FL with <= fl_starve_thres buffers is starving and a periodic
3676 	 * timer will attempt to refill it.  This needs to be larger than the
3677 	 * SGE's Egress Congestion Threshold.  If it isn't, then we can get
3678 	 * stuck waiting for new packets while the SGE is waiting for us to
3679 	 * give it more Free List entries.  (Note that the SGE's Egress
3680 	 * Congestion Threshold is in units of 2 Free List pointers.) For T4,
3681 	 * there was only a single field to control this.  For T5 there's the
3682 	 * original field which now only applies to Unpacked Mode Free List
3683 	 * buffers and a new field which only applies to Packed Mode Free List
3684 	 * buffers.
3685 	 */
3686 	sge_conm_ctrl = t4_read_reg(adap, SGE_CONM_CTRL_A);
3687 	switch (CHELSIO_CHIP_VERSION(adap->params.chip)) {
3688 	case CHELSIO_T4:
3689 		egress_threshold = EGRTHRESHOLD_G(sge_conm_ctrl);
3690 		break;
3691 	case CHELSIO_T5:
3692 		egress_threshold = EGRTHRESHOLDPACKING_G(sge_conm_ctrl);
3693 		break;
3694 	case CHELSIO_T6:
3695 		egress_threshold = T6_EGRTHRESHOLDPACKING_G(sge_conm_ctrl);
3696 		break;
3697 	default:
3698 		dev_err(adap->pdev_dev, "Unsupported Chip version %d\n",
3699 			CHELSIO_CHIP_VERSION(adap->params.chip));
3700 		return -EINVAL;
3701 	}
3702 	s->fl_starve_thres = 2*egress_threshold + 1;
3703 
3704 	t4_idma_monitor_init(adap, &s->idma_monitor);
3705 
3706 	/* Set up timers used for recuring callbacks to process RX and TX
3707 	 * administrative tasks.
3708 	 */
3709 	timer_setup(&s->rx_timer, sge_rx_timer_cb, 0);
3710 	timer_setup(&s->tx_timer, sge_tx_timer_cb, 0);
3711 
3712 	spin_lock_init(&s->intrq_lock);
3713 
3714 	return 0;
3715 }
3716