xref: /dpdk/drivers/net/cxgbe/sge.c (revision 02edbfab)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2014-2018 Chelsio Communications.
3  * All rights reserved.
4  */
5 
6 #include <sys/queue.h>
7 #include <stdio.h>
8 #include <errno.h>
9 #include <stdint.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <stdarg.h>
13 #include <inttypes.h>
14 #include <netinet/in.h>
15 
16 #include <rte_byteorder.h>
17 #include <rte_common.h>
18 #include <rte_cycles.h>
19 #include <rte_interrupts.h>
20 #include <rte_log.h>
21 #include <rte_debug.h>
22 #include <rte_pci.h>
23 #include <rte_branch_prediction.h>
24 #include <rte_memory.h>
25 #include <rte_memzone.h>
26 #include <rte_tailq.h>
27 #include <rte_eal.h>
28 #include <rte_alarm.h>
29 #include <rte_ether.h>
30 #include <ethdev_driver.h>
31 #include <rte_malloc.h>
32 #include <rte_random.h>
33 #include <rte_dev.h>
34 
35 #include "base/common.h"
36 #include "base/t4_regs.h"
37 #include "base/t4_msg.h"
38 #include "cxgbe.h"
39 
40 static inline void ship_tx_pkt_coalesce_wr(struct adapter *adap,
41 					   struct sge_eth_txq *txq);
42 
43 /*
44  * Max number of Rx buffers we replenish at a time.
45  */
46 #define MAX_RX_REFILL 64U
47 
48 #define NOMEM_TMR_IDX (SGE_NTIMERS - 1)
49 
50 /*
51  * Max Tx descriptor space we allow for an Ethernet packet to be inlined
52  * into a WR.
53  */
54 #define MAX_IMM_TX_PKT_LEN 256
55 
56 /*
57  * Max size of a WR sent through a control Tx queue.
58  */
59 #define MAX_CTRL_WR_LEN SGE_MAX_WR_LEN
60 
61 /*
62  * Rx buffer sizes for "usembufs" Free List buffers (one ingress packet
63  * per mbuf buffer).  We currently only support two sizes for 1500- and
64  * 9000-byte MTUs. We could easily support more but there doesn't seem to be
65  * much need for that ...
66  */
67 #define FL_MTU_SMALL 1500
68 #define FL_MTU_LARGE 9000
69 
70 static inline unsigned int fl_mtu_bufsize(struct adapter *adapter,
71 					  unsigned int mtu)
72 {
73 	struct sge *s = &adapter->sge;
74 
75 	return CXGBE_ALIGN(s->pktshift + RTE_ETHER_HDR_LEN + VLAN_HLEN + mtu,
76 			   s->fl_align);
77 }
78 
79 #define FL_MTU_SMALL_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_SMALL)
80 #define FL_MTU_LARGE_BUFSIZE(adapter) fl_mtu_bufsize(adapter, FL_MTU_LARGE)
81 
82 /*
83  * Bits 0..3 of rx_sw_desc.dma_addr have special meaning.  The hardware uses
84  * these to specify the buffer size as an index into the SGE Free List Buffer
85  * Size register array.  We also use bit 4, when the buffer has been unmapped
86  * for DMA, but this is of course never sent to the hardware and is only used
87  * to prevent double unmappings.  All of the above requires that the Free List
88  * Buffers which we allocate have the bottom 5 bits free (0) -- i.e. are
89  * 32-byte or or a power of 2 greater in alignment.  Since the SGE's minimal
90  * Free List Buffer alignment is 32 bytes, this works out for us ...
91  */
92 enum {
93 	RX_BUF_FLAGS     = 0x1f,   /* bottom five bits are special */
94 	RX_BUF_SIZE      = 0x0f,   /* bottom three bits are for buf sizes */
95 	RX_UNMAPPED_BUF  = 0x10,   /* buffer is not mapped */
96 
97 	/*
98 	 * XXX We shouldn't depend on being able to use these indices.
99 	 * XXX Especially when some other Master PF has initialized the
100 	 * XXX adapter or we use the Firmware Configuration File.  We
101 	 * XXX should really search through the Host Buffer Size register
102 	 * XXX array for the appropriately sized buffer indices.
103 	 */
104 	RX_SMALL_PG_BUF  = 0x0,   /* small (PAGE_SIZE) page buffer */
105 	RX_LARGE_PG_BUF  = 0x1,   /* buffer large page buffer */
106 
107 	RX_SMALL_MTU_BUF = 0x2,   /* small MTU buffer */
108 	RX_LARGE_MTU_BUF = 0x3,   /* large MTU buffer */
109 };
110 
111 /**
112  * txq_avail - return the number of available slots in a Tx queue
113  * @q: the Tx queue
114  *
115  * Returns the number of descriptors in a Tx queue available to write new
116  * packets.
117  */
118 static inline unsigned int txq_avail(const struct sge_txq *q)
119 {
120 	return q->size - 1 - q->in_use;
121 }
122 
123 static int map_mbuf(struct rte_mbuf *mbuf, dma_addr_t *addr)
124 {
125 	struct rte_mbuf *m = mbuf;
126 
127 	for (; m; m = m->next, addr++) {
128 		*addr = m->buf_iova + rte_pktmbuf_headroom(m);
129 		if (*addr == 0)
130 			goto out_err;
131 	}
132 	return 0;
133 
134 out_err:
135 	return -ENOMEM;
136 }
137 
138 /**
139  * free_tx_desc - reclaims Tx descriptors and their buffers
140  * @q: the Tx queue to reclaim descriptors from
141  * @n: the number of descriptors to reclaim
142  *
143  * Reclaims Tx descriptors from an SGE Tx queue and frees the associated
144  * Tx buffers.  Called with the Tx queue lock held.
145  */
146 static void free_tx_desc(struct sge_txq *q, unsigned int n)
147 {
148 	struct tx_sw_desc *d;
149 	unsigned int cidx = 0;
150 
151 	d = &q->sdesc[cidx];
152 	while (n--) {
153 		if (d->mbuf) {                       /* an SGL is present */
154 			rte_pktmbuf_free(d->mbuf);
155 			d->mbuf = NULL;
156 		}
157 		if (d->coalesce.idx) {
158 			int i;
159 
160 			for (i = 0; i < d->coalesce.idx; i++) {
161 				rte_pktmbuf_free(d->coalesce.mbuf[i]);
162 				d->coalesce.mbuf[i] = NULL;
163 			}
164 			d->coalesce.idx = 0;
165 		}
166 		++d;
167 		if (++cidx == q->size) {
168 			cidx = 0;
169 			d = q->sdesc;
170 		}
171 		RTE_MBUF_PREFETCH_TO_FREE(&q->sdesc->mbuf->pool);
172 	}
173 }
174 
175 static void reclaim_tx_desc(struct sge_txq *q, unsigned int n)
176 {
177 	struct tx_sw_desc *d;
178 	unsigned int cidx = q->cidx;
179 
180 	d = &q->sdesc[cidx];
181 	while (n--) {
182 		if (d->mbuf) {                       /* an SGL is present */
183 			rte_pktmbuf_free(d->mbuf);
184 			d->mbuf = NULL;
185 		}
186 		++d;
187 		if (++cidx == q->size) {
188 			cidx = 0;
189 			d = q->sdesc;
190 		}
191 	}
192 	q->cidx = cidx;
193 }
194 
195 /**
196  * fl_cap - return the capacity of a free-buffer list
197  * @fl: the FL
198  *
199  * Returns the capacity of a free-buffer list.  The capacity is less than
200  * the size because one descriptor needs to be left unpopulated, otherwise
201  * HW will think the FL is empty.
202  */
203 static inline unsigned int fl_cap(const struct sge_fl *fl)
204 {
205 	return fl->size - 8;   /* 1 descriptor = 8 buffers */
206 }
207 
208 /**
209  * fl_starving - return whether a Free List is starving.
210  * @adapter: pointer to the adapter
211  * @fl: the Free List
212  *
213  * Tests specified Free List to see whether the number of buffers
214  * available to the hardware has falled below our "starvation"
215  * threshold.
216  */
217 static inline bool fl_starving(const struct adapter *adapter,
218 			       const struct sge_fl *fl)
219 {
220 	const struct sge *s = &adapter->sge;
221 
222 	return fl->avail - fl->pend_cred <= s->fl_starve_thres;
223 }
224 
225 static inline unsigned int get_buf_size(struct adapter *adapter,
226 					const struct rx_sw_desc *d)
227 {
228 	unsigned int rx_buf_size_idx = d->dma_addr & RX_BUF_SIZE;
229 	unsigned int buf_size = 0;
230 
231 	switch (rx_buf_size_idx) {
232 	case RX_SMALL_MTU_BUF:
233 		buf_size = FL_MTU_SMALL_BUFSIZE(adapter);
234 		break;
235 
236 	case RX_LARGE_MTU_BUF:
237 		buf_size = FL_MTU_LARGE_BUFSIZE(adapter);
238 		break;
239 
240 	default:
241 		BUG_ON(1);
242 		/* NOT REACHED */
243 	}
244 
245 	return buf_size;
246 }
247 
248 /**
249  * free_rx_bufs - free the Rx buffers on an SGE free list
250  * @q: the SGE free list to free buffers from
251  * @n: how many buffers to free
252  *
253  * Release the next @n buffers on an SGE free-buffer Rx queue.   The
254  * buffers must be made inaccessible to HW before calling this function.
255  */
256 static void free_rx_bufs(struct sge_fl *q, int n)
257 {
258 	unsigned int cidx = q->cidx;
259 	struct rx_sw_desc *d;
260 
261 	d = &q->sdesc[cidx];
262 	while (n--) {
263 		if (d->buf) {
264 			rte_pktmbuf_free(d->buf);
265 			d->buf = NULL;
266 		}
267 		++d;
268 		if (++cidx == q->size) {
269 			cidx = 0;
270 			d = q->sdesc;
271 		}
272 		q->avail--;
273 	}
274 	q->cidx = cidx;
275 }
276 
277 /**
278  * unmap_rx_buf - unmap the current Rx buffer on an SGE free list
279  * @q: the SGE free list
280  *
281  * Unmap the current buffer on an SGE free-buffer Rx queue.   The
282  * buffer must be made inaccessible to HW before calling this function.
283  *
284  * This is similar to @free_rx_bufs above but does not free the buffer.
285  * Do note that the FL still loses any further access to the buffer.
286  */
287 static void unmap_rx_buf(struct sge_fl *q)
288 {
289 	if (++q->cidx == q->size)
290 		q->cidx = 0;
291 	q->avail--;
292 }
293 
294 static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q)
295 {
296 	if (q->pend_cred >= 64) {
297 		u32 val = adap->params.arch.sge_fl_db;
298 
299 		if (is_t4(adap->params.chip))
300 			val |= V_PIDX(q->pend_cred / 8);
301 		else
302 			val |= V_PIDX_T5(q->pend_cred / 8);
303 
304 		/*
305 		 * Make sure all memory writes to the Free List queue are
306 		 * committed before we tell the hardware about them.
307 		 */
308 		wmb();
309 
310 		/*
311 		 * If we don't have access to the new User Doorbell (T5+), use
312 		 * the old doorbell mechanism; otherwise use the new BAR2
313 		 * mechanism.
314 		 */
315 		if (unlikely(!q->bar2_addr)) {
316 			u32 reg = is_pf4(adap) ? MYPF_REG(A_SGE_PF_KDOORBELL) :
317 						 T4VF_SGE_BASE_ADDR +
318 						 A_SGE_VF_KDOORBELL;
319 
320 			t4_write_reg_relaxed(adap, reg,
321 					     val | V_QID(q->cntxt_id));
322 		} else {
323 			writel_relaxed(val | V_QID(q->bar2_qid),
324 				       (void *)((uintptr_t)q->bar2_addr +
325 				       SGE_UDB_KDOORBELL));
326 
327 			/*
328 			 * This Write memory Barrier will force the write to
329 			 * the User Doorbell area to be flushed.
330 			 */
331 			wmb();
332 		}
333 		q->pend_cred &= 7;
334 	}
335 }
336 
337 static inline void set_rx_sw_desc(struct rx_sw_desc *sd, void *buf,
338 				  dma_addr_t mapping)
339 {
340 	sd->buf = buf;
341 	sd->dma_addr = mapping;      /* includes size low bits */
342 }
343 
344 /**
345  * refill_fl_usembufs - refill an SGE Rx buffer ring with mbufs
346  * @adap: the adapter
347  * @q: the ring to refill
348  * @n: the number of new buffers to allocate
349  *
350  * (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
351  * allocated with the supplied gfp flags.  The caller must assure that
352  * @n does not exceed the queue's capacity.  If afterwards the queue is
353  * found critically low mark it as starving in the bitmap of starving FLs.
354  *
355  * Returns the number of buffers allocated.
356  */
357 static unsigned int refill_fl_usembufs(struct adapter *adap, struct sge_fl *q,
358 				       int n)
359 {
360 	struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, fl);
361 	unsigned int cred = q->avail;
362 	__be64 *d = &q->desc[q->pidx];
363 	struct rx_sw_desc *sd = &q->sdesc[q->pidx];
364 	unsigned int buf_size_idx = RX_SMALL_MTU_BUF;
365 	struct rte_mbuf *buf_bulk[n];
366 	int ret, i;
367 	struct rte_pktmbuf_pool_private *mbp_priv;
368 	u8 jumbo_en = rxq->rspq.eth_dev->data->dev_conf.rxmode.offloads &
369 		DEV_RX_OFFLOAD_JUMBO_FRAME;
370 
371 	/* Use jumbo mtu buffers if mbuf data room size can fit jumbo data. */
372 	mbp_priv = rte_mempool_get_priv(rxq->rspq.mb_pool);
373 	if (jumbo_en &&
374 	    ((mbp_priv->mbuf_data_room_size - RTE_PKTMBUF_HEADROOM) >= 9000))
375 		buf_size_idx = RX_LARGE_MTU_BUF;
376 
377 	ret = rte_mempool_get_bulk(rxq->rspq.mb_pool, (void *)buf_bulk, n);
378 	if (unlikely(ret != 0)) {
379 		dev_debug(adap, "%s: failed to allocated fl entries in bulk ..\n",
380 			  __func__);
381 		q->alloc_failed++;
382 		rxq->rspq.eth_dev->data->rx_mbuf_alloc_failed++;
383 		goto out;
384 	}
385 
386 	for (i = 0; i < n; i++) {
387 		struct rte_mbuf *mbuf = buf_bulk[i];
388 		dma_addr_t mapping;
389 
390 		if (!mbuf) {
391 			dev_debug(adap, "%s: mbuf alloc failed\n", __func__);
392 			q->alloc_failed++;
393 			rxq->rspq.eth_dev->data->rx_mbuf_alloc_failed++;
394 			goto out;
395 		}
396 
397 		rte_mbuf_refcnt_set(mbuf, 1);
398 		mbuf->data_off =
399 			(uint16_t)((char *)
400 				   RTE_PTR_ALIGN((char *)mbuf->buf_addr +
401 						 RTE_PKTMBUF_HEADROOM,
402 						 adap->sge.fl_align) -
403 				   (char *)mbuf->buf_addr);
404 		mbuf->next = NULL;
405 		mbuf->nb_segs = 1;
406 		mbuf->port = rxq->rspq.port_id;
407 
408 		mapping = (dma_addr_t)RTE_ALIGN(mbuf->buf_iova +
409 						mbuf->data_off,
410 						adap->sge.fl_align);
411 		mapping |= buf_size_idx;
412 		*d++ = cpu_to_be64(mapping);
413 		set_rx_sw_desc(sd, mbuf, mapping);
414 		sd++;
415 
416 		q->avail++;
417 		if (++q->pidx == q->size) {
418 			q->pidx = 0;
419 			sd = q->sdesc;
420 			d = q->desc;
421 		}
422 	}
423 
424 out:    cred = q->avail - cred;
425 	q->pend_cred += cred;
426 	ring_fl_db(adap, q);
427 
428 	if (unlikely(fl_starving(adap, q))) {
429 		/*
430 		 * Make sure data has been written to free list
431 		 */
432 		wmb();
433 		q->low++;
434 	}
435 
436 	return cred;
437 }
438 
439 /**
440  * refill_fl - refill an SGE Rx buffer ring with mbufs
441  * @adap: the adapter
442  * @q: the ring to refill
443  * @n: the number of new buffers to allocate
444  *
445  * (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
446  * allocated with the supplied gfp flags.  The caller must assure that
447  * @n does not exceed the queue's capacity.  Returns the number of buffers
448  * allocated.
449  */
450 static unsigned int refill_fl(struct adapter *adap, struct sge_fl *q, int n)
451 {
452 	return refill_fl_usembufs(adap, q, n);
453 }
454 
455 static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl)
456 {
457 	refill_fl(adap, fl, min(MAX_RX_REFILL, fl_cap(fl) - fl->avail));
458 }
459 
460 /*
461  * Return the number of reclaimable descriptors in a Tx queue.
462  */
463 static inline int reclaimable(const struct sge_txq *q)
464 {
465 	int hw_cidx = ntohs(q->stat->cidx);
466 
467 	hw_cidx -= q->cidx;
468 	if (hw_cidx < 0)
469 		return hw_cidx + q->size;
470 	return hw_cidx;
471 }
472 
473 /**
474  * reclaim_completed_tx - reclaims completed Tx descriptors
475  * @q: the Tx queue to reclaim completed descriptors from
476  *
477  * Reclaims Tx descriptors that the SGE has indicated it has processed.
478  */
479 void reclaim_completed_tx(struct sge_txq *q)
480 {
481 	unsigned int avail = reclaimable(q);
482 
483 	do {
484 		/* reclaim as much as possible */
485 		reclaim_tx_desc(q, avail);
486 		q->in_use -= avail;
487 		avail = reclaimable(q);
488 	} while (avail);
489 }
490 
491 /**
492  * sgl_len - calculates the size of an SGL of the given capacity
493  * @n: the number of SGL entries
494  *
495  * Calculates the number of flits needed for a scatter/gather list that
496  * can hold the given number of entries.
497  */
498 static inline unsigned int sgl_len(unsigned int n)
499 {
500 	/*
501 	 * A Direct Scatter Gather List uses 32-bit lengths and 64-bit PCI DMA
502 	 * addresses.  The DSGL Work Request starts off with a 32-bit DSGL
503 	 * ULPTX header, then Length0, then Address0, then, for 1 <= i <= N,
504 	 * repeated sequences of { Length[i], Length[i+1], Address[i],
505 	 * Address[i+1] } (this ensures that all addresses are on 64-bit
506 	 * boundaries).  If N is even, then Length[N+1] should be set to 0 and
507 	 * Address[N+1] is omitted.
508 	 *
509 	 * The following calculation incorporates all of the above.  It's
510 	 * somewhat hard to follow but, briefly: the "+2" accounts for the
511 	 * first two flits which include the DSGL header, Length0 and
512 	 * Address0; the "(3*(n-1))/2" covers the main body of list entries (3
513 	 * flits for every pair of the remaining N) +1 if (n-1) is odd; and
514 	 * finally the "+((n-1)&1)" adds the one remaining flit needed if
515 	 * (n-1) is odd ...
516 	 */
517 	n--;
518 	return (3 * n) / 2 + (n & 1) + 2;
519 }
520 
521 /**
522  * flits_to_desc - returns the num of Tx descriptors for the given flits
523  * @n: the number of flits
524  *
525  * Returns the number of Tx descriptors needed for the supplied number
526  * of flits.
527  */
528 static inline unsigned int flits_to_desc(unsigned int n)
529 {
530 	return DIV_ROUND_UP(n, 8);
531 }
532 
533 /**
534  * is_eth_imm - can an Ethernet packet be sent as immediate data?
535  * @m: the packet
536  *
537  * Returns whether an Ethernet packet is small enough to fit as
538  * immediate data. Return value corresponds to the headroom required.
539  */
540 static inline int is_eth_imm(const struct rte_mbuf *m)
541 {
542 	unsigned int hdrlen = (m->ol_flags & PKT_TX_TCP_SEG) ?
543 			      sizeof(struct cpl_tx_pkt_lso_core) : 0;
544 
545 	hdrlen += sizeof(struct cpl_tx_pkt);
546 	if (m->pkt_len <= MAX_IMM_TX_PKT_LEN - hdrlen)
547 		return hdrlen;
548 
549 	return 0;
550 }
551 
552 /**
553  * calc_tx_flits - calculate the number of flits for a packet Tx WR
554  * @m: the packet
555  * @adap: adapter structure pointer
556  *
557  * Returns the number of flits needed for a Tx WR for the given Ethernet
558  * packet, including the needed WR and CPL headers.
559  */
560 static inline unsigned int calc_tx_flits(const struct rte_mbuf *m,
561 					 struct adapter *adap)
562 {
563 	size_t wr_size = is_pf4(adap) ? sizeof(struct fw_eth_tx_pkt_wr) :
564 					sizeof(struct fw_eth_tx_pkt_vm_wr);
565 	unsigned int flits;
566 	int hdrlen;
567 
568 	/*
569 	 * If the mbuf is small enough, we can pump it out as a work request
570 	 * with only immediate data.  In that case we just have to have the
571 	 * TX Packet header plus the mbuf data in the Work Request.
572 	 */
573 
574 	hdrlen = is_eth_imm(m);
575 	if (hdrlen)
576 		return DIV_ROUND_UP(m->pkt_len + hdrlen, sizeof(__be64));
577 
578 	/*
579 	 * Otherwise, we're going to have to construct a Scatter gather list
580 	 * of the mbuf body and fragments.  We also include the flits necessary
581 	 * for the TX Packet Work Request and CPL.  We always have a firmware
582 	 * Write Header (incorporated as part of the cpl_tx_pkt_lso and
583 	 * cpl_tx_pkt structures), followed by either a TX Packet Write CPL
584 	 * message or, if we're doing a Large Send Offload, an LSO CPL message
585 	 * with an embedded TX Packet Write CPL message.
586 	 */
587 	flits = sgl_len(m->nb_segs);
588 	if (m->tso_segsz)
589 		flits += (wr_size + sizeof(struct cpl_tx_pkt_lso_core) +
590 			  sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
591 	else
592 		flits += (wr_size +
593 			  sizeof(struct cpl_tx_pkt_core)) / sizeof(__be64);
594 	return flits;
595 }
596 
597 /**
598  * write_sgl - populate a scatter/gather list for a packet
599  * @mbuf: the packet
600  * @q: the Tx queue we are writing into
601  * @sgl: starting location for writing the SGL
602  * @end: points right after the end of the SGL
603  * @start: start offset into mbuf main-body data to include in the SGL
604  * @addr: address of mapped region
605  *
606  * Generates a scatter/gather list for the buffers that make up a packet.
607  * The caller must provide adequate space for the SGL that will be written.
608  * The SGL includes all of the packet's page fragments and the data in its
609  * main body except for the first @start bytes.  @sgl must be 16-byte
610  * aligned and within a Tx descriptor with available space.  @end points
611  * write after the end of the SGL but does not account for any potential
612  * wrap around, i.e., @end > @sgl.
613  */
614 static void write_sgl(struct rte_mbuf *mbuf, struct sge_txq *q,
615 		      struct ulptx_sgl *sgl, u64 *end, unsigned int start,
616 		      const dma_addr_t *addr)
617 {
618 	unsigned int i, len;
619 	struct ulptx_sge_pair *to;
620 	struct rte_mbuf *m = mbuf;
621 	unsigned int nfrags = m->nb_segs;
622 	struct ulptx_sge_pair buf[nfrags / 2];
623 
624 	len = m->data_len - start;
625 	sgl->len0 = htonl(len);
626 	sgl->addr0 = rte_cpu_to_be_64(addr[0]);
627 
628 	sgl->cmd_nsge = htonl(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
629 			      V_ULPTX_NSGE(nfrags));
630 	if (likely(--nfrags == 0))
631 		return;
632 	/*
633 	 * Most of the complexity below deals with the possibility we hit the
634 	 * end of the queue in the middle of writing the SGL.  For this case
635 	 * only we create the SGL in a temporary buffer and then copy it.
636 	 */
637 	to = (u8 *)end > (u8 *)q->stat ? buf : sgl->sge;
638 
639 	for (i = 0; nfrags >= 2; nfrags -= 2, to++) {
640 		m = m->next;
641 		to->len[0] = rte_cpu_to_be_32(m->data_len);
642 		to->addr[0] = rte_cpu_to_be_64(addr[++i]);
643 		m = m->next;
644 		to->len[1] = rte_cpu_to_be_32(m->data_len);
645 		to->addr[1] = rte_cpu_to_be_64(addr[++i]);
646 	}
647 	if (nfrags) {
648 		m = m->next;
649 		to->len[0] = rte_cpu_to_be_32(m->data_len);
650 		to->len[1] = rte_cpu_to_be_32(0);
651 		to->addr[0] = rte_cpu_to_be_64(addr[i + 1]);
652 	}
653 	if (unlikely((u8 *)end > (u8 *)q->stat)) {
654 		unsigned int part0 = RTE_PTR_DIFF((u8 *)q->stat,
655 						  (u8 *)sgl->sge);
656 		unsigned int part1;
657 
658 		if (likely(part0))
659 			memcpy(sgl->sge, buf, part0);
660 		part1 = RTE_PTR_DIFF((u8 *)end, (u8 *)q->stat);
661 		rte_memcpy(q->desc, RTE_PTR_ADD((u8 *)buf, part0), part1);
662 		end = RTE_PTR_ADD((void *)q->desc, part1);
663 	}
664 	if ((uintptr_t)end & 8)           /* 0-pad to multiple of 16 */
665 		*(u64 *)end = 0;
666 }
667 
668 #define IDXDIFF(head, tail, wrap) \
669 	((head) >= (tail) ? (head) - (tail) : (wrap) - (tail) + (head))
670 
671 #define Q_IDXDIFF(q, idx) IDXDIFF((q)->pidx, (q)->idx, (q)->size)
672 #define R_IDXDIFF(q, idx) IDXDIFF((q)->cidx, (q)->idx, (q)->size)
673 
674 #define PIDXDIFF(head, tail, wrap) \
675 	((tail) >= (head) ? (tail) - (head) : (wrap) - (head) + (tail))
676 #define P_IDXDIFF(q, idx) PIDXDIFF((q)->cidx, idx, (q)->size)
677 
678 /**
679  * ring_tx_db - ring a Tx queue's doorbell
680  * @adap: the adapter
681  * @q: the Tx queue
682  * @n: number of new descriptors to give to HW
683  *
684  * Ring the doorbel for a Tx queue.
685  */
686 static inline void ring_tx_db(struct adapter *adap, struct sge_txq *q)
687 {
688 	int n = Q_IDXDIFF(q, dbidx);
689 
690 	/*
691 	 * Make sure that all writes to the TX Descriptors are committed
692 	 * before we tell the hardware about them.
693 	 */
694 	rte_wmb();
695 
696 	/*
697 	 * If we don't have access to the new User Doorbell (T5+), use the old
698 	 * doorbell mechanism; otherwise use the new BAR2 mechanism.
699 	 */
700 	if (unlikely(!q->bar2_addr)) {
701 		u32 val = V_PIDX(n);
702 
703 		/*
704 		 * For T4 we need to participate in the Doorbell Recovery
705 		 * mechanism.
706 		 */
707 		if (!q->db_disabled)
708 			t4_write_reg(adap, MYPF_REG(A_SGE_PF_KDOORBELL),
709 				     V_QID(q->cntxt_id) | val);
710 		else
711 			q->db_pidx_inc += n;
712 		q->db_pidx = q->pidx;
713 	} else {
714 		u32 val = V_PIDX_T5(n);
715 
716 		/*
717 		 * T4 and later chips share the same PIDX field offset within
718 		 * the doorbell, but T5 and later shrank the field in order to
719 		 * gain a bit for Doorbell Priority.  The field was absurdly
720 		 * large in the first place (14 bits) so we just use the T5
721 		 * and later limits and warn if a Queue ID is too large.
722 		 */
723 		WARN_ON(val & F_DBPRIO);
724 
725 		writel(val | V_QID(q->bar2_qid),
726 		       (void *)((uintptr_t)q->bar2_addr + SGE_UDB_KDOORBELL));
727 
728 		/*
729 		 * This Write Memory Barrier will force the write to the User
730 		 * Doorbell area to be flushed.  This is needed to prevent
731 		 * writes on different CPUs for the same queue from hitting
732 		 * the adapter out of order.  This is required when some Work
733 		 * Requests take the Write Combine Gather Buffer path (user
734 		 * doorbell area offset [SGE_UDB_WCDOORBELL..+63]) and some
735 		 * take the traditional path where we simply increment the
736 		 * PIDX (User Doorbell area SGE_UDB_KDOORBELL) and have the
737 		 * hardware DMA read the actual Work Request.
738 		 */
739 		rte_wmb();
740 	}
741 	q->dbidx = q->pidx;
742 }
743 
744 /*
745  * Figure out what HW csum a packet wants and return the appropriate control
746  * bits.
747  */
748 static u64 hwcsum(enum chip_type chip, const struct rte_mbuf *m)
749 {
750 	int csum_type;
751 
752 	if (m->ol_flags & PKT_TX_IP_CKSUM) {
753 		switch (m->ol_flags & PKT_TX_L4_MASK) {
754 		case PKT_TX_TCP_CKSUM:
755 			csum_type = TX_CSUM_TCPIP;
756 			break;
757 		case PKT_TX_UDP_CKSUM:
758 			csum_type = TX_CSUM_UDPIP;
759 			break;
760 		default:
761 			goto nocsum;
762 		}
763 	} else {
764 		goto nocsum;
765 	}
766 
767 	if (likely(csum_type >= TX_CSUM_TCPIP)) {
768 		u64 hdr_len = V_TXPKT_IPHDR_LEN(m->l3_len);
769 		int eth_hdr_len = m->l2_len;
770 
771 		if (CHELSIO_CHIP_VERSION(chip) <= CHELSIO_T5)
772 			hdr_len |= V_TXPKT_ETHHDR_LEN(eth_hdr_len);
773 		else
774 			hdr_len |= V_T6_TXPKT_ETHHDR_LEN(eth_hdr_len);
775 		return V_TXPKT_CSUM_TYPE(csum_type) | hdr_len;
776 	}
777 nocsum:
778 	/*
779 	 * unknown protocol, disable HW csum
780 	 * and hope a bad packet is detected
781 	 */
782 	return F_TXPKT_L4CSUM_DIS;
783 }
784 
785 static inline void txq_advance(struct sge_txq *q, unsigned int n)
786 {
787 	q->in_use += n;
788 	q->pidx += n;
789 	if (q->pidx >= q->size)
790 		q->pidx -= q->size;
791 }
792 
793 #define MAX_COALESCE_LEN 64000
794 
795 static inline int wraps_around(struct sge_txq *q, int ndesc)
796 {
797 	return (q->pidx + ndesc) > q->size ? 1 : 0;
798 }
799 
800 static void tx_timer_cb(void *data)
801 {
802 	struct adapter *adap = (struct adapter *)data;
803 	struct sge_eth_txq *txq = &adap->sge.ethtxq[0];
804 	int i;
805 	unsigned int coal_idx;
806 
807 	/* monitor any pending tx */
808 	for (i = 0; i < adap->sge.max_ethqsets; i++, txq++) {
809 		if (t4_os_trylock(&txq->txq_lock)) {
810 			coal_idx = txq->q.coalesce.idx;
811 			if (coal_idx) {
812 				if (coal_idx == txq->q.last_coal_idx &&
813 				    txq->q.pidx == txq->q.last_pidx) {
814 					ship_tx_pkt_coalesce_wr(adap, txq);
815 				} else {
816 					txq->q.last_coal_idx = coal_idx;
817 					txq->q.last_pidx = txq->q.pidx;
818 				}
819 			}
820 			t4_os_unlock(&txq->txq_lock);
821 		}
822 	}
823 	rte_eal_alarm_set(50, tx_timer_cb, (void *)adap);
824 }
825 
826 /**
827  * ship_tx_pkt_coalesce_wr - finalizes and ships a coalesce WR
828  * @ adap: adapter structure
829  * @txq: tx queue
830  *
831  * writes the different fields of the pkts WR and sends it.
832  */
833 static inline void ship_tx_pkt_coalesce_wr(struct adapter *adap,
834 					   struct sge_eth_txq *txq)
835 {
836 	struct fw_eth_tx_pkts_vm_wr *vmwr;
837 	const size_t fw_hdr_copy_len = (sizeof(vmwr->ethmacdst) +
838 					sizeof(vmwr->ethmacsrc) +
839 					sizeof(vmwr->ethtype) +
840 					sizeof(vmwr->vlantci));
841 	struct fw_eth_tx_pkts_wr *wr;
842 	struct sge_txq *q = &txq->q;
843 	unsigned int ndesc;
844 	u32 wr_mid;
845 
846 	/* fill the pkts WR header */
847 	wr = (void *)&q->desc[q->pidx];
848 	wr->op_pkd = htonl(V_FW_WR_OP(FW_ETH_TX_PKTS2_WR));
849 	vmwr = (void *)&q->desc[q->pidx];
850 
851 	wr_mid = V_FW_WR_LEN16(DIV_ROUND_UP(q->coalesce.flits, 2));
852 	ndesc = flits_to_desc(q->coalesce.flits);
853 	wr->equiq_to_len16 = htonl(wr_mid);
854 	wr->plen = cpu_to_be16(q->coalesce.len);
855 	wr->npkt = q->coalesce.idx;
856 	wr->r3 = 0;
857 	if (is_pf4(adap)) {
858 		wr->op_pkd = htonl(V_FW_WR_OP(FW_ETH_TX_PKTS2_WR));
859 		wr->type = q->coalesce.type;
860 	} else {
861 		wr->op_pkd = htonl(V_FW_WR_OP(FW_ETH_TX_PKTS_VM_WR));
862 		vmwr->r4 = 0;
863 		memcpy((void *)vmwr->ethmacdst, (void *)q->coalesce.ethmacdst,
864 		       fw_hdr_copy_len);
865 	}
866 
867 	/* zero out coalesce structure members */
868 	memset((void *)&q->coalesce, 0, sizeof(struct eth_coalesce));
869 
870 	txq_advance(q, ndesc);
871 	txq->stats.coal_wr++;
872 	txq->stats.coal_pkts += wr->npkt;
873 
874 	if (Q_IDXDIFF(q, equeidx) >= q->size / 2) {
875 		q->equeidx = q->pidx;
876 		wr_mid |= F_FW_WR_EQUEQ;
877 		wr->equiq_to_len16 = htonl(wr_mid);
878 	}
879 	ring_tx_db(adap, q);
880 }
881 
882 /**
883  * should_tx_packet_coalesce - decides wether to coalesce an mbuf or not
884  * @txq: tx queue where the mbuf is sent
885  * @mbuf: mbuf to be sent
886  * @nflits: return value for number of flits needed
887  * @adap: adapter structure
888  *
889  * This function decides if a packet should be coalesced or not.
890  */
891 static inline int should_tx_packet_coalesce(struct sge_eth_txq *txq,
892 					    struct rte_mbuf *mbuf,
893 					    unsigned int *nflits,
894 					    struct adapter *adap)
895 {
896 	struct fw_eth_tx_pkts_vm_wr *wr;
897 	const size_t fw_hdr_copy_len = (sizeof(wr->ethmacdst) +
898 					sizeof(wr->ethmacsrc) +
899 					sizeof(wr->ethtype) +
900 					sizeof(wr->vlantci));
901 	struct sge_txq *q = &txq->q;
902 	unsigned int flits, ndesc;
903 	unsigned char type = 0;
904 	int credits, wr_size;
905 
906 	/* use coal WR type 1 when no frags are present */
907 	type = (mbuf->nb_segs == 1) ? 1 : 0;
908 	if (!is_pf4(adap)) {
909 		if (!type)
910 			return 0;
911 
912 		if (q->coalesce.idx && memcmp((void *)q->coalesce.ethmacdst,
913 					      rte_pktmbuf_mtod(mbuf, void *),
914 					      fw_hdr_copy_len))
915 			ship_tx_pkt_coalesce_wr(adap, txq);
916 	}
917 
918 	if (unlikely(type != q->coalesce.type && q->coalesce.idx))
919 		ship_tx_pkt_coalesce_wr(adap, txq);
920 
921 	/* calculate the number of flits required for coalescing this packet
922 	 * without the 2 flits of the WR header. These are added further down
923 	 * if we are just starting in new PKTS WR. sgl_len doesn't account for
924 	 * the possible 16 bytes alignment ULP TX commands so we do it here.
925 	 */
926 	flits = (sgl_len(mbuf->nb_segs) + 1) & ~1U;
927 	if (type == 0)
928 		flits += (sizeof(struct ulp_txpkt) +
929 			  sizeof(struct ulptx_idata)) / sizeof(__be64);
930 	flits += sizeof(struct cpl_tx_pkt_core) / sizeof(__be64);
931 	*nflits = flits;
932 
933 	/* If coalescing is on, the mbuf is added to a pkts WR */
934 	if (q->coalesce.idx) {
935 		ndesc = DIV_ROUND_UP(q->coalesce.flits + flits, 8);
936 		credits = txq_avail(q) - ndesc;
937 
938 		/* If we are wrapping or this is last mbuf then, send the
939 		 * already coalesced mbufs and let the non-coalesce pass
940 		 * handle the mbuf.
941 		 */
942 		if (unlikely(credits < 0 || wraps_around(q, ndesc))) {
943 			ship_tx_pkt_coalesce_wr(adap, txq);
944 			return 0;
945 		}
946 
947 		/* If the max coalesce len or the max WR len is reached
948 		 * ship the WR and keep coalescing on.
949 		 */
950 		if (unlikely((q->coalesce.len + mbuf->pkt_len >
951 						MAX_COALESCE_LEN) ||
952 			     (q->coalesce.flits + flits >
953 			      q->coalesce.max))) {
954 			ship_tx_pkt_coalesce_wr(adap, txq);
955 			goto new;
956 		}
957 		return 1;
958 	}
959 
960 new:
961 	/* start a new pkts WR, the WR header is not filled below */
962 	wr_size = is_pf4(adap) ? sizeof(struct fw_eth_tx_pkts_wr) :
963 				 sizeof(struct fw_eth_tx_pkts_vm_wr);
964 	flits += wr_size / sizeof(__be64);
965 	ndesc = flits_to_desc(q->coalesce.flits + flits);
966 	credits = txq_avail(q) - ndesc;
967 
968 	if (unlikely(credits < 0 || wraps_around(q, ndesc)))
969 		return 0;
970 	q->coalesce.flits += wr_size / sizeof(__be64);
971 	q->coalesce.type = type;
972 	q->coalesce.ptr = (unsigned char *)&q->desc[q->pidx] +
973 			   q->coalesce.flits * sizeof(__be64);
974 	if (!is_pf4(adap))
975 		memcpy((void *)q->coalesce.ethmacdst,
976 		       rte_pktmbuf_mtod(mbuf, void *), fw_hdr_copy_len);
977 	return 1;
978 }
979 
980 /**
981  * tx_do_packet_coalesce - add an mbuf to a coalesce WR
982  * @txq: sge_eth_txq used send the mbuf
983  * @mbuf: mbuf to be sent
984  * @flits: flits needed for this mbuf
985  * @adap: adapter structure
986  * @pi: port_info structure
987  * @addr: mapped address of the mbuf
988  *
989  * Adds an mbuf to be sent as part of a coalesce WR by filling a
990  * ulp_tx_pkt command, ulp_tx_sc_imm command, cpl message and
991  * ulp_tx_sc_dsgl command.
992  */
993 static inline int tx_do_packet_coalesce(struct sge_eth_txq *txq,
994 					struct rte_mbuf *mbuf,
995 					int flits, struct adapter *adap,
996 					const struct port_info *pi,
997 					dma_addr_t *addr, uint16_t nb_pkts)
998 {
999 	u64 cntrl, *end;
1000 	struct sge_txq *q = &txq->q;
1001 	struct ulp_txpkt *mc;
1002 	struct ulptx_idata *sc_imm;
1003 	struct cpl_tx_pkt_core *cpl;
1004 	struct tx_sw_desc *sd;
1005 	unsigned int idx = q->coalesce.idx, len = mbuf->pkt_len;
1006 
1007 	if (q->coalesce.type == 0) {
1008 		mc = (struct ulp_txpkt *)q->coalesce.ptr;
1009 		mc->cmd_dest = htonl(V_ULPTX_CMD(4) | V_ULP_TXPKT_DEST(0) |
1010 				     V_ULP_TXPKT_FID(adap->sge.fw_evtq.cntxt_id) |
1011 				     F_ULP_TXPKT_RO);
1012 		mc->len = htonl(DIV_ROUND_UP(flits, 2));
1013 		sc_imm = (struct ulptx_idata *)(mc + 1);
1014 		sc_imm->cmd_more = htonl(V_ULPTX_CMD(ULP_TX_SC_IMM) |
1015 					 F_ULP_TX_SC_MORE);
1016 		sc_imm->len = htonl(sizeof(*cpl));
1017 		end = (u64 *)mc + flits;
1018 		cpl = (struct cpl_tx_pkt_core *)(sc_imm + 1);
1019 	} else {
1020 		end = (u64 *)q->coalesce.ptr + flits;
1021 		cpl = (struct cpl_tx_pkt_core *)q->coalesce.ptr;
1022 	}
1023 
1024 	/* update coalesce structure for this txq */
1025 	q->coalesce.flits += flits;
1026 	q->coalesce.ptr += flits * sizeof(__be64);
1027 	q->coalesce.len += mbuf->pkt_len;
1028 
1029 	/* fill the cpl message, same as in t4_eth_xmit, this should be kept
1030 	 * similar to t4_eth_xmit
1031 	 */
1032 	if (mbuf->ol_flags & PKT_TX_IP_CKSUM) {
1033 		cntrl = hwcsum(adap->params.chip, mbuf) |
1034 			       F_TXPKT_IPCSUM_DIS;
1035 		txq->stats.tx_cso++;
1036 	} else {
1037 		cntrl = F_TXPKT_L4CSUM_DIS | F_TXPKT_IPCSUM_DIS;
1038 	}
1039 
1040 	if (mbuf->ol_flags & PKT_TX_VLAN_PKT) {
1041 		txq->stats.vlan_ins++;
1042 		cntrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(mbuf->vlan_tci);
1043 	}
1044 
1045 	cpl->ctrl0 = htonl(V_TXPKT_OPCODE(CPL_TX_PKT_XT));
1046 	if (is_pf4(adap))
1047 		cpl->ctrl0 |= htonl(V_TXPKT_INTF(pi->tx_chan) |
1048 				    V_TXPKT_PF(adap->pf));
1049 	else
1050 		cpl->ctrl0 |= htonl(V_TXPKT_INTF(pi->port_id));
1051 	cpl->pack = htons(0);
1052 	cpl->len = htons(len);
1053 	cpl->ctrl1 = cpu_to_be64(cntrl);
1054 	write_sgl(mbuf, q, (struct ulptx_sgl *)(cpl + 1), end, 0,  addr);
1055 	txq->stats.pkts++;
1056 	txq->stats.tx_bytes += len;
1057 
1058 	sd = &q->sdesc[q->pidx + (idx >> 1)];
1059 	if (!(idx & 1)) {
1060 		if (sd->coalesce.idx) {
1061 			int i;
1062 
1063 			for (i = 0; i < sd->coalesce.idx; i++) {
1064 				rte_pktmbuf_free(sd->coalesce.mbuf[i]);
1065 				sd->coalesce.mbuf[i] = NULL;
1066 			}
1067 		}
1068 	}
1069 
1070 	/* store pointers to the mbuf and the sgl used in free_tx_desc.
1071 	 * each tx desc can hold two pointers corresponding to the value
1072 	 * of ETH_COALESCE_PKT_PER_DESC
1073 	 */
1074 	sd->coalesce.mbuf[idx & 1] = mbuf;
1075 	sd->coalesce.sgl[idx & 1] = (struct ulptx_sgl *)(cpl + 1);
1076 	sd->coalesce.idx = (idx & 1) + 1;
1077 
1078 	/* Send the coalesced work request, only if max reached. However,
1079 	 * if lower latency is preferred over throughput, then don't wait
1080 	 * for coalescing the next Tx burst and send the packets now.
1081 	 */
1082 	q->coalesce.idx++;
1083 	if (q->coalesce.idx == adap->params.max_tx_coalesce_num ||
1084 	    (adap->devargs.tx_mode_latency && q->coalesce.idx >= nb_pkts))
1085 		ship_tx_pkt_coalesce_wr(adap, txq);
1086 
1087 	return 0;
1088 }
1089 
1090 /**
1091  * t4_eth_xmit - add a packet to an Ethernet Tx queue
1092  * @txq: the egress queue
1093  * @mbuf: the packet
1094  *
1095  * Add a packet to an SGE Ethernet Tx queue.  Runs with softirqs disabled.
1096  */
1097 int t4_eth_xmit(struct sge_eth_txq *txq, struct rte_mbuf *mbuf,
1098 		uint16_t nb_pkts)
1099 {
1100 	const struct port_info *pi;
1101 	struct cpl_tx_pkt_lso_core *lso;
1102 	struct adapter *adap;
1103 	struct rte_mbuf *m = mbuf;
1104 	struct fw_eth_tx_pkt_wr *wr;
1105 	struct fw_eth_tx_pkt_vm_wr *vmwr;
1106 	struct cpl_tx_pkt_core *cpl;
1107 	struct tx_sw_desc *d;
1108 	dma_addr_t addr[m->nb_segs];
1109 	unsigned int flits, ndesc, cflits;
1110 	int l3hdr_len, l4hdr_len, eth_xtra_len;
1111 	int len, last_desc;
1112 	int credits;
1113 	u32 wr_mid;
1114 	u64 cntrl, *end;
1115 	bool v6;
1116 	u32 max_pkt_len = txq->data->dev_conf.rxmode.max_rx_pkt_len;
1117 
1118 	/* Reject xmit if queue is stopped */
1119 	if (unlikely(txq->flags & EQ_STOPPED))
1120 		return -(EBUSY);
1121 
1122 	/*
1123 	 * The chip min packet length is 10 octets but play safe and reject
1124 	 * anything shorter than an Ethernet header.
1125 	 */
1126 	if (unlikely(m->pkt_len < RTE_ETHER_HDR_LEN)) {
1127 out_free:
1128 		rte_pktmbuf_free(m);
1129 		return 0;
1130 	}
1131 
1132 	if ((!(m->ol_flags & PKT_TX_TCP_SEG)) &&
1133 	    (unlikely(m->pkt_len > max_pkt_len)))
1134 		goto out_free;
1135 
1136 	pi = txq->data->dev_private;
1137 	adap = pi->adapter;
1138 
1139 	cntrl = F_TXPKT_L4CSUM_DIS | F_TXPKT_IPCSUM_DIS;
1140 	/* align the end of coalesce WR to a 512 byte boundary */
1141 	txq->q.coalesce.max = (8 - (txq->q.pidx & 7)) * 8;
1142 
1143 	if (!((m->ol_flags & PKT_TX_TCP_SEG) ||
1144 			m->pkt_len > RTE_ETHER_MAX_LEN)) {
1145 		if (should_tx_packet_coalesce(txq, mbuf, &cflits, adap)) {
1146 			if (unlikely(map_mbuf(mbuf, addr) < 0)) {
1147 				dev_warn(adap, "%s: mapping err for coalesce\n",
1148 					 __func__);
1149 				txq->stats.mapping_err++;
1150 				goto out_free;
1151 			}
1152 			return tx_do_packet_coalesce(txq, mbuf, cflits, adap,
1153 						     pi, addr, nb_pkts);
1154 		} else {
1155 			return -EBUSY;
1156 		}
1157 	}
1158 
1159 	if (txq->q.coalesce.idx)
1160 		ship_tx_pkt_coalesce_wr(adap, txq);
1161 
1162 	flits = calc_tx_flits(m, adap);
1163 	ndesc = flits_to_desc(flits);
1164 	credits = txq_avail(&txq->q) - ndesc;
1165 
1166 	if (unlikely(credits < 0)) {
1167 		dev_debug(adap, "%s: Tx ring %u full; credits = %d\n",
1168 			  __func__, txq->q.cntxt_id, credits);
1169 		return -EBUSY;
1170 	}
1171 
1172 	if (unlikely(map_mbuf(m, addr) < 0)) {
1173 		txq->stats.mapping_err++;
1174 		goto out_free;
1175 	}
1176 
1177 	wr_mid = V_FW_WR_LEN16(DIV_ROUND_UP(flits, 2));
1178 	if (Q_IDXDIFF(&txq->q, equeidx)  >= 64) {
1179 		txq->q.equeidx = txq->q.pidx;
1180 		wr_mid |= F_FW_WR_EQUEQ;
1181 	}
1182 
1183 	wr = (void *)&txq->q.desc[txq->q.pidx];
1184 	vmwr = (void *)&txq->q.desc[txq->q.pidx];
1185 	wr->equiq_to_len16 = htonl(wr_mid);
1186 	if (is_pf4(adap)) {
1187 		wr->r3 = rte_cpu_to_be_64(0);
1188 		end = (u64 *)wr + flits;
1189 	} else {
1190 		const size_t fw_hdr_copy_len = (sizeof(vmwr->ethmacdst) +
1191 						sizeof(vmwr->ethmacsrc) +
1192 						sizeof(vmwr->ethtype) +
1193 						sizeof(vmwr->vlantci));
1194 
1195 		vmwr->r3[0] = rte_cpu_to_be_32(0);
1196 		vmwr->r3[1] = rte_cpu_to_be_32(0);
1197 		memcpy((void *)vmwr->ethmacdst, rte_pktmbuf_mtod(m, void *),
1198 		       fw_hdr_copy_len);
1199 		end = (u64 *)vmwr + flits;
1200 	}
1201 
1202 	len = 0;
1203 	len += sizeof(*cpl);
1204 
1205 	/* Coalescing skipped and we send through normal path */
1206 	if (!(m->ol_flags & PKT_TX_TCP_SEG)) {
1207 		wr->op_immdlen = htonl(V_FW_WR_OP(is_pf4(adap) ?
1208 						  FW_ETH_TX_PKT_WR :
1209 						  FW_ETH_TX_PKT_VM_WR) |
1210 				       V_FW_WR_IMMDLEN(len));
1211 		if (is_pf4(adap))
1212 			cpl = (void *)(wr + 1);
1213 		else
1214 			cpl = (void *)(vmwr + 1);
1215 		if (m->ol_flags & PKT_TX_IP_CKSUM) {
1216 			cntrl = hwcsum(adap->params.chip, m) |
1217 				F_TXPKT_IPCSUM_DIS;
1218 			txq->stats.tx_cso++;
1219 		}
1220 	} else {
1221 		if (is_pf4(adap))
1222 			lso = (void *)(wr + 1);
1223 		else
1224 			lso = (void *)(vmwr + 1);
1225 		v6 = (m->ol_flags & PKT_TX_IPV6) != 0;
1226 		l3hdr_len = m->l3_len;
1227 		l4hdr_len = m->l4_len;
1228 		eth_xtra_len = m->l2_len - RTE_ETHER_HDR_LEN;
1229 		len += sizeof(*lso);
1230 		wr->op_immdlen = htonl(V_FW_WR_OP(is_pf4(adap) ?
1231 						  FW_ETH_TX_PKT_WR :
1232 						  FW_ETH_TX_PKT_VM_WR) |
1233 				       V_FW_WR_IMMDLEN(len));
1234 		lso->lso_ctrl = htonl(V_LSO_OPCODE(CPL_TX_PKT_LSO) |
1235 				      F_LSO_FIRST_SLICE | F_LSO_LAST_SLICE |
1236 				      V_LSO_IPV6(v6) |
1237 				      V_LSO_ETHHDR_LEN(eth_xtra_len / 4) |
1238 				      V_LSO_IPHDR_LEN(l3hdr_len / 4) |
1239 				      V_LSO_TCPHDR_LEN(l4hdr_len / 4));
1240 		lso->ipid_ofst = htons(0);
1241 		lso->mss = htons(m->tso_segsz);
1242 		lso->seqno_offset = htonl(0);
1243 		if (is_t4(adap->params.chip))
1244 			lso->len = htonl(m->pkt_len);
1245 		else
1246 			lso->len = htonl(V_LSO_T5_XFER_SIZE(m->pkt_len));
1247 		cpl = (void *)(lso + 1);
1248 
1249 		if (CHELSIO_CHIP_VERSION(adap->params.chip) <= CHELSIO_T5)
1250 			cntrl = V_TXPKT_ETHHDR_LEN(eth_xtra_len);
1251 		else
1252 			cntrl = V_T6_TXPKT_ETHHDR_LEN(eth_xtra_len);
1253 
1254 		cntrl |= V_TXPKT_CSUM_TYPE(v6 ? TX_CSUM_TCPIP6 :
1255 						TX_CSUM_TCPIP) |
1256 			 V_TXPKT_IPHDR_LEN(l3hdr_len);
1257 		txq->stats.tso++;
1258 		txq->stats.tx_cso += m->tso_segsz;
1259 	}
1260 
1261 	if (m->ol_flags & PKT_TX_VLAN_PKT) {
1262 		txq->stats.vlan_ins++;
1263 		cntrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->vlan_tci);
1264 	}
1265 
1266 	cpl->ctrl0 = htonl(V_TXPKT_OPCODE(CPL_TX_PKT_XT));
1267 	if (is_pf4(adap))
1268 		cpl->ctrl0 |= htonl(V_TXPKT_INTF(pi->tx_chan) |
1269 				    V_TXPKT_PF(adap->pf));
1270 	else
1271 		cpl->ctrl0 |= htonl(V_TXPKT_INTF(pi->port_id) |
1272 				    V_TXPKT_PF(0));
1273 
1274 	cpl->pack = htons(0);
1275 	cpl->len = htons(m->pkt_len);
1276 	cpl->ctrl1 = cpu_to_be64(cntrl);
1277 
1278 	txq->stats.pkts++;
1279 	txq->stats.tx_bytes += m->pkt_len;
1280 	last_desc = txq->q.pidx + ndesc - 1;
1281 	if (last_desc >= (int)txq->q.size)
1282 		last_desc -= txq->q.size;
1283 
1284 	d = &txq->q.sdesc[last_desc];
1285 	if (d->coalesce.idx) {
1286 		int i;
1287 
1288 		for (i = 0; i < d->coalesce.idx; i++) {
1289 			rte_pktmbuf_free(d->coalesce.mbuf[i]);
1290 			d->coalesce.mbuf[i] = NULL;
1291 		}
1292 		d->coalesce.idx = 0;
1293 	}
1294 	write_sgl(m, &txq->q, (struct ulptx_sgl *)(cpl + 1), end, 0,
1295 		  addr);
1296 	txq->q.sdesc[last_desc].mbuf = m;
1297 	txq->q.sdesc[last_desc].sgl = (struct ulptx_sgl *)(cpl + 1);
1298 	txq_advance(&txq->q, ndesc);
1299 	ring_tx_db(adap, &txq->q);
1300 	return 0;
1301 }
1302 
1303 /**
1304  * reclaim_completed_tx_imm - reclaim completed control-queue Tx descs
1305  * @q: the SGE control Tx queue
1306  *
1307  * This is a variant of reclaim_completed_tx() that is used for Tx queues
1308  * that send only immediate data (presently just the control queues) and
1309  * thus do not have any mbufs to release.
1310  */
1311 static inline void reclaim_completed_tx_imm(struct sge_txq *q)
1312 {
1313 	int hw_cidx = ntohs(q->stat->cidx);
1314 	int reclaim = hw_cidx - q->cidx;
1315 
1316 	if (reclaim < 0)
1317 		reclaim += q->size;
1318 
1319 	q->in_use -= reclaim;
1320 	q->cidx = hw_cidx;
1321 }
1322 
1323 /**
1324  * is_imm - check whether a packet can be sent as immediate data
1325  * @mbuf: the packet
1326  *
1327  * Returns true if a packet can be sent as a WR with immediate data.
1328  */
1329 static inline int is_imm(const struct rte_mbuf *mbuf)
1330 {
1331 	return mbuf->pkt_len <= MAX_CTRL_WR_LEN;
1332 }
1333 
1334 /**
1335  * inline_tx_mbuf: inline a packet's data into TX descriptors
1336  * @q: the TX queue where the packet will be inlined
1337  * @from: pointer to data portion of packet
1338  * @to: pointer after cpl where data has to be inlined
1339  * @len: length of data to inline
1340  *
1341  * Inline a packet's contents directly to TX descriptors, starting at
1342  * the given position within the TX DMA ring.
1343  * Most of the complexity of this operation is dealing with wrap arounds
1344  * in the middle of the packet we want to inline.
1345  */
1346 static void inline_tx_mbuf(const struct sge_txq *q, caddr_t from, caddr_t *to,
1347 			   int len)
1348 {
1349 	int left = RTE_PTR_DIFF(q->stat, *to);
1350 
1351 	if (likely((uintptr_t)*to + len <= (uintptr_t)q->stat)) {
1352 		rte_memcpy(*to, from, len);
1353 		*to = RTE_PTR_ADD(*to, len);
1354 	} else {
1355 		rte_memcpy(*to, from, left);
1356 		from = RTE_PTR_ADD(from, left);
1357 		left = len - left;
1358 		rte_memcpy((void *)q->desc, from, left);
1359 		*to = RTE_PTR_ADD((void *)q->desc, left);
1360 	}
1361 }
1362 
1363 /**
1364  * ctrl_xmit - send a packet through an SGE control Tx queue
1365  * @q: the control queue
1366  * @mbuf: the packet
1367  *
1368  * Send a packet through an SGE control Tx queue.  Packets sent through
1369  * a control queue must fit entirely as immediate data.
1370  */
1371 static int ctrl_xmit(struct sge_ctrl_txq *q, struct rte_mbuf *mbuf)
1372 {
1373 	unsigned int ndesc;
1374 	struct fw_wr_hdr *wr;
1375 	caddr_t dst;
1376 
1377 	if (unlikely(!is_imm(mbuf))) {
1378 		WARN_ON(1);
1379 		rte_pktmbuf_free(mbuf);
1380 		return -1;
1381 	}
1382 
1383 	reclaim_completed_tx_imm(&q->q);
1384 	ndesc = DIV_ROUND_UP(mbuf->pkt_len, sizeof(struct tx_desc));
1385 	t4_os_lock(&q->ctrlq_lock);
1386 
1387 	q->full = txq_avail(&q->q) < ndesc ? 1 : 0;
1388 	if (unlikely(q->full)) {
1389 		t4_os_unlock(&q->ctrlq_lock);
1390 		return -1;
1391 	}
1392 
1393 	wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
1394 	dst = (void *)wr;
1395 	inline_tx_mbuf(&q->q, rte_pktmbuf_mtod(mbuf, caddr_t),
1396 		       &dst, mbuf->data_len);
1397 
1398 	txq_advance(&q->q, ndesc);
1399 	if (unlikely(txq_avail(&q->q) < 64))
1400 		wr->lo |= htonl(F_FW_WR_EQUEQ);
1401 
1402 	q->txp++;
1403 
1404 	ring_tx_db(q->adapter, &q->q);
1405 	t4_os_unlock(&q->ctrlq_lock);
1406 
1407 	rte_pktmbuf_free(mbuf);
1408 	return 0;
1409 }
1410 
1411 /**
1412  * t4_mgmt_tx - send a management message
1413  * @q: the control queue
1414  * @mbuf: the packet containing the management message
1415  *
1416  * Send a management message through control queue.
1417  */
1418 int t4_mgmt_tx(struct sge_ctrl_txq *q, struct rte_mbuf *mbuf)
1419 {
1420 	return ctrl_xmit(q, mbuf);
1421 }
1422 
1423 /**
1424  * alloc_ring - allocate resources for an SGE descriptor ring
1425  * @dev: the port associated with the queue
1426  * @z_name: memzone's name
1427  * @queue_id: queue index
1428  * @socket_id: preferred socket id for memory allocations
1429  * @nelem: the number of descriptors
1430  * @elem_size: the size of each descriptor
1431  * @stat_size: extra space in HW ring for status information
1432  * @sw_size: the size of the SW state associated with each ring element
1433  * @phys: the physical address of the allocated ring
1434  * @metadata: address of the array holding the SW state for the ring
1435  *
1436  * Allocates resources for an SGE descriptor ring, such as Tx queues,
1437  * free buffer lists, or response queues.  Each SGE ring requires
1438  * space for its HW descriptors plus, optionally, space for the SW state
1439  * associated with each HW entry (the metadata).  The function returns
1440  * three values: the virtual address for the HW ring (the return value
1441  * of the function), the bus address of the HW ring, and the address
1442  * of the SW ring.
1443  */
1444 static void *alloc_ring(struct rte_eth_dev *dev, const char *z_name,
1445 			uint16_t queue_id, int socket_id, size_t nelem,
1446 			size_t elem_size, size_t stat_size, size_t sw_size,
1447 			dma_addr_t *phys, void *metadata)
1448 {
1449 	size_t len = CXGBE_MAX_RING_DESC_SIZE * elem_size + stat_size;
1450 	char z_name_sw[RTE_MEMZONE_NAMESIZE];
1451 	const struct rte_memzone *tz;
1452 	void *s = NULL;
1453 
1454 	snprintf(z_name_sw, sizeof(z_name_sw), "eth_p%d_q%d_%s_sw_ring",
1455 		 dev->data->port_id, queue_id, z_name);
1456 
1457 	dev_debug(adapter, "%s: nelem = %zu; elem_size = %zu; sw_size = %zu; "
1458 		  "stat_size = %zu; queue_id = %u; socket_id = %d; z_name = %s;"
1459 		  " z_name_sw = %s\n", __func__, nelem, elem_size, sw_size,
1460 		  stat_size, queue_id, socket_id, z_name, z_name_sw);
1461 
1462 	/*
1463 	 * Allocate TX/RX ring hardware descriptors. A memzone large enough to
1464 	 * handle the maximum ring size is allocated in order to allow for
1465 	 * resizing in later calls to the queue setup function.
1466 	 */
1467 	tz = rte_eth_dma_zone_reserve(dev, z_name, queue_id, len, 4096,
1468 				      socket_id);
1469 	if (!tz)
1470 		return NULL;
1471 
1472 	memset(tz->addr, 0, len);
1473 	if (sw_size) {
1474 		s = rte_zmalloc_socket(z_name_sw, nelem * sw_size,
1475 				       RTE_CACHE_LINE_SIZE, socket_id);
1476 
1477 		if (!s) {
1478 			dev_err(adapter, "%s: failed to get sw_ring memory\n",
1479 				__func__);
1480 			return NULL;
1481 		}
1482 	}
1483 	if (metadata)
1484 		*(void **)metadata = s;
1485 
1486 	*phys = (uint64_t)tz->iova;
1487 	return tz->addr;
1488 }
1489 
1490 #define CXGB4_MSG_AN ((void *)1)
1491 
1492 /**
1493  * rspq_next - advance to the next entry in a response queue
1494  * @q: the queue
1495  *
1496  * Updates the state of a response queue to advance it to the next entry.
1497  */
1498 static inline void rspq_next(struct sge_rspq *q)
1499 {
1500 	q->cur_desc = (const __be64 *)((const char *)q->cur_desc + q->iqe_len);
1501 	if (unlikely(++q->cidx == q->size)) {
1502 		q->cidx = 0;
1503 		q->gen ^= 1;
1504 		q->cur_desc = q->desc;
1505 	}
1506 }
1507 
1508 static inline void cxgbe_set_mbuf_info(struct rte_mbuf *pkt, uint32_t ptype,
1509 				       uint64_t ol_flags)
1510 {
1511 	pkt->packet_type |= ptype;
1512 	pkt->ol_flags |= ol_flags;
1513 }
1514 
1515 static inline void cxgbe_fill_mbuf_info(struct adapter *adap,
1516 					const struct cpl_rx_pkt *cpl,
1517 					struct rte_mbuf *pkt)
1518 {
1519 	bool csum_ok;
1520 	u16 err_vec;
1521 
1522 	if (adap->params.tp.rx_pkt_encap)
1523 		err_vec = G_T6_COMPR_RXERR_VEC(ntohs(cpl->err_vec));
1524 	else
1525 		err_vec = ntohs(cpl->err_vec);
1526 
1527 	csum_ok = cpl->csum_calc && !err_vec;
1528 
1529 	if (cpl->vlan_ex)
1530 		cxgbe_set_mbuf_info(pkt, RTE_PTYPE_L2_ETHER_VLAN,
1531 				    PKT_RX_VLAN | PKT_RX_VLAN_STRIPPED);
1532 	else
1533 		cxgbe_set_mbuf_info(pkt, RTE_PTYPE_L2_ETHER, 0);
1534 
1535 	if (cpl->l2info & htonl(F_RXF_IP))
1536 		cxgbe_set_mbuf_info(pkt, RTE_PTYPE_L3_IPV4,
1537 				    csum_ok ? PKT_RX_IP_CKSUM_GOOD :
1538 					      PKT_RX_IP_CKSUM_BAD);
1539 	else if (cpl->l2info & htonl(F_RXF_IP6))
1540 		cxgbe_set_mbuf_info(pkt, RTE_PTYPE_L3_IPV6,
1541 				    csum_ok ? PKT_RX_IP_CKSUM_GOOD :
1542 					      PKT_RX_IP_CKSUM_BAD);
1543 
1544 	if (cpl->l2info & htonl(F_RXF_TCP))
1545 		cxgbe_set_mbuf_info(pkt, RTE_PTYPE_L4_TCP,
1546 				    csum_ok ? PKT_RX_L4_CKSUM_GOOD :
1547 					      PKT_RX_L4_CKSUM_BAD);
1548 	else if (cpl->l2info & htonl(F_RXF_UDP))
1549 		cxgbe_set_mbuf_info(pkt, RTE_PTYPE_L4_UDP,
1550 				    csum_ok ? PKT_RX_L4_CKSUM_GOOD :
1551 					      PKT_RX_L4_CKSUM_BAD);
1552 }
1553 
1554 /**
1555  * process_responses - process responses from an SGE response queue
1556  * @q: the ingress queue to process
1557  * @budget: how many responses can be processed in this round
1558  * @rx_pkts: mbuf to put the pkts
1559  *
1560  * Process responses from an SGE response queue up to the supplied budget.
1561  * Responses include received packets as well as control messages from FW
1562  * or HW.
1563  *
1564  * Additionally choose the interrupt holdoff time for the next interrupt
1565  * on this queue.  If the system is under memory shortage use a fairly
1566  * long delay to help recovery.
1567  */
1568 static int process_responses(struct sge_rspq *q, int budget,
1569 			     struct rte_mbuf **rx_pkts)
1570 {
1571 	int ret = 0, rsp_type;
1572 	int budget_left = budget;
1573 	const struct rsp_ctrl *rc;
1574 	struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
1575 
1576 	while (likely(budget_left)) {
1577 		if (q->cidx == ntohs(q->stat->pidx))
1578 			break;
1579 
1580 		rc = (const struct rsp_ctrl *)
1581 		     ((const char *)q->cur_desc + (q->iqe_len - sizeof(*rc)));
1582 
1583 		/*
1584 		 * Ensure response has been read
1585 		 */
1586 		rmb();
1587 		rsp_type = G_RSPD_TYPE(rc->u.type_gen);
1588 
1589 		if (likely(rsp_type == X_RSPD_TYPE_FLBUF)) {
1590 			struct sge *s = &q->adapter->sge;
1591 			unsigned int stat_pidx;
1592 			int stat_pidx_diff;
1593 
1594 			stat_pidx = ntohs(q->stat->pidx);
1595 			stat_pidx_diff = P_IDXDIFF(q, stat_pidx);
1596 			while (stat_pidx_diff && budget_left) {
1597 				const struct rx_sw_desc *rsd =
1598 					&rxq->fl.sdesc[rxq->fl.cidx];
1599 				const struct rss_header *rss_hdr =
1600 					(const void *)q->cur_desc;
1601 				const struct cpl_rx_pkt *cpl =
1602 					(const void *)&q->cur_desc[1];
1603 				struct rte_mbuf *pkt, *npkt;
1604 				u32 len, bufsz;
1605 
1606 				rc = (const struct rsp_ctrl *)
1607 				     ((const char *)q->cur_desc +
1608 				      (q->iqe_len - sizeof(*rc)));
1609 
1610 				rsp_type = G_RSPD_TYPE(rc->u.type_gen);
1611 				if (unlikely(rsp_type != X_RSPD_TYPE_FLBUF))
1612 					break;
1613 
1614 				len = ntohl(rc->pldbuflen_qid);
1615 				BUG_ON(!(len & F_RSPD_NEWBUF));
1616 				pkt = rsd->buf;
1617 				npkt = pkt;
1618 				len = G_RSPD_LEN(len);
1619 				pkt->pkt_len = len;
1620 
1621 				/* Chain mbufs into len if necessary */
1622 				while (len) {
1623 					struct rte_mbuf *new_pkt = rsd->buf;
1624 
1625 					bufsz = min(get_buf_size(q->adapter,
1626 								 rsd), len);
1627 					new_pkt->data_len = bufsz;
1628 					unmap_rx_buf(&rxq->fl);
1629 					len -= bufsz;
1630 					npkt->next = new_pkt;
1631 					npkt = new_pkt;
1632 					pkt->nb_segs++;
1633 					rsd = &rxq->fl.sdesc[rxq->fl.cidx];
1634 				}
1635 				npkt->next = NULL;
1636 				pkt->nb_segs--;
1637 
1638 				cxgbe_fill_mbuf_info(q->adapter, cpl, pkt);
1639 
1640 				if (!rss_hdr->filter_tid &&
1641 				    rss_hdr->hash_type) {
1642 					pkt->ol_flags |= PKT_RX_RSS_HASH;
1643 					pkt->hash.rss =
1644 						ntohl(rss_hdr->hash_val);
1645 				}
1646 
1647 				if (cpl->vlan_ex)
1648 					pkt->vlan_tci = ntohs(cpl->vlan);
1649 
1650 				rte_pktmbuf_adj(pkt, s->pktshift);
1651 				rxq->stats.pkts++;
1652 				rxq->stats.rx_bytes += pkt->pkt_len;
1653 				rx_pkts[budget - budget_left] = pkt;
1654 
1655 				rspq_next(q);
1656 				budget_left--;
1657 				stat_pidx_diff--;
1658 			}
1659 			continue;
1660 		} else if (likely(rsp_type == X_RSPD_TYPE_CPL)) {
1661 			ret = q->handler(q, q->cur_desc, NULL);
1662 		} else {
1663 			ret = q->handler(q, (const __be64 *)rc, CXGB4_MSG_AN);
1664 		}
1665 
1666 		if (unlikely(ret)) {
1667 			/* couldn't process descriptor, back off for recovery */
1668 			q->next_intr_params = V_QINTR_TIMER_IDX(NOMEM_TMR_IDX);
1669 			break;
1670 		}
1671 
1672 		rspq_next(q);
1673 		budget_left--;
1674 	}
1675 
1676 	/*
1677 	 * If this is a Response Queue with an associated Free List and
1678 	 * there's room for another chunk of new Free List buffer pointers,
1679 	 * refill the Free List.
1680 	 */
1681 
1682 	if (q->offset >= 0 && fl_cap(&rxq->fl) - rxq->fl.avail >= 64)
1683 		__refill_fl(q->adapter, &rxq->fl);
1684 
1685 	return budget - budget_left;
1686 }
1687 
1688 int cxgbe_poll(struct sge_rspq *q, struct rte_mbuf **rx_pkts,
1689 	       unsigned int budget, unsigned int *work_done)
1690 {
1691 	struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
1692 	unsigned int cidx_inc;
1693 	unsigned int params;
1694 	u32 val;
1695 
1696 	if (unlikely(rxq->flags & IQ_STOPPED)) {
1697 		*work_done = 0;
1698 		return 0;
1699 	}
1700 
1701 	*work_done = process_responses(q, budget, rx_pkts);
1702 
1703 	if (*work_done) {
1704 		cidx_inc = R_IDXDIFF(q, gts_idx);
1705 
1706 		if (q->offset >= 0 && fl_cap(&rxq->fl) - rxq->fl.avail >= 64)
1707 			__refill_fl(q->adapter, &rxq->fl);
1708 
1709 		params = q->intr_params;
1710 		q->next_intr_params = params;
1711 		val = V_CIDXINC(cidx_inc) | V_SEINTARM(params);
1712 
1713 		if (unlikely(!q->bar2_addr)) {
1714 			u32 reg = is_pf4(q->adapter) ? MYPF_REG(A_SGE_PF_GTS) :
1715 						       T4VF_SGE_BASE_ADDR +
1716 						       A_SGE_VF_GTS;
1717 
1718 			t4_write_reg(q->adapter, reg,
1719 				     val | V_INGRESSQID((u32)q->cntxt_id));
1720 		} else {
1721 			writel(val | V_INGRESSQID(q->bar2_qid),
1722 			       (void *)((uintptr_t)q->bar2_addr + SGE_UDB_GTS));
1723 			/* This Write memory Barrier will force the
1724 			 * write to the User Doorbell area to be
1725 			 * flushed.
1726 			 */
1727 			wmb();
1728 		}
1729 		q->gts_idx = q->cidx;
1730 	}
1731 	return 0;
1732 }
1733 
1734 /**
1735  * bar2_address - return the BAR2 address for an SGE Queue's Registers
1736  * @adapter: the adapter
1737  * @qid: the SGE Queue ID
1738  * @qtype: the SGE Queue Type (Egress or Ingress)
1739  * @pbar2_qid: BAR2 Queue ID or 0 for Queue ID inferred SGE Queues
1740  *
1741  * Returns the BAR2 address for the SGE Queue Registers associated with
1742  * @qid.  If BAR2 SGE Registers aren't available, returns NULL.  Also
1743  * returns the BAR2 Queue ID to be used with writes to the BAR2 SGE
1744  * Queue Registers.  If the BAR2 Queue ID is 0, then "Inferred Queue ID"
1745  * Registers are supported (e.g. the Write Combining Doorbell Buffer).
1746  */
1747 static void __iomem *bar2_address(struct adapter *adapter, unsigned int qid,
1748 				  enum t4_bar2_qtype qtype,
1749 				  unsigned int *pbar2_qid)
1750 {
1751 	u64 bar2_qoffset;
1752 	int ret;
1753 
1754 	ret = t4_bar2_sge_qregs(adapter, qid, qtype, &bar2_qoffset, pbar2_qid);
1755 	if (ret)
1756 		return NULL;
1757 
1758 	return adapter->bar2 + bar2_qoffset;
1759 }
1760 
1761 int t4_sge_eth_rxq_start(struct adapter *adap, struct sge_eth_rxq *rxq)
1762 {
1763 	unsigned int fl_id = rxq->fl.size ? rxq->fl.cntxt_id : 0xffff;
1764 
1765 	rxq->flags &= ~IQ_STOPPED;
1766 	return t4_iq_start_stop(adap, adap->mbox, true, adap->pf, 0,
1767 				rxq->rspq.cntxt_id, fl_id, 0xffff);
1768 }
1769 
1770 int t4_sge_eth_rxq_stop(struct adapter *adap, struct sge_eth_rxq *rxq)
1771 {
1772 	unsigned int fl_id = rxq->fl.size ? rxq->fl.cntxt_id : 0xffff;
1773 
1774 	rxq->flags |= IQ_STOPPED;
1775 	return t4_iq_start_stop(adap, adap->mbox, false, adap->pf, 0,
1776 				rxq->rspq.cntxt_id, fl_id, 0xffff);
1777 }
1778 
1779 /*
1780  * @intr_idx: MSI/MSI-X vector if >=0, -(absolute qid + 1) if < 0
1781  * @cong: < 0 -> no congestion feedback, >= 0 -> congestion channel map
1782  */
1783 int t4_sge_alloc_rxq(struct adapter *adap, struct sge_rspq *iq, bool fwevtq,
1784 		     struct rte_eth_dev *eth_dev, int intr_idx,
1785 		     struct sge_fl *fl, rspq_handler_t hnd, int cong,
1786 		     struct rte_mempool *mp, int queue_id, int socket_id)
1787 {
1788 	int ret, flsz = 0;
1789 	struct fw_iq_cmd c;
1790 	struct sge *s = &adap->sge;
1791 	struct port_info *pi = eth_dev->data->dev_private;
1792 	unsigned int nb_refill;
1793 	u8 pciechan;
1794 
1795 	/* Size needs to be multiple of 16, including status entry. */
1796 	iq->size = cxgbe_roundup(iq->size, 16);
1797 
1798 	iq->desc = alloc_ring(eth_dev, fwevtq ? "fwq_ring" : "rx_ring",
1799 			      queue_id, socket_id, iq->size, iq->iqe_len,
1800 			      0, 0, &iq->phys_addr, NULL);
1801 	if (!iq->desc)
1802 		return -ENOMEM;
1803 
1804 	memset(&c, 0, sizeof(c));
1805 	c.op_to_vfn = htonl(V_FW_CMD_OP(FW_IQ_CMD) | F_FW_CMD_REQUEST |
1806 			    F_FW_CMD_WRITE | F_FW_CMD_EXEC);
1807 
1808 	if (is_pf4(adap)) {
1809 		pciechan = pi->tx_chan;
1810 		c.op_to_vfn |= htonl(V_FW_IQ_CMD_PFN(adap->pf) |
1811 				     V_FW_IQ_CMD_VFN(0));
1812 		if (cong >= 0)
1813 			c.iqns_to_fl0congen =
1814 				htonl(F_FW_IQ_CMD_IQFLINTCONGEN |
1815 				      V_FW_IQ_CMD_IQTYPE(cong ?
1816 							 FW_IQ_IQTYPE_NIC :
1817 							 FW_IQ_IQTYPE_OFLD) |
1818 				      F_FW_IQ_CMD_IQRO);
1819 	} else {
1820 		pciechan = pi->port_id;
1821 	}
1822 
1823 	c.alloc_to_len16 = htonl(F_FW_IQ_CMD_ALLOC | F_FW_IQ_CMD_IQSTART |
1824 				 (sizeof(c) / 16));
1825 	c.type_to_iqandstindex =
1826 		htonl(V_FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
1827 		      V_FW_IQ_CMD_IQASYNCH(fwevtq) |
1828 		      V_FW_IQ_CMD_VIID(pi->viid) |
1829 		      V_FW_IQ_CMD_IQANDST(intr_idx < 0) |
1830 		      V_FW_IQ_CMD_IQANUD(X_UPDATEDELIVERY_STATUS_PAGE) |
1831 		      V_FW_IQ_CMD_IQANDSTINDEX(intr_idx >= 0 ? intr_idx :
1832 							       -intr_idx - 1));
1833 	c.iqdroprss_to_iqesize =
1834 		htons(V_FW_IQ_CMD_IQPCIECH(pciechan) |
1835 		      F_FW_IQ_CMD_IQGTSMODE |
1836 		      V_FW_IQ_CMD_IQINTCNTTHRESH(iq->pktcnt_idx) |
1837 		      V_FW_IQ_CMD_IQESIZE(ilog2(iq->iqe_len) - 4));
1838 	c.iqsize = htons(iq->size);
1839 	c.iqaddr = cpu_to_be64(iq->phys_addr);
1840 
1841 	if (fl) {
1842 		struct sge_eth_rxq *rxq = container_of(fl, struct sge_eth_rxq,
1843 						       fl);
1844 		unsigned int chip_ver = CHELSIO_CHIP_VERSION(adap->params.chip);
1845 
1846 		/*
1847 		 * Allocate the ring for the hardware free list (with space
1848 		 * for its status page) along with the associated software
1849 		 * descriptor ring.  The free list size needs to be a multiple
1850 		 * of the Egress Queue Unit and at least 2 Egress Units larger
1851 		 * than the SGE's Egress Congrestion Threshold
1852 		 * (fl_starve_thres - 1).
1853 		 */
1854 		if (fl->size < s->fl_starve_thres - 1 + 2 * 8)
1855 			fl->size = s->fl_starve_thres - 1 + 2 * 8;
1856 		fl->size = cxgbe_roundup(fl->size, 8);
1857 
1858 		fl->desc = alloc_ring(eth_dev, "fl_ring", queue_id, socket_id,
1859 				      fl->size, sizeof(__be64), s->stat_len,
1860 				      sizeof(struct rx_sw_desc),
1861 				      &fl->addr, &fl->sdesc);
1862 		if (!fl->desc) {
1863 			ret = -ENOMEM;
1864 			goto err;
1865 		}
1866 
1867 		flsz = fl->size / 8 + s->stat_len / sizeof(struct tx_desc);
1868 		c.iqns_to_fl0congen |=
1869 			htonl(V_FW_IQ_CMD_FL0HOSTFCMODE(X_HOSTFCMODE_NONE) |
1870 			      (unlikely(rxq->usembufs) ?
1871 			       0 : F_FW_IQ_CMD_FL0PACKEN) |
1872 			      F_FW_IQ_CMD_FL0FETCHRO | F_FW_IQ_CMD_FL0DATARO |
1873 			      F_FW_IQ_CMD_FL0PADEN);
1874 		if (is_pf4(adap) && cong >= 0)
1875 			c.iqns_to_fl0congen |=
1876 				htonl(V_FW_IQ_CMD_FL0CNGCHMAP(cong) |
1877 				      F_FW_IQ_CMD_FL0CONGCIF |
1878 				      F_FW_IQ_CMD_FL0CONGEN);
1879 
1880 		/* In T6, for egress queue type FL there is internal overhead
1881 		 * of 16B for header going into FLM module.
1882 		 * Hence maximum allowed burst size will be 448 bytes.
1883 		 */
1884 		c.fl0dcaen_to_fl0cidxfthresh =
1885 			htons(V_FW_IQ_CMD_FL0FBMIN(chip_ver <= CHELSIO_T5 ?
1886 						   X_FETCHBURSTMIN_128B :
1887 						   X_FETCHBURSTMIN_64B) |
1888 			      V_FW_IQ_CMD_FL0FBMAX(chip_ver <= CHELSIO_T5 ?
1889 						   X_FETCHBURSTMAX_512B :
1890 						   X_FETCHBURSTMAX_256B));
1891 		c.fl0size = htons(flsz);
1892 		c.fl0addr = cpu_to_be64(fl->addr);
1893 	}
1894 
1895 	if (is_pf4(adap))
1896 		ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
1897 	else
1898 		ret = t4vf_wr_mbox(adap, &c, sizeof(c), &c);
1899 	if (ret)
1900 		goto err;
1901 
1902 	iq->cur_desc = iq->desc;
1903 	iq->cidx = 0;
1904 	iq->gts_idx = 0;
1905 	iq->gen = 1;
1906 	iq->next_intr_params = iq->intr_params;
1907 	iq->cntxt_id = ntohs(c.iqid);
1908 	iq->abs_id = ntohs(c.physiqid);
1909 	iq->bar2_addr = bar2_address(adap, iq->cntxt_id, T4_BAR2_QTYPE_INGRESS,
1910 				     &iq->bar2_qid);
1911 	iq->size--;                           /* subtract status entry */
1912 	iq->stat = (void *)&iq->desc[iq->size * 8];
1913 	iq->eth_dev = eth_dev;
1914 	iq->handler = hnd;
1915 	iq->port_id = pi->pidx;
1916 	iq->mb_pool = mp;
1917 
1918 	/* set offset to -1 to distinguish ingress queues without FL */
1919 	iq->offset = fl ? 0 : -1;
1920 
1921 	if (fl) {
1922 		fl->cntxt_id = ntohs(c.fl0id);
1923 		fl->avail = 0;
1924 		fl->pend_cred = 0;
1925 		fl->pidx = 0;
1926 		fl->cidx = 0;
1927 		fl->alloc_failed = 0;
1928 
1929 		/*
1930 		 * Note, we must initialize the BAR2 Free List User Doorbell
1931 		 * information before refilling the Free List!
1932 		 */
1933 		fl->bar2_addr = bar2_address(adap, fl->cntxt_id,
1934 					     T4_BAR2_QTYPE_EGRESS,
1935 					     &fl->bar2_qid);
1936 
1937 		nb_refill = refill_fl(adap, fl, fl_cap(fl));
1938 		if (nb_refill != fl_cap(fl)) {
1939 			ret = -ENOMEM;
1940 			dev_err(adap, "%s: mbuf alloc failed with error: %d\n",
1941 				__func__, ret);
1942 			goto refill_fl_err;
1943 		}
1944 	}
1945 
1946 	/*
1947 	 * For T5 and later we attempt to set up the Congestion Manager values
1948 	 * of the new RX Ethernet Queue.  This should really be handled by
1949 	 * firmware because it's more complex than any host driver wants to
1950 	 * get involved with and it's different per chip and this is almost
1951 	 * certainly wrong.  Formware would be wrong as well, but it would be
1952 	 * a lot easier to fix in one place ...  For now we do something very
1953 	 * simple (and hopefully less wrong).
1954 	 */
1955 	if (is_pf4(adap) && !is_t4(adap->params.chip) && cong >= 0) {
1956 		u8 cng_ch_bits_log = adap->params.arch.cng_ch_bits_log;
1957 		u32 param, val, ch_map = 0;
1958 		int i;
1959 
1960 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DMAQ) |
1961 			 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DMAQ_CONM_CTXT) |
1962 			 V_FW_PARAMS_PARAM_YZ(iq->cntxt_id));
1963 		if (cong == 0) {
1964 			val = V_CONMCTXT_CNGTPMODE(X_CONMCTXT_CNGTPMODE_QUEUE);
1965 		} else {
1966 			val = V_CONMCTXT_CNGTPMODE(
1967 					X_CONMCTXT_CNGTPMODE_CHANNEL);
1968 			for (i = 0; i < 4; i++) {
1969 				if (cong & (1 << i))
1970 					ch_map |= 1 << (i << cng_ch_bits_log);
1971 			}
1972 			val |= V_CONMCTXT_CNGCHMAP(ch_map);
1973 		}
1974 		ret = t4_set_params(adap, adap->mbox, adap->pf, 0, 1,
1975 				    &param, &val);
1976 		if (ret)
1977 			dev_warn(adap->pdev_dev, "Failed to set Congestion Manager Context for Ingress Queue %d: %d\n",
1978 				 iq->cntxt_id, -ret);
1979 	}
1980 
1981 	return 0;
1982 
1983 refill_fl_err:
1984 	t4_iq_free(adap, adap->mbox, adap->pf, 0, FW_IQ_TYPE_FL_INT_CAP,
1985 		   iq->cntxt_id, fl->cntxt_id, 0xffff);
1986 err:
1987 	iq->cntxt_id = 0;
1988 	iq->abs_id = 0;
1989 	if (iq->desc)
1990 		iq->desc = NULL;
1991 
1992 	if (fl && fl->desc) {
1993 		rte_free(fl->sdesc);
1994 		fl->cntxt_id = 0;
1995 		fl->sdesc = NULL;
1996 		fl->desc = NULL;
1997 	}
1998 	return ret;
1999 }
2000 
2001 static void init_txq(struct adapter *adap, struct sge_txq *q, unsigned int id,
2002 		     unsigned int abs_id)
2003 {
2004 	q->cntxt_id = id;
2005 	q->abs_id = abs_id;
2006 	q->bar2_addr = bar2_address(adap, q->cntxt_id, T4_BAR2_QTYPE_EGRESS,
2007 				    &q->bar2_qid);
2008 	q->cidx = 0;
2009 	q->pidx = 0;
2010 	q->dbidx = 0;
2011 	q->in_use = 0;
2012 	q->equeidx = 0;
2013 	q->coalesce.idx = 0;
2014 	q->coalesce.len = 0;
2015 	q->coalesce.flits = 0;
2016 	q->last_coal_idx = 0;
2017 	q->last_pidx = 0;
2018 	q->stat = (void *)&q->desc[q->size];
2019 }
2020 
2021 int t4_sge_eth_txq_start(struct sge_eth_txq *txq)
2022 {
2023 	/*
2024 	 *  TODO: For flow-control, queue may be stopped waiting to reclaim
2025 	 *  credits.
2026 	 *  Ensure queue is in EQ_STOPPED state before starting it.
2027 	 */
2028 	if (!(txq->flags & EQ_STOPPED))
2029 		return -(EBUSY);
2030 
2031 	txq->flags &= ~EQ_STOPPED;
2032 
2033 	return 0;
2034 }
2035 
2036 int t4_sge_eth_txq_stop(struct sge_eth_txq *txq)
2037 {
2038 	txq->flags |= EQ_STOPPED;
2039 
2040 	return 0;
2041 }
2042 
2043 int t4_sge_alloc_eth_txq(struct adapter *adap, struct sge_eth_txq *txq,
2044 			 struct rte_eth_dev *eth_dev, uint16_t queue_id,
2045 			 unsigned int iqid, int socket_id)
2046 {
2047 	int ret, nentries;
2048 	struct fw_eq_eth_cmd c;
2049 	struct sge *s = &adap->sge;
2050 	struct port_info *pi = eth_dev->data->dev_private;
2051 	u8 pciechan;
2052 
2053 	/* Add status entries */
2054 	nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
2055 
2056 	txq->q.desc = alloc_ring(eth_dev, "tx_ring", queue_id, socket_id,
2057 				 txq->q.size, sizeof(struct tx_desc),
2058 				 s->stat_len, sizeof(struct tx_sw_desc),
2059 				 &txq->q.phys_addr, &txq->q.sdesc);
2060 	if (!txq->q.desc)
2061 		return -ENOMEM;
2062 
2063 	memset(&c, 0, sizeof(c));
2064 	c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
2065 			    F_FW_CMD_WRITE | F_FW_CMD_EXEC);
2066 	if (is_pf4(adap)) {
2067 		pciechan = pi->tx_chan;
2068 		c.op_to_vfn |= htonl(V_FW_EQ_ETH_CMD_PFN(adap->pf) |
2069 				     V_FW_EQ_ETH_CMD_VFN(0));
2070 	} else {
2071 		pciechan = pi->port_id;
2072 	}
2073 
2074 	c.alloc_to_len16 = htonl(F_FW_EQ_ETH_CMD_ALLOC |
2075 				 F_FW_EQ_ETH_CMD_EQSTART | (sizeof(c) / 16));
2076 	c.autoequiqe_to_viid = htonl(F_FW_EQ_ETH_CMD_AUTOEQUEQE |
2077 				     V_FW_EQ_ETH_CMD_VIID(pi->viid));
2078 	c.fetchszm_to_iqid =
2079 		htonl(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_NONE) |
2080 		      V_FW_EQ_ETH_CMD_PCIECHN(pciechan) |
2081 		      F_FW_EQ_ETH_CMD_FETCHRO | V_FW_EQ_ETH_CMD_IQID(iqid));
2082 	c.dcaen_to_eqsize =
2083 		htonl(V_FW_EQ_ETH_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2084 		      V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2085 		      V_FW_EQ_ETH_CMD_EQSIZE(nentries));
2086 	c.eqaddr = rte_cpu_to_be_64(txq->q.phys_addr);
2087 
2088 	if (is_pf4(adap))
2089 		ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
2090 	else
2091 		ret = t4vf_wr_mbox(adap, &c, sizeof(c), &c);
2092 	if (ret) {
2093 		rte_free(txq->q.sdesc);
2094 		txq->q.sdesc = NULL;
2095 		txq->q.desc = NULL;
2096 		return ret;
2097 	}
2098 
2099 	init_txq(adap, &txq->q, G_FW_EQ_ETH_CMD_EQID(ntohl(c.eqid_pkd)),
2100 		 G_FW_EQ_ETH_CMD_PHYSEQID(ntohl(c.physeqid_pkd)));
2101 	txq->stats.tso = 0;
2102 	txq->stats.pkts = 0;
2103 	txq->stats.tx_cso = 0;
2104 	txq->stats.coal_wr = 0;
2105 	txq->stats.vlan_ins = 0;
2106 	txq->stats.tx_bytes = 0;
2107 	txq->stats.coal_pkts = 0;
2108 	txq->stats.mapping_err = 0;
2109 	txq->flags |= EQ_STOPPED;
2110 	txq->eth_dev = eth_dev;
2111 	txq->data = eth_dev->data;
2112 	t4_os_lock_init(&txq->txq_lock);
2113 	return 0;
2114 }
2115 
2116 int t4_sge_alloc_ctrl_txq(struct adapter *adap, struct sge_ctrl_txq *txq,
2117 			  struct rte_eth_dev *eth_dev, uint16_t queue_id,
2118 			  unsigned int iqid, int socket_id)
2119 {
2120 	int ret, nentries;
2121 	struct fw_eq_ctrl_cmd c;
2122 	struct sge *s = &adap->sge;
2123 	struct port_info *pi = eth_dev->data->dev_private;
2124 
2125 	/* Add status entries */
2126 	nentries = txq->q.size + s->stat_len / sizeof(struct tx_desc);
2127 
2128 	txq->q.desc = alloc_ring(eth_dev, "ctrl_tx_ring", queue_id,
2129 				 socket_id, txq->q.size, sizeof(struct tx_desc),
2130 				 0, 0, &txq->q.phys_addr, NULL);
2131 	if (!txq->q.desc)
2132 		return -ENOMEM;
2133 
2134 	memset(&c, 0, sizeof(c));
2135 	c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_CTRL_CMD) | F_FW_CMD_REQUEST |
2136 			    F_FW_CMD_WRITE | F_FW_CMD_EXEC |
2137 			    V_FW_EQ_CTRL_CMD_PFN(adap->pf) |
2138 			    V_FW_EQ_CTRL_CMD_VFN(0));
2139 	c.alloc_to_len16 = htonl(F_FW_EQ_CTRL_CMD_ALLOC |
2140 				 F_FW_EQ_CTRL_CMD_EQSTART | (sizeof(c) / 16));
2141 	c.cmpliqid_eqid = htonl(V_FW_EQ_CTRL_CMD_CMPLIQID(0));
2142 	c.physeqid_pkd = htonl(0);
2143 	c.fetchszm_to_iqid =
2144 		htonl(V_FW_EQ_CTRL_CMD_HOSTFCMODE(X_HOSTFCMODE_NONE) |
2145 		      V_FW_EQ_CTRL_CMD_PCIECHN(pi->tx_chan) |
2146 		      F_FW_EQ_CTRL_CMD_FETCHRO | V_FW_EQ_CTRL_CMD_IQID(iqid));
2147 	c.dcaen_to_eqsize =
2148 		htonl(V_FW_EQ_CTRL_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2149 		      V_FW_EQ_CTRL_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2150 		      V_FW_EQ_CTRL_CMD_EQSIZE(nentries));
2151 	c.eqaddr = cpu_to_be64(txq->q.phys_addr);
2152 
2153 	ret = t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), &c);
2154 	if (ret) {
2155 		txq->q.desc = NULL;
2156 		return ret;
2157 	}
2158 
2159 	init_txq(adap, &txq->q, G_FW_EQ_CTRL_CMD_EQID(ntohl(c.cmpliqid_eqid)),
2160 		 G_FW_EQ_CTRL_CMD_EQID(ntohl(c. physeqid_pkd)));
2161 	txq->adapter = adap;
2162 	txq->full = 0;
2163 	return 0;
2164 }
2165 
2166 static void free_txq(struct sge_txq *q)
2167 {
2168 	q->cntxt_id = 0;
2169 	q->sdesc = NULL;
2170 	q->desc = NULL;
2171 }
2172 
2173 static void free_rspq_fl(struct adapter *adap, struct sge_rspq *rq,
2174 			 struct sge_fl *fl)
2175 {
2176 	unsigned int fl_id = fl ? fl->cntxt_id : 0xffff;
2177 
2178 	t4_iq_free(adap, adap->mbox, adap->pf, 0, FW_IQ_TYPE_FL_INT_CAP,
2179 		   rq->cntxt_id, fl_id, 0xffff);
2180 	rq->cntxt_id = 0;
2181 	rq->abs_id = 0;
2182 	rq->desc = NULL;
2183 
2184 	if (fl) {
2185 		free_rx_bufs(fl, fl->avail);
2186 		rte_free(fl->sdesc);
2187 		fl->sdesc = NULL;
2188 		fl->cntxt_id = 0;
2189 		fl->desc = NULL;
2190 	}
2191 }
2192 
2193 /*
2194  * Clear all queues of the port
2195  *
2196  * Note:  This function must only be called after rx and tx path
2197  * of the port have been disabled.
2198  */
2199 void t4_sge_eth_clear_queues(struct port_info *pi)
2200 {
2201 	struct adapter *adap = pi->adapter;
2202 	struct sge_eth_rxq *rxq;
2203 	struct sge_eth_txq *txq;
2204 	int i;
2205 
2206 	rxq = &adap->sge.ethrxq[pi->first_rxqset];
2207 	for (i = 0; i < pi->n_rx_qsets; i++, rxq++) {
2208 		if (rxq->rspq.desc)
2209 			t4_sge_eth_rxq_stop(adap, rxq);
2210 	}
2211 
2212 	txq = &adap->sge.ethtxq[pi->first_txqset];
2213 	for (i = 0; i < pi->n_tx_qsets; i++, txq++) {
2214 		if (txq->q.desc) {
2215 			struct sge_txq *q = &txq->q;
2216 
2217 			t4_sge_eth_txq_stop(txq);
2218 			reclaim_completed_tx(q);
2219 			free_tx_desc(q, q->size);
2220 			q->equeidx = q->pidx;
2221 		}
2222 	}
2223 }
2224 
2225 void t4_sge_eth_rxq_release(struct adapter *adap, struct sge_eth_rxq *rxq)
2226 {
2227 	if (rxq->rspq.desc) {
2228 		t4_sge_eth_rxq_stop(adap, rxq);
2229 		free_rspq_fl(adap, &rxq->rspq, rxq->fl.size ? &rxq->fl : NULL);
2230 	}
2231 }
2232 
2233 void t4_sge_eth_txq_release(struct adapter *adap, struct sge_eth_txq *txq)
2234 {
2235 	if (txq->q.desc) {
2236 		t4_sge_eth_txq_stop(txq);
2237 		reclaim_completed_tx(&txq->q);
2238 		t4_eth_eq_free(adap, adap->mbox, adap->pf, 0, txq->q.cntxt_id);
2239 		free_tx_desc(&txq->q, txq->q.size);
2240 		rte_free(txq->q.sdesc);
2241 		free_txq(&txq->q);
2242 	}
2243 }
2244 
2245 void t4_sge_eth_release_queues(struct port_info *pi)
2246 {
2247 	struct adapter *adap = pi->adapter;
2248 	struct sge_eth_rxq *rxq;
2249 	struct sge_eth_txq *txq;
2250 	unsigned int i;
2251 
2252 	rxq = &adap->sge.ethrxq[pi->first_rxqset];
2253 	/* clean up Ethernet Tx/Rx queues */
2254 	for (i = 0; i < pi->n_rx_qsets; i++, rxq++) {
2255 		/* Free only the queues allocated */
2256 		if (rxq->rspq.desc) {
2257 			t4_sge_eth_rxq_release(adap, rxq);
2258 			rte_eth_dma_zone_free(rxq->rspq.eth_dev, "fl_ring", i);
2259 			rte_eth_dma_zone_free(rxq->rspq.eth_dev, "rx_ring", i);
2260 			rxq->rspq.eth_dev = NULL;
2261 		}
2262 	}
2263 
2264 	txq = &adap->sge.ethtxq[pi->first_txqset];
2265 	for (i = 0; i < pi->n_tx_qsets; i++, txq++) {
2266 		/* Free only the queues allocated */
2267 		if (txq->q.desc) {
2268 			t4_sge_eth_txq_release(adap, txq);
2269 			rte_eth_dma_zone_free(txq->eth_dev, "tx_ring", i);
2270 			txq->eth_dev = NULL;
2271 		}
2272 	}
2273 }
2274 
2275 void t4_sge_tx_monitor_start(struct adapter *adap)
2276 {
2277 	rte_eal_alarm_set(50, tx_timer_cb, (void *)adap);
2278 }
2279 
2280 void t4_sge_tx_monitor_stop(struct adapter *adap)
2281 {
2282 	rte_eal_alarm_cancel(tx_timer_cb, (void *)adap);
2283 }
2284 
2285 /**
2286  * t4_free_sge_resources - free SGE resources
2287  * @adap: the adapter
2288  *
2289  * Frees resources used by the SGE queue sets.
2290  */
2291 void t4_free_sge_resources(struct adapter *adap)
2292 {
2293 	unsigned int i;
2294 
2295 	/* clean up control Tx queues */
2296 	for (i = 0; i < ARRAY_SIZE(adap->sge.ctrlq); i++) {
2297 		struct sge_ctrl_txq *cq = &adap->sge.ctrlq[i];
2298 
2299 		if (cq->q.desc) {
2300 			reclaim_completed_tx_imm(&cq->q);
2301 			t4_ctrl_eq_free(adap, adap->mbox, adap->pf, 0,
2302 					cq->q.cntxt_id);
2303 			rte_eth_dma_zone_free(adap->eth_dev, "ctrl_tx_ring", i);
2304 			rte_mempool_free(cq->mb_pool);
2305 			free_txq(&cq->q);
2306 		}
2307 	}
2308 
2309 	/* clean up firmware event queue */
2310 	if (adap->sge.fw_evtq.desc) {
2311 		free_rspq_fl(adap, &adap->sge.fw_evtq, NULL);
2312 		rte_eth_dma_zone_free(adap->eth_dev, "fwq_ring", 0);
2313 	}
2314 }
2315 
2316 /**
2317  * t4_sge_init - initialize SGE
2318  * @adap: the adapter
2319  *
2320  * Performs SGE initialization needed every time after a chip reset.
2321  * We do not initialize any of the queues here, instead the driver
2322  * top-level must request those individually.
2323  *
2324  * Called in two different modes:
2325  *
2326  *  1. Perform actual hardware initialization and record hard-coded
2327  *     parameters which were used.  This gets used when we're the
2328  *     Master PF and the Firmware Configuration File support didn't
2329  *     work for some reason.
2330  *
2331  *  2. We're not the Master PF or initialization was performed with
2332  *     a Firmware Configuration File.  In this case we need to grab
2333  *     any of the SGE operating parameters that we need to have in
2334  *     order to do our job and make sure we can live with them ...
2335  */
2336 static int t4_sge_init_soft(struct adapter *adap)
2337 {
2338 	struct sge *s = &adap->sge;
2339 	u32 fl_small_pg, fl_large_pg, fl_small_mtu, fl_large_mtu;
2340 	u32 timer_value_0_and_1, timer_value_2_and_3, timer_value_4_and_5;
2341 	u32 ingress_rx_threshold;
2342 
2343 	/*
2344 	 * Verify that CPL messages are going to the Ingress Queue for
2345 	 * process_responses() and that only packet data is going to the
2346 	 * Free Lists.
2347 	 */
2348 	if ((t4_read_reg(adap, A_SGE_CONTROL) & F_RXPKTCPLMODE) !=
2349 	    V_RXPKTCPLMODE(X_RXPKTCPLMODE_SPLIT)) {
2350 		dev_err(adap, "bad SGE CPL MODE\n");
2351 		return -EINVAL;
2352 	}
2353 
2354 	/*
2355 	 * Validate the Host Buffer Register Array indices that we want to
2356 	 * use ...
2357 	 *
2358 	 * XXX Note that we should really read through the Host Buffer Size
2359 	 * XXX register array and find the indices of the Buffer Sizes which
2360 	 * XXX meet our needs!
2361 	 */
2362 #define READ_FL_BUF(x) \
2363 	t4_read_reg(adap, A_SGE_FL_BUFFER_SIZE0 + (x) * sizeof(u32))
2364 
2365 	fl_small_pg = READ_FL_BUF(RX_SMALL_PG_BUF);
2366 	fl_large_pg = READ_FL_BUF(RX_LARGE_PG_BUF);
2367 	fl_small_mtu = READ_FL_BUF(RX_SMALL_MTU_BUF);
2368 	fl_large_mtu = READ_FL_BUF(RX_LARGE_MTU_BUF);
2369 
2370 	/*
2371 	 * We only bother using the Large Page logic if the Large Page Buffer
2372 	 * is larger than our Page Size Buffer.
2373 	 */
2374 	if (fl_large_pg <= fl_small_pg)
2375 		fl_large_pg = 0;
2376 
2377 #undef READ_FL_BUF
2378 
2379 	/*
2380 	 * The Page Size Buffer must be exactly equal to our Page Size and the
2381 	 * Large Page Size Buffer should be 0 (per above) or a power of 2.
2382 	 */
2383 	if (fl_small_pg != CXGBE_PAGE_SIZE ||
2384 	    (fl_large_pg & (fl_large_pg - 1)) != 0) {
2385 		dev_err(adap, "bad SGE FL page buffer sizes [%d, %d]\n",
2386 			fl_small_pg, fl_large_pg);
2387 		return -EINVAL;
2388 	}
2389 	if (fl_large_pg)
2390 		s->fl_pg_order = ilog2(fl_large_pg) - PAGE_SHIFT;
2391 
2392 	if (adap->use_unpacked_mode) {
2393 		int err = 0;
2394 
2395 		if (fl_small_mtu < FL_MTU_SMALL_BUFSIZE(adap)) {
2396 			dev_err(adap, "bad SGE FL small MTU %d\n",
2397 				fl_small_mtu);
2398 			err = -EINVAL;
2399 		}
2400 		if (fl_large_mtu < FL_MTU_LARGE_BUFSIZE(adap)) {
2401 			dev_err(adap, "bad SGE FL large MTU %d\n",
2402 				fl_large_mtu);
2403 			err = -EINVAL;
2404 		}
2405 		if (err)
2406 			return err;
2407 	}
2408 
2409 	/*
2410 	 * Retrieve our RX interrupt holdoff timer values and counter
2411 	 * threshold values from the SGE parameters.
2412 	 */
2413 	timer_value_0_and_1 = t4_read_reg(adap, A_SGE_TIMER_VALUE_0_AND_1);
2414 	timer_value_2_and_3 = t4_read_reg(adap, A_SGE_TIMER_VALUE_2_AND_3);
2415 	timer_value_4_and_5 = t4_read_reg(adap, A_SGE_TIMER_VALUE_4_AND_5);
2416 	s->timer_val[0] = core_ticks_to_us(adap,
2417 					   G_TIMERVALUE0(timer_value_0_and_1));
2418 	s->timer_val[1] = core_ticks_to_us(adap,
2419 					   G_TIMERVALUE1(timer_value_0_and_1));
2420 	s->timer_val[2] = core_ticks_to_us(adap,
2421 					   G_TIMERVALUE2(timer_value_2_and_3));
2422 	s->timer_val[3] = core_ticks_to_us(adap,
2423 					   G_TIMERVALUE3(timer_value_2_and_3));
2424 	s->timer_val[4] = core_ticks_to_us(adap,
2425 					   G_TIMERVALUE4(timer_value_4_and_5));
2426 	s->timer_val[5] = core_ticks_to_us(adap,
2427 					   G_TIMERVALUE5(timer_value_4_and_5));
2428 
2429 	ingress_rx_threshold = t4_read_reg(adap, A_SGE_INGRESS_RX_THRESHOLD);
2430 	s->counter_val[0] = G_THRESHOLD_0(ingress_rx_threshold);
2431 	s->counter_val[1] = G_THRESHOLD_1(ingress_rx_threshold);
2432 	s->counter_val[2] = G_THRESHOLD_2(ingress_rx_threshold);
2433 	s->counter_val[3] = G_THRESHOLD_3(ingress_rx_threshold);
2434 
2435 	return 0;
2436 }
2437 
2438 int t4_sge_init(struct adapter *adap)
2439 {
2440 	struct sge *s = &adap->sge;
2441 	u32 sge_control, sge_conm_ctrl;
2442 	int ret, egress_threshold;
2443 
2444 	/*
2445 	 * Ingress Padding Boundary and Egress Status Page Size are set up by
2446 	 * t4_fixup_host_params().
2447 	 */
2448 	sge_control = t4_read_reg(adap, A_SGE_CONTROL);
2449 	s->pktshift = G_PKTSHIFT(sge_control);
2450 	s->stat_len = (sge_control & F_EGRSTATUSPAGESIZE) ? 128 : 64;
2451 	s->fl_align = t4_fl_pkt_align(adap);
2452 	ret = t4_sge_init_soft(adap);
2453 	if (ret < 0) {
2454 		dev_err(adap, "%s: t4_sge_init_soft failed, error %d\n",
2455 			__func__, -ret);
2456 		return ret;
2457 	}
2458 
2459 	/*
2460 	 * A FL with <= fl_starve_thres buffers is starving and a periodic
2461 	 * timer will attempt to refill it.  This needs to be larger than the
2462 	 * SGE's Egress Congestion Threshold.  If it isn't, then we can get
2463 	 * stuck waiting for new packets while the SGE is waiting for us to
2464 	 * give it more Free List entries.  (Note that the SGE's Egress
2465 	 * Congestion Threshold is in units of 2 Free List pointers.)  For T4,
2466 	 * there was only a single field to control this.  For T5 there's the
2467 	 * original field which now only applies to Unpacked Mode Free List
2468 	 * buffers and a new field which only applies to Packed Mode Free List
2469 	 * buffers.
2470 	 */
2471 	sge_conm_ctrl = t4_read_reg(adap, A_SGE_CONM_CTRL);
2472 	if (is_t4(adap->params.chip) || adap->use_unpacked_mode)
2473 		egress_threshold = G_EGRTHRESHOLD(sge_conm_ctrl);
2474 	else
2475 		egress_threshold = G_EGRTHRESHOLDPACKING(sge_conm_ctrl);
2476 	s->fl_starve_thres = 2 * egress_threshold + 1;
2477 
2478 	return 0;
2479 }
2480 
2481 int t4vf_sge_init(struct adapter *adap)
2482 {
2483 	struct sge_params *sge_params = &adap->params.sge;
2484 	u32 sge_ingress_queues_per_page;
2485 	u32 sge_egress_queues_per_page;
2486 	u32 sge_control, sge_control2;
2487 	u32 fl_small_pg, fl_large_pg;
2488 	u32 sge_ingress_rx_threshold;
2489 	u32 sge_timer_value_0_and_1;
2490 	u32 sge_timer_value_2_and_3;
2491 	u32 sge_timer_value_4_and_5;
2492 	u32 sge_congestion_control;
2493 	struct sge *s = &adap->sge;
2494 	unsigned int s_hps, s_qpp;
2495 	u32 sge_host_page_size;
2496 	u32 params[7], vals[7];
2497 	int v;
2498 
2499 	/* query basic params from fw */
2500 	params[0] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2501 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_CONTROL));
2502 	params[1] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2503 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_HOST_PAGE_SIZE));
2504 	params[2] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2505 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_FL_BUFFER_SIZE0));
2506 	params[3] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2507 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_FL_BUFFER_SIZE1));
2508 	params[4] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2509 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_TIMER_VALUE_0_AND_1));
2510 	params[5] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2511 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_TIMER_VALUE_2_AND_3));
2512 	params[6] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2513 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_TIMER_VALUE_4_AND_5));
2514 	v = t4vf_query_params(adap, 7, params, vals);
2515 	if (v != FW_SUCCESS)
2516 		return v;
2517 
2518 	sge_control = vals[0];
2519 	sge_host_page_size = vals[1];
2520 	fl_small_pg = vals[2];
2521 	fl_large_pg = vals[3];
2522 	sge_timer_value_0_and_1 = vals[4];
2523 	sge_timer_value_2_and_3 = vals[5];
2524 	sge_timer_value_4_and_5 = vals[6];
2525 
2526 	/*
2527 	 * Start by vetting the basic SGE parameters which have been set up by
2528 	 * the Physical Function Driver.
2529 	 */
2530 
2531 	/* We only bother using the Large Page logic if the Large Page Buffer
2532 	 * is larger than our Page Size Buffer.
2533 	 */
2534 	if (fl_large_pg <= fl_small_pg)
2535 		fl_large_pg = 0;
2536 
2537 	/* The Page Size Buffer must be exactly equal to our Page Size and the
2538 	 * Large Page Size Buffer should be 0 (per above) or a power of 2.
2539 	 */
2540 	if (fl_small_pg != CXGBE_PAGE_SIZE ||
2541 	    (fl_large_pg & (fl_large_pg - 1)) != 0) {
2542 		dev_err(adapter->pdev_dev, "bad SGE FL buffer sizes [%d, %d]\n",
2543 			fl_small_pg, fl_large_pg);
2544 		return -EINVAL;
2545 	}
2546 
2547 	if ((sge_control & F_RXPKTCPLMODE) !=
2548 	    V_RXPKTCPLMODE(X_RXPKTCPLMODE_SPLIT)) {
2549 		dev_err(adapter->pdev_dev, "bad SGE CPL MODE\n");
2550 		return -EINVAL;
2551 	}
2552 
2553 
2554 	/* Grab ingress packing boundary from SGE_CONTROL2 for */
2555 	params[0] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2556 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_CONTROL2));
2557 	v = t4vf_query_params(adap, 1, params, vals);
2558 	if (v != FW_SUCCESS) {
2559 		dev_err(adapter, "Unable to get SGE Control2; "
2560 			"probably old firmware.\n");
2561 		return v;
2562 	}
2563 	sge_control2 = vals[0];
2564 
2565 	params[0] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2566 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_INGRESS_RX_THRESHOLD));
2567 	params[1] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2568 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_CONM_CTRL));
2569 	v = t4vf_query_params(adap, 2, params, vals);
2570 	if (v != FW_SUCCESS)
2571 		return v;
2572 	sge_ingress_rx_threshold = vals[0];
2573 	sge_congestion_control = vals[1];
2574 	params[0] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2575 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_EGRESS_QUEUES_PER_PAGE_VF));
2576 	params[1] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_REG) |
2577 		     V_FW_PARAMS_PARAM_XYZ(A_SGE_INGRESS_QUEUES_PER_PAGE_VF));
2578 	v = t4vf_query_params(adap, 2, params, vals);
2579 	if (v != FW_SUCCESS) {
2580 		dev_warn(adap, "Unable to get VF SGE Queues/Page; "
2581 			 "probably old firmware.\n");
2582 		return v;
2583 	}
2584 	sge_egress_queues_per_page = vals[0];
2585 	sge_ingress_queues_per_page = vals[1];
2586 
2587 	/*
2588 	 * We need the Queues/Page for our VF.  This is based on the
2589 	 * PF from which we're instantiated and is indexed in the
2590 	 * register we just read.
2591 	 */
2592 	s_hps = (S_HOSTPAGESIZEPF0 +
2593 		 (S_HOSTPAGESIZEPF1 - S_HOSTPAGESIZEPF0) * adap->pf);
2594 	sge_params->hps =
2595 		((sge_host_page_size >> s_hps) & M_HOSTPAGESIZEPF0);
2596 
2597 	s_qpp = (S_QUEUESPERPAGEPF0 +
2598 		 (S_QUEUESPERPAGEPF1 - S_QUEUESPERPAGEPF0) * adap->pf);
2599 	sge_params->eq_qpp =
2600 		((sge_egress_queues_per_page >> s_qpp)
2601 		 & M_QUEUESPERPAGEPF0);
2602 	sge_params->iq_qpp =
2603 		((sge_ingress_queues_per_page >> s_qpp)
2604 		 & M_QUEUESPERPAGEPF0);
2605 
2606 	/*
2607 	 * Now translate the queried parameters into our internal forms.
2608 	 */
2609 	if (fl_large_pg)
2610 		s->fl_pg_order = ilog2(fl_large_pg) - PAGE_SHIFT;
2611 	s->stat_len = ((sge_control & F_EGRSTATUSPAGESIZE)
2612 			? 128 : 64);
2613 	s->pktshift = G_PKTSHIFT(sge_control);
2614 	s->fl_align = t4vf_fl_pkt_align(adap, sge_control, sge_control2);
2615 
2616 	/*
2617 	 * A FL with <= fl_starve_thres buffers is starving and a periodic
2618 	 * timer will attempt to refill it.  This needs to be larger than the
2619 	 * SGE's Egress Congestion Threshold.  If it isn't, then we can get
2620 	 * stuck waiting for new packets while the SGE is waiting for us to
2621 	 * give it more Free List entries.  (Note that the SGE's Egress
2622 	 * Congestion Threshold is in units of 2 Free List pointers.)
2623 	 */
2624 	switch (CHELSIO_CHIP_VERSION(adap->params.chip)) {
2625 	case CHELSIO_T5:
2626 		s->fl_starve_thres =
2627 			G_EGRTHRESHOLDPACKING(sge_congestion_control);
2628 		break;
2629 	case CHELSIO_T6:
2630 	default:
2631 		s->fl_starve_thres =
2632 			G_T6_EGRTHRESHOLDPACKING(sge_congestion_control);
2633 		break;
2634 	}
2635 	s->fl_starve_thres = s->fl_starve_thres * 2 + 1;
2636 
2637 	/*
2638 	 * Save RX interrupt holdoff timer values and counter
2639 	 * threshold values from the SGE parameters.
2640 	 */
2641 	s->timer_val[0] = core_ticks_to_us(adap,
2642 			G_TIMERVALUE0(sge_timer_value_0_and_1));
2643 	s->timer_val[1] = core_ticks_to_us(adap,
2644 			G_TIMERVALUE1(sge_timer_value_0_and_1));
2645 	s->timer_val[2] = core_ticks_to_us(adap,
2646 			G_TIMERVALUE2(sge_timer_value_2_and_3));
2647 	s->timer_val[3] = core_ticks_to_us(adap,
2648 			G_TIMERVALUE3(sge_timer_value_2_and_3));
2649 	s->timer_val[4] = core_ticks_to_us(adap,
2650 			G_TIMERVALUE4(sge_timer_value_4_and_5));
2651 	s->timer_val[5] = core_ticks_to_us(adap,
2652 			G_TIMERVALUE5(sge_timer_value_4_and_5));
2653 	s->counter_val[0] = G_THRESHOLD_0(sge_ingress_rx_threshold);
2654 	s->counter_val[1] = G_THRESHOLD_1(sge_ingress_rx_threshold);
2655 	s->counter_val[2] = G_THRESHOLD_2(sge_ingress_rx_threshold);
2656 	s->counter_val[3] = G_THRESHOLD_3(sge_ingress_rx_threshold);
2657 	return 0;
2658 }
2659