xref: /freebsd/sys/dev/sfxge/sfxge_tx.c (revision cc349066556bcdeed0d6cc72aad340d0f383e35c)
1 /*-
2  * Copyright (c) 2010-2016 Solarflare Communications Inc.
3  * All rights reserved.
4  *
5  * This software was developed in part by Philip Paeps under contract for
6  * Solarflare Communications, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright notice,
12  *    this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright notice,
14  *    this list of conditions and the following disclaimer in the documentation
15  *    and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
19  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
24  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
27  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * The views and conclusions contained in the software and documentation are
30  * those of the authors and should not be interpreted as representing official
31  * policies, either expressed or implied, of the FreeBSD Project.
32  */
33 
34 /* Theory of operation:
35  *
36  * Tx queues allocation and mapping
37  *
38  * One Tx queue with enabled checksum offload is allocated per Rx channel
39  * (event queue).  Also 2 Tx queues (one without checksum offload and one
40  * with IP checksum offload only) are allocated and bound to event queue 0.
41  * sfxge_txq_type is used as Tx queue label.
42  *
43  * So, event queue plus label mapping to Tx queue index is:
44  *	if event queue index is 0, TxQ-index = TxQ-label * [0..SFXGE_TXQ_NTYPES)
45  *	else TxQ-index = SFXGE_TXQ_NTYPES + EvQ-index - 1
46  * See sfxge_get_txq_by_label() sfxge_ev.c
47  */
48 
49 #include <sys/cdefs.h>
50 __FBSDID("$FreeBSD$");
51 
52 #include "opt_rss.h"
53 
54 #include <sys/param.h>
55 #include <sys/malloc.h>
56 #include <sys/mbuf.h>
57 #include <sys/smp.h>
58 #include <sys/socket.h>
59 #include <sys/sysctl.h>
60 #include <sys/syslog.h>
61 #include <sys/limits.h>
62 
63 #include <net/bpf.h>
64 #include <net/ethernet.h>
65 #include <net/if.h>
66 #include <net/if_vlan_var.h>
67 
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip6.h>
71 #include <netinet/tcp.h>
72 
73 #ifdef RSS
74 #include <net/rss_config.h>
75 #endif
76 
77 #include "common/efx.h"
78 
79 #include "sfxge.h"
80 #include "sfxge_tx.h"
81 
82 
83 #define	SFXGE_PARAM_TX_DPL_GET_MAX	SFXGE_PARAM(tx_dpl_get_max)
84 static int sfxge_tx_dpl_get_max = SFXGE_TX_DPL_GET_PKT_LIMIT_DEFAULT;
85 TUNABLE_INT(SFXGE_PARAM_TX_DPL_GET_MAX, &sfxge_tx_dpl_get_max);
86 SYSCTL_INT(_hw_sfxge, OID_AUTO, tx_dpl_get_max, CTLFLAG_RDTUN,
87 	   &sfxge_tx_dpl_get_max, 0,
88 	   "Maximum number of any packets in deferred packet get-list");
89 
90 #define	SFXGE_PARAM_TX_DPL_GET_NON_TCP_MAX \
91 	SFXGE_PARAM(tx_dpl_get_non_tcp_max)
92 static int sfxge_tx_dpl_get_non_tcp_max =
93 	SFXGE_TX_DPL_GET_NON_TCP_PKT_LIMIT_DEFAULT;
94 TUNABLE_INT(SFXGE_PARAM_TX_DPL_GET_NON_TCP_MAX, &sfxge_tx_dpl_get_non_tcp_max);
95 SYSCTL_INT(_hw_sfxge, OID_AUTO, tx_dpl_get_non_tcp_max, CTLFLAG_RDTUN,
96 	   &sfxge_tx_dpl_get_non_tcp_max, 0,
97 	   "Maximum number of non-TCP packets in deferred packet get-list");
98 
99 #define	SFXGE_PARAM_TX_DPL_PUT_MAX	SFXGE_PARAM(tx_dpl_put_max)
100 static int sfxge_tx_dpl_put_max = SFXGE_TX_DPL_PUT_PKT_LIMIT_DEFAULT;
101 TUNABLE_INT(SFXGE_PARAM_TX_DPL_PUT_MAX, &sfxge_tx_dpl_put_max);
102 SYSCTL_INT(_hw_sfxge, OID_AUTO, tx_dpl_put_max, CTLFLAG_RDTUN,
103 	   &sfxge_tx_dpl_put_max, 0,
104 	   "Maximum number of any packets in deferred packet put-list");
105 
106 #define	SFXGE_PARAM_TSO_FW_ASSISTED	SFXGE_PARAM(tso_fw_assisted)
107 static int sfxge_tso_fw_assisted = (SFXGE_FATSOV1 | SFXGE_FATSOV2);
108 TUNABLE_INT(SFXGE_PARAM_TSO_FW_ASSISTED, &sfxge_tso_fw_assisted);
109 SYSCTL_INT(_hw_sfxge, OID_AUTO, tso_fw_assisted, CTLFLAG_RDTUN,
110 	   &sfxge_tso_fw_assisted, 0,
111 	   "Bitmask of FW-assisted TSO allowed to use if supported by NIC firmware");
112 
113 
114 static const struct {
115 	const char *name;
116 	size_t offset;
117 } sfxge_tx_stats[] = {
118 #define	SFXGE_TX_STAT(name, member) \
119 	{ #name, offsetof(struct sfxge_txq, member) }
120 	SFXGE_TX_STAT(tso_bursts, tso_bursts),
121 	SFXGE_TX_STAT(tso_packets, tso_packets),
122 	SFXGE_TX_STAT(tso_long_headers, tso_long_headers),
123 	SFXGE_TX_STAT(tso_pdrop_too_many, tso_pdrop_too_many),
124 	SFXGE_TX_STAT(tso_pdrop_no_rsrc, tso_pdrop_no_rsrc),
125 	SFXGE_TX_STAT(tx_collapses, collapses),
126 	SFXGE_TX_STAT(tx_drops, drops),
127 	SFXGE_TX_STAT(tx_get_overflow, get_overflow),
128 	SFXGE_TX_STAT(tx_get_non_tcp_overflow, get_non_tcp_overflow),
129 	SFXGE_TX_STAT(tx_put_overflow, put_overflow),
130 	SFXGE_TX_STAT(tx_netdown_drops, netdown_drops),
131 };
132 
133 
134 /* Forward declarations. */
135 static void sfxge_tx_qdpl_service(struct sfxge_txq *txq);
136 static void sfxge_tx_qlist_post(struct sfxge_txq *txq);
137 static void sfxge_tx_qunblock(struct sfxge_txq *txq);
138 static int sfxge_tx_queue_tso(struct sfxge_txq *txq, struct mbuf *mbuf,
139 			      const bus_dma_segment_t *dma_seg, int n_dma_seg,
140 			      int vlan_tagged);
141 
142 static int
143 sfxge_tx_maybe_insert_tag(struct sfxge_txq *txq, struct mbuf *mbuf)
144 {
145 	uint16_t this_tag = ((mbuf->m_flags & M_VLANTAG) ?
146 			     mbuf->m_pkthdr.ether_vtag :
147 			     0);
148 
149 	if (this_tag == txq->hw_vlan_tci)
150 		return (0);
151 
152 	efx_tx_qdesc_vlantci_create(txq->common,
153 				    bswap16(this_tag),
154 				    &txq->pend_desc[0]);
155 	txq->n_pend_desc = 1;
156 	txq->hw_vlan_tci = this_tag;
157 	return (1);
158 }
159 
160 static inline void
161 sfxge_next_stmp(struct sfxge_txq *txq, struct sfxge_tx_mapping **pstmp)
162 {
163 	KASSERT((*pstmp)->flags == 0, ("stmp flags are not 0"));
164 	if (__predict_false(*pstmp ==
165 			    &txq->stmp[txq->ptr_mask]))
166 		*pstmp = &txq->stmp[0];
167 	else
168 		(*pstmp)++;
169 }
170 
171 
172 void
173 sfxge_tx_qcomplete(struct sfxge_txq *txq, struct sfxge_evq *evq)
174 {
175 	unsigned int completed;
176 
177 	SFXGE_EVQ_LOCK_ASSERT_OWNED(evq);
178 
179 	completed = txq->completed;
180 	while (completed != txq->pending) {
181 		struct sfxge_tx_mapping *stmp;
182 		unsigned int id;
183 
184 		id = completed++ & txq->ptr_mask;
185 
186 		stmp = &txq->stmp[id];
187 		if (stmp->flags & TX_BUF_UNMAP) {
188 			bus_dmamap_unload(txq->packet_dma_tag, stmp->map);
189 			if (stmp->flags & TX_BUF_MBUF) {
190 				struct mbuf *m = stmp->u.mbuf;
191 				do
192 					m = m_free(m);
193 				while (m != NULL);
194 			} else {
195 				free(stmp->u.heap_buf, M_SFXGE);
196 			}
197 			stmp->flags = 0;
198 		}
199 	}
200 	txq->completed = completed;
201 
202 	/* Check whether we need to unblock the queue. */
203 	mb();
204 	if (txq->blocked) {
205 		unsigned int level;
206 
207 		level = txq->added - txq->completed;
208 		if (level <= SFXGE_TXQ_UNBLOCK_LEVEL(txq->entries))
209 			sfxge_tx_qunblock(txq);
210 	}
211 }
212 
213 static unsigned int
214 sfxge_is_mbuf_non_tcp(struct mbuf *mbuf)
215 {
216 	/* Absence of TCP checksum flags does not mean that it is non-TCP
217 	 * but it should be true if user wants to achieve high throughput.
218 	 */
219 	return (!(mbuf->m_pkthdr.csum_flags & (CSUM_IP_TCP | CSUM_IP6_TCP)));
220 }
221 
222 /*
223  * Reorder the put list and append it to the get list.
224  */
225 static void
226 sfxge_tx_qdpl_swizzle(struct sfxge_txq *txq)
227 {
228 	struct sfxge_tx_dpl *stdp;
229 	struct mbuf *mbuf, *get_next, **get_tailp;
230 	volatile uintptr_t *putp;
231 	uintptr_t put;
232 	unsigned int count;
233 	unsigned int non_tcp_count;
234 
235 	SFXGE_TXQ_LOCK_ASSERT_OWNED(txq);
236 
237 	stdp = &txq->dpl;
238 
239 	/* Acquire the put list. */
240 	putp = &stdp->std_put;
241 	put = atomic_readandclear_ptr(putp);
242 	mbuf = (void *)put;
243 
244 	if (mbuf == NULL)
245 		return;
246 
247 	/* Reverse the put list. */
248 	get_tailp = &mbuf->m_nextpkt;
249 	get_next = NULL;
250 
251 	count = 0;
252 	non_tcp_count = 0;
253 	do {
254 		struct mbuf *put_next;
255 
256 		non_tcp_count += sfxge_is_mbuf_non_tcp(mbuf);
257 		put_next = mbuf->m_nextpkt;
258 		mbuf->m_nextpkt = get_next;
259 		get_next = mbuf;
260 		mbuf = put_next;
261 
262 		count++;
263 	} while (mbuf != NULL);
264 
265 	if (count > stdp->std_put_hiwat)
266 		stdp->std_put_hiwat = count;
267 
268 	/* Append the reversed put list to the get list. */
269 	KASSERT(*get_tailp == NULL, ("*get_tailp != NULL"));
270 	*stdp->std_getp = get_next;
271 	stdp->std_getp = get_tailp;
272 	stdp->std_get_count += count;
273 	stdp->std_get_non_tcp_count += non_tcp_count;
274 }
275 
276 static void
277 sfxge_tx_qreap(struct sfxge_txq *txq)
278 {
279 	SFXGE_TXQ_LOCK_ASSERT_OWNED(txq);
280 
281 	txq->reaped = txq->completed;
282 }
283 
284 static void
285 sfxge_tx_qlist_post(struct sfxge_txq *txq)
286 {
287 	unsigned int old_added;
288 	unsigned int block_level;
289 	unsigned int level;
290 	int rc;
291 
292 	SFXGE_TXQ_LOCK_ASSERT_OWNED(txq);
293 
294 	KASSERT(txq->n_pend_desc != 0, ("txq->n_pend_desc == 0"));
295 	KASSERT(txq->n_pend_desc <= txq->max_pkt_desc,
296 		("txq->n_pend_desc too large"));
297 	KASSERT(!txq->blocked, ("txq->blocked"));
298 
299 	old_added = txq->added;
300 
301 	/* Post the fragment list. */
302 	rc = efx_tx_qdesc_post(txq->common, txq->pend_desc, txq->n_pend_desc,
303 			  txq->reaped, &txq->added);
304 	KASSERT(rc == 0, ("efx_tx_qdesc_post() failed"));
305 
306 	/* If efx_tx_qdesc_post() had to refragment, our information about
307 	 * buffers to free may be associated with the wrong
308 	 * descriptors.
309 	 */
310 	KASSERT(txq->added - old_added == txq->n_pend_desc,
311 		("efx_tx_qdesc_post() refragmented descriptors"));
312 
313 	level = txq->added - txq->reaped;
314 	KASSERT(level <= txq->entries, ("overfilled TX queue"));
315 
316 	/* Clear the fragment list. */
317 	txq->n_pend_desc = 0;
318 
319 	/*
320 	 * Set the block level to ensure there is space to generate a
321 	 * large number of descriptors for TSO.
322 	 */
323 	block_level = EFX_TXQ_LIMIT(txq->entries) - txq->max_pkt_desc;
324 
325 	/* Have we reached the block level? */
326 	if (level < block_level)
327 		return;
328 
329 	/* Reap, and check again */
330 	sfxge_tx_qreap(txq);
331 	level = txq->added - txq->reaped;
332 	if (level < block_level)
333 		return;
334 
335 	txq->blocked = 1;
336 
337 	/*
338 	 * Avoid a race with completion interrupt handling that could leave
339 	 * the queue blocked.
340 	 */
341 	mb();
342 	sfxge_tx_qreap(txq);
343 	level = txq->added - txq->reaped;
344 	if (level < block_level) {
345 		mb();
346 		txq->blocked = 0;
347 	}
348 }
349 
350 static int sfxge_tx_queue_mbuf(struct sfxge_txq *txq, struct mbuf *mbuf)
351 {
352 	bus_dmamap_t *used_map;
353 	bus_dmamap_t map;
354 	bus_dma_segment_t dma_seg[SFXGE_TX_MAPPING_MAX_SEG];
355 	unsigned int id;
356 	struct sfxge_tx_mapping *stmp;
357 	efx_desc_t *desc;
358 	int n_dma_seg;
359 	int rc;
360 	int i;
361 	int eop;
362 	int vlan_tagged;
363 
364 	KASSERT(!txq->blocked, ("txq->blocked"));
365 
366 	if (mbuf->m_pkthdr.csum_flags & CSUM_TSO)
367 		prefetch_read_many(mbuf->m_data);
368 
369 	if (__predict_false(txq->init_state != SFXGE_TXQ_STARTED)) {
370 		rc = EINTR;
371 		goto reject;
372 	}
373 
374 	/* Load the packet for DMA. */
375 	id = txq->added & txq->ptr_mask;
376 	stmp = &txq->stmp[id];
377 	rc = bus_dmamap_load_mbuf_sg(txq->packet_dma_tag, stmp->map,
378 				     mbuf, dma_seg, &n_dma_seg, 0);
379 	if (rc == EFBIG) {
380 		/* Try again. */
381 		struct mbuf *new_mbuf = m_collapse(mbuf, M_NOWAIT,
382 						   SFXGE_TX_MAPPING_MAX_SEG);
383 		if (new_mbuf == NULL)
384 			goto reject;
385 		++txq->collapses;
386 		mbuf = new_mbuf;
387 		rc = bus_dmamap_load_mbuf_sg(txq->packet_dma_tag,
388 					     stmp->map, mbuf,
389 					     dma_seg, &n_dma_seg, 0);
390 	}
391 	if (rc != 0)
392 		goto reject;
393 
394 	/* Make the packet visible to the hardware. */
395 	bus_dmamap_sync(txq->packet_dma_tag, stmp->map, BUS_DMASYNC_PREWRITE);
396 
397 	used_map = &stmp->map;
398 
399 	vlan_tagged = sfxge_tx_maybe_insert_tag(txq, mbuf);
400 	if (vlan_tagged) {
401 		sfxge_next_stmp(txq, &stmp);
402 	}
403 	if (mbuf->m_pkthdr.csum_flags & CSUM_TSO) {
404 		rc = sfxge_tx_queue_tso(txq, mbuf, dma_seg, n_dma_seg, vlan_tagged);
405 		if (rc < 0)
406 			goto reject_mapped;
407 		stmp = &txq->stmp[(rc - 1) & txq->ptr_mask];
408 	} else {
409 		/* Add the mapping to the fragment list, and set flags
410 		 * for the buffer.
411 		 */
412 
413 		i = 0;
414 		for (;;) {
415 			desc = &txq->pend_desc[i + vlan_tagged];
416 			eop = (i == n_dma_seg - 1);
417 			efx_tx_qdesc_dma_create(txq->common,
418 						dma_seg[i].ds_addr,
419 						dma_seg[i].ds_len,
420 						eop,
421 						desc);
422 			if (eop)
423 				break;
424 			i++;
425 			sfxge_next_stmp(txq, &stmp);
426 		}
427 		txq->n_pend_desc = n_dma_seg + vlan_tagged;
428 	}
429 
430 	/*
431 	 * If the mapping required more than one descriptor
432 	 * then we need to associate the DMA map with the last
433 	 * descriptor, not the first.
434 	 */
435 	if (used_map != &stmp->map) {
436 		map = stmp->map;
437 		stmp->map = *used_map;
438 		*used_map = map;
439 	}
440 
441 	stmp->u.mbuf = mbuf;
442 	stmp->flags = TX_BUF_UNMAP | TX_BUF_MBUF;
443 
444 	/* Post the fragment list. */
445 	sfxge_tx_qlist_post(txq);
446 
447 	return (0);
448 
449 reject_mapped:
450 	bus_dmamap_unload(txq->packet_dma_tag, *used_map);
451 reject:
452 	/* Drop the packet on the floor. */
453 	m_freem(mbuf);
454 	++txq->drops;
455 
456 	return (rc);
457 }
458 
459 /*
460  * Drain the deferred packet list into the transmit queue.
461  */
462 static void
463 sfxge_tx_qdpl_drain(struct sfxge_txq *txq)
464 {
465 	struct sfxge_softc *sc;
466 	struct sfxge_tx_dpl *stdp;
467 	struct mbuf *mbuf, *next;
468 	unsigned int count;
469 	unsigned int non_tcp_count;
470 	unsigned int pushed;
471 	int rc;
472 
473 	SFXGE_TXQ_LOCK_ASSERT_OWNED(txq);
474 
475 	sc = txq->sc;
476 	stdp = &txq->dpl;
477 	pushed = txq->added;
478 
479 	if (__predict_true(txq->init_state == SFXGE_TXQ_STARTED)) {
480 		prefetch_read_many(sc->enp);
481 		prefetch_read_many(txq->common);
482 	}
483 
484 	mbuf = stdp->std_get;
485 	count = stdp->std_get_count;
486 	non_tcp_count = stdp->std_get_non_tcp_count;
487 
488 	if (count > stdp->std_get_hiwat)
489 		stdp->std_get_hiwat = count;
490 
491 	while (count != 0) {
492 		KASSERT(mbuf != NULL, ("mbuf == NULL"));
493 
494 		next = mbuf->m_nextpkt;
495 		mbuf->m_nextpkt = NULL;
496 
497 		ETHER_BPF_MTAP(sc->ifnet, mbuf); /* packet capture */
498 
499 		if (next != NULL)
500 			prefetch_read_many(next);
501 
502 		rc = sfxge_tx_queue_mbuf(txq, mbuf);
503 		--count;
504 		non_tcp_count -= sfxge_is_mbuf_non_tcp(mbuf);
505 		mbuf = next;
506 		if (rc != 0)
507 			continue;
508 
509 		if (txq->blocked)
510 			break;
511 
512 		/* Push the fragments to the hardware in batches. */
513 		if (txq->added - pushed >= SFXGE_TX_BATCH) {
514 			efx_tx_qpush(txq->common, txq->added, pushed);
515 			pushed = txq->added;
516 		}
517 	}
518 
519 	if (count == 0) {
520 		KASSERT(mbuf == NULL, ("mbuf != NULL"));
521 		KASSERT(non_tcp_count == 0,
522 			("inconsistent TCP/non-TCP detection"));
523 		stdp->std_get = NULL;
524 		stdp->std_get_count = 0;
525 		stdp->std_get_non_tcp_count = 0;
526 		stdp->std_getp = &stdp->std_get;
527 	} else {
528 		stdp->std_get = mbuf;
529 		stdp->std_get_count = count;
530 		stdp->std_get_non_tcp_count = non_tcp_count;
531 	}
532 
533 	if (txq->added != pushed)
534 		efx_tx_qpush(txq->common, txq->added, pushed);
535 
536 	KASSERT(txq->blocked || stdp->std_get_count == 0,
537 		("queue unblocked but count is non-zero"));
538 }
539 
540 #define	SFXGE_TX_QDPL_PENDING(_txq)	((_txq)->dpl.std_put != 0)
541 
542 /*
543  * Service the deferred packet list.
544  *
545  * NOTE: drops the txq mutex!
546  */
547 static void
548 sfxge_tx_qdpl_service(struct sfxge_txq *txq)
549 {
550 	SFXGE_TXQ_LOCK_ASSERT_OWNED(txq);
551 
552 	do {
553 		if (SFXGE_TX_QDPL_PENDING(txq))
554 			sfxge_tx_qdpl_swizzle(txq);
555 
556 		if (!txq->blocked)
557 			sfxge_tx_qdpl_drain(txq);
558 
559 		SFXGE_TXQ_UNLOCK(txq);
560 	} while (SFXGE_TX_QDPL_PENDING(txq) &&
561 		 SFXGE_TXQ_TRYLOCK(txq));
562 }
563 
564 /*
565  * Put a packet on the deferred packet get-list.
566  */
567 static int
568 sfxge_tx_qdpl_put_locked(struct sfxge_txq *txq, struct mbuf *mbuf)
569 {
570 	struct sfxge_tx_dpl *stdp;
571 
572 	stdp = &txq->dpl;
573 
574 	KASSERT(mbuf->m_nextpkt == NULL, ("mbuf->m_nextpkt != NULL"));
575 
576 	SFXGE_TXQ_LOCK_ASSERT_OWNED(txq);
577 
578 	if (stdp->std_get_count >= stdp->std_get_max) {
579 		txq->get_overflow++;
580 		return (ENOBUFS);
581 	}
582 	if (sfxge_is_mbuf_non_tcp(mbuf)) {
583 		if (stdp->std_get_non_tcp_count >=
584 		    stdp->std_get_non_tcp_max) {
585 			txq->get_non_tcp_overflow++;
586 			return (ENOBUFS);
587 		}
588 		stdp->std_get_non_tcp_count++;
589 	}
590 
591 	*(stdp->std_getp) = mbuf;
592 	stdp->std_getp = &mbuf->m_nextpkt;
593 	stdp->std_get_count++;
594 
595 	return (0);
596 }
597 
598 /*
599  * Put a packet on the deferred packet put-list.
600  *
601  * We overload the csum_data field in the mbuf to keep track of this length
602  * because there is no cheap alternative to avoid races.
603  */
604 static int
605 sfxge_tx_qdpl_put_unlocked(struct sfxge_txq *txq, struct mbuf *mbuf)
606 {
607 	struct sfxge_tx_dpl *stdp;
608 	volatile uintptr_t *putp;
609 	uintptr_t old;
610 	uintptr_t new;
611 	unsigned int put_count;
612 
613 	KASSERT(mbuf->m_nextpkt == NULL, ("mbuf->m_nextpkt != NULL"));
614 
615 	SFXGE_TXQ_LOCK_ASSERT_NOTOWNED(txq);
616 
617 	stdp = &txq->dpl;
618 	putp = &stdp->std_put;
619 	new = (uintptr_t)mbuf;
620 
621 	do {
622 		old = *putp;
623 		if (old != 0) {
624 			struct mbuf *mp = (struct mbuf *)old;
625 			put_count = mp->m_pkthdr.csum_data;
626 		} else
627 			put_count = 0;
628 		if (put_count >= stdp->std_put_max) {
629 			atomic_add_long(&txq->put_overflow, 1);
630 			return (ENOBUFS);
631 		}
632 		mbuf->m_pkthdr.csum_data = put_count + 1;
633 		mbuf->m_nextpkt = (void *)old;
634 	} while (atomic_cmpset_ptr(putp, old, new) == 0);
635 
636 	return (0);
637 }
638 
639 /*
640  * Called from if_transmit - will try to grab the txq lock and enqueue to the
641  * put list if it succeeds, otherwise try to push onto the defer list if space.
642  */
643 static int
644 sfxge_tx_packet_add(struct sfxge_txq *txq, struct mbuf *m)
645 {
646 	int rc;
647 
648 	if (!SFXGE_LINK_UP(txq->sc)) {
649 		atomic_add_long(&txq->netdown_drops, 1);
650 		return (ENETDOWN);
651 	}
652 
653 	/*
654 	 * Try to grab the txq lock.  If we are able to get the lock,
655 	 * the packet will be appended to the "get list" of the deferred
656 	 * packet list.  Otherwise, it will be pushed on the "put list".
657 	 */
658 	if (SFXGE_TXQ_TRYLOCK(txq)) {
659 		/* First swizzle put-list to get-list to keep order */
660 		sfxge_tx_qdpl_swizzle(txq);
661 
662 		rc = sfxge_tx_qdpl_put_locked(txq, m);
663 
664 		/* Try to service the list. */
665 		sfxge_tx_qdpl_service(txq);
666 		/* Lock has been dropped. */
667 	} else {
668 		rc = sfxge_tx_qdpl_put_unlocked(txq, m);
669 
670 		/*
671 		 * Try to grab the lock again.
672 		 *
673 		 * If we are able to get the lock, we need to process
674 		 * the deferred packet list.  If we are not able to get
675 		 * the lock, another thread is processing the list.
676 		 */
677 		if ((rc == 0) && SFXGE_TXQ_TRYLOCK(txq)) {
678 			sfxge_tx_qdpl_service(txq);
679 			/* Lock has been dropped. */
680 		}
681 	}
682 
683 	SFXGE_TXQ_LOCK_ASSERT_NOTOWNED(txq);
684 
685 	return (rc);
686 }
687 
688 static void
689 sfxge_tx_qdpl_flush(struct sfxge_txq *txq)
690 {
691 	struct sfxge_tx_dpl *stdp = &txq->dpl;
692 	struct mbuf *mbuf, *next;
693 
694 	SFXGE_TXQ_LOCK(txq);
695 
696 	sfxge_tx_qdpl_swizzle(txq);
697 	for (mbuf = stdp->std_get; mbuf != NULL; mbuf = next) {
698 		next = mbuf->m_nextpkt;
699 		m_freem(mbuf);
700 	}
701 	stdp->std_get = NULL;
702 	stdp->std_get_count = 0;
703 	stdp->std_get_non_tcp_count = 0;
704 	stdp->std_getp = &stdp->std_get;
705 
706 	SFXGE_TXQ_UNLOCK(txq);
707 }
708 
709 void
710 sfxge_if_qflush(struct ifnet *ifp)
711 {
712 	struct sfxge_softc *sc;
713 	unsigned int i;
714 
715 	sc = ifp->if_softc;
716 
717 	for (i = 0; i < sc->txq_count; i++)
718 		sfxge_tx_qdpl_flush(sc->txq[i]);
719 }
720 
721 #if SFXGE_TX_PARSE_EARLY
722 
723 /* There is little space for user data in mbuf pkthdr, so we
724  * use l*hlen fields which are not used by the driver otherwise
725  * to store header offsets.
726  * The fields are 8-bit, but it's ok, no header may be longer than 255 bytes.
727  */
728 
729 
730 #define TSO_MBUF_PROTO(_mbuf)    ((_mbuf)->m_pkthdr.PH_loc.sixteen[0])
731 /* We abuse l5hlen here because PH_loc can hold only 64 bits of data */
732 #define TSO_MBUF_FLAGS(_mbuf)    ((_mbuf)->m_pkthdr.l5hlen)
733 #define TSO_MBUF_PACKETID(_mbuf) ((_mbuf)->m_pkthdr.PH_loc.sixteen[1])
734 #define TSO_MBUF_SEQNUM(_mbuf)   ((_mbuf)->m_pkthdr.PH_loc.thirtytwo[1])
735 
736 static void sfxge_parse_tx_packet(struct mbuf *mbuf)
737 {
738 	struct ether_header *eh = mtod(mbuf, struct ether_header *);
739 	const struct tcphdr *th;
740 	struct tcphdr th_copy;
741 
742 	/* Find network protocol and header */
743 	TSO_MBUF_PROTO(mbuf) = eh->ether_type;
744 	if (TSO_MBUF_PROTO(mbuf) == htons(ETHERTYPE_VLAN)) {
745 		struct ether_vlan_header *veh =
746 			mtod(mbuf, struct ether_vlan_header *);
747 		TSO_MBUF_PROTO(mbuf) = veh->evl_proto;
748 		mbuf->m_pkthdr.l2hlen = sizeof(*veh);
749 	} else {
750 		mbuf->m_pkthdr.l2hlen = sizeof(*eh);
751 	}
752 
753 	/* Find TCP header */
754 	if (TSO_MBUF_PROTO(mbuf) == htons(ETHERTYPE_IP)) {
755 		const struct ip *iph = (const struct ip *)mtodo(mbuf, mbuf->m_pkthdr.l2hlen);
756 
757 		KASSERT(iph->ip_p == IPPROTO_TCP,
758 			("TSO required on non-TCP packet"));
759 		mbuf->m_pkthdr.l3hlen = mbuf->m_pkthdr.l2hlen + 4 * iph->ip_hl;
760 		TSO_MBUF_PACKETID(mbuf) = iph->ip_id;
761 	} else {
762 		KASSERT(TSO_MBUF_PROTO(mbuf) == htons(ETHERTYPE_IPV6),
763 			("TSO required on non-IP packet"));
764 		KASSERT(((const struct ip6_hdr *)mtodo(mbuf, mbuf->m_pkthdr.l2hlen))->ip6_nxt ==
765 			IPPROTO_TCP,
766 			("TSO required on non-TCP packet"));
767 		mbuf->m_pkthdr.l3hlen = mbuf->m_pkthdr.l2hlen + sizeof(struct ip6_hdr);
768 		TSO_MBUF_PACKETID(mbuf) = 0;
769 	}
770 
771 	KASSERT(mbuf->m_len >= mbuf->m_pkthdr.l3hlen,
772 		("network header is fragmented in mbuf"));
773 
774 	/* We need TCP header including flags (window is the next) */
775 	if (mbuf->m_len < mbuf->m_pkthdr.l3hlen + offsetof(struct tcphdr, th_win)) {
776 		m_copydata(mbuf, mbuf->m_pkthdr.l3hlen, sizeof(th_copy),
777 			   (caddr_t)&th_copy);
778 		th = &th_copy;
779 	} else {
780 		th = (const struct tcphdr *)mtodo(mbuf, mbuf->m_pkthdr.l3hlen);
781 	}
782 
783 	mbuf->m_pkthdr.l4hlen = mbuf->m_pkthdr.l3hlen + 4 * th->th_off;
784 	TSO_MBUF_SEQNUM(mbuf) = ntohl(th->th_seq);
785 
786 	/* These flags must not be duplicated */
787 	/*
788 	 * RST should not be duplicated as well, but FreeBSD kernel
789 	 * generates TSO packets with RST flag. So, do not assert
790 	 * its absence.
791 	 */
792 	KASSERT(!(th->th_flags & (TH_URG | TH_SYN)),
793 		("incompatible TCP flag 0x%x on TSO packet",
794 		 th->th_flags & (TH_URG | TH_SYN)));
795 	TSO_MBUF_FLAGS(mbuf) = th->th_flags;
796 }
797 #endif
798 
799 /*
800  * TX start -- called by the stack.
801  */
802 int
803 sfxge_if_transmit(struct ifnet *ifp, struct mbuf *m)
804 {
805 	struct sfxge_softc *sc;
806 	struct sfxge_txq *txq;
807 	int rc;
808 
809 	sc = (struct sfxge_softc *)ifp->if_softc;
810 
811 	/*
812 	 * Transmit may be called when interface is up from the kernel
813 	 * point of view, but not yet up (in progress) from the driver
814 	 * point of view. I.e. link aggregation bring up.
815 	 * Transmit may be called when interface is up from the driver
816 	 * point of view, but already down from the kernel point of
817 	 * view. I.e. Rx when interface shutdown is in progress.
818 	 */
819 	KASSERT((ifp->if_flags & IFF_UP) || (sc->if_flags & IFF_UP),
820 		("interface not up"));
821 
822 	/* Pick the desired transmit queue. */
823 	if (m->m_pkthdr.csum_flags &
824 	    (CSUM_DELAY_DATA | CSUM_TCP_IPV6 | CSUM_UDP_IPV6 | CSUM_TSO)) {
825 		int index = 0;
826 
827 #ifdef RSS
828 		uint32_t bucket_id;
829 
830 		/*
831 		 * Select a TX queue which matches the corresponding
832 		 * RX queue for the hash in order to assign both
833 		 * TX and RX parts of the flow to the same CPU
834 		 */
835 		if (rss_m2bucket(m, &bucket_id) == 0)
836 			index = bucket_id % (sc->txq_count - (SFXGE_TXQ_NTYPES - 1));
837 #else
838 		/* check if flowid is set */
839 		if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
840 			uint32_t hash = m->m_pkthdr.flowid;
841 			uint32_t idx = hash % nitems(sc->rx_indir_table);
842 
843 			index = sc->rx_indir_table[idx];
844 		}
845 #endif
846 #if SFXGE_TX_PARSE_EARLY
847 		if (m->m_pkthdr.csum_flags & CSUM_TSO)
848 			sfxge_parse_tx_packet(m);
849 #endif
850 		txq = sc->txq[SFXGE_TXQ_IP_TCP_UDP_CKSUM + index];
851 	} else if (m->m_pkthdr.csum_flags & CSUM_DELAY_IP) {
852 		txq = sc->txq[SFXGE_TXQ_IP_CKSUM];
853 	} else {
854 		txq = sc->txq[SFXGE_TXQ_NON_CKSUM];
855 	}
856 
857 	rc = sfxge_tx_packet_add(txq, m);
858 	if (rc != 0)
859 		m_freem(m);
860 
861 	return (rc);
862 }
863 
864 /*
865  * Software "TSO".  Not quite as good as doing it in hardware, but
866  * still faster than segmenting in the stack.
867  */
868 
869 struct sfxge_tso_state {
870 	/* Output position */
871 	unsigned out_len;	/* Remaining length in current segment */
872 	unsigned seqnum;	/* Current sequence number */
873 	unsigned packet_space;	/* Remaining space in current packet */
874 	unsigned segs_space;	/* Remaining number of DMA segments
875 				   for the packet (FATSOv2 only) */
876 
877 	/* Input position */
878 	uint64_t dma_addr;	/* DMA address of current position */
879 	unsigned in_len;	/* Remaining length in current mbuf */
880 
881 	const struct mbuf *mbuf; /* Input mbuf (head of chain) */
882 	u_short protocol;	/* Network protocol (after VLAN decap) */
883 	ssize_t nh_off;		/* Offset of network header */
884 	ssize_t tcph_off;	/* Offset of TCP header */
885 	unsigned header_len;	/* Number of bytes of header */
886 	unsigned seg_size;	/* TCP segment size */
887 	int fw_assisted;	/* Use FW-assisted TSO */
888 	u_short packet_id;	/* IPv4 packet ID from the original packet */
889 	uint8_t tcp_flags;	/* TCP flags */
890 	efx_desc_t header_desc; /* Precomputed header descriptor for
891 				 * FW-assisted TSO */
892 };
893 
894 #if !SFXGE_TX_PARSE_EARLY
895 static const struct ip *tso_iph(const struct sfxge_tso_state *tso)
896 {
897 	KASSERT(tso->protocol == htons(ETHERTYPE_IP),
898 		("tso_iph() in non-IPv4 state"));
899 	return (const struct ip *)(tso->mbuf->m_data + tso->nh_off);
900 }
901 
902 static __unused const struct ip6_hdr *tso_ip6h(const struct sfxge_tso_state *tso)
903 {
904 	KASSERT(tso->protocol == htons(ETHERTYPE_IPV6),
905 		("tso_ip6h() in non-IPv6 state"));
906 	return (const struct ip6_hdr *)(tso->mbuf->m_data + tso->nh_off);
907 }
908 
909 static const struct tcphdr *tso_tcph(const struct sfxge_tso_state *tso)
910 {
911 	return (const struct tcphdr *)(tso->mbuf->m_data + tso->tcph_off);
912 }
913 #endif
914 
915 
916 /* Size of preallocated TSO header buffers.  Larger blocks must be
917  * allocated from the heap.
918  */
919 #define	TSOH_STD_SIZE	128
920 
921 /* At most half the descriptors in the queue at any time will refer to
922  * a TSO header buffer, since they must always be followed by a
923  * payload descriptor referring to an mbuf.
924  */
925 #define	TSOH_COUNT(_txq_entries)	((_txq_entries) / 2u)
926 #define	TSOH_PER_PAGE	(PAGE_SIZE / TSOH_STD_SIZE)
927 #define	TSOH_PAGE_COUNT(_txq_entries)	\
928 	howmany(TSOH_COUNT(_txq_entries), TSOH_PER_PAGE)
929 
930 static int tso_init(struct sfxge_txq *txq)
931 {
932 	struct sfxge_softc *sc = txq->sc;
933 	unsigned int tsoh_page_count = TSOH_PAGE_COUNT(sc->txq_entries);
934 	int i, rc;
935 
936 	/* Allocate TSO header buffers */
937 	txq->tsoh_buffer = malloc(tsoh_page_count * sizeof(txq->tsoh_buffer[0]),
938 				  M_SFXGE, M_WAITOK);
939 
940 	for (i = 0; i < tsoh_page_count; i++) {
941 		rc = sfxge_dma_alloc(sc, PAGE_SIZE, &txq->tsoh_buffer[i]);
942 		if (rc != 0)
943 			goto fail;
944 	}
945 
946 	return (0);
947 
948 fail:
949 	while (i-- > 0)
950 		sfxge_dma_free(&txq->tsoh_buffer[i]);
951 	free(txq->tsoh_buffer, M_SFXGE);
952 	txq->tsoh_buffer = NULL;
953 	return (rc);
954 }
955 
956 static void tso_fini(struct sfxge_txq *txq)
957 {
958 	int i;
959 
960 	if (txq->tsoh_buffer != NULL) {
961 		for (i = 0; i < TSOH_PAGE_COUNT(txq->sc->txq_entries); i++)
962 			sfxge_dma_free(&txq->tsoh_buffer[i]);
963 		free(txq->tsoh_buffer, M_SFXGE);
964 	}
965 }
966 
967 static void tso_start(struct sfxge_txq *txq, struct sfxge_tso_state *tso,
968 		      const bus_dma_segment_t *hdr_dma_seg,
969 		      struct mbuf *mbuf)
970 {
971 	const efx_nic_cfg_t *encp = efx_nic_cfg_get(txq->sc->enp);
972 #if !SFXGE_TX_PARSE_EARLY
973 	struct ether_header *eh = mtod(mbuf, struct ether_header *);
974 	const struct tcphdr *th;
975 	struct tcphdr th_copy;
976 #endif
977 
978 	tso->fw_assisted = txq->tso_fw_assisted;
979 	tso->mbuf = mbuf;
980 
981 	/* Find network protocol and header */
982 #if !SFXGE_TX_PARSE_EARLY
983 	tso->protocol = eh->ether_type;
984 	if (tso->protocol == htons(ETHERTYPE_VLAN)) {
985 		struct ether_vlan_header *veh =
986 			mtod(mbuf, struct ether_vlan_header *);
987 		tso->protocol = veh->evl_proto;
988 		tso->nh_off = sizeof(*veh);
989 	} else {
990 		tso->nh_off = sizeof(*eh);
991 	}
992 #else
993 	tso->protocol = TSO_MBUF_PROTO(mbuf);
994 	tso->nh_off = mbuf->m_pkthdr.l2hlen;
995 	tso->tcph_off = mbuf->m_pkthdr.l3hlen;
996 	tso->packet_id = ntohs(TSO_MBUF_PACKETID(mbuf));
997 #endif
998 
999 #if !SFXGE_TX_PARSE_EARLY
1000 	/* Find TCP header */
1001 	if (tso->protocol == htons(ETHERTYPE_IP)) {
1002 		KASSERT(tso_iph(tso)->ip_p == IPPROTO_TCP,
1003 			("TSO required on non-TCP packet"));
1004 		tso->tcph_off = tso->nh_off + 4 * tso_iph(tso)->ip_hl;
1005 		tso->packet_id = ntohs(tso_iph(tso)->ip_id);
1006 	} else {
1007 		KASSERT(tso->protocol == htons(ETHERTYPE_IPV6),
1008 			("TSO required on non-IP packet"));
1009 		KASSERT(tso_ip6h(tso)->ip6_nxt == IPPROTO_TCP,
1010 			("TSO required on non-TCP packet"));
1011 		tso->tcph_off = tso->nh_off + sizeof(struct ip6_hdr);
1012 		tso->packet_id = 0;
1013 	}
1014 #endif
1015 
1016 
1017 	if (tso->fw_assisted &&
1018 	    __predict_false(tso->tcph_off >
1019 			    encp->enc_tx_tso_tcp_header_offset_limit)) {
1020 		tso->fw_assisted = 0;
1021 	}
1022 
1023 
1024 #if !SFXGE_TX_PARSE_EARLY
1025 	KASSERT(mbuf->m_len >= tso->tcph_off,
1026 		("network header is fragmented in mbuf"));
1027 	/* We need TCP header including flags (window is the next) */
1028 	if (mbuf->m_len < tso->tcph_off + offsetof(struct tcphdr, th_win)) {
1029 		m_copydata(tso->mbuf, tso->tcph_off, sizeof(th_copy),
1030 			   (caddr_t)&th_copy);
1031 		th = &th_copy;
1032 	} else {
1033 		th = tso_tcph(tso);
1034 	}
1035 	tso->header_len = tso->tcph_off + 4 * th->th_off;
1036 #else
1037 	tso->header_len = mbuf->m_pkthdr.l4hlen;
1038 #endif
1039 	tso->seg_size = mbuf->m_pkthdr.tso_segsz;
1040 
1041 #if !SFXGE_TX_PARSE_EARLY
1042 	tso->seqnum = ntohl(th->th_seq);
1043 
1044 	/* These flags must not be duplicated */
1045 	/*
1046 	 * RST should not be duplicated as well, but FreeBSD kernel
1047 	 * generates TSO packets with RST flag. So, do not assert
1048 	 * its absence.
1049 	 */
1050 	KASSERT(!(th->th_flags & (TH_URG | TH_SYN)),
1051 		("incompatible TCP flag 0x%x on TSO packet",
1052 		 th->th_flags & (TH_URG | TH_SYN)));
1053 	tso->tcp_flags = th->th_flags;
1054 #else
1055 	tso->seqnum = TSO_MBUF_SEQNUM(mbuf);
1056 	tso->tcp_flags = TSO_MBUF_FLAGS(mbuf);
1057 #endif
1058 
1059 	tso->out_len = mbuf->m_pkthdr.len - tso->header_len;
1060 
1061 	if (tso->fw_assisted) {
1062 		if (hdr_dma_seg->ds_len >= tso->header_len)
1063 			efx_tx_qdesc_dma_create(txq->common,
1064 						hdr_dma_seg->ds_addr,
1065 						tso->header_len,
1066 						B_FALSE,
1067 						&tso->header_desc);
1068 		else
1069 			tso->fw_assisted = 0;
1070 	}
1071 }
1072 
1073 /*
1074  * tso_fill_packet_with_fragment - form descriptors for the current fragment
1075  *
1076  * Form descriptors for the current fragment, until we reach the end
1077  * of fragment or end-of-packet.  Return 0 on success, 1 if not enough
1078  * space.
1079  */
1080 static void tso_fill_packet_with_fragment(struct sfxge_txq *txq,
1081 					  struct sfxge_tso_state *tso)
1082 {
1083 	efx_desc_t *desc;
1084 	int n;
1085 	uint64_t dma_addr = tso->dma_addr;
1086 	boolean_t eop;
1087 
1088 	if (tso->in_len == 0 || tso->packet_space == 0)
1089 		return;
1090 
1091 	KASSERT(tso->in_len > 0, ("TSO input length went negative"));
1092 	KASSERT(tso->packet_space > 0, ("TSO packet space went negative"));
1093 
1094 	if (tso->fw_assisted & SFXGE_FATSOV2) {
1095 		n = tso->in_len;
1096 		tso->out_len -= n;
1097 		tso->seqnum += n;
1098 		tso->in_len = 0;
1099 		if (n < tso->packet_space) {
1100 			tso->packet_space -= n;
1101 			tso->segs_space--;
1102 		} else {
1103 			tso->packet_space = tso->seg_size -
1104 			    (n - tso->packet_space) % tso->seg_size;
1105 			tso->segs_space =
1106 			    EFX_TX_FATSOV2_DMA_SEGS_PER_PKT_MAX - 1 -
1107 			    (tso->packet_space != tso->seg_size);
1108 		}
1109 	} else {
1110 		n = min(tso->in_len, tso->packet_space);
1111 		tso->packet_space -= n;
1112 		tso->out_len -= n;
1113 		tso->dma_addr += n;
1114 		tso->in_len -= n;
1115 	}
1116 
1117 	/*
1118 	 * It is OK to use binary OR below to avoid extra branching
1119 	 * since all conditions may always be checked.
1120 	 */
1121 	eop = (tso->out_len == 0) | (tso->packet_space == 0) |
1122 	    (tso->segs_space == 0);
1123 
1124 	desc = &txq->pend_desc[txq->n_pend_desc++];
1125 	efx_tx_qdesc_dma_create(txq->common, dma_addr, n, eop, desc);
1126 }
1127 
1128 /* Callback from bus_dmamap_load() for long TSO headers. */
1129 static void tso_map_long_header(void *dma_addr_ret,
1130 				bus_dma_segment_t *segs, int nseg,
1131 				int error)
1132 {
1133 	*(uint64_t *)dma_addr_ret = ((__predict_true(error == 0) &&
1134 				      __predict_true(nseg == 1)) ?
1135 				     segs->ds_addr : 0);
1136 }
1137 
1138 /*
1139  * tso_start_new_packet - generate a new header and prepare for the new packet
1140  *
1141  * Generate a new header and prepare for the new packet.  Return 0 on
1142  * success, or an error code if failed to alloc header.
1143  */
1144 static int tso_start_new_packet(struct sfxge_txq *txq,
1145 				struct sfxge_tso_state *tso,
1146 				unsigned int *idp)
1147 {
1148 	unsigned int id = *idp;
1149 	struct tcphdr *tsoh_th;
1150 	unsigned ip_length;
1151 	caddr_t header;
1152 	uint64_t dma_addr;
1153 	bus_dmamap_t map;
1154 	efx_desc_t *desc;
1155 	int rc;
1156 
1157 	if (tso->fw_assisted) {
1158 		if (tso->fw_assisted & SFXGE_FATSOV2) {
1159 			/* Add 2 FATSOv2 option descriptors */
1160 			desc = &txq->pend_desc[txq->n_pend_desc];
1161 			efx_tx_qdesc_tso2_create(txq->common,
1162 						 tso->packet_id,
1163 						 tso->seqnum,
1164 						 tso->seg_size,
1165 						 desc,
1166 						 EFX_TX_FATSOV2_OPT_NDESCS);
1167 			desc += EFX_TX_FATSOV2_OPT_NDESCS;
1168 			txq->n_pend_desc += EFX_TX_FATSOV2_OPT_NDESCS;
1169 			KASSERT(txq->stmp[id].flags == 0, ("stmp flags are not 0"));
1170 			id = (id + EFX_TX_FATSOV2_OPT_NDESCS) & txq->ptr_mask;
1171 
1172 			tso->segs_space =
1173 			    EFX_TX_FATSOV2_DMA_SEGS_PER_PKT_MAX - 1;
1174 		} else {
1175 			uint8_t tcp_flags = tso->tcp_flags;
1176 
1177 			if (tso->out_len > tso->seg_size)
1178 				tcp_flags &= ~(TH_FIN | TH_PUSH);
1179 
1180 			/* Add FATSOv1 option descriptor */
1181 			desc = &txq->pend_desc[txq->n_pend_desc++];
1182 			efx_tx_qdesc_tso_create(txq->common,
1183 						tso->packet_id,
1184 						tso->seqnum,
1185 						tcp_flags,
1186 						desc++);
1187 			KASSERT(txq->stmp[id].flags == 0, ("stmp flags are not 0"));
1188 			id = (id + 1) & txq->ptr_mask;
1189 
1190 			tso->seqnum += tso->seg_size;
1191 			tso->segs_space = UINT_MAX;
1192 		}
1193 
1194 		/* Header DMA descriptor */
1195 		*desc = tso->header_desc;
1196 		txq->n_pend_desc++;
1197 		KASSERT(txq->stmp[id].flags == 0, ("stmp flags are not 0"));
1198 		id = (id + 1) & txq->ptr_mask;
1199 	} else {
1200 		/* Allocate a DMA-mapped header buffer. */
1201 		if (__predict_true(tso->header_len <= TSOH_STD_SIZE)) {
1202 			unsigned int page_index = (id / 2) / TSOH_PER_PAGE;
1203 			unsigned int buf_index = (id / 2) % TSOH_PER_PAGE;
1204 
1205 			header = (txq->tsoh_buffer[page_index].esm_base +
1206 				  buf_index * TSOH_STD_SIZE);
1207 			dma_addr = (txq->tsoh_buffer[page_index].esm_addr +
1208 				    buf_index * TSOH_STD_SIZE);
1209 			map = txq->tsoh_buffer[page_index].esm_map;
1210 
1211 			KASSERT(txq->stmp[id].flags == 0,
1212 				("stmp flags are not 0"));
1213 		} else {
1214 			struct sfxge_tx_mapping *stmp = &txq->stmp[id];
1215 
1216 			/* We cannot use bus_dmamem_alloc() as that may sleep */
1217 			header = malloc(tso->header_len, M_SFXGE, M_NOWAIT);
1218 			if (__predict_false(!header))
1219 				return (ENOMEM);
1220 			rc = bus_dmamap_load(txq->packet_dma_tag, stmp->map,
1221 					     header, tso->header_len,
1222 					     tso_map_long_header, &dma_addr,
1223 					     BUS_DMA_NOWAIT);
1224 			if (__predict_false(dma_addr == 0)) {
1225 				if (rc == 0) {
1226 					/* Succeeded but got >1 segment */
1227 					bus_dmamap_unload(txq->packet_dma_tag,
1228 							  stmp->map);
1229 					rc = EINVAL;
1230 				}
1231 				free(header, M_SFXGE);
1232 				return (rc);
1233 			}
1234 			map = stmp->map;
1235 
1236 			txq->tso_long_headers++;
1237 			stmp->u.heap_buf = header;
1238 			stmp->flags = TX_BUF_UNMAP;
1239 		}
1240 
1241 		tsoh_th = (struct tcphdr *)(header + tso->tcph_off);
1242 
1243 		/* Copy and update the headers. */
1244 		m_copydata(tso->mbuf, 0, tso->header_len, header);
1245 
1246 		tsoh_th->th_seq = htonl(tso->seqnum);
1247 		tso->seqnum += tso->seg_size;
1248 		if (tso->out_len > tso->seg_size) {
1249 			/* This packet will not finish the TSO burst. */
1250 			ip_length = tso->header_len - tso->nh_off + tso->seg_size;
1251 			tsoh_th->th_flags &= ~(TH_FIN | TH_PUSH);
1252 		} else {
1253 			/* This packet will be the last in the TSO burst. */
1254 			ip_length = tso->header_len - tso->nh_off + tso->out_len;
1255 		}
1256 
1257 		if (tso->protocol == htons(ETHERTYPE_IP)) {
1258 			struct ip *tsoh_iph = (struct ip *)(header + tso->nh_off);
1259 			tsoh_iph->ip_len = htons(ip_length);
1260 			/* XXX We should increment ip_id, but FreeBSD doesn't
1261 			 * currently allocate extra IDs for multiple segments.
1262 			 */
1263 		} else {
1264 			struct ip6_hdr *tsoh_iph =
1265 				(struct ip6_hdr *)(header + tso->nh_off);
1266 			tsoh_iph->ip6_plen = htons(ip_length - sizeof(*tsoh_iph));
1267 		}
1268 
1269 		/* Make the header visible to the hardware. */
1270 		bus_dmamap_sync(txq->packet_dma_tag, map, BUS_DMASYNC_PREWRITE);
1271 
1272 		/* Form a descriptor for this header. */
1273 		desc = &txq->pend_desc[txq->n_pend_desc++];
1274 		efx_tx_qdesc_dma_create(txq->common,
1275 					dma_addr,
1276 					tso->header_len,
1277 					0,
1278 					desc);
1279 		id = (id + 1) & txq->ptr_mask;
1280 
1281 		tso->segs_space = UINT_MAX;
1282 	}
1283 	tso->packet_space = tso->seg_size;
1284 	txq->tso_packets++;
1285 	*idp = id;
1286 
1287 	return (0);
1288 }
1289 
1290 static int
1291 sfxge_tx_queue_tso(struct sfxge_txq *txq, struct mbuf *mbuf,
1292 		   const bus_dma_segment_t *dma_seg, int n_dma_seg,
1293 		   int vlan_tagged)
1294 {
1295 	struct sfxge_tso_state tso;
1296 	unsigned int id;
1297 	unsigned skipped = 0;
1298 
1299 	tso_start(txq, &tso, dma_seg, mbuf);
1300 
1301 	while (dma_seg->ds_len + skipped <= tso.header_len) {
1302 		skipped += dma_seg->ds_len;
1303 		--n_dma_seg;
1304 		KASSERT(n_dma_seg, ("no payload found in TSO packet"));
1305 		++dma_seg;
1306 	}
1307 	tso.in_len = dma_seg->ds_len - (tso.header_len - skipped);
1308 	tso.dma_addr = dma_seg->ds_addr + (tso.header_len - skipped);
1309 
1310 	id = (txq->added + vlan_tagged) & txq->ptr_mask;
1311 	if (__predict_false(tso_start_new_packet(txq, &tso, &id)))
1312 		return (-1);
1313 
1314 	while (1) {
1315 		tso_fill_packet_with_fragment(txq, &tso);
1316 		/* Exactly one DMA descriptor is added */
1317 		KASSERT(txq->stmp[id].flags == 0, ("stmp flags are not 0"));
1318 		id = (id + 1) & txq->ptr_mask;
1319 
1320 		/* Move onto the next fragment? */
1321 		if (tso.in_len == 0) {
1322 			--n_dma_seg;
1323 			if (n_dma_seg == 0)
1324 				break;
1325 			++dma_seg;
1326 			tso.in_len = dma_seg->ds_len;
1327 			tso.dma_addr = dma_seg->ds_addr;
1328 		}
1329 
1330 		/* End of packet? */
1331 		if ((tso.packet_space == 0) | (tso.segs_space == 0)) {
1332 			unsigned int n_fatso_opt_desc =
1333 			    (tso.fw_assisted & SFXGE_FATSOV2) ?
1334 			    EFX_TX_FATSOV2_OPT_NDESCS :
1335 			    (tso.fw_assisted & SFXGE_FATSOV1) ? 1 : 0;
1336 
1337 			/* If the queue is now full due to tiny MSS,
1338 			 * or we can't create another header, discard
1339 			 * the remainder of the input mbuf but do not
1340 			 * roll back the work we have done.
1341 			 */
1342 			if (txq->n_pend_desc + n_fatso_opt_desc +
1343 			    1 /* header */ + n_dma_seg > txq->max_pkt_desc) {
1344 				txq->tso_pdrop_too_many++;
1345 				break;
1346 			}
1347 			if (__predict_false(tso_start_new_packet(txq, &tso,
1348 								 &id))) {
1349 				txq->tso_pdrop_no_rsrc++;
1350 				break;
1351 			}
1352 		}
1353 	}
1354 
1355 	txq->tso_bursts++;
1356 	return (id);
1357 }
1358 
1359 static void
1360 sfxge_tx_qunblock(struct sfxge_txq *txq)
1361 {
1362 	struct sfxge_softc *sc;
1363 	struct sfxge_evq *evq;
1364 
1365 	sc = txq->sc;
1366 	evq = sc->evq[txq->evq_index];
1367 
1368 	SFXGE_EVQ_LOCK_ASSERT_OWNED(evq);
1369 
1370 	if (__predict_false(txq->init_state != SFXGE_TXQ_STARTED))
1371 		return;
1372 
1373 	SFXGE_TXQ_LOCK(txq);
1374 
1375 	if (txq->blocked) {
1376 		unsigned int level;
1377 
1378 		level = txq->added - txq->completed;
1379 		if (level <= SFXGE_TXQ_UNBLOCK_LEVEL(txq->entries)) {
1380 			/* reaped must be in sync with blocked */
1381 			sfxge_tx_qreap(txq);
1382 			txq->blocked = 0;
1383 		}
1384 	}
1385 
1386 	sfxge_tx_qdpl_service(txq);
1387 	/* note: lock has been dropped */
1388 }
1389 
1390 void
1391 sfxge_tx_qflush_done(struct sfxge_txq *txq)
1392 {
1393 
1394 	txq->flush_state = SFXGE_FLUSH_DONE;
1395 }
1396 
1397 static void
1398 sfxge_tx_qstop(struct sfxge_softc *sc, unsigned int index)
1399 {
1400 	struct sfxge_txq *txq;
1401 	struct sfxge_evq *evq;
1402 	unsigned int count;
1403 
1404 	SFXGE_ADAPTER_LOCK_ASSERT_OWNED(sc);
1405 
1406 	txq = sc->txq[index];
1407 	evq = sc->evq[txq->evq_index];
1408 
1409 	SFXGE_EVQ_LOCK(evq);
1410 	SFXGE_TXQ_LOCK(txq);
1411 
1412 	KASSERT(txq->init_state == SFXGE_TXQ_STARTED,
1413 	    ("txq->init_state != SFXGE_TXQ_STARTED"));
1414 
1415 	txq->init_state = SFXGE_TXQ_INITIALIZED;
1416 
1417 	if (txq->flush_state != SFXGE_FLUSH_DONE) {
1418 		txq->flush_state = SFXGE_FLUSH_PENDING;
1419 
1420 		SFXGE_EVQ_UNLOCK(evq);
1421 		SFXGE_TXQ_UNLOCK(txq);
1422 
1423 		/* Flush the transmit queue. */
1424 		if (efx_tx_qflush(txq->common) != 0) {
1425 			log(LOG_ERR, "%s: Flushing Tx queue %u failed\n",
1426 			    device_get_nameunit(sc->dev), index);
1427 			txq->flush_state = SFXGE_FLUSH_DONE;
1428 		} else {
1429 			count = 0;
1430 			do {
1431 				/* Spin for 100ms. */
1432 				DELAY(100000);
1433 				if (txq->flush_state != SFXGE_FLUSH_PENDING)
1434 					break;
1435 			} while (++count < 20);
1436 		}
1437 		SFXGE_EVQ_LOCK(evq);
1438 		SFXGE_TXQ_LOCK(txq);
1439 
1440 		KASSERT(txq->flush_state != SFXGE_FLUSH_FAILED,
1441 		    ("txq->flush_state == SFXGE_FLUSH_FAILED"));
1442 
1443 		if (txq->flush_state != SFXGE_FLUSH_DONE) {
1444 			/* Flush timeout */
1445 			log(LOG_ERR, "%s: Cannot flush Tx queue %u\n",
1446 			    device_get_nameunit(sc->dev), index);
1447 			txq->flush_state = SFXGE_FLUSH_DONE;
1448 		}
1449 	}
1450 
1451 	txq->blocked = 0;
1452 	txq->pending = txq->added;
1453 
1454 	sfxge_tx_qcomplete(txq, evq);
1455 	KASSERT(txq->completed == txq->added,
1456 	    ("txq->completed != txq->added"));
1457 
1458 	sfxge_tx_qreap(txq);
1459 	KASSERT(txq->reaped == txq->completed,
1460 	    ("txq->reaped != txq->completed"));
1461 
1462 	txq->added = 0;
1463 	txq->pending = 0;
1464 	txq->completed = 0;
1465 	txq->reaped = 0;
1466 
1467 	/* Destroy the common code transmit queue. */
1468 	efx_tx_qdestroy(txq->common);
1469 	txq->common = NULL;
1470 
1471 	efx_sram_buf_tbl_clear(sc->enp, txq->buf_base_id,
1472 	    EFX_TXQ_NBUFS(sc->txq_entries));
1473 
1474 	SFXGE_EVQ_UNLOCK(evq);
1475 	SFXGE_TXQ_UNLOCK(txq);
1476 }
1477 
1478 /*
1479  * Estimate maximum number of Tx descriptors required for TSO packet.
1480  * With minimum MSS and maximum mbuf length we might need more (even
1481  * than a ring-ful of descriptors), but this should not happen in
1482  * practice except due to deliberate attack.  In that case we will
1483  * truncate the output at a packet boundary.
1484  */
1485 static unsigned int
1486 sfxge_tx_max_pkt_desc(const struct sfxge_softc *sc, enum sfxge_txq_type type,
1487 		      unsigned int tso_fw_assisted)
1488 {
1489 	/* One descriptor for every input fragment */
1490 	unsigned int max_descs = SFXGE_TX_MAPPING_MAX_SEG;
1491 	unsigned int sw_tso_max_descs;
1492 	unsigned int fa_tso_v1_max_descs = 0;
1493 	unsigned int fa_tso_v2_max_descs = 0;
1494 
1495 	/* VLAN tagging Tx option descriptor may be required */
1496 	if (efx_nic_cfg_get(sc->enp)->enc_hw_tx_insert_vlan_enabled)
1497 		max_descs++;
1498 
1499 	if (type == SFXGE_TXQ_IP_TCP_UDP_CKSUM) {
1500 		/*
1501 		 * Plus header and payload descriptor for each output segment.
1502 		 * Minus one since header fragment is already counted.
1503 		 * Even if FATSO is used, we should be ready to fallback
1504 		 * to do it in the driver.
1505 		 */
1506 		sw_tso_max_descs = SFXGE_TSO_MAX_SEGS * 2 - 1;
1507 
1508 		/* FW assisted TSOv1 requires one more descriptor per segment
1509 		 * in comparison to SW TSO */
1510 		if (tso_fw_assisted & SFXGE_FATSOV1)
1511 			fa_tso_v1_max_descs =
1512 			    sw_tso_max_descs + SFXGE_TSO_MAX_SEGS;
1513 
1514 		/* FW assisted TSOv2 requires 3 (2 FATSO plus header) extra
1515 		 * descriptors per superframe limited by number of DMA fetches
1516 		 * per packet. The first packet header is already counted.
1517 		 */
1518 		if (tso_fw_assisted & SFXGE_FATSOV2) {
1519 			fa_tso_v2_max_descs =
1520 			    howmany(SFXGE_TX_MAPPING_MAX_SEG,
1521 				    EFX_TX_FATSOV2_DMA_SEGS_PER_PKT_MAX - 1) *
1522 			    (EFX_TX_FATSOV2_OPT_NDESCS + 1) - 1;
1523 		}
1524 
1525 		max_descs += MAX(sw_tso_max_descs,
1526 				 MAX(fa_tso_v1_max_descs, fa_tso_v2_max_descs));
1527 	}
1528 
1529 	return (max_descs);
1530 }
1531 
1532 static int
1533 sfxge_tx_qstart(struct sfxge_softc *sc, unsigned int index)
1534 {
1535 	struct sfxge_txq *txq;
1536 	efsys_mem_t *esmp;
1537 	uint16_t flags;
1538 	unsigned int tso_fw_assisted;
1539 	struct sfxge_evq *evq;
1540 	unsigned int desc_index;
1541 	int rc;
1542 
1543 	SFXGE_ADAPTER_LOCK_ASSERT_OWNED(sc);
1544 
1545 	txq = sc->txq[index];
1546 	esmp = &txq->mem;
1547 	evq = sc->evq[txq->evq_index];
1548 
1549 	KASSERT(txq->init_state == SFXGE_TXQ_INITIALIZED,
1550 	    ("txq->init_state != SFXGE_TXQ_INITIALIZED"));
1551 	KASSERT(evq->init_state == SFXGE_EVQ_STARTED,
1552 	    ("evq->init_state != SFXGE_EVQ_STARTED"));
1553 
1554 	/* Program the buffer table. */
1555 	if ((rc = efx_sram_buf_tbl_set(sc->enp, txq->buf_base_id, esmp,
1556 	    EFX_TXQ_NBUFS(sc->txq_entries))) != 0)
1557 		return (rc);
1558 
1559 	/* Determine the kind of queue we are creating. */
1560 	tso_fw_assisted = 0;
1561 	switch (txq->type) {
1562 	case SFXGE_TXQ_NON_CKSUM:
1563 		flags = 0;
1564 		break;
1565 	case SFXGE_TXQ_IP_CKSUM:
1566 		flags = EFX_TXQ_CKSUM_IPV4;
1567 		break;
1568 	case SFXGE_TXQ_IP_TCP_UDP_CKSUM:
1569 		flags = EFX_TXQ_CKSUM_IPV4 | EFX_TXQ_CKSUM_TCPUDP;
1570 		tso_fw_assisted = sc->tso_fw_assisted;
1571 		if (tso_fw_assisted & SFXGE_FATSOV2)
1572 			flags |= EFX_TXQ_FATSOV2;
1573 		break;
1574 	default:
1575 		KASSERT(0, ("Impossible TX queue"));
1576 		flags = 0;
1577 		break;
1578 	}
1579 
1580 	/* Create the common code transmit queue. */
1581 	if ((rc = efx_tx_qcreate(sc->enp, index, txq->type, esmp,
1582 	    sc->txq_entries, txq->buf_base_id, flags, evq->common,
1583 	    &txq->common, &desc_index)) != 0) {
1584 		/* Retry if no FATSOv2 resources, otherwise fail */
1585 		if ((rc != ENOSPC) || (~flags & EFX_TXQ_FATSOV2))
1586 			goto fail;
1587 
1588 		/* Looks like all FATSOv2 contexts are used */
1589 		flags &= ~EFX_TXQ_FATSOV2;
1590 		tso_fw_assisted &= ~SFXGE_FATSOV2;
1591 		if ((rc = efx_tx_qcreate(sc->enp, index, txq->type, esmp,
1592 		    sc->txq_entries, txq->buf_base_id, flags, evq->common,
1593 		    &txq->common, &desc_index)) != 0)
1594 			goto fail;
1595 	}
1596 
1597 	/* Initialise queue descriptor indexes */
1598 	txq->added = txq->pending = txq->completed = txq->reaped = desc_index;
1599 
1600 	SFXGE_TXQ_LOCK(txq);
1601 
1602 	/* Enable the transmit queue. */
1603 	efx_tx_qenable(txq->common);
1604 
1605 	txq->init_state = SFXGE_TXQ_STARTED;
1606 	txq->flush_state = SFXGE_FLUSH_REQUIRED;
1607 	txq->tso_fw_assisted = tso_fw_assisted;
1608 
1609 	txq->max_pkt_desc = sfxge_tx_max_pkt_desc(sc, txq->type,
1610 						  tso_fw_assisted);
1611 
1612 	SFXGE_TXQ_UNLOCK(txq);
1613 
1614 	return (0);
1615 
1616 fail:
1617 	efx_sram_buf_tbl_clear(sc->enp, txq->buf_base_id,
1618 	    EFX_TXQ_NBUFS(sc->txq_entries));
1619 	return (rc);
1620 }
1621 
1622 void
1623 sfxge_tx_stop(struct sfxge_softc *sc)
1624 {
1625 	int index;
1626 
1627 	index = sc->txq_count;
1628 	while (--index >= 0)
1629 		sfxge_tx_qstop(sc, index);
1630 
1631 	/* Tear down the transmit module */
1632 	efx_tx_fini(sc->enp);
1633 }
1634 
1635 int
1636 sfxge_tx_start(struct sfxge_softc *sc)
1637 {
1638 	int index;
1639 	int rc;
1640 
1641 	/* Initialize the common code transmit module. */
1642 	if ((rc = efx_tx_init(sc->enp)) != 0)
1643 		return (rc);
1644 
1645 	for (index = 0; index < sc->txq_count; index++) {
1646 		if ((rc = sfxge_tx_qstart(sc, index)) != 0)
1647 			goto fail;
1648 	}
1649 
1650 	return (0);
1651 
1652 fail:
1653 	while (--index >= 0)
1654 		sfxge_tx_qstop(sc, index);
1655 
1656 	efx_tx_fini(sc->enp);
1657 
1658 	return (rc);
1659 }
1660 
1661 static int
1662 sfxge_txq_stat_init(struct sfxge_txq *txq, struct sysctl_oid *txq_node)
1663 {
1664 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(txq->sc->dev);
1665 	struct sysctl_oid *stat_node;
1666 	unsigned int id;
1667 
1668 	stat_node = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(txq_node), OID_AUTO,
1669 				    "stats", CTLFLAG_RD, NULL,
1670 				    "Tx queue statistics");
1671 	if (stat_node == NULL)
1672 		return (ENOMEM);
1673 
1674 	for (id = 0; id < nitems(sfxge_tx_stats); id++) {
1675 		SYSCTL_ADD_ULONG(
1676 		    ctx, SYSCTL_CHILDREN(stat_node), OID_AUTO,
1677 		    sfxge_tx_stats[id].name, CTLFLAG_RD | CTLFLAG_STATS,
1678 		    (unsigned long *)((caddr_t)txq + sfxge_tx_stats[id].offset),
1679 		    "");
1680 	}
1681 
1682 	return (0);
1683 }
1684 
1685 /**
1686  * Destroy a transmit queue.
1687  */
1688 static void
1689 sfxge_tx_qfini(struct sfxge_softc *sc, unsigned int index)
1690 {
1691 	struct sfxge_txq *txq;
1692 	unsigned int nmaps;
1693 
1694 	txq = sc->txq[index];
1695 
1696 	KASSERT(txq->init_state == SFXGE_TXQ_INITIALIZED,
1697 	    ("txq->init_state != SFXGE_TXQ_INITIALIZED"));
1698 
1699 	if (txq->type == SFXGE_TXQ_IP_TCP_UDP_CKSUM)
1700 		tso_fini(txq);
1701 
1702 	/* Free the context arrays. */
1703 	free(txq->pend_desc, M_SFXGE);
1704 	nmaps = sc->txq_entries;
1705 	while (nmaps-- != 0)
1706 		bus_dmamap_destroy(txq->packet_dma_tag, txq->stmp[nmaps].map);
1707 	free(txq->stmp, M_SFXGE);
1708 
1709 	/* Release DMA memory mapping. */
1710 	sfxge_dma_free(&txq->mem);
1711 
1712 	sc->txq[index] = NULL;
1713 
1714 	SFXGE_TXQ_LOCK_DESTROY(txq);
1715 
1716 	free(txq, M_SFXGE);
1717 }
1718 
1719 static int
1720 sfxge_tx_qinit(struct sfxge_softc *sc, unsigned int txq_index,
1721 	       enum sfxge_txq_type type, unsigned int evq_index)
1722 {
1723 	char name[16];
1724 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->dev);
1725 	struct sysctl_oid *txq_node;
1726 	struct sfxge_txq *txq;
1727 	struct sfxge_evq *evq;
1728 	struct sfxge_tx_dpl *stdp;
1729 	struct sysctl_oid *dpl_node;
1730 	efsys_mem_t *esmp;
1731 	unsigned int nmaps;
1732 	int rc;
1733 
1734 	txq = malloc(sizeof(struct sfxge_txq), M_SFXGE, M_ZERO | M_WAITOK);
1735 	txq->sc = sc;
1736 	txq->entries = sc->txq_entries;
1737 	txq->ptr_mask = txq->entries - 1;
1738 
1739 	sc->txq[txq_index] = txq;
1740 	esmp = &txq->mem;
1741 
1742 	evq = sc->evq[evq_index];
1743 
1744 	/* Allocate and zero DMA space for the descriptor ring. */
1745 	if ((rc = sfxge_dma_alloc(sc, EFX_TXQ_SIZE(sc->txq_entries), esmp)) != 0)
1746 		return (rc);
1747 
1748 	/* Allocate buffer table entries. */
1749 	sfxge_sram_buf_tbl_alloc(sc, EFX_TXQ_NBUFS(sc->txq_entries),
1750 				 &txq->buf_base_id);
1751 
1752 	/* Create a DMA tag for packet mappings. */
1753 	if (bus_dma_tag_create(sc->parent_dma_tag, 1, 0x1000,
1754 	    MIN(0x3FFFFFFFFFFFUL, BUS_SPACE_MAXADDR), BUS_SPACE_MAXADDR, NULL,
1755 	    NULL, 0x11000, SFXGE_TX_MAPPING_MAX_SEG, 0x1000, 0, NULL, NULL,
1756 	    &txq->packet_dma_tag) != 0) {
1757 		device_printf(sc->dev, "Couldn't allocate txq DMA tag\n");
1758 		rc = ENOMEM;
1759 		goto fail;
1760 	}
1761 
1762 	/* Allocate pending descriptor array for batching writes. */
1763 	txq->pend_desc = malloc(sizeof(efx_desc_t) * sc->txq_entries,
1764 				M_SFXGE, M_ZERO | M_WAITOK);
1765 
1766 	/* Allocate and initialise mbuf DMA mapping array. */
1767 	txq->stmp = malloc(sizeof(struct sfxge_tx_mapping) * sc->txq_entries,
1768 	    M_SFXGE, M_ZERO | M_WAITOK);
1769 	for (nmaps = 0; nmaps < sc->txq_entries; nmaps++) {
1770 		rc = bus_dmamap_create(txq->packet_dma_tag, 0,
1771 				       &txq->stmp[nmaps].map);
1772 		if (rc != 0)
1773 			goto fail2;
1774 	}
1775 
1776 	snprintf(name, sizeof(name), "%u", txq_index);
1777 	txq_node = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(sc->txqs_node),
1778 				   OID_AUTO, name, CTLFLAG_RD, NULL, "");
1779 	if (txq_node == NULL) {
1780 		rc = ENOMEM;
1781 		goto fail_txq_node;
1782 	}
1783 
1784 	if (type == SFXGE_TXQ_IP_TCP_UDP_CKSUM &&
1785 	    (rc = tso_init(txq)) != 0)
1786 		goto fail3;
1787 
1788 	/* Initialize the deferred packet list. */
1789 	stdp = &txq->dpl;
1790 	stdp->std_put_max = sfxge_tx_dpl_put_max;
1791 	stdp->std_get_max = sfxge_tx_dpl_get_max;
1792 	stdp->std_get_non_tcp_max = sfxge_tx_dpl_get_non_tcp_max;
1793 	stdp->std_getp = &stdp->std_get;
1794 
1795 	SFXGE_TXQ_LOCK_INIT(txq, device_get_nameunit(sc->dev), txq_index);
1796 
1797 	dpl_node = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(txq_node), OID_AUTO,
1798 				   "dpl", CTLFLAG_RD, NULL,
1799 				   "Deferred packet list statistics");
1800 	if (dpl_node == NULL) {
1801 		rc = ENOMEM;
1802 		goto fail_dpl_node;
1803 	}
1804 
1805 	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(dpl_node), OID_AUTO,
1806 			"get_count", CTLFLAG_RD | CTLFLAG_STATS,
1807 			&stdp->std_get_count, 0, "");
1808 	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(dpl_node), OID_AUTO,
1809 			"get_non_tcp_count", CTLFLAG_RD | CTLFLAG_STATS,
1810 			&stdp->std_get_non_tcp_count, 0, "");
1811 	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(dpl_node), OID_AUTO,
1812 			"get_hiwat", CTLFLAG_RD | CTLFLAG_STATS,
1813 			&stdp->std_get_hiwat, 0, "");
1814 	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(dpl_node), OID_AUTO,
1815 			"put_hiwat", CTLFLAG_RD | CTLFLAG_STATS,
1816 			&stdp->std_put_hiwat, 0, "");
1817 
1818 	rc = sfxge_txq_stat_init(txq, txq_node);
1819 	if (rc != 0)
1820 		goto fail_txq_stat_init;
1821 
1822 	txq->type = type;
1823 	txq->evq_index = evq_index;
1824 	txq->txq_index = txq_index;
1825 	txq->init_state = SFXGE_TXQ_INITIALIZED;
1826 	txq->hw_vlan_tci = 0;
1827 
1828 	return (0);
1829 
1830 fail_txq_stat_init:
1831 fail_dpl_node:
1832 fail3:
1833 fail_txq_node:
1834 	free(txq->pend_desc, M_SFXGE);
1835 fail2:
1836 	while (nmaps-- != 0)
1837 		bus_dmamap_destroy(txq->packet_dma_tag, txq->stmp[nmaps].map);
1838 	free(txq->stmp, M_SFXGE);
1839 	bus_dma_tag_destroy(txq->packet_dma_tag);
1840 
1841 fail:
1842 	sfxge_dma_free(esmp);
1843 
1844 	return (rc);
1845 }
1846 
1847 static int
1848 sfxge_tx_stat_handler(SYSCTL_HANDLER_ARGS)
1849 {
1850 	struct sfxge_softc *sc = arg1;
1851 	unsigned int id = arg2;
1852 	unsigned long sum;
1853 	unsigned int index;
1854 
1855 	/* Sum across all TX queues */
1856 	sum = 0;
1857 	for (index = 0; index < sc->txq_count; index++)
1858 		sum += *(unsigned long *)((caddr_t)sc->txq[index] +
1859 					  sfxge_tx_stats[id].offset);
1860 
1861 	return (SYSCTL_OUT(req, &sum, sizeof(sum)));
1862 }
1863 
1864 static void
1865 sfxge_tx_stat_init(struct sfxge_softc *sc)
1866 {
1867 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->dev);
1868 	struct sysctl_oid_list *stat_list;
1869 	unsigned int id;
1870 
1871 	stat_list = SYSCTL_CHILDREN(sc->stats_node);
1872 
1873 	for (id = 0; id < nitems(sfxge_tx_stats); id++) {
1874 		SYSCTL_ADD_PROC(
1875 			ctx, stat_list,
1876 			OID_AUTO, sfxge_tx_stats[id].name,
1877 			CTLTYPE_ULONG|CTLFLAG_RD,
1878 			sc, id, sfxge_tx_stat_handler, "LU",
1879 			"");
1880 	}
1881 }
1882 
1883 uint64_t
1884 sfxge_tx_get_drops(struct sfxge_softc *sc)
1885 {
1886 	unsigned int index;
1887 	uint64_t drops = 0;
1888 	struct sfxge_txq *txq;
1889 
1890 	/* Sum across all TX queues */
1891 	for (index = 0; index < sc->txq_count; index++) {
1892 		txq = sc->txq[index];
1893 		/*
1894 		 * In theory, txq->put_overflow and txq->netdown_drops
1895 		 * should use atomic operation and other should be
1896 		 * obtained under txq lock, but it is just statistics.
1897 		 */
1898 		drops += txq->drops + txq->get_overflow +
1899 			 txq->get_non_tcp_overflow +
1900 			 txq->put_overflow + txq->netdown_drops +
1901 			 txq->tso_pdrop_too_many + txq->tso_pdrop_no_rsrc;
1902 	}
1903 	return (drops);
1904 }
1905 
1906 void
1907 sfxge_tx_fini(struct sfxge_softc *sc)
1908 {
1909 	int index;
1910 
1911 	index = sc->txq_count;
1912 	while (--index >= 0)
1913 		sfxge_tx_qfini(sc, index);
1914 
1915 	sc->txq_count = 0;
1916 }
1917 
1918 
1919 int
1920 sfxge_tx_init(struct sfxge_softc *sc)
1921 {
1922 	const efx_nic_cfg_t *encp = efx_nic_cfg_get(sc->enp);
1923 	struct sfxge_intr *intr;
1924 	int index;
1925 	int rc;
1926 
1927 	intr = &sc->intr;
1928 
1929 	KASSERT(intr->state == SFXGE_INTR_INITIALIZED,
1930 	    ("intr->state != SFXGE_INTR_INITIALIZED"));
1931 
1932 	if (sfxge_tx_dpl_get_max <= 0) {
1933 		log(LOG_ERR, "%s=%d must be greater than 0",
1934 		    SFXGE_PARAM_TX_DPL_GET_MAX, sfxge_tx_dpl_get_max);
1935 		rc = EINVAL;
1936 		goto fail_tx_dpl_get_max;
1937 	}
1938 	if (sfxge_tx_dpl_get_non_tcp_max <= 0) {
1939 		log(LOG_ERR, "%s=%d must be greater than 0",
1940 		    SFXGE_PARAM_TX_DPL_GET_NON_TCP_MAX,
1941 		    sfxge_tx_dpl_get_non_tcp_max);
1942 		rc = EINVAL;
1943 		goto fail_tx_dpl_get_non_tcp_max;
1944 	}
1945 	if (sfxge_tx_dpl_put_max < 0) {
1946 		log(LOG_ERR, "%s=%d must be greater or equal to 0",
1947 		    SFXGE_PARAM_TX_DPL_PUT_MAX, sfxge_tx_dpl_put_max);
1948 		rc = EINVAL;
1949 		goto fail_tx_dpl_put_max;
1950 	}
1951 
1952 	sc->txq_count = SFXGE_TXQ_NTYPES - 1 + sc->intr.n_alloc;
1953 
1954 	sc->tso_fw_assisted = sfxge_tso_fw_assisted;
1955 	if ((~encp->enc_features & EFX_FEATURE_FW_ASSISTED_TSO) ||
1956 	    (!encp->enc_fw_assisted_tso_enabled))
1957 		sc->tso_fw_assisted &= ~SFXGE_FATSOV1;
1958 	if ((~encp->enc_features & EFX_FEATURE_FW_ASSISTED_TSO_V2) ||
1959 	    (!encp->enc_fw_assisted_tso_v2_enabled))
1960 		sc->tso_fw_assisted &= ~SFXGE_FATSOV2;
1961 
1962 	sc->txqs_node = SYSCTL_ADD_NODE(
1963 		device_get_sysctl_ctx(sc->dev),
1964 		SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
1965 		OID_AUTO, "txq", CTLFLAG_RD, NULL, "Tx queues");
1966 	if (sc->txqs_node == NULL) {
1967 		rc = ENOMEM;
1968 		goto fail_txq_node;
1969 	}
1970 
1971 	/* Initialize the transmit queues */
1972 	if ((rc = sfxge_tx_qinit(sc, SFXGE_TXQ_NON_CKSUM,
1973 	    SFXGE_TXQ_NON_CKSUM, 0)) != 0)
1974 		goto fail;
1975 
1976 	if ((rc = sfxge_tx_qinit(sc, SFXGE_TXQ_IP_CKSUM,
1977 	    SFXGE_TXQ_IP_CKSUM, 0)) != 0)
1978 		goto fail2;
1979 
1980 	for (index = 0;
1981 	     index < sc->txq_count - SFXGE_TXQ_NTYPES + 1;
1982 	     index++) {
1983 		if ((rc = sfxge_tx_qinit(sc, SFXGE_TXQ_NTYPES - 1 + index,
1984 		    SFXGE_TXQ_IP_TCP_UDP_CKSUM, index)) != 0)
1985 			goto fail3;
1986 	}
1987 
1988 	sfxge_tx_stat_init(sc);
1989 
1990 	return (0);
1991 
1992 fail3:
1993 	while (--index >= 0)
1994 		sfxge_tx_qfini(sc, SFXGE_TXQ_IP_TCP_UDP_CKSUM + index);
1995 
1996 	sfxge_tx_qfini(sc, SFXGE_TXQ_IP_CKSUM);
1997 
1998 fail2:
1999 	sfxge_tx_qfini(sc, SFXGE_TXQ_NON_CKSUM);
2000 
2001 fail:
2002 fail_txq_node:
2003 	sc->txq_count = 0;
2004 fail_tx_dpl_put_max:
2005 fail_tx_dpl_get_non_tcp_max:
2006 fail_tx_dpl_get_max:
2007 	return (rc);
2008 }
2009