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