xref: /freebsd-13-stable/sys/net/iflib.c (revision f500e5c6c99bd4520daa4524113462e3cf68f032)
1 /*-
2  * Copyright (c) 2014-2018, Matthew Macy <mmacy@mattmacy.io>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *  1. Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *
11  *  2. Neither the name of Matthew Macy nor the names of its
12  *     contributors may be used to endorse or promote products derived from
13  *     this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 #include "opt_inet.h"
30 #include "opt_inet6.h"
31 #include "opt_acpi.h"
32 #include "opt_sched.h"
33 
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <sys/bus.h>
37 #include <sys/eventhandler.h>
38 #include <sys/kernel.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/module.h>
42 #include <sys/kobj.h>
43 #include <sys/rman.h>
44 #include <sys/sbuf.h>
45 #include <sys/smp.h>
46 #include <sys/socket.h>
47 #include <sys/sockio.h>
48 #include <sys/sysctl.h>
49 #include <sys/syslog.h>
50 #include <sys/taskqueue.h>
51 #include <sys/limits.h>
52 
53 #include <net/if.h>
54 #include <net/if_var.h>
55 #include <net/if_types.h>
56 #include <net/if_media.h>
57 #include <net/bpf.h>
58 #include <net/ethernet.h>
59 #include <net/mp_ring.h>
60 #include <net/debugnet.h>
61 #include <net/pfil.h>
62 #include <net/vnet.h>
63 
64 #include <netinet/in.h>
65 #include <netinet/in_pcb.h>
66 #include <netinet/tcp_lro.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/if_ether.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip6.h>
71 #include <netinet/tcp.h>
72 #include <netinet/ip_var.h>
73 #include <netinet6/ip6_var.h>
74 
75 #include <machine/bus.h>
76 #include <machine/in_cksum.h>
77 
78 #include <vm/vm.h>
79 #include <vm/pmap.h>
80 
81 #include <dev/led/led.h>
82 #include <dev/pci/pcireg.h>
83 #include <dev/pci/pcivar.h>
84 #include <dev/pci/pci_private.h>
85 
86 #include <net/iflib.h>
87 #include <net/iflib_private.h>
88 
89 #include "ifdi_if.h"
90 
91 #ifdef PCI_IOV
92 #include <dev/pci/pci_iov.h>
93 #endif
94 
95 #include <sys/bitstring.h>
96 /*
97  * enable accounting of every mbuf as it comes in to and goes out of
98  * iflib's software descriptor references
99  */
100 #define MEMORY_LOGGING 0
101 /*
102  * Enable mbuf vectors for compressing long mbuf chains
103  */
104 
105 /*
106  * NB:
107  * - Prefetching in tx cleaning should perhaps be a tunable. The distance ahead
108  *   we prefetch needs to be determined by the time spent in m_free vis a vis
109  *   the cost of a prefetch. This will of course vary based on the workload:
110  *      - NFLX's m_free path is dominated by vm-based M_EXT manipulation which
111  *        is quite expensive, thus suggesting very little prefetch.
112  *      - small packet forwarding which is just returning a single mbuf to
113  *        UMA will typically be very fast vis a vis the cost of a memory
114  *        access.
115  */
116 
117 /*
118  * File organization:
119  *  - private structures
120  *  - iflib private utility functions
121  *  - ifnet functions
122  *  - vlan registry and other exported functions
123  *  - iflib public core functions
124  *
125  *
126  */
127 MALLOC_DEFINE(M_IFLIB, "iflib", "ifnet library");
128 
129 #define	IFLIB_RXEOF_MORE	(1U << 0)
130 #define	IFLIB_RXEOF_EMPTY	(2U << 0)
131 
132 struct iflib_txq;
133 typedef struct iflib_txq *iflib_txq_t;
134 struct iflib_rxq;
135 typedef struct iflib_rxq *iflib_rxq_t;
136 struct iflib_fl;
137 typedef struct iflib_fl *iflib_fl_t;
138 
139 struct iflib_ctx;
140 
141 static void iru_init(if_rxd_update_t iru, iflib_rxq_t rxq, uint8_t flid);
142 static void iflib_timer(void *arg);
143 static void iflib_tqg_detach(if_ctx_t ctx);
144 
145 typedef struct iflib_filter_info {
146 	driver_filter_t *ifi_filter;
147 	void *ifi_filter_arg;
148 	struct grouptask *ifi_task;
149 	void *ifi_ctx;
150 } *iflib_filter_info_t;
151 
152 struct iflib_ctx {
153 	KOBJ_FIELDS;
154 	/*
155 	 * Pointer to hardware driver's softc
156 	 */
157 	void *ifc_softc;
158 	device_t ifc_dev;
159 	if_t ifc_ifp;
160 
161 	cpuset_t ifc_cpus;
162 	if_shared_ctx_t ifc_sctx;
163 	struct if_softc_ctx ifc_softc_ctx;
164 
165 	struct sx ifc_ctx_sx;
166 	struct mtx ifc_state_mtx;
167 
168 	iflib_txq_t ifc_txqs;
169 	iflib_rxq_t ifc_rxqs;
170 	uint32_t ifc_if_flags;
171 	uint32_t ifc_flags;
172 	uint32_t ifc_max_fl_buf_size;
173 	uint32_t ifc_rx_mbuf_sz;
174 
175 	int ifc_link_state;
176 	int ifc_watchdog_events;
177 	struct cdev *ifc_led_dev;
178 	struct resource *ifc_msix_mem;
179 
180 	struct if_irq ifc_legacy_irq;
181 	struct grouptask ifc_admin_task;
182 	struct grouptask ifc_vflr_task;
183 	struct iflib_filter_info ifc_filter_info;
184 	struct ifmedia	ifc_media;
185 	struct ifmedia	*ifc_mediap;
186 
187 	struct sysctl_oid *ifc_sysctl_node;
188 	uint16_t ifc_sysctl_ntxqs;
189 	uint16_t ifc_sysctl_nrxqs;
190 	uint16_t ifc_sysctl_qs_eq_override;
191 	uint16_t ifc_sysctl_rx_budget;
192 	uint16_t ifc_sysctl_tx_abdicate;
193 	uint16_t ifc_sysctl_core_offset;
194 #define	CORE_OFFSET_UNSPECIFIED	0xffff
195 	uint8_t  ifc_sysctl_separate_txrx;
196 	uint8_t  ifc_sysctl_use_logical_cores;
197 	uint16_t ifc_sysctl_extra_msix_vectors;
198 	bool	 ifc_cpus_are_physical_cores;
199 
200 	qidx_t ifc_sysctl_ntxds[8];
201 	qidx_t ifc_sysctl_nrxds[8];
202 	struct if_txrx ifc_txrx;
203 #define isc_txd_encap		ifc_txrx.ift_txd_encap
204 #define isc_txd_flush		ifc_txrx.ift_txd_flush
205 #define isc_txd_credits_update	ifc_txrx.ift_txd_credits_update
206 #define isc_rxd_available	ifc_txrx.ift_rxd_available
207 #define isc_rxd_pkt_get		ifc_txrx.ift_rxd_pkt_get
208 #define isc_rxd_refill		ifc_txrx.ift_rxd_refill
209 #define isc_rxd_flush		ifc_txrx.ift_rxd_flush
210 #define isc_legacy_intr		ifc_txrx.ift_legacy_intr
211 #define isc_txq_select		ifc_txrx.ift_txq_select
212 #define isc_txq_select_v2	ifc_txrx.ift_txq_select_v2
213 
214 	eventhandler_tag ifc_vlan_attach_event;
215 	eventhandler_tag ifc_vlan_detach_event;
216 	struct ether_addr ifc_mac;
217 };
218 
219 void *
iflib_get_softc(if_ctx_t ctx)220 iflib_get_softc(if_ctx_t ctx)
221 {
222 
223 	return (ctx->ifc_softc);
224 }
225 
226 device_t
iflib_get_dev(if_ctx_t ctx)227 iflib_get_dev(if_ctx_t ctx)
228 {
229 
230 	return (ctx->ifc_dev);
231 }
232 
233 if_t
iflib_get_ifp(if_ctx_t ctx)234 iflib_get_ifp(if_ctx_t ctx)
235 {
236 
237 	return (ctx->ifc_ifp);
238 }
239 
240 struct ifmedia *
iflib_get_media(if_ctx_t ctx)241 iflib_get_media(if_ctx_t ctx)
242 {
243 
244 	return (ctx->ifc_mediap);
245 }
246 
247 uint32_t
iflib_get_flags(if_ctx_t ctx)248 iflib_get_flags(if_ctx_t ctx)
249 {
250 	return (ctx->ifc_flags);
251 }
252 
253 void
iflib_set_mac(if_ctx_t ctx,uint8_t mac[ETHER_ADDR_LEN])254 iflib_set_mac(if_ctx_t ctx, uint8_t mac[ETHER_ADDR_LEN])
255 {
256 
257 	bcopy(mac, ctx->ifc_mac.octet, ETHER_ADDR_LEN);
258 }
259 
260 if_softc_ctx_t
iflib_get_softc_ctx(if_ctx_t ctx)261 iflib_get_softc_ctx(if_ctx_t ctx)
262 {
263 
264 	return (&ctx->ifc_softc_ctx);
265 }
266 
267 if_shared_ctx_t
iflib_get_sctx(if_ctx_t ctx)268 iflib_get_sctx(if_ctx_t ctx)
269 {
270 
271 	return (ctx->ifc_sctx);
272 }
273 
274 uint16_t
iflib_get_extra_msix_vectors_sysctl(if_ctx_t ctx)275 iflib_get_extra_msix_vectors_sysctl(if_ctx_t ctx)
276 {
277 
278 	return (ctx->ifc_sysctl_extra_msix_vectors);
279 }
280 
281 #define IP_ALIGNED(m)		((((uintptr_t)(m)->m_data) & 0x3) == 0x2)
282 #define CACHE_PTR_INCREMENT	(CACHE_LINE_SIZE / sizeof(void *))
283 #define CACHE_PTR_NEXT(ptr)	((void *)(((uintptr_t)(ptr) + CACHE_LINE_SIZE - 1) & (CACHE_LINE_SIZE - 1)))
284 
285 #define LINK_ACTIVE(ctx)	((ctx)->ifc_link_state == LINK_STATE_UP)
286 #define CTX_IS_VF(ctx)		((ctx)->ifc_sctx->isc_flags & IFLIB_IS_VF)
287 
288 typedef struct iflib_sw_rx_desc_array {
289 	bus_dmamap_t	*ifsd_map;         /* bus_dma maps for packet */
290 	struct mbuf	**ifsd_m;           /* pkthdr mbufs */
291 	caddr_t		*ifsd_cl;          /* direct cluster pointer for rx */
292 	bus_addr_t	*ifsd_ba;          /* bus addr of cluster for rx */
293 } iflib_rxsd_array_t;
294 
295 typedef struct iflib_sw_tx_desc_array {
296 	bus_dmamap_t    *ifsd_map;         /* bus_dma maps for packet */
297 	bus_dmamap_t	*ifsd_tso_map;     /* bus_dma maps for TSO packet */
298 	struct mbuf    **ifsd_m;           /* pkthdr mbufs */
299 } if_txsd_vec_t;
300 
301 /* magic number that should be high enough for any hardware */
302 #define IFLIB_MAX_TX_SEGS		128
303 #define IFLIB_RX_COPY_THRESH		128
304 #define IFLIB_MAX_RX_REFRESH		32
305 /* The minimum descriptors per second before we start coalescing */
306 #define IFLIB_MIN_DESC_SEC		16384
307 #define IFLIB_DEFAULT_TX_UPDATE_FREQ	16
308 #define IFLIB_QUEUE_IDLE		0
309 #define IFLIB_QUEUE_HUNG		1
310 #define IFLIB_QUEUE_WORKING		2
311 /* maximum number of txqs that can share an rx interrupt */
312 #define IFLIB_MAX_TX_SHARED_INTR	4
313 
314 /* this should really scale with ring size - this is a fairly arbitrary value */
315 #define TX_BATCH_SIZE			32
316 
317 #define IFLIB_RESTART_BUDGET		8
318 
319 #define CSUM_OFFLOAD		(CSUM_IP_TSO | CSUM_IP6_TSO | CSUM_IP | \
320 				 CSUM_IP_UDP | CSUM_IP_TCP | CSUM_IP_SCTP | \
321 				 CSUM_IP6_UDP | CSUM_IP6_TCP | CSUM_IP6_SCTP)
322 
323 struct iflib_txq {
324 	qidx_t		ift_in_use;
325 	qidx_t		ift_cidx;
326 	qidx_t		ift_cidx_processed;
327 	qidx_t		ift_pidx;
328 	uint8_t		ift_gen;
329 	uint8_t		ift_br_offset;
330 	uint16_t	ift_npending;
331 	uint16_t	ift_db_pending;
332 	uint16_t	ift_rs_pending;
333 	/* implicit pad */
334 	uint8_t		ift_txd_size[8];
335 	uint64_t	ift_processed;
336 	uint64_t	ift_cleaned;
337 	uint64_t	ift_cleaned_prev;
338 #if MEMORY_LOGGING
339 	uint64_t	ift_enqueued;
340 	uint64_t	ift_dequeued;
341 #endif
342 	uint64_t	ift_no_tx_dma_setup;
343 	uint64_t	ift_no_desc_avail;
344 	uint64_t	ift_mbuf_defrag_failed;
345 	uint64_t	ift_mbuf_defrag;
346 	uint64_t	ift_map_failed;
347 	uint64_t	ift_txd_encap_efbig;
348 	uint64_t	ift_pullups;
349 	uint64_t	ift_last_timer_tick;
350 
351 	struct mtx	ift_mtx;
352 	struct mtx	ift_db_mtx;
353 
354 	/* constant values */
355 	if_ctx_t	ift_ctx;
356 	struct ifmp_ring        *ift_br;
357 	struct grouptask	ift_task;
358 	qidx_t		ift_size;
359 	uint16_t	ift_id;
360 	struct callout	ift_timer;
361 #ifdef DEV_NETMAP
362 	struct callout	ift_netmap_timer;
363 #endif /* DEV_NETMAP */
364 
365 	if_txsd_vec_t	ift_sds;
366 	uint8_t		ift_qstatus;
367 	uint8_t		ift_closed;
368 	uint8_t		ift_update_freq;
369 	struct iflib_filter_info ift_filter_info;
370 	bus_dma_tag_t	ift_buf_tag;
371 	bus_dma_tag_t	ift_tso_buf_tag;
372 	iflib_dma_info_t	ift_ifdi;
373 #define	MTX_NAME_LEN	32
374 	char                    ift_mtx_name[MTX_NAME_LEN];
375 	bus_dma_segment_t	ift_segs[IFLIB_MAX_TX_SEGS]  __aligned(CACHE_LINE_SIZE);
376 #ifdef IFLIB_DIAGNOSTICS
377 	uint64_t ift_cpu_exec_count[256];
378 #endif
379 } __aligned(CACHE_LINE_SIZE);
380 
381 struct iflib_fl {
382 	qidx_t		ifl_cidx;
383 	qidx_t		ifl_pidx;
384 	qidx_t		ifl_credits;
385 	uint8_t		ifl_gen;
386 	uint8_t		ifl_rxd_size;
387 #if MEMORY_LOGGING
388 	uint64_t	ifl_m_enqueued;
389 	uint64_t	ifl_m_dequeued;
390 	uint64_t	ifl_cl_enqueued;
391 	uint64_t	ifl_cl_dequeued;
392 #endif
393 	/* implicit pad */
394 	bitstr_t 	*ifl_rx_bitmap;
395 	qidx_t		ifl_fragidx;
396 	/* constant */
397 	qidx_t		ifl_size;
398 	uint16_t	ifl_buf_size;
399 	uint16_t	ifl_cltype;
400 	uma_zone_t	ifl_zone;
401 	iflib_rxsd_array_t	ifl_sds;
402 	iflib_rxq_t	ifl_rxq;
403 	uint8_t		ifl_id;
404 	bus_dma_tag_t	ifl_buf_tag;
405 	iflib_dma_info_t	ifl_ifdi;
406 	uint64_t	ifl_bus_addrs[IFLIB_MAX_RX_REFRESH] __aligned(CACHE_LINE_SIZE);
407 	qidx_t		ifl_rxd_idxs[IFLIB_MAX_RX_REFRESH];
408 }  __aligned(CACHE_LINE_SIZE);
409 
410 static inline qidx_t
get_inuse(int size,qidx_t cidx,qidx_t pidx,uint8_t gen)411 get_inuse(int size, qidx_t cidx, qidx_t pidx, uint8_t gen)
412 {
413 	qidx_t used;
414 
415 	if (pidx > cidx)
416 		used = pidx - cidx;
417 	else if (pidx < cidx)
418 		used = size - cidx + pidx;
419 	else if (gen == 0 && pidx == cidx)
420 		used = 0;
421 	else if (gen == 1 && pidx == cidx)
422 		used = size;
423 	else
424 		panic("bad state");
425 
426 	return (used);
427 }
428 
429 #define TXQ_AVAIL(txq) (txq->ift_size - get_inuse(txq->ift_size, txq->ift_cidx, txq->ift_pidx, txq->ift_gen))
430 
431 #define IDXDIFF(head, tail, wrap) \
432 	((head) >= (tail) ? (head) - (tail) : (wrap) - (tail) + (head))
433 
434 struct iflib_rxq {
435 	if_ctx_t	ifr_ctx;
436 	iflib_fl_t	ifr_fl;
437 	uint64_t	ifr_rx_irq;
438 	struct pfil_head	*pfil;
439 	/*
440 	 * If there is a separate completion queue (IFLIB_HAS_RXCQ), this is
441 	 * the completion queue consumer index.  Otherwise it's unused.
442 	 */
443 	qidx_t		ifr_cq_cidx;
444 	uint16_t	ifr_id;
445 	uint8_t		ifr_nfl;
446 	uint8_t		ifr_ntxqirq;
447 	uint8_t		ifr_txqid[IFLIB_MAX_TX_SHARED_INTR];
448 	uint8_t		ifr_fl_offset;
449 	struct lro_ctrl		ifr_lc;
450 	struct grouptask        ifr_task;
451 	struct callout		ifr_watchdog;
452 	struct iflib_filter_info ifr_filter_info;
453 	iflib_dma_info_t	ifr_ifdi;
454 
455 	/* dynamically allocate if any drivers need a value substantially larger than this */
456 	struct if_rxd_frag	ifr_frags[IFLIB_MAX_RX_SEGS] __aligned(CACHE_LINE_SIZE);
457 #ifdef IFLIB_DIAGNOSTICS
458 	uint64_t ifr_cpu_exec_count[256];
459 #endif
460 }  __aligned(CACHE_LINE_SIZE);
461 
462 typedef struct if_rxsd {
463 	caddr_t *ifsd_cl;
464 	iflib_fl_t ifsd_fl;
465 } *if_rxsd_t;
466 
467 /* multiple of word size */
468 #ifdef __LP64__
469 #define PKT_INFO_SIZE	6
470 #define RXD_INFO_SIZE	5
471 #define PKT_TYPE uint64_t
472 #else
473 #define PKT_INFO_SIZE	11
474 #define RXD_INFO_SIZE	8
475 #define PKT_TYPE uint32_t
476 #endif
477 #define PKT_LOOP_BOUND	((PKT_INFO_SIZE / 3) * 3)
478 #define RXD_LOOP_BOUND	((RXD_INFO_SIZE / 4) * 4)
479 
480 typedef struct if_pkt_info_pad {
481 	PKT_TYPE pkt_val[PKT_INFO_SIZE];
482 } *if_pkt_info_pad_t;
483 typedef struct if_rxd_info_pad {
484 	PKT_TYPE rxd_val[RXD_INFO_SIZE];
485 } *if_rxd_info_pad_t;
486 
487 CTASSERT(sizeof(struct if_pkt_info_pad) == sizeof(struct if_pkt_info));
488 CTASSERT(sizeof(struct if_rxd_info_pad) == sizeof(struct if_rxd_info));
489 
490 static inline void
pkt_info_zero(if_pkt_info_t pi)491 pkt_info_zero(if_pkt_info_t pi)
492 {
493 	if_pkt_info_pad_t pi_pad;
494 
495 	pi_pad = (if_pkt_info_pad_t)pi;
496 	pi_pad->pkt_val[0] = 0; pi_pad->pkt_val[1] = 0; pi_pad->pkt_val[2] = 0;
497 	pi_pad->pkt_val[3] = 0; pi_pad->pkt_val[4] = 0; pi_pad->pkt_val[5] = 0;
498 #ifndef __LP64__
499 	pi_pad->pkt_val[6] = 0; pi_pad->pkt_val[7] = 0; pi_pad->pkt_val[8] = 0;
500 	pi_pad->pkt_val[9] = 0; pi_pad->pkt_val[10] = 0;
501 #endif
502 }
503 
504 static device_method_t iflib_pseudo_methods[] = {
505 	DEVMETHOD(device_attach, noop_attach),
506 	DEVMETHOD(device_detach, iflib_pseudo_detach),
507 	DEVMETHOD_END
508 };
509 
510 driver_t iflib_pseudodriver = {
511 	"iflib_pseudo", iflib_pseudo_methods, sizeof(struct iflib_ctx),
512 };
513 
514 static inline void
rxd_info_zero(if_rxd_info_t ri)515 rxd_info_zero(if_rxd_info_t ri)
516 {
517 	if_rxd_info_pad_t ri_pad;
518 	int i;
519 
520 	ri_pad = (if_rxd_info_pad_t)ri;
521 	for (i = 0; i < RXD_LOOP_BOUND; i += 4) {
522 		ri_pad->rxd_val[i] = 0;
523 		ri_pad->rxd_val[i + 1] = 0;
524 		ri_pad->rxd_val[i + 2] = 0;
525 		ri_pad->rxd_val[i + 3] = 0;
526 	}
527 #ifdef __LP64__
528 	ri_pad->rxd_val[RXD_INFO_SIZE - 1] = 0;
529 #endif
530 }
531 
532 /*
533  * Only allow a single packet to take up most 1/nth of the tx ring
534  */
535 #define MAX_SINGLE_PACKET_FRACTION 12
536 #define IF_BAD_DMA	((bus_addr_t)-1)
537 
538 #define CTX_ACTIVE(ctx)	((if_getdrvflags((ctx)->ifc_ifp) & IFF_DRV_RUNNING))
539 
540 #define CTX_LOCK_INIT(_sc)	sx_init(&(_sc)->ifc_ctx_sx, "iflib ctx lock")
541 #define CTX_LOCK(ctx)		sx_xlock(&(ctx)->ifc_ctx_sx)
542 #define CTX_UNLOCK(ctx)		sx_xunlock(&(ctx)->ifc_ctx_sx)
543 #define CTX_LOCK_DESTROY(ctx)	sx_destroy(&(ctx)->ifc_ctx_sx)
544 
545 #define STATE_LOCK_INIT(_sc, _name)	mtx_init(&(_sc)->ifc_state_mtx, _name, "iflib state lock", MTX_DEF)
546 #define STATE_LOCK(ctx)		mtx_lock(&(ctx)->ifc_state_mtx)
547 #define STATE_UNLOCK(ctx)	mtx_unlock(&(ctx)->ifc_state_mtx)
548 #define STATE_LOCK_DESTROY(ctx)	mtx_destroy(&(ctx)->ifc_state_mtx)
549 
550 #define CALLOUT_LOCK(txq)	mtx_lock(&txq->ift_mtx)
551 #define CALLOUT_UNLOCK(txq) 	mtx_unlock(&txq->ift_mtx)
552 
553 void
iflib_set_detach(if_ctx_t ctx)554 iflib_set_detach(if_ctx_t ctx)
555 {
556 	STATE_LOCK(ctx);
557 	ctx->ifc_flags |= IFC_IN_DETACH;
558 	STATE_UNLOCK(ctx);
559 }
560 
561 /* Our boot-time initialization hook */
562 static int	iflib_module_event_handler(module_t, int, void *);
563 
564 static moduledata_t iflib_moduledata = {
565 	"iflib",
566 	iflib_module_event_handler,
567 	NULL
568 };
569 
570 DECLARE_MODULE(iflib, iflib_moduledata, SI_SUB_INIT_IF, SI_ORDER_ANY);
571 MODULE_VERSION(iflib, 1);
572 
573 MODULE_DEPEND(iflib, pci, 1, 1, 1);
574 MODULE_DEPEND(iflib, ether, 1, 1, 1);
575 
576 TASKQGROUP_DEFINE(if_io_tqg, mp_ncpus, 1);
577 TASKQGROUP_DEFINE(if_config_tqg, 1, 1);
578 
579 #ifndef IFLIB_DEBUG_COUNTERS
580 #ifdef INVARIANTS
581 #define IFLIB_DEBUG_COUNTERS 1
582 #else
583 #define IFLIB_DEBUG_COUNTERS 0
584 #endif /* !INVARIANTS */
585 #endif
586 
587 static SYSCTL_NODE(_net, OID_AUTO, iflib, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
588     "iflib driver parameters");
589 
590 /*
591  * XXX need to ensure that this can't accidentally cause the head to be moved backwards
592  */
593 static int iflib_min_tx_latency = 0;
594 SYSCTL_INT(_net_iflib, OID_AUTO, min_tx_latency, CTLFLAG_RW,
595     &iflib_min_tx_latency, 0,
596     "minimize transmit latency at the possible expense of throughput");
597 static int iflib_no_tx_batch = 0;
598 SYSCTL_INT(_net_iflib, OID_AUTO, no_tx_batch, CTLFLAG_RW,
599     &iflib_no_tx_batch, 0,
600     "minimize transmit latency at the possible expense of throughput");
601 static int iflib_timer_default = 1000;
602 SYSCTL_INT(_net_iflib, OID_AUTO, timer_default, CTLFLAG_RW,
603     &iflib_timer_default, 0, "number of ticks between iflib_timer calls");
604 
605 
606 #if IFLIB_DEBUG_COUNTERS
607 
608 static int iflib_tx_seen;
609 static int iflib_tx_sent;
610 static int iflib_tx_encap;
611 static int iflib_rx_allocs;
612 static int iflib_fl_refills;
613 static int iflib_fl_refills_large;
614 static int iflib_tx_frees;
615 
616 SYSCTL_INT(_net_iflib, OID_AUTO, tx_seen, CTLFLAG_RD, &iflib_tx_seen, 0,
617     "# TX mbufs seen");
618 SYSCTL_INT(_net_iflib, OID_AUTO, tx_sent, CTLFLAG_RD, &iflib_tx_sent, 0,
619     "# TX mbufs sent");
620 SYSCTL_INT(_net_iflib, OID_AUTO, tx_encap, CTLFLAG_RD, &iflib_tx_encap, 0,
621     "# TX mbufs encapped");
622 SYSCTL_INT(_net_iflib, OID_AUTO, tx_frees, CTLFLAG_RD, &iflib_tx_frees, 0,
623     "# TX frees");
624 SYSCTL_INT(_net_iflib, OID_AUTO, rx_allocs, CTLFLAG_RD, &iflib_rx_allocs, 0,
625     "# RX allocations");
626 SYSCTL_INT(_net_iflib, OID_AUTO, fl_refills, CTLFLAG_RD, &iflib_fl_refills, 0,
627     "# refills");
628 SYSCTL_INT(_net_iflib, OID_AUTO, fl_refills_large, CTLFLAG_RD,
629     &iflib_fl_refills_large, 0, "# large refills");
630 
631 static int iflib_txq_drain_flushing;
632 static int iflib_txq_drain_oactive;
633 static int iflib_txq_drain_notready;
634 
635 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_flushing, CTLFLAG_RD,
636     &iflib_txq_drain_flushing, 0, "# drain flushes");
637 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_oactive, CTLFLAG_RD,
638     &iflib_txq_drain_oactive, 0, "# drain oactives");
639 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_notready, CTLFLAG_RD,
640     &iflib_txq_drain_notready, 0, "# drain notready");
641 
642 static int iflib_encap_load_mbuf_fail;
643 static int iflib_encap_pad_mbuf_fail;
644 static int iflib_encap_txq_avail_fail;
645 static int iflib_encap_txd_encap_fail;
646 
647 SYSCTL_INT(_net_iflib, OID_AUTO, encap_load_mbuf_fail, CTLFLAG_RD,
648     &iflib_encap_load_mbuf_fail, 0, "# busdma load failures");
649 SYSCTL_INT(_net_iflib, OID_AUTO, encap_pad_mbuf_fail, CTLFLAG_RD,
650     &iflib_encap_pad_mbuf_fail, 0, "# runt frame pad failures");
651 SYSCTL_INT(_net_iflib, OID_AUTO, encap_txq_avail_fail, CTLFLAG_RD,
652     &iflib_encap_txq_avail_fail, 0, "# txq avail failures");
653 SYSCTL_INT(_net_iflib, OID_AUTO, encap_txd_encap_fail, CTLFLAG_RD,
654     &iflib_encap_txd_encap_fail, 0, "# driver encap failures");
655 
656 static int iflib_task_fn_rxs;
657 static int iflib_rx_intr_enables;
658 static int iflib_fast_intrs;
659 static int iflib_rx_unavail;
660 static int iflib_rx_ctx_inactive;
661 static int iflib_rx_if_input;
662 static int iflib_rxd_flush;
663 
664 static int iflib_verbose_debug;
665 
666 SYSCTL_INT(_net_iflib, OID_AUTO, task_fn_rx, CTLFLAG_RD, &iflib_task_fn_rxs, 0,
667     "# task_fn_rx calls");
668 SYSCTL_INT(_net_iflib, OID_AUTO, rx_intr_enables, CTLFLAG_RD,
669     &iflib_rx_intr_enables, 0, "# RX intr enables");
670 SYSCTL_INT(_net_iflib, OID_AUTO, fast_intrs, CTLFLAG_RD, &iflib_fast_intrs, 0,
671     "# fast_intr calls");
672 SYSCTL_INT(_net_iflib, OID_AUTO, rx_unavail, CTLFLAG_RD, &iflib_rx_unavail, 0,
673     "# times rxeof called with no available data");
674 SYSCTL_INT(_net_iflib, OID_AUTO, rx_ctx_inactive, CTLFLAG_RD,
675     &iflib_rx_ctx_inactive, 0, "# times rxeof called with inactive context");
676 SYSCTL_INT(_net_iflib, OID_AUTO, rx_if_input, CTLFLAG_RD, &iflib_rx_if_input,
677     0, "# times rxeof called if_input");
678 SYSCTL_INT(_net_iflib, OID_AUTO, rxd_flush, CTLFLAG_RD, &iflib_rxd_flush, 0,
679     "# times rxd_flush called");
680 SYSCTL_INT(_net_iflib, OID_AUTO, verbose_debug, CTLFLAG_RW,
681     &iflib_verbose_debug, 0, "enable verbose debugging");
682 
683 #define DBG_COUNTER_INC(name) atomic_add_int(&(iflib_ ## name), 1)
684 static void
iflib_debug_reset(void)685 iflib_debug_reset(void)
686 {
687 	iflib_tx_seen = iflib_tx_sent = iflib_tx_encap = iflib_rx_allocs =
688 		iflib_fl_refills = iflib_fl_refills_large = iflib_tx_frees =
689 		iflib_txq_drain_flushing = iflib_txq_drain_oactive =
690 		iflib_txq_drain_notready =
691 		iflib_encap_load_mbuf_fail = iflib_encap_pad_mbuf_fail =
692 		iflib_encap_txq_avail_fail = iflib_encap_txd_encap_fail =
693 		iflib_task_fn_rxs = iflib_rx_intr_enables = iflib_fast_intrs =
694 		iflib_rx_unavail =
695 		iflib_rx_ctx_inactive = iflib_rx_if_input =
696 		iflib_rxd_flush = 0;
697 }
698 
699 #else
700 #define DBG_COUNTER_INC(name)
iflib_debug_reset(void)701 static void iflib_debug_reset(void) {}
702 #endif
703 
704 #define IFLIB_DEBUG 0
705 
706 static void iflib_tx_structures_free(if_ctx_t ctx);
707 static void iflib_rx_structures_free(if_ctx_t ctx);
708 static int iflib_queues_alloc(if_ctx_t ctx);
709 static int iflib_tx_credits_update(if_ctx_t ctx, iflib_txq_t txq);
710 static int iflib_rxd_avail(if_ctx_t ctx, iflib_rxq_t rxq, qidx_t cidx, qidx_t budget);
711 static int iflib_qset_structures_setup(if_ctx_t ctx);
712 static int iflib_msix_init(if_ctx_t ctx);
713 static int iflib_legacy_setup(if_ctx_t ctx, driver_filter_t filter, void *filterarg, int *rid, const char *str);
714 static void iflib_txq_check_drain(iflib_txq_t txq, int budget);
715 static uint32_t iflib_txq_can_drain(struct ifmp_ring *);
716 #ifdef ALTQ
717 static void iflib_altq_if_start(if_t ifp);
718 static int iflib_altq_if_transmit(if_t ifp, struct mbuf *m);
719 #endif
720 static int iflib_register(if_ctx_t);
721 static void iflib_deregister(if_ctx_t);
722 static void iflib_unregister_vlan_handlers(if_ctx_t ctx);
723 static uint16_t iflib_get_mbuf_size_for(unsigned int size);
724 static void iflib_init_locked(if_ctx_t ctx);
725 static void iflib_add_device_sysctl_pre(if_ctx_t ctx);
726 static void iflib_add_device_sysctl_post(if_ctx_t ctx);
727 static void iflib_ifmp_purge(iflib_txq_t txq);
728 static void _iflib_pre_assert(if_softc_ctx_t scctx);
729 static void iflib_if_init_locked(if_ctx_t ctx);
730 static void iflib_free_intr_mem(if_ctx_t ctx);
731 #ifndef __NO_STRICT_ALIGNMENT
732 static struct mbuf *iflib_fixup_rx(struct mbuf *m);
733 #endif
734 
735 static SLIST_HEAD(cpu_offset_list, cpu_offset) cpu_offsets =
736     SLIST_HEAD_INITIALIZER(cpu_offsets);
737 struct cpu_offset {
738 	SLIST_ENTRY(cpu_offset) entries;
739 	cpuset_t	set;
740 	unsigned int	refcount;
741 	uint16_t	next_cpuid;
742 };
743 static struct mtx cpu_offset_mtx;
744 MTX_SYSINIT(iflib_cpu_offset, &cpu_offset_mtx, "iflib_cpu_offset lock",
745     MTX_DEF);
746 
747 DEBUGNET_DEFINE(iflib);
748 
749 static int
iflib_num_rx_descs(if_ctx_t ctx)750 iflib_num_rx_descs(if_ctx_t ctx)
751 {
752 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
753 	if_shared_ctx_t sctx = ctx->ifc_sctx;
754 	uint16_t first_rxq = (sctx->isc_flags & IFLIB_HAS_RXCQ) ? 1 : 0;
755 
756 	return (scctx->isc_nrxd[first_rxq]);
757 }
758 
759 static int
iflib_num_tx_descs(if_ctx_t ctx)760 iflib_num_tx_descs(if_ctx_t ctx)
761 {
762 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
763 	if_shared_ctx_t sctx = ctx->ifc_sctx;
764 	uint16_t first_txq = (sctx->isc_flags & IFLIB_HAS_TXCQ) ? 1 : 0;
765 
766 	return (scctx->isc_ntxd[first_txq]);
767 }
768 
769 #ifdef DEV_NETMAP
770 #include <sys/selinfo.h>
771 #include <net/netmap.h>
772 #include <dev/netmap/netmap_kern.h>
773 
774 MODULE_DEPEND(iflib, netmap, 1, 1, 1);
775 
776 static int netmap_fl_refill(iflib_rxq_t rxq, struct netmap_kring *kring, bool init);
777 static void iflib_netmap_timer(void *arg);
778 
779 /*
780  * device-specific sysctl variables:
781  *
782  * iflib_crcstrip: 0: keep CRC in rx frames (default), 1: strip it.
783  *	During regular operations the CRC is stripped, but on some
784  *	hardware reception of frames not multiple of 64 is slower,
785  *	so using crcstrip=0 helps in benchmarks.
786  *
787  * iflib_rx_miss, iflib_rx_miss_bufs:
788  *	count packets that might be missed due to lost interrupts.
789  */
790 SYSCTL_DECL(_dev_netmap);
791 /*
792  * The xl driver by default strips CRCs and we do not override it.
793  */
794 
795 int iflib_crcstrip = 1;
796 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_crcstrip,
797     CTLFLAG_RW, &iflib_crcstrip, 1, "strip CRC on RX frames");
798 
799 int iflib_rx_miss, iflib_rx_miss_bufs;
800 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_rx_miss,
801     CTLFLAG_RW, &iflib_rx_miss, 0, "potentially missed RX intr");
802 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_rx_miss_bufs,
803     CTLFLAG_RW, &iflib_rx_miss_bufs, 0, "potentially missed RX intr bufs");
804 
805 /*
806  * Register/unregister. We are already under netmap lock.
807  * Only called on the first register or the last unregister.
808  */
809 static int
iflib_netmap_register(struct netmap_adapter * na,int onoff)810 iflib_netmap_register(struct netmap_adapter *na, int onoff)
811 {
812 	if_t ifp = na->ifp;
813 	if_ctx_t ctx = ifp->if_softc;
814 	int status;
815 
816 	CTX_LOCK(ctx);
817 	if (!CTX_IS_VF(ctx))
818 		IFDI_CRCSTRIP_SET(ctx, onoff, iflib_crcstrip);
819 
820 	iflib_stop(ctx);
821 
822 	/*
823 	 * Enable (or disable) netmap flags, and intercept (or restore)
824 	 * ifp->if_transmit. This is done once the device has been stopped
825 	 * to prevent race conditions. Also, this must be done after
826 	 * calling netmap_disable_all_rings() and before calling
827 	 * netmap_enable_all_rings(), so that these two functions see the
828 	 * updated state of the NAF_NETMAP_ON bit.
829 	 */
830 	if (onoff) {
831 		nm_set_native_flags(na);
832 	} else {
833 		nm_clear_native_flags(na);
834 	}
835 
836 	iflib_init_locked(ctx);
837 	IFDI_CRCSTRIP_SET(ctx, onoff, iflib_crcstrip); // XXX why twice ?
838 	status = ifp->if_drv_flags & IFF_DRV_RUNNING ? 0 : 1;
839 	if (status)
840 		nm_clear_native_flags(na);
841 	CTX_UNLOCK(ctx);
842 	return (status);
843 }
844 
845 static int
iflib_netmap_config(struct netmap_adapter * na,struct nm_config_info * info)846 iflib_netmap_config(struct netmap_adapter *na, struct nm_config_info *info)
847 {
848 	if_t ifp = na->ifp;
849 	if_ctx_t ctx = ifp->if_softc;
850 	iflib_rxq_t rxq = &ctx->ifc_rxqs[0];
851 	iflib_fl_t fl = &rxq->ifr_fl[0];
852 
853 	info->num_tx_rings = ctx->ifc_softc_ctx.isc_ntxqsets;
854 	info->num_rx_rings = ctx->ifc_softc_ctx.isc_nrxqsets;
855 	info->num_tx_descs = iflib_num_tx_descs(ctx);
856 	info->num_rx_descs = iflib_num_rx_descs(ctx);
857 	info->rx_buf_maxsize = fl->ifl_buf_size;
858 	nm_prinf("txr %u rxr %u txd %u rxd %u rbufsz %u",
859 		info->num_tx_rings, info->num_rx_rings, info->num_tx_descs,
860 		info->num_rx_descs, info->rx_buf_maxsize);
861 
862 	return (0);
863 }
864 
865 static int
netmap_fl_refill(iflib_rxq_t rxq,struct netmap_kring * kring,bool init)866 netmap_fl_refill(iflib_rxq_t rxq, struct netmap_kring *kring, bool init)
867 {
868 	struct netmap_adapter *na = kring->na;
869 	u_int const lim = kring->nkr_num_slots - 1;
870 	struct netmap_ring *ring = kring->ring;
871 	bus_dmamap_t *map;
872 	struct if_rxd_update iru;
873 	if_ctx_t ctx = rxq->ifr_ctx;
874 	iflib_fl_t fl = &rxq->ifr_fl[0];
875 	u_int nic_i_first, nic_i;
876 	u_int nm_i;
877 	int i, n;
878 #if IFLIB_DEBUG_COUNTERS
879 	int rf_count = 0;
880 #endif
881 
882 	/*
883 	 * This function is used both at initialization and in rxsync.
884 	 * At initialization we need to prepare (with isc_rxd_refill())
885 	 * all the netmap buffers currently owned by the kernel, in
886 	 * such a way to keep fl->ifl_pidx and kring->nr_hwcur in sync
887 	 * (except for kring->nkr_hwofs). These may be less than
888 	 * kring->nkr_num_slots if netmap_reset() was called while
889 	 * an application using the kring that still owned some
890 	 * buffers.
891 	 * At rxsync time, both indexes point to the next buffer to be
892 	 * refilled.
893 	 * In any case we publish (with isc_rxd_flush()) up to
894 	 * (fl->ifl_pidx - 1) % N (included), to avoid the NIC tail/prod
895 	 * pointer to overrun the head/cons pointer, although this is
896 	 * not necessary for some NICs (e.g. vmx).
897 	 */
898 	if (__predict_false(init)) {
899 		n = kring->nkr_num_slots - nm_kr_rxspace(kring);
900 	} else {
901 		n = kring->rhead - kring->nr_hwcur;
902 		if (n == 0)
903 			return (0); /* Nothing to do. */
904 		if (n < 0)
905 			n += kring->nkr_num_slots;
906 	}
907 
908 	iru_init(&iru, rxq, 0 /* flid */);
909 	map = fl->ifl_sds.ifsd_map;
910 	nic_i = fl->ifl_pidx;
911 	nm_i = netmap_idx_n2k(kring, nic_i);
912 	if (__predict_false(init)) {
913 		/*
914 		 * On init/reset, nic_i must be 0, and we must
915 		 * start to refill from hwtail (see netmap_reset()).
916 		 */
917 		MPASS(nic_i == 0);
918 		MPASS(nm_i == kring->nr_hwtail);
919 	} else
920 		MPASS(nm_i == kring->nr_hwcur);
921 	DBG_COUNTER_INC(fl_refills);
922 	while (n > 0) {
923 #if IFLIB_DEBUG_COUNTERS
924 		if (++rf_count == 9)
925 			DBG_COUNTER_INC(fl_refills_large);
926 #endif
927 		nic_i_first = nic_i;
928 		for (i = 0; n > 0 && i < IFLIB_MAX_RX_REFRESH; n--, i++) {
929 			struct netmap_slot *slot = &ring->slot[nm_i];
930 			void *addr = PNMB(na, slot, &fl->ifl_bus_addrs[i]);
931 
932 			MPASS(i < IFLIB_MAX_RX_REFRESH);
933 
934 			if (addr == NETMAP_BUF_BASE(na)) /* bad buf */
935 			        return (netmap_ring_reinit(kring));
936 
937 			fl->ifl_rxd_idxs[i] = nic_i;
938 
939 			if (__predict_false(init)) {
940 				netmap_load_map(na, fl->ifl_buf_tag,
941 				    map[nic_i], addr);
942 			} else if (slot->flags & NS_BUF_CHANGED) {
943 				/* buffer has changed, reload map */
944 				netmap_reload_map(na, fl->ifl_buf_tag,
945 				    map[nic_i], addr);
946 			}
947 			bus_dmamap_sync(fl->ifl_buf_tag, map[nic_i],
948 			    BUS_DMASYNC_PREREAD);
949 			slot->flags &= ~NS_BUF_CHANGED;
950 
951 			nm_i = nm_next(nm_i, lim);
952 			nic_i = nm_next(nic_i, lim);
953 		}
954 
955 		iru.iru_pidx = nic_i_first;
956 		iru.iru_count = i;
957 		ctx->isc_rxd_refill(ctx->ifc_softc, &iru);
958 	}
959 	fl->ifl_pidx = nic_i;
960 	/*
961 	 * At the end of the loop we must have refilled everything
962 	 * we could possibly refill.
963 	 */
964 	MPASS(nm_i == kring->rhead);
965 	kring->nr_hwcur = nm_i;
966 
967 	bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
968 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
969 	ctx->isc_rxd_flush(ctx->ifc_softc, rxq->ifr_id, fl->ifl_id,
970 	    nm_prev(nic_i, lim));
971 	DBG_COUNTER_INC(rxd_flush);
972 
973 	return (0);
974 }
975 
976 #define NETMAP_TX_TIMER_US	90
977 
978 /*
979  * Reconcile kernel and user view of the transmit ring.
980  *
981  * All information is in the kring.
982  * Userspace wants to send packets up to the one before kring->rhead,
983  * kernel knows kring->nr_hwcur is the first unsent packet.
984  *
985  * Here we push packets out (as many as possible), and possibly
986  * reclaim buffers from previously completed transmission.
987  *
988  * The caller (netmap) guarantees that there is only one instance
989  * running at any time. Any interference with other driver
990  * methods should be handled by the individual drivers.
991  */
992 static int
iflib_netmap_txsync(struct netmap_kring * kring,int flags)993 iflib_netmap_txsync(struct netmap_kring *kring, int flags)
994 {
995 	struct netmap_adapter *na = kring->na;
996 	if_t ifp = na->ifp;
997 	struct netmap_ring *ring = kring->ring;
998 	u_int nm_i;	/* index into the netmap kring */
999 	u_int nic_i;	/* index into the NIC ring */
1000 	u_int const lim = kring->nkr_num_slots - 1;
1001 	u_int const head = kring->rhead;
1002 	struct if_pkt_info pi;
1003 	int tx_pkts = 0, tx_bytes = 0;
1004 
1005 	/*
1006 	 * interrupts on every tx packet are expensive so request
1007 	 * them every half ring, or where NS_REPORT is set
1008 	 */
1009 	u_int report_frequency = kring->nkr_num_slots >> 1;
1010 	/* device-specific */
1011 	if_ctx_t ctx = ifp->if_softc;
1012 	iflib_txq_t txq = &ctx->ifc_txqs[kring->ring_id];
1013 
1014 	bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
1015 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1016 
1017 	/*
1018 	 * First part: process new packets to send.
1019 	 * nm_i is the current index in the netmap kring,
1020 	 * nic_i is the corresponding index in the NIC ring.
1021 	 *
1022 	 * If we have packets to send (nm_i != head)
1023 	 * iterate over the netmap ring, fetch length and update
1024 	 * the corresponding slot in the NIC ring. Some drivers also
1025 	 * need to update the buffer's physical address in the NIC slot
1026 	 * even NS_BUF_CHANGED is not set (PNMB computes the addresses).
1027 	 *
1028 	 * The netmap_reload_map() calls is especially expensive,
1029 	 * even when (as in this case) the tag is 0, so do only
1030 	 * when the buffer has actually changed.
1031 	 *
1032 	 * If possible do not set the report/intr bit on all slots,
1033 	 * but only a few times per ring or when NS_REPORT is set.
1034 	 *
1035 	 * Finally, on 10G and faster drivers, it might be useful
1036 	 * to prefetch the next slot and txr entry.
1037 	 */
1038 
1039 	nm_i = kring->nr_hwcur;
1040 	if (nm_i != head) {	/* we have new packets to send */
1041 		uint32_t pkt_len = 0, seg_idx = 0;
1042 		int nic_i_start = -1, flags = 0;
1043 		pkt_info_zero(&pi);
1044 		pi.ipi_segs = txq->ift_segs;
1045 		pi.ipi_qsidx = kring->ring_id;
1046 		nic_i = netmap_idx_k2n(kring, nm_i);
1047 
1048 		__builtin_prefetch(&ring->slot[nm_i]);
1049 		__builtin_prefetch(&txq->ift_sds.ifsd_m[nic_i]);
1050 		__builtin_prefetch(&txq->ift_sds.ifsd_map[nic_i]);
1051 
1052 		while (nm_i != head) {
1053 			struct netmap_slot *slot = &ring->slot[nm_i];
1054 			u_int len = slot->len;
1055 			uint64_t paddr;
1056 			void *addr = PNMB(na, slot, &paddr);
1057 
1058 			flags |= (slot->flags & NS_REPORT ||
1059 				nic_i == 0 || nic_i == report_frequency) ?
1060 				IPI_TX_INTR : 0;
1061 
1062 			/*
1063 			 * If this is the first packet fragment, save the
1064 			 * index of the first NIC slot for later.
1065 			 */
1066 			if (nic_i_start < 0)
1067 				nic_i_start = nic_i;
1068 
1069 			pi.ipi_segs[seg_idx].ds_addr = paddr;
1070 			pi.ipi_segs[seg_idx].ds_len = len;
1071 			if (len) {
1072 				pkt_len += len;
1073 				seg_idx++;
1074 			}
1075 
1076 			if (!(slot->flags & NS_MOREFRAG)) {
1077 				pi.ipi_len = pkt_len;
1078 				pi.ipi_nsegs = seg_idx;
1079 				pi.ipi_pidx = nic_i_start;
1080 				pi.ipi_ndescs = 0;
1081 				pi.ipi_flags = flags;
1082 
1083 				/* Prepare the NIC TX ring. */
1084 				ctx->isc_txd_encap(ctx->ifc_softc, &pi);
1085 				DBG_COUNTER_INC(tx_encap);
1086 
1087 				/* Update transmit counters */
1088 				tx_bytes += pi.ipi_len;
1089 				tx_pkts++;
1090 
1091 				/* Reinit per-packet info for the next one. */
1092 				flags = seg_idx = pkt_len = 0;
1093 				nic_i_start = -1;
1094 			}
1095 
1096 			/* prefetch for next round */
1097 			__builtin_prefetch(&ring->slot[nm_i + 1]);
1098 			__builtin_prefetch(&txq->ift_sds.ifsd_m[nic_i + 1]);
1099 			__builtin_prefetch(&txq->ift_sds.ifsd_map[nic_i + 1]);
1100 
1101 			NM_CHECK_ADDR_LEN(na, addr, len);
1102 
1103 			if (slot->flags & NS_BUF_CHANGED) {
1104 				/* buffer has changed, reload map */
1105 				netmap_reload_map(na, txq->ift_buf_tag,
1106 				    txq->ift_sds.ifsd_map[nic_i], addr);
1107 			}
1108 			/* make sure changes to the buffer are synced */
1109 			bus_dmamap_sync(txq->ift_buf_tag,
1110 			    txq->ift_sds.ifsd_map[nic_i],
1111 			    BUS_DMASYNC_PREWRITE);
1112 
1113 			slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED | NS_MOREFRAG);
1114 			nm_i = nm_next(nm_i, lim);
1115 			nic_i = nm_next(nic_i, lim);
1116 		}
1117 		kring->nr_hwcur = nm_i;
1118 
1119 		/* synchronize the NIC ring */
1120 		bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
1121 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1122 
1123 		/* (re)start the tx unit up to slot nic_i (excluded) */
1124 		ctx->isc_txd_flush(ctx->ifc_softc, txq->ift_id, nic_i);
1125 	}
1126 
1127 	/*
1128 	 * Second part: reclaim buffers for completed transmissions.
1129 	 *
1130 	 * If there are unclaimed buffers, attempt to reclaim them.
1131 	 * If we don't manage to reclaim them all, and TX IRQs are not in use,
1132 	 * trigger a per-tx-queue timer to try again later.
1133 	 */
1134 	if (kring->nr_hwtail != nm_prev(kring->nr_hwcur, lim)) {
1135 		if (iflib_tx_credits_update(ctx, txq)) {
1136 			/* some tx completed, increment avail */
1137 			nic_i = txq->ift_cidx_processed;
1138 			kring->nr_hwtail = nm_prev(netmap_idx_n2k(kring, nic_i), lim);
1139 		}
1140 	}
1141 
1142 	if (!(ctx->ifc_flags & IFC_NETMAP_TX_IRQ))
1143 		if (kring->nr_hwtail != nm_prev(kring->nr_hwcur, lim)) {
1144 			callout_reset_sbt_on(&txq->ift_netmap_timer,
1145 			    NETMAP_TX_TIMER_US * SBT_1US, SBT_1US,
1146 			    iflib_netmap_timer, txq,
1147 			    txq->ift_netmap_timer.c_cpu, 0);
1148 		}
1149 
1150 	if_inc_counter(ifp, IFCOUNTER_OBYTES, tx_bytes);
1151 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, tx_pkts);
1152 
1153 	return (0);
1154 }
1155 
1156 /*
1157  * Reconcile kernel and user view of the receive ring.
1158  * Same as for the txsync, this routine must be efficient.
1159  * The caller guarantees a single invocations, but races against
1160  * the rest of the driver should be handled here.
1161  *
1162  * On call, kring->rhead is the first packet that userspace wants
1163  * to keep, and kring->rcur is the wakeup point.
1164  * The kernel has previously reported packets up to kring->rtail.
1165  *
1166  * If (flags & NAF_FORCE_READ) also check for incoming packets irrespective
1167  * of whether or not we received an interrupt.
1168  */
1169 static int
iflib_netmap_rxsync(struct netmap_kring * kring,int flags)1170 iflib_netmap_rxsync(struct netmap_kring *kring, int flags)
1171 {
1172 	struct netmap_adapter *na = kring->na;
1173 	struct netmap_ring *ring = kring->ring;
1174 	if_t ifp = na->ifp;
1175 	uint32_t nm_i;	/* index into the netmap ring */
1176 	uint32_t nic_i;	/* index into the NIC ring */
1177 	u_int n;
1178 	u_int const lim = kring->nkr_num_slots - 1;
1179 	int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
1180 	int i = 0, rx_bytes = 0, rx_pkts = 0;
1181 
1182 	if_ctx_t ctx = ifp->if_softc;
1183 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1184 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1185 	iflib_rxq_t rxq = &ctx->ifc_rxqs[kring->ring_id];
1186 	iflib_fl_t fl = &rxq->ifr_fl[0];
1187 	struct if_rxd_info ri;
1188 	qidx_t *cidxp;
1189 
1190 	/*
1191 	 * netmap only uses free list 0, to avoid out of order consumption
1192 	 * of receive buffers
1193 	 */
1194 
1195 	bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
1196 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1197 
1198 	/*
1199 	 * First part: import newly received packets.
1200 	 *
1201 	 * nm_i is the index of the next free slot in the netmap ring,
1202 	 * nic_i is the index of the next received packet in the NIC ring
1203 	 * (or in the free list 0 if IFLIB_HAS_RXCQ is set), and they may
1204 	 * differ in case if_init() has been called while
1205 	 * in netmap mode. For the receive ring we have
1206 	 *
1207 	 *	nic_i = fl->ifl_cidx;
1208 	 *	nm_i = kring->nr_hwtail (previous)
1209 	 * and
1210 	 *	nm_i == (nic_i + kring->nkr_hwofs) % ring_size
1211 	 *
1212 	 * fl->ifl_cidx is set to 0 on a ring reinit
1213 	 */
1214 	if (netmap_no_pendintr || force_update) {
1215 		uint32_t hwtail_lim = nm_prev(kring->nr_hwcur, lim);
1216 		bool have_rxcq = sctx->isc_flags & IFLIB_HAS_RXCQ;
1217 		int crclen = iflib_crcstrip ? 0 : 4;
1218 		int error, avail;
1219 
1220 		/*
1221 		 * For the free list consumer index, we use the same
1222 		 * logic as in iflib_rxeof().
1223 		 */
1224 		if (have_rxcq)
1225 			cidxp = &rxq->ifr_cq_cidx;
1226 		else
1227 			cidxp = &fl->ifl_cidx;
1228 		avail = ctx->isc_rxd_available(ctx->ifc_softc,
1229 		    rxq->ifr_id, *cidxp, USHRT_MAX);
1230 
1231 		nic_i = fl->ifl_cidx;
1232 		nm_i = netmap_idx_n2k(kring, nic_i);
1233 		MPASS(nm_i == kring->nr_hwtail);
1234 		for (n = 0; avail > 0 && nm_i != hwtail_lim; n++, avail--) {
1235 			rxd_info_zero(&ri);
1236 			ri.iri_frags = rxq->ifr_frags;
1237 			ri.iri_qsidx = kring->ring_id;
1238 			ri.iri_ifp = ctx->ifc_ifp;
1239 			ri.iri_cidx = *cidxp;
1240 
1241 			error = ctx->isc_rxd_pkt_get(ctx->ifc_softc, &ri);
1242 			for (i = 0; i < ri.iri_nfrags; i++) {
1243 				if (error) {
1244 					ring->slot[nm_i].len = 0;
1245 					ring->slot[nm_i].flags = 0;
1246 				} else {
1247 					ring->slot[nm_i].len = ri.iri_frags[i].irf_len;
1248 					if (i == (ri.iri_nfrags - 1)) {
1249 						ring->slot[nm_i].len -= crclen;
1250 						ring->slot[nm_i].flags = 0;
1251 
1252 						/* Update receive counters */
1253 						rx_bytes += ri.iri_len;
1254 						rx_pkts++;
1255 					} else
1256 						ring->slot[nm_i].flags = NS_MOREFRAG;
1257 				}
1258 
1259 				bus_dmamap_sync(fl->ifl_buf_tag,
1260 				    fl->ifl_sds.ifsd_map[nic_i], BUS_DMASYNC_POSTREAD);
1261 				nm_i = nm_next(nm_i, lim);
1262 				fl->ifl_cidx = nic_i = nm_next(nic_i, lim);
1263 			}
1264 
1265 			if (have_rxcq) {
1266 				*cidxp = ri.iri_cidx;
1267 				while (*cidxp >= scctx->isc_nrxd[0])
1268 					*cidxp -= scctx->isc_nrxd[0];
1269 			}
1270 
1271 		}
1272 		if (n) { /* update the state variables */
1273 			if (netmap_no_pendintr && !force_update) {
1274 				/* diagnostics */
1275 				iflib_rx_miss++;
1276 				iflib_rx_miss_bufs += n;
1277 			}
1278 			kring->nr_hwtail = nm_i;
1279 		}
1280 		kring->nr_kflags &= ~NKR_PENDINTR;
1281 	}
1282 	/*
1283 	 * Second part: skip past packets that userspace has released.
1284 	 * (kring->nr_hwcur to head excluded),
1285 	 * and make the buffers available for reception.
1286 	 * As usual nm_i is the index in the netmap ring,
1287 	 * nic_i is the index in the NIC ring, and
1288 	 * nm_i == (nic_i + kring->nkr_hwofs) % ring_size
1289 	 */
1290 	netmap_fl_refill(rxq, kring, false);
1291 
1292 	if_inc_counter(ifp, IFCOUNTER_IBYTES, rx_bytes);
1293 	if_inc_counter(ifp, IFCOUNTER_IPACKETS, rx_pkts);
1294 
1295 	return (0);
1296 }
1297 
1298 static void
iflib_netmap_intr(struct netmap_adapter * na,int onoff)1299 iflib_netmap_intr(struct netmap_adapter *na, int onoff)
1300 {
1301 	if_ctx_t ctx = na->ifp->if_softc;
1302 
1303 	CTX_LOCK(ctx);
1304 	if (onoff) {
1305 		IFDI_INTR_ENABLE(ctx);
1306 	} else {
1307 		IFDI_INTR_DISABLE(ctx);
1308 	}
1309 	CTX_UNLOCK(ctx);
1310 }
1311 
1312 static int
iflib_netmap_attach(if_ctx_t ctx)1313 iflib_netmap_attach(if_ctx_t ctx)
1314 {
1315 	struct netmap_adapter na;
1316 
1317 	bzero(&na, sizeof(na));
1318 
1319 	na.ifp = ctx->ifc_ifp;
1320 	na.na_flags = NAF_BDG_MAYSLEEP | NAF_MOREFRAG;
1321 	MPASS(ctx->ifc_softc_ctx.isc_ntxqsets);
1322 	MPASS(ctx->ifc_softc_ctx.isc_nrxqsets);
1323 
1324 	na.num_tx_desc = iflib_num_tx_descs(ctx);
1325 	na.num_rx_desc = iflib_num_rx_descs(ctx);
1326 	na.nm_txsync = iflib_netmap_txsync;
1327 	na.nm_rxsync = iflib_netmap_rxsync;
1328 	na.nm_register = iflib_netmap_register;
1329 	na.nm_intr = iflib_netmap_intr;
1330 	na.nm_config = iflib_netmap_config;
1331 	na.num_tx_rings = ctx->ifc_softc_ctx.isc_ntxqsets;
1332 	na.num_rx_rings = ctx->ifc_softc_ctx.isc_nrxqsets;
1333 	return (netmap_attach(&na));
1334 }
1335 
1336 static int
iflib_netmap_txq_init(if_ctx_t ctx,iflib_txq_t txq)1337 iflib_netmap_txq_init(if_ctx_t ctx, iflib_txq_t txq)
1338 {
1339 	struct netmap_adapter *na = NA(ctx->ifc_ifp);
1340 	struct netmap_slot *slot;
1341 
1342 	slot = netmap_reset(na, NR_TX, txq->ift_id, 0);
1343 	if (slot == NULL)
1344 		return (0);
1345 	for (int i = 0; i < ctx->ifc_softc_ctx.isc_ntxd[0]; i++) {
1346 		/*
1347 		 * In netmap mode, set the map for the packet buffer.
1348 		 * NOTE: Some drivers (not this one) also need to set
1349 		 * the physical buffer address in the NIC ring.
1350 		 * netmap_idx_n2k() maps a nic index, i, into the corresponding
1351 		 * netmap slot index, si
1352 		 */
1353 		int si = netmap_idx_n2k(na->tx_rings[txq->ift_id], i);
1354 		netmap_load_map(na, txq->ift_buf_tag, txq->ift_sds.ifsd_map[i],
1355 		    NMB(na, slot + si));
1356 	}
1357 	return (1);
1358 }
1359 
1360 static int
iflib_netmap_rxq_init(if_ctx_t ctx,iflib_rxq_t rxq)1361 iflib_netmap_rxq_init(if_ctx_t ctx, iflib_rxq_t rxq)
1362 {
1363 	struct netmap_adapter *na = NA(ctx->ifc_ifp);
1364 	struct netmap_kring *kring;
1365 	struct netmap_slot *slot;
1366 
1367 	slot = netmap_reset(na, NR_RX, rxq->ifr_id, 0);
1368 	if (slot == NULL)
1369 		return (0);
1370 	kring = na->rx_rings[rxq->ifr_id];
1371 	netmap_fl_refill(rxq, kring, true);
1372 	return (1);
1373 }
1374 
1375 static void
iflib_netmap_timer(void * arg)1376 iflib_netmap_timer(void *arg)
1377 {
1378 	iflib_txq_t txq = arg;
1379 	if_ctx_t ctx = txq->ift_ctx;
1380 
1381 	/*
1382 	 * Wake up the netmap application, to give it a chance to
1383 	 * call txsync and reclaim more completed TX buffers.
1384 	 */
1385 	netmap_tx_irq(ctx->ifc_ifp, txq->ift_id);
1386 }
1387 
1388 #define iflib_netmap_detach(ifp) netmap_detach(ifp)
1389 
1390 #else
1391 #define iflib_netmap_txq_init(ctx, txq) (0)
1392 #define iflib_netmap_rxq_init(ctx, rxq) (0)
1393 #define iflib_netmap_detach(ifp)
1394 #define netmap_enable_all_rings(ifp)
1395 #define netmap_disable_all_rings(ifp)
1396 
1397 #define iflib_netmap_attach(ctx) (0)
1398 #define netmap_rx_irq(ifp, qid, budget) (0)
1399 #endif
1400 
1401 #if defined(__i386__) || defined(__amd64__)
1402 static __inline void
prefetch(void * x)1403 prefetch(void *x)
1404 {
1405 	__asm volatile("prefetcht0 %0" :: "m" (*(unsigned long *)x));
1406 }
1407 static __inline void
prefetch2cachelines(void * x)1408 prefetch2cachelines(void *x)
1409 {
1410 	__asm volatile("prefetcht0 %0" :: "m" (*(unsigned long *)x));
1411 #if (CACHE_LINE_SIZE < 128)
1412 	__asm volatile("prefetcht0 %0" :: "m" (*(((unsigned long *)x) + CACHE_LINE_SIZE / (sizeof(unsigned long)))));
1413 #endif
1414 }
1415 #else
1416 #define prefetch(x)
1417 #define prefetch2cachelines(x)
1418 #endif
1419 
1420 static void
iru_init(if_rxd_update_t iru,iflib_rxq_t rxq,uint8_t flid)1421 iru_init(if_rxd_update_t iru, iflib_rxq_t rxq, uint8_t flid)
1422 {
1423 	iflib_fl_t fl;
1424 
1425 	fl = &rxq->ifr_fl[flid];
1426 	iru->iru_paddrs = fl->ifl_bus_addrs;
1427 	iru->iru_idxs = fl->ifl_rxd_idxs;
1428 	iru->iru_qsidx = rxq->ifr_id;
1429 	iru->iru_buf_size = fl->ifl_buf_size;
1430 	iru->iru_flidx = fl->ifl_id;
1431 }
1432 
1433 static void
_iflib_dmamap_cb(void * arg,bus_dma_segment_t * segs,int nseg,int err)1434 _iflib_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int err)
1435 {
1436 	if (err)
1437 		return;
1438 	*(bus_addr_t *) arg = segs[0].ds_addr;
1439 }
1440 
1441 int
iflib_dma_alloc_align(if_ctx_t ctx,int size,int align,iflib_dma_info_t dma,int mapflags)1442 iflib_dma_alloc_align(if_ctx_t ctx, int size, int align, iflib_dma_info_t dma, int mapflags)
1443 {
1444 	int err;
1445 	device_t dev = ctx->ifc_dev;
1446 
1447 	err = bus_dma_tag_create(bus_get_dma_tag(dev),	/* parent */
1448 				align, 0,		/* alignment, bounds */
1449 				BUS_SPACE_MAXADDR,	/* lowaddr */
1450 				BUS_SPACE_MAXADDR,	/* highaddr */
1451 				NULL, NULL,		/* filter, filterarg */
1452 				size,			/* maxsize */
1453 				1,			/* nsegments */
1454 				size,			/* maxsegsize */
1455 				BUS_DMA_ALLOCNOW,	/* flags */
1456 				NULL,			/* lockfunc */
1457 				NULL,			/* lockarg */
1458 				&dma->idi_tag);
1459 	if (err) {
1460 		device_printf(dev,
1461 		    "%s: bus_dma_tag_create failed: %d (size=%d, align=%d)\n",
1462 		    __func__, err, size, align);
1463 		goto fail_0;
1464 	}
1465 
1466 	err = bus_dmamem_alloc(dma->idi_tag, (void **)&dma->idi_vaddr,
1467 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT | BUS_DMA_ZERO, &dma->idi_map);
1468 	if (err) {
1469 		device_printf(dev,
1470 		    "%s: bus_dmamem_alloc(%ju) failed: %d\n",
1471 		    __func__, (uintmax_t)size, err);
1472 		goto fail_1;
1473 	}
1474 
1475 	dma->idi_paddr = IF_BAD_DMA;
1476 	err = bus_dmamap_load(dma->idi_tag, dma->idi_map, dma->idi_vaddr,
1477 	    size, _iflib_dmamap_cb, &dma->idi_paddr, mapflags | BUS_DMA_NOWAIT);
1478 	if (err || dma->idi_paddr == IF_BAD_DMA) {
1479 		device_printf(dev,
1480 		    "%s: bus_dmamap_load failed: %d\n",
1481 		    __func__, err);
1482 		goto fail_2;
1483 	}
1484 
1485 	dma->idi_size = size;
1486 	return (0);
1487 
1488 fail_2:
1489 	bus_dmamem_free(dma->idi_tag, dma->idi_vaddr, dma->idi_map);
1490 fail_1:
1491 	bus_dma_tag_destroy(dma->idi_tag);
1492 fail_0:
1493 	dma->idi_tag = NULL;
1494 
1495 	return (err);
1496 }
1497 
1498 int
iflib_dma_alloc(if_ctx_t ctx,int size,iflib_dma_info_t dma,int mapflags)1499 iflib_dma_alloc(if_ctx_t ctx, int size, iflib_dma_info_t dma, int mapflags)
1500 {
1501 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1502 
1503 	KASSERT(sctx->isc_q_align != 0, ("alignment value not initialized"));
1504 
1505 	return (iflib_dma_alloc_align(ctx, size, sctx->isc_q_align, dma, mapflags));
1506 }
1507 
1508 int
iflib_dma_alloc_multi(if_ctx_t ctx,int * sizes,iflib_dma_info_t * dmalist,int mapflags,int count)1509 iflib_dma_alloc_multi(if_ctx_t ctx, int *sizes, iflib_dma_info_t *dmalist, int mapflags, int count)
1510 {
1511 	int i, err;
1512 	iflib_dma_info_t *dmaiter;
1513 
1514 	dmaiter = dmalist;
1515 	for (i = 0; i < count; i++, dmaiter++) {
1516 		if ((err = iflib_dma_alloc(ctx, sizes[i], *dmaiter, mapflags)) != 0)
1517 			break;
1518 	}
1519 	if (err)
1520 		iflib_dma_free_multi(dmalist, i);
1521 	return (err);
1522 }
1523 
1524 void
iflib_dma_free(iflib_dma_info_t dma)1525 iflib_dma_free(iflib_dma_info_t dma)
1526 {
1527 	if (dma->idi_tag == NULL)
1528 		return;
1529 	if (dma->idi_paddr != IF_BAD_DMA) {
1530 		bus_dmamap_sync(dma->idi_tag, dma->idi_map,
1531 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1532 		bus_dmamap_unload(dma->idi_tag, dma->idi_map);
1533 		dma->idi_paddr = IF_BAD_DMA;
1534 	}
1535 	if (dma->idi_vaddr != NULL) {
1536 		bus_dmamem_free(dma->idi_tag, dma->idi_vaddr, dma->idi_map);
1537 		dma->idi_vaddr = NULL;
1538 	}
1539 	bus_dma_tag_destroy(dma->idi_tag);
1540 	dma->idi_tag = NULL;
1541 }
1542 
1543 void
iflib_dma_free_multi(iflib_dma_info_t * dmalist,int count)1544 iflib_dma_free_multi(iflib_dma_info_t *dmalist, int count)
1545 {
1546 	int i;
1547 	iflib_dma_info_t *dmaiter = dmalist;
1548 
1549 	for (i = 0; i < count; i++, dmaiter++)
1550 		iflib_dma_free(*dmaiter);
1551 }
1552 
1553 static int
iflib_fast_intr(void * arg)1554 iflib_fast_intr(void *arg)
1555 {
1556 	iflib_filter_info_t info = arg;
1557 	struct grouptask *gtask = info->ifi_task;
1558 	int result;
1559 
1560 	DBG_COUNTER_INC(fast_intrs);
1561 	if (info->ifi_filter != NULL) {
1562 		result = info->ifi_filter(info->ifi_filter_arg);
1563 		if ((result & FILTER_SCHEDULE_THREAD) == 0)
1564 			return (result);
1565 	}
1566 
1567 	GROUPTASK_ENQUEUE(gtask);
1568 	return (FILTER_HANDLED);
1569 }
1570 
1571 static int
iflib_fast_intr_rxtx(void * arg)1572 iflib_fast_intr_rxtx(void *arg)
1573 {
1574 	iflib_filter_info_t info = arg;
1575 	struct grouptask *gtask = info->ifi_task;
1576 	if_ctx_t ctx;
1577 	iflib_rxq_t rxq = (iflib_rxq_t)info->ifi_ctx;
1578 	iflib_txq_t txq;
1579 	void *sc;
1580 	int i, cidx, result;
1581 	qidx_t txqid;
1582 	bool intr_enable, intr_legacy;
1583 
1584 	DBG_COUNTER_INC(fast_intrs);
1585 	if (info->ifi_filter != NULL) {
1586 		result = info->ifi_filter(info->ifi_filter_arg);
1587 		if ((result & FILTER_SCHEDULE_THREAD) == 0)
1588 			return (result);
1589 	}
1590 
1591 	ctx = rxq->ifr_ctx;
1592 	sc = ctx->ifc_softc;
1593 	intr_enable = false;
1594 	intr_legacy = !!(ctx->ifc_flags & IFC_LEGACY);
1595 	MPASS(rxq->ifr_ntxqirq);
1596 	for (i = 0; i < rxq->ifr_ntxqirq; i++) {
1597 		txqid = rxq->ifr_txqid[i];
1598 		txq = &ctx->ifc_txqs[txqid];
1599 		bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
1600 		    BUS_DMASYNC_POSTREAD);
1601 		if (!ctx->isc_txd_credits_update(sc, txqid, false)) {
1602 			if (intr_legacy)
1603 				intr_enable = true;
1604 			else
1605 				IFDI_TX_QUEUE_INTR_ENABLE(ctx, txqid);
1606 			continue;
1607 		}
1608 		GROUPTASK_ENQUEUE(&txq->ift_task);
1609 	}
1610 	if (ctx->ifc_sctx->isc_flags & IFLIB_HAS_RXCQ)
1611 		cidx = rxq->ifr_cq_cidx;
1612 	else
1613 		cidx = rxq->ifr_fl[0].ifl_cidx;
1614 	if (iflib_rxd_avail(ctx, rxq, cidx, 1))
1615 		GROUPTASK_ENQUEUE(gtask);
1616 	else {
1617 		if (intr_legacy)
1618 			intr_enable = true;
1619 		else
1620 			IFDI_RX_QUEUE_INTR_ENABLE(ctx, rxq->ifr_id);
1621 		DBG_COUNTER_INC(rx_intr_enables);
1622 	}
1623 	if (intr_enable)
1624 		IFDI_INTR_ENABLE(ctx);
1625 	return (FILTER_HANDLED);
1626 }
1627 
1628 static int
iflib_fast_intr_ctx(void * arg)1629 iflib_fast_intr_ctx(void *arg)
1630 {
1631 	iflib_filter_info_t info = arg;
1632 	struct grouptask *gtask = info->ifi_task;
1633 	int result;
1634 
1635 	DBG_COUNTER_INC(fast_intrs);
1636 	if (info->ifi_filter != NULL) {
1637 		result = info->ifi_filter(info->ifi_filter_arg);
1638 		if ((result & FILTER_SCHEDULE_THREAD) == 0)
1639 			return (result);
1640 	}
1641 
1642 	if (gtask->gt_taskqueue != NULL)
1643 		GROUPTASK_ENQUEUE(gtask);
1644 	return (FILTER_HANDLED);
1645 }
1646 
1647 static int
_iflib_irq_alloc(if_ctx_t ctx,if_irq_t irq,int rid,driver_filter_t filter,driver_intr_t handler,void * arg,const char * name)1648 _iflib_irq_alloc(if_ctx_t ctx, if_irq_t irq, int rid,
1649 		 driver_filter_t filter, driver_intr_t handler, void *arg,
1650 		 const char *name)
1651 {
1652 	struct resource *res;
1653 	void *tag = NULL;
1654 	device_t dev = ctx->ifc_dev;
1655 	int flags, i, rc;
1656 
1657 	flags = RF_ACTIVE;
1658 	if (ctx->ifc_flags & IFC_LEGACY)
1659 		flags |= RF_SHAREABLE;
1660 	MPASS(rid < 512);
1661 	i = rid;
1662 	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &i, flags);
1663 	if (res == NULL) {
1664 		device_printf(dev,
1665 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
1666 		return (ENOMEM);
1667 	}
1668 	irq->ii_res = res;
1669 	KASSERT(filter == NULL || handler == NULL, ("filter and handler can't both be non-NULL"));
1670 	rc = bus_setup_intr(dev, res, INTR_MPSAFE | INTR_TYPE_NET,
1671 						filter, handler, arg, &tag);
1672 	if (rc != 0) {
1673 		device_printf(dev,
1674 		    "failed to setup interrupt for rid %d, name %s: %d\n",
1675 					  rid, name ? name : "unknown", rc);
1676 		return (rc);
1677 	} else if (name)
1678 		bus_describe_intr(dev, res, tag, "%s", name);
1679 
1680 	irq->ii_tag = tag;
1681 	return (0);
1682 }
1683 
1684 /*********************************************************************
1685  *
1686  *  Allocate DMA resources for TX buffers as well as memory for the TX
1687  *  mbuf map.  TX DMA maps (non-TSO/TSO) and TX mbuf map are kept in a
1688  *  iflib_sw_tx_desc_array structure, storing all the information that
1689  *  is needed to transmit a packet on the wire.  This is called only
1690  *  once at attach, setup is done every reset.
1691  *
1692  **********************************************************************/
1693 static int
iflib_txsd_alloc(iflib_txq_t txq)1694 iflib_txsd_alloc(iflib_txq_t txq)
1695 {
1696 	if_ctx_t ctx = txq->ift_ctx;
1697 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1698 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1699 	device_t dev = ctx->ifc_dev;
1700 	bus_size_t tsomaxsize;
1701 	int err, nsegments, ntsosegments;
1702 	bool tso;
1703 
1704 	nsegments = scctx->isc_tx_nsegments;
1705 	ntsosegments = scctx->isc_tx_tso_segments_max;
1706 	tsomaxsize = scctx->isc_tx_tso_size_max;
1707 	if (if_getcapabilities(ctx->ifc_ifp) & IFCAP_VLAN_MTU)
1708 		tsomaxsize += sizeof(struct ether_vlan_header);
1709 	MPASS(scctx->isc_ntxd[0] > 0);
1710 	MPASS(scctx->isc_ntxd[txq->ift_br_offset] > 0);
1711 	MPASS(nsegments > 0);
1712 	if (if_getcapabilities(ctx->ifc_ifp) & IFCAP_TSO) {
1713 		MPASS(ntsosegments > 0);
1714 		MPASS(sctx->isc_tso_maxsize >= tsomaxsize);
1715 	}
1716 
1717 	/*
1718 	 * Set up DMA tags for TX buffers.
1719 	 */
1720 	if ((err = bus_dma_tag_create(bus_get_dma_tag(dev),
1721 			       1, 0,			/* alignment, bounds */
1722 			       BUS_SPACE_MAXADDR,	/* lowaddr */
1723 			       BUS_SPACE_MAXADDR,	/* highaddr */
1724 			       NULL, NULL,		/* filter, filterarg */
1725 			       sctx->isc_tx_maxsize,		/* maxsize */
1726 			       nsegments,	/* nsegments */
1727 			       sctx->isc_tx_maxsegsize,	/* maxsegsize */
1728 			       0,			/* flags */
1729 			       NULL,			/* lockfunc */
1730 			       NULL,			/* lockfuncarg */
1731 			       &txq->ift_buf_tag))) {
1732 		device_printf(dev, "Unable to allocate TX DMA tag: %d\n", err);
1733 		device_printf(dev, "maxsize: %ju nsegments: %d maxsegsize: %ju\n",
1734 		    (uintmax_t)sctx->isc_tx_maxsize, nsegments, (uintmax_t)sctx->isc_tx_maxsegsize);
1735 		goto fail;
1736 	}
1737 	tso = (if_getcapabilities(ctx->ifc_ifp) & IFCAP_TSO) != 0;
1738 	if (tso && (err = bus_dma_tag_create(bus_get_dma_tag(dev),
1739 			       1, 0,			/* alignment, bounds */
1740 			       BUS_SPACE_MAXADDR,	/* lowaddr */
1741 			       BUS_SPACE_MAXADDR,	/* highaddr */
1742 			       NULL, NULL,		/* filter, filterarg */
1743 			       tsomaxsize,		/* maxsize */
1744 			       ntsosegments,	/* nsegments */
1745 			       sctx->isc_tso_maxsegsize,/* maxsegsize */
1746 			       0,			/* flags */
1747 			       NULL,			/* lockfunc */
1748 			       NULL,			/* lockfuncarg */
1749 			       &txq->ift_tso_buf_tag))) {
1750 		device_printf(dev, "Unable to allocate TSO TX DMA tag: %d\n",
1751 		    err);
1752 		goto fail;
1753 	}
1754 
1755 	/* Allocate memory for the TX mbuf map. */
1756 	if (!(txq->ift_sds.ifsd_m =
1757 	    (struct mbuf **) malloc(sizeof(struct mbuf *) *
1758 	    scctx->isc_ntxd[txq->ift_br_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1759 		device_printf(dev, "Unable to allocate TX mbuf map memory\n");
1760 		err = ENOMEM;
1761 		goto fail;
1762 	}
1763 
1764 	/*
1765 	 * Create the DMA maps for TX buffers.
1766 	 */
1767 	if ((txq->ift_sds.ifsd_map = (bus_dmamap_t *)malloc(
1768 	    sizeof(bus_dmamap_t) * scctx->isc_ntxd[txq->ift_br_offset],
1769 	    M_IFLIB, M_NOWAIT | M_ZERO)) == NULL) {
1770 		device_printf(dev,
1771 		    "Unable to allocate TX buffer DMA map memory\n");
1772 		err = ENOMEM;
1773 		goto fail;
1774 	}
1775 	if (tso && (txq->ift_sds.ifsd_tso_map = (bus_dmamap_t *)malloc(
1776 	    sizeof(bus_dmamap_t) * scctx->isc_ntxd[txq->ift_br_offset],
1777 	    M_IFLIB, M_NOWAIT | M_ZERO)) == NULL) {
1778 		device_printf(dev,
1779 		    "Unable to allocate TSO TX buffer map memory\n");
1780 		err = ENOMEM;
1781 		goto fail;
1782 	}
1783 	for (int i = 0; i < scctx->isc_ntxd[txq->ift_br_offset]; i++) {
1784 		err = bus_dmamap_create(txq->ift_buf_tag, 0,
1785 		    &txq->ift_sds.ifsd_map[i]);
1786 		if (err != 0) {
1787 			device_printf(dev, "Unable to create TX DMA map\n");
1788 			goto fail;
1789 		}
1790 		if (!tso)
1791 			continue;
1792 		err = bus_dmamap_create(txq->ift_tso_buf_tag, 0,
1793 		    &txq->ift_sds.ifsd_tso_map[i]);
1794 		if (err != 0) {
1795 			device_printf(dev, "Unable to create TSO TX DMA map\n");
1796 			goto fail;
1797 		}
1798 	}
1799 	return (0);
1800 fail:
1801 	/* We free all, it handles case where we are in the middle */
1802 	iflib_tx_structures_free(ctx);
1803 	return (err);
1804 }
1805 
1806 static void
iflib_txsd_destroy(if_ctx_t ctx,iflib_txq_t txq,int i)1807 iflib_txsd_destroy(if_ctx_t ctx, iflib_txq_t txq, int i)
1808 {
1809 	bus_dmamap_t map;
1810 
1811 	if (txq->ift_sds.ifsd_map != NULL) {
1812 		map = txq->ift_sds.ifsd_map[i];
1813 		bus_dmamap_sync(txq->ift_buf_tag, map, BUS_DMASYNC_POSTWRITE);
1814 		bus_dmamap_unload(txq->ift_buf_tag, map);
1815 		bus_dmamap_destroy(txq->ift_buf_tag, map);
1816 		txq->ift_sds.ifsd_map[i] = NULL;
1817 	}
1818 
1819 	if (txq->ift_sds.ifsd_tso_map != NULL) {
1820 		map = txq->ift_sds.ifsd_tso_map[i];
1821 		bus_dmamap_sync(txq->ift_tso_buf_tag, map,
1822 		    BUS_DMASYNC_POSTWRITE);
1823 		bus_dmamap_unload(txq->ift_tso_buf_tag, map);
1824 		bus_dmamap_destroy(txq->ift_tso_buf_tag, map);
1825 		txq->ift_sds.ifsd_tso_map[i] = NULL;
1826 	}
1827 }
1828 
1829 static void
iflib_txq_destroy(iflib_txq_t txq)1830 iflib_txq_destroy(iflib_txq_t txq)
1831 {
1832 	if_ctx_t ctx = txq->ift_ctx;
1833 
1834 	for (int i = 0; i < txq->ift_size; i++)
1835 		iflib_txsd_destroy(ctx, txq, i);
1836 
1837 	if (txq->ift_br != NULL) {
1838 		ifmp_ring_free(txq->ift_br);
1839 		txq->ift_br = NULL;
1840 	}
1841 
1842 	mtx_destroy(&txq->ift_mtx);
1843 
1844 	if (txq->ift_sds.ifsd_map != NULL) {
1845 		free(txq->ift_sds.ifsd_map, M_IFLIB);
1846 		txq->ift_sds.ifsd_map = NULL;
1847 	}
1848 	if (txq->ift_sds.ifsd_tso_map != NULL) {
1849 		free(txq->ift_sds.ifsd_tso_map, M_IFLIB);
1850 		txq->ift_sds.ifsd_tso_map = NULL;
1851 	}
1852 	if (txq->ift_sds.ifsd_m != NULL) {
1853 		free(txq->ift_sds.ifsd_m, M_IFLIB);
1854 		txq->ift_sds.ifsd_m = NULL;
1855 	}
1856 	if (txq->ift_buf_tag != NULL) {
1857 		bus_dma_tag_destroy(txq->ift_buf_tag);
1858 		txq->ift_buf_tag = NULL;
1859 	}
1860 	if (txq->ift_tso_buf_tag != NULL) {
1861 		bus_dma_tag_destroy(txq->ift_tso_buf_tag);
1862 		txq->ift_tso_buf_tag = NULL;
1863 	}
1864 	if (txq->ift_ifdi != NULL) {
1865 		free(txq->ift_ifdi, M_IFLIB);
1866 	}
1867 }
1868 
1869 static void
iflib_txsd_free(if_ctx_t ctx,iflib_txq_t txq,int i)1870 iflib_txsd_free(if_ctx_t ctx, iflib_txq_t txq, int i)
1871 {
1872 	struct mbuf **mp;
1873 
1874 	mp = &txq->ift_sds.ifsd_m[i];
1875 	if (*mp == NULL)
1876 		return;
1877 
1878 	if (txq->ift_sds.ifsd_map != NULL) {
1879 		bus_dmamap_sync(txq->ift_buf_tag,
1880 		    txq->ift_sds.ifsd_map[i], BUS_DMASYNC_POSTWRITE);
1881 		bus_dmamap_unload(txq->ift_buf_tag, txq->ift_sds.ifsd_map[i]);
1882 	}
1883 	if (txq->ift_sds.ifsd_tso_map != NULL) {
1884 		bus_dmamap_sync(txq->ift_tso_buf_tag,
1885 		    txq->ift_sds.ifsd_tso_map[i], BUS_DMASYNC_POSTWRITE);
1886 		bus_dmamap_unload(txq->ift_tso_buf_tag,
1887 		    txq->ift_sds.ifsd_tso_map[i]);
1888 	}
1889 	m_freem(*mp);
1890 	DBG_COUNTER_INC(tx_frees);
1891 	*mp = NULL;
1892 }
1893 
1894 static int
iflib_txq_setup(iflib_txq_t txq)1895 iflib_txq_setup(iflib_txq_t txq)
1896 {
1897 	if_ctx_t ctx = txq->ift_ctx;
1898 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1899 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1900 	iflib_dma_info_t di;
1901 	int i;
1902 
1903 	/* Set number of descriptors available */
1904 	txq->ift_qstatus = IFLIB_QUEUE_IDLE;
1905 	/* XXX make configurable */
1906 	txq->ift_update_freq = IFLIB_DEFAULT_TX_UPDATE_FREQ;
1907 
1908 	/* Reset indices */
1909 	txq->ift_cidx_processed = 0;
1910 	txq->ift_pidx = txq->ift_cidx = txq->ift_npending = 0;
1911 	txq->ift_size = scctx->isc_ntxd[txq->ift_br_offset];
1912 
1913 	for (i = 0, di = txq->ift_ifdi; i < sctx->isc_ntxqs; i++, di++)
1914 		bzero((void *)di->idi_vaddr, di->idi_size);
1915 
1916 	IFDI_TXQ_SETUP(ctx, txq->ift_id);
1917 	for (i = 0, di = txq->ift_ifdi; i < sctx->isc_ntxqs; i++, di++)
1918 		bus_dmamap_sync(di->idi_tag, di->idi_map,
1919 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1920 	return (0);
1921 }
1922 
1923 /*********************************************************************
1924  *
1925  *  Allocate DMA resources for RX buffers as well as memory for the RX
1926  *  mbuf map, direct RX cluster pointer map and RX cluster bus address
1927  *  map.  RX DMA map, RX mbuf map, direct RX cluster pointer map and
1928  *  RX cluster map are kept in a iflib_sw_rx_desc_array structure.
1929  *  Since we use use one entry in iflib_sw_rx_desc_array per received
1930  *  packet, the maximum number of entries we'll need is equal to the
1931  *  number of hardware receive descriptors that we've allocated.
1932  *
1933  **********************************************************************/
1934 static int
iflib_rxsd_alloc(iflib_rxq_t rxq)1935 iflib_rxsd_alloc(iflib_rxq_t rxq)
1936 {
1937 	if_ctx_t ctx = rxq->ifr_ctx;
1938 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1939 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1940 	device_t dev = ctx->ifc_dev;
1941 	iflib_fl_t fl;
1942 	int err;
1943 
1944 	MPASS(scctx->isc_nrxd[0] > 0);
1945 	MPASS(scctx->isc_nrxd[rxq->ifr_fl_offset] > 0);
1946 
1947 	fl = rxq->ifr_fl;
1948 	for (int i = 0; i < rxq->ifr_nfl; i++, fl++) {
1949 		fl->ifl_size = scctx->isc_nrxd[rxq->ifr_fl_offset]; /* this isn't necessarily the same */
1950 		/* Set up DMA tag for RX buffers. */
1951 		err = bus_dma_tag_create(bus_get_dma_tag(dev), /* parent */
1952 					 1, 0,			/* alignment, bounds */
1953 					 BUS_SPACE_MAXADDR,	/* lowaddr */
1954 					 BUS_SPACE_MAXADDR,	/* highaddr */
1955 					 NULL, NULL,		/* filter, filterarg */
1956 					 sctx->isc_rx_maxsize,	/* maxsize */
1957 					 sctx->isc_rx_nsegments,	/* nsegments */
1958 					 sctx->isc_rx_maxsegsize,	/* maxsegsize */
1959 					 0,			/* flags */
1960 					 NULL,			/* lockfunc */
1961 					 NULL,			/* lockarg */
1962 					 &fl->ifl_buf_tag);
1963 		if (err) {
1964 			device_printf(dev,
1965 			    "Unable to allocate RX DMA tag: %d\n", err);
1966 			goto fail;
1967 		}
1968 
1969 		/* Allocate memory for the RX mbuf map. */
1970 		if (!(fl->ifl_sds.ifsd_m =
1971 		      (struct mbuf **) malloc(sizeof(struct mbuf *) *
1972 					      scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1973 			device_printf(dev,
1974 			    "Unable to allocate RX mbuf map memory\n");
1975 			err = ENOMEM;
1976 			goto fail;
1977 		}
1978 
1979 		/* Allocate memory for the direct RX cluster pointer map. */
1980 		if (!(fl->ifl_sds.ifsd_cl =
1981 		      (caddr_t *) malloc(sizeof(caddr_t) *
1982 					      scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1983 			device_printf(dev,
1984 			    "Unable to allocate RX cluster map memory\n");
1985 			err = ENOMEM;
1986 			goto fail;
1987 		}
1988 
1989 		/* Allocate memory for the RX cluster bus address map. */
1990 		if (!(fl->ifl_sds.ifsd_ba =
1991 		      (bus_addr_t *) malloc(sizeof(bus_addr_t) *
1992 					      scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1993 			device_printf(dev,
1994 			    "Unable to allocate RX bus address map memory\n");
1995 			err = ENOMEM;
1996 			goto fail;
1997 		}
1998 
1999 		/*
2000 		 * Create the DMA maps for RX buffers.
2001 		 */
2002 		if (!(fl->ifl_sds.ifsd_map =
2003 		      (bus_dmamap_t *) malloc(sizeof(bus_dmamap_t) * scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
2004 			device_printf(dev,
2005 			    "Unable to allocate RX buffer DMA map memory\n");
2006 			err = ENOMEM;
2007 			goto fail;
2008 		}
2009 		for (int i = 0; i < scctx->isc_nrxd[rxq->ifr_fl_offset]; i++) {
2010 			err = bus_dmamap_create(fl->ifl_buf_tag, 0,
2011 			    &fl->ifl_sds.ifsd_map[i]);
2012 			if (err != 0) {
2013 				device_printf(dev, "Unable to create RX buffer DMA map\n");
2014 				goto fail;
2015 			}
2016 		}
2017 	}
2018 	return (0);
2019 
2020 fail:
2021 	iflib_rx_structures_free(ctx);
2022 	return (err);
2023 }
2024 
2025 /*
2026  * Internal service routines
2027  */
2028 
2029 struct rxq_refill_cb_arg {
2030 	int               error;
2031 	bus_dma_segment_t seg;
2032 	int               nseg;
2033 };
2034 
2035 static void
_rxq_refill_cb(void * arg,bus_dma_segment_t * segs,int nseg,int error)2036 _rxq_refill_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2037 {
2038 	struct rxq_refill_cb_arg *cb_arg = arg;
2039 
2040 	cb_arg->error = error;
2041 	cb_arg->seg = segs[0];
2042 	cb_arg->nseg = nseg;
2043 }
2044 
2045 /**
2046  * iflib_fl_refill - refill an rxq free-buffer list
2047  * @ctx: the iflib context
2048  * @fl: the free list to refill
2049  * @count: the number of new buffers to allocate
2050  *
2051  * (Re)populate an rxq free-buffer list with up to @count new packet buffers.
2052  * The caller must assure that @count does not exceed the queue's capacity
2053  * minus one (since we always leave a descriptor unavailable).
2054  */
2055 static uint8_t
iflib_fl_refill(if_ctx_t ctx,iflib_fl_t fl,int count)2056 iflib_fl_refill(if_ctx_t ctx, iflib_fl_t fl, int count)
2057 {
2058 	struct if_rxd_update iru;
2059 	struct rxq_refill_cb_arg cb_arg;
2060 	struct mbuf *m;
2061 	caddr_t cl, *sd_cl;
2062 	struct mbuf **sd_m;
2063 	bus_dmamap_t *sd_map;
2064 	bus_addr_t bus_addr, *sd_ba;
2065 	int err, frag_idx, i, idx, n, pidx;
2066 	qidx_t credits;
2067 
2068 	MPASS(count <= fl->ifl_size - fl->ifl_credits - 1);
2069 
2070 	sd_m = fl->ifl_sds.ifsd_m;
2071 	sd_map = fl->ifl_sds.ifsd_map;
2072 	sd_cl = fl->ifl_sds.ifsd_cl;
2073 	sd_ba = fl->ifl_sds.ifsd_ba;
2074 	pidx = fl->ifl_pidx;
2075 	idx = pidx;
2076 	frag_idx = fl->ifl_fragidx;
2077 	credits = fl->ifl_credits;
2078 
2079 	i = 0;
2080 	n = count;
2081 	MPASS(n > 0);
2082 	MPASS(credits + n <= fl->ifl_size);
2083 
2084 	if (pidx < fl->ifl_cidx)
2085 		MPASS(pidx + n <= fl->ifl_cidx);
2086 	if (pidx == fl->ifl_cidx && (credits < fl->ifl_size))
2087 		MPASS(fl->ifl_gen == 0);
2088 	if (pidx > fl->ifl_cidx)
2089 		MPASS(n <= fl->ifl_size - pidx + fl->ifl_cidx);
2090 
2091 	DBG_COUNTER_INC(fl_refills);
2092 	if (n > 8)
2093 		DBG_COUNTER_INC(fl_refills_large);
2094 	iru_init(&iru, fl->ifl_rxq, fl->ifl_id);
2095 	while (n-- > 0) {
2096 		/*
2097 		 * We allocate an uninitialized mbuf + cluster, mbuf is
2098 		 * initialized after rx.
2099 		 *
2100 		 * If the cluster is still set then we know a minimum sized
2101 		 * packet was received
2102 		 */
2103 		bit_ffc_at(fl->ifl_rx_bitmap, frag_idx, fl->ifl_size,
2104 		    &frag_idx);
2105 		if (frag_idx < 0)
2106 			bit_ffc(fl->ifl_rx_bitmap, fl->ifl_size, &frag_idx);
2107 		MPASS(frag_idx >= 0);
2108 		if ((cl = sd_cl[frag_idx]) == NULL) {
2109 			cl = uma_zalloc(fl->ifl_zone, M_NOWAIT);
2110 			if (__predict_false(cl == NULL))
2111 				break;
2112 
2113 			cb_arg.error = 0;
2114 			MPASS(sd_map != NULL);
2115 			err = bus_dmamap_load(fl->ifl_buf_tag, sd_map[frag_idx],
2116 			    cl, fl->ifl_buf_size, _rxq_refill_cb, &cb_arg,
2117 			    BUS_DMA_NOWAIT);
2118 			if (__predict_false(err != 0 || cb_arg.error)) {
2119 				uma_zfree(fl->ifl_zone, cl);
2120 				break;
2121 			}
2122 
2123 			sd_ba[frag_idx] = bus_addr = cb_arg.seg.ds_addr;
2124 			sd_cl[frag_idx] = cl;
2125 #if MEMORY_LOGGING
2126 			fl->ifl_cl_enqueued++;
2127 #endif
2128 		} else {
2129 			bus_addr = sd_ba[frag_idx];
2130 		}
2131 		bus_dmamap_sync(fl->ifl_buf_tag, sd_map[frag_idx],
2132 		    BUS_DMASYNC_PREREAD);
2133 
2134 		if (sd_m[frag_idx] == NULL) {
2135 			m = m_gethdr(M_NOWAIT, MT_NOINIT);
2136 			if (__predict_false(m == NULL))
2137 				break;
2138 			sd_m[frag_idx] = m;
2139 		}
2140 		bit_set(fl->ifl_rx_bitmap, frag_idx);
2141 #if MEMORY_LOGGING
2142 		fl->ifl_m_enqueued++;
2143 #endif
2144 
2145 		DBG_COUNTER_INC(rx_allocs);
2146 		fl->ifl_rxd_idxs[i] = frag_idx;
2147 		fl->ifl_bus_addrs[i] = bus_addr;
2148 		credits++;
2149 		i++;
2150 		MPASS(credits <= fl->ifl_size);
2151 		if (++idx == fl->ifl_size) {
2152 #ifdef INVARIANTS
2153 			fl->ifl_gen = 1;
2154 #endif
2155 			idx = 0;
2156 		}
2157 		if (n == 0 || i == IFLIB_MAX_RX_REFRESH) {
2158 			iru.iru_pidx = pidx;
2159 			iru.iru_count = i;
2160 			ctx->isc_rxd_refill(ctx->ifc_softc, &iru);
2161 			fl->ifl_pidx = idx;
2162 			fl->ifl_credits = credits;
2163 			pidx = idx;
2164 			i = 0;
2165 		}
2166 	}
2167 
2168 	if (n < count - 1) {
2169 		if (i != 0) {
2170 			iru.iru_pidx = pidx;
2171 			iru.iru_count = i;
2172 			ctx->isc_rxd_refill(ctx->ifc_softc, &iru);
2173 			fl->ifl_pidx = idx;
2174 			fl->ifl_credits = credits;
2175 		}
2176 		DBG_COUNTER_INC(rxd_flush);
2177 		bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
2178 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2179 		ctx->isc_rxd_flush(ctx->ifc_softc, fl->ifl_rxq->ifr_id,
2180 		    fl->ifl_id, fl->ifl_pidx);
2181 		if (__predict_true(bit_test(fl->ifl_rx_bitmap, frag_idx))) {
2182 			fl->ifl_fragidx = frag_idx + 1;
2183 			if (fl->ifl_fragidx == fl->ifl_size)
2184 				fl->ifl_fragidx = 0;
2185 		} else {
2186 			fl->ifl_fragidx = frag_idx;
2187 		}
2188 	}
2189 
2190 	return (n == -1 ? 0 : IFLIB_RXEOF_EMPTY);
2191 }
2192 
2193 static inline uint8_t
iflib_fl_refill_all(if_ctx_t ctx,iflib_fl_t fl)2194 iflib_fl_refill_all(if_ctx_t ctx, iflib_fl_t fl)
2195 {
2196 	/*
2197 	 * We leave an unused descriptor to avoid pidx to catch up with cidx.
2198 	 * This is important as it confuses most NICs. For instance,
2199 	 * Intel NICs have (per receive ring) RDH and RDT registers, where
2200 	 * RDH points to the next receive descriptor to be used by the NIC,
2201 	 * and RDT for the next receive descriptor to be published by the
2202 	 * driver to the NIC (RDT - 1 is thus the last valid one).
2203 	 * The condition RDH == RDT means no descriptors are available to
2204 	 * the NIC, and thus it would be ambiguous if it also meant that
2205 	 * all the descriptors are available to the NIC.
2206 	 */
2207 	int32_t reclaimable = fl->ifl_size - fl->ifl_credits - 1;
2208 #ifdef INVARIANTS
2209 	int32_t delta = fl->ifl_size - get_inuse(fl->ifl_size, fl->ifl_cidx, fl->ifl_pidx, fl->ifl_gen) - 1;
2210 #endif
2211 
2212 	MPASS(fl->ifl_credits <= fl->ifl_size);
2213 	MPASS(reclaimable == delta);
2214 
2215 	if (reclaimable > 0)
2216 		return (iflib_fl_refill(ctx, fl, reclaimable));
2217 	return (0);
2218 }
2219 
2220 uint8_t
iflib_in_detach(if_ctx_t ctx)2221 iflib_in_detach(if_ctx_t ctx)
2222 {
2223 	bool in_detach;
2224 
2225 	STATE_LOCK(ctx);
2226 	in_detach = !!(ctx->ifc_flags & IFC_IN_DETACH);
2227 	STATE_UNLOCK(ctx);
2228 	return (in_detach);
2229 }
2230 
2231 static void
iflib_fl_bufs_free(iflib_fl_t fl)2232 iflib_fl_bufs_free(iflib_fl_t fl)
2233 {
2234 	iflib_dma_info_t idi = fl->ifl_ifdi;
2235 	bus_dmamap_t sd_map;
2236 	uint32_t i;
2237 
2238 	for (i = 0; i < fl->ifl_size; i++) {
2239 		struct mbuf **sd_m = &fl->ifl_sds.ifsd_m[i];
2240 		caddr_t *sd_cl = &fl->ifl_sds.ifsd_cl[i];
2241 
2242 		if (*sd_cl != NULL) {
2243 			sd_map = fl->ifl_sds.ifsd_map[i];
2244 			bus_dmamap_sync(fl->ifl_buf_tag, sd_map,
2245 			    BUS_DMASYNC_POSTREAD);
2246 			bus_dmamap_unload(fl->ifl_buf_tag, sd_map);
2247 			uma_zfree(fl->ifl_zone, *sd_cl);
2248 			*sd_cl = NULL;
2249 			if (*sd_m != NULL) {
2250 				m_init(*sd_m, M_NOWAIT, MT_DATA, 0);
2251 				m_free_raw(*sd_m);
2252 				*sd_m = NULL;
2253 			}
2254 		} else {
2255 			MPASS(*sd_m == NULL);
2256 		}
2257 #if MEMORY_LOGGING
2258 		fl->ifl_m_dequeued++;
2259 		fl->ifl_cl_dequeued++;
2260 #endif
2261 	}
2262 #ifdef INVARIANTS
2263 	for (i = 0; i < fl->ifl_size; i++) {
2264 		MPASS(fl->ifl_sds.ifsd_cl[i] == NULL);
2265 		MPASS(fl->ifl_sds.ifsd_m[i] == NULL);
2266 	}
2267 #endif
2268 	/*
2269 	 * Reset free list values
2270 	 */
2271 	fl->ifl_credits = fl->ifl_cidx = fl->ifl_pidx = fl->ifl_gen = fl->ifl_fragidx = 0;
2272 	bzero(idi->idi_vaddr, idi->idi_size);
2273 }
2274 
2275 /*********************************************************************
2276  *
2277  *  Initialize a free list and its buffers.
2278  *
2279  **********************************************************************/
2280 static int
iflib_fl_setup(iflib_fl_t fl)2281 iflib_fl_setup(iflib_fl_t fl)
2282 {
2283 	iflib_rxq_t rxq = fl->ifl_rxq;
2284 	if_ctx_t ctx = rxq->ifr_ctx;
2285 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2286 	int qidx;
2287 
2288 	bit_nclear(fl->ifl_rx_bitmap, 0, fl->ifl_size - 1);
2289 	/*
2290 	 * Free current RX buffer structs and their mbufs
2291 	 */
2292 	iflib_fl_bufs_free(fl);
2293 	/* Now replenish the mbufs */
2294 	MPASS(fl->ifl_credits == 0);
2295 	qidx = rxq->ifr_fl_offset + fl->ifl_id;
2296 	if (scctx->isc_rxd_buf_size[qidx] != 0)
2297 		fl->ifl_buf_size = scctx->isc_rxd_buf_size[qidx];
2298 	else
2299 		fl->ifl_buf_size = ctx->ifc_rx_mbuf_sz;
2300 	/*
2301 	 * ifl_buf_size may be a driver-supplied value, so pull it up
2302 	 * to the selected mbuf size.
2303 	 */
2304 	fl->ifl_buf_size = iflib_get_mbuf_size_for(fl->ifl_buf_size);
2305 	if (fl->ifl_buf_size > ctx->ifc_max_fl_buf_size)
2306 		ctx->ifc_max_fl_buf_size = fl->ifl_buf_size;
2307 	fl->ifl_cltype = m_gettype(fl->ifl_buf_size);
2308 	fl->ifl_zone = m_getzone(fl->ifl_buf_size);
2309 
2310 	/*
2311 	 * Avoid pre-allocating zillions of clusters to an idle card
2312 	 * potentially speeding up attach. In any case make sure
2313 	 * to leave a descriptor unavailable. See the comment in
2314 	 * iflib_fl_refill_all().
2315 	 */
2316 	MPASS(fl->ifl_size > 0);
2317 	(void)iflib_fl_refill(ctx, fl, min(128, fl->ifl_size - 1));
2318 	if (min(128, fl->ifl_size - 1) != fl->ifl_credits)
2319 		return (ENOBUFS);
2320 	/*
2321 	 * handle failure
2322 	 */
2323 	MPASS(rxq != NULL);
2324 	MPASS(fl->ifl_ifdi != NULL);
2325 	bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
2326 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2327 	return (0);
2328 }
2329 
2330 /*********************************************************************
2331  *
2332  *  Free receive ring data structures
2333  *
2334  **********************************************************************/
2335 static void
iflib_rx_sds_free(iflib_rxq_t rxq)2336 iflib_rx_sds_free(iflib_rxq_t rxq)
2337 {
2338 	iflib_fl_t fl;
2339 	int i, j;
2340 
2341 	if (rxq->ifr_fl != NULL) {
2342 		for (i = 0; i < rxq->ifr_nfl; i++) {
2343 			fl = &rxq->ifr_fl[i];
2344 			if (fl->ifl_buf_tag != NULL) {
2345 				if (fl->ifl_sds.ifsd_map != NULL) {
2346 					for (j = 0; j < fl->ifl_size; j++) {
2347 						bus_dmamap_sync(
2348 						    fl->ifl_buf_tag,
2349 						    fl->ifl_sds.ifsd_map[j],
2350 						    BUS_DMASYNC_POSTREAD);
2351 						bus_dmamap_unload(
2352 						    fl->ifl_buf_tag,
2353 						    fl->ifl_sds.ifsd_map[j]);
2354 						bus_dmamap_destroy(
2355 						    fl->ifl_buf_tag,
2356 						    fl->ifl_sds.ifsd_map[j]);
2357 					}
2358 				}
2359 				bus_dma_tag_destroy(fl->ifl_buf_tag);
2360 				fl->ifl_buf_tag = NULL;
2361 			}
2362 			free(fl->ifl_sds.ifsd_m, M_IFLIB);
2363 			free(fl->ifl_sds.ifsd_cl, M_IFLIB);
2364 			free(fl->ifl_sds.ifsd_ba, M_IFLIB);
2365 			free(fl->ifl_sds.ifsd_map, M_IFLIB);
2366 			free(fl->ifl_rx_bitmap, M_IFLIB);
2367 			fl->ifl_sds.ifsd_m = NULL;
2368 			fl->ifl_sds.ifsd_cl = NULL;
2369 			fl->ifl_sds.ifsd_ba = NULL;
2370 			fl->ifl_sds.ifsd_map = NULL;
2371 			fl->ifl_rx_bitmap = NULL;
2372 		}
2373 		free(rxq->ifr_fl, M_IFLIB);
2374 		rxq->ifr_fl = NULL;
2375 		free(rxq->ifr_ifdi, M_IFLIB);
2376 		rxq->ifr_ifdi = NULL;
2377 		rxq->ifr_cq_cidx = 0;
2378 	}
2379 }
2380 
2381 /*
2382  * Timer routine
2383  */
2384 static void
iflib_timer(void * arg)2385 iflib_timer(void *arg)
2386 {
2387 	iflib_txq_t txq = arg;
2388 	if_ctx_t ctx = txq->ift_ctx;
2389 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
2390 	uint64_t this_tick = ticks;
2391 
2392 	if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
2393 		return;
2394 
2395 	/*
2396 	** Check on the state of the TX queue(s), this
2397 	** can be done without the lock because its RO
2398 	** and the HUNG state will be static if set.
2399 	*/
2400 	if (this_tick - txq->ift_last_timer_tick >= iflib_timer_default) {
2401 		txq->ift_last_timer_tick = this_tick;
2402 		IFDI_TIMER(ctx, txq->ift_id);
2403 		if ((txq->ift_qstatus == IFLIB_QUEUE_HUNG) &&
2404 		    ((txq->ift_cleaned_prev == txq->ift_cleaned) ||
2405 		     (sctx->isc_pause_frames == 0)))
2406 			goto hung;
2407 
2408 		if (txq->ift_qstatus != IFLIB_QUEUE_IDLE &&
2409 		    ifmp_ring_is_stalled(txq->ift_br)) {
2410 			KASSERT(ctx->ifc_link_state == LINK_STATE_UP,
2411 			    ("queue can't be marked as hung if interface is down"));
2412 			txq->ift_qstatus = IFLIB_QUEUE_HUNG;
2413 		}
2414 		txq->ift_cleaned_prev = txq->ift_cleaned;
2415 	}
2416 	/* handle any laggards */
2417 	if (txq->ift_db_pending)
2418 		GROUPTASK_ENQUEUE(&txq->ift_task);
2419 
2420 	sctx->isc_pause_frames = 0;
2421 	if (if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)
2422 		callout_reset_on(&txq->ift_timer, iflib_timer_default, iflib_timer,
2423 		    txq, txq->ift_timer.c_cpu);
2424 	return;
2425 
2426  hung:
2427 	device_printf(ctx->ifc_dev,
2428 	    "Watchdog timeout (TX: %d desc avail: %d pidx: %d) -- resetting\n",
2429 	    txq->ift_id, TXQ_AVAIL(txq), txq->ift_pidx);
2430 	STATE_LOCK(ctx);
2431 	if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
2432 	ctx->ifc_flags |= (IFC_DO_WATCHDOG | IFC_DO_RESET);
2433 	iflib_admin_intr_deferred(ctx);
2434 	STATE_UNLOCK(ctx);
2435 }
2436 
2437 static uint16_t
iflib_get_mbuf_size_for(unsigned int size)2438 iflib_get_mbuf_size_for(unsigned int size)
2439 {
2440 
2441 	if (size <= MCLBYTES)
2442 		return (MCLBYTES);
2443 	else
2444 		return (MJUMPAGESIZE);
2445 }
2446 
2447 static void
iflib_calc_rx_mbuf_sz(if_ctx_t ctx)2448 iflib_calc_rx_mbuf_sz(if_ctx_t ctx)
2449 {
2450 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
2451 
2452 	/*
2453 	 * XXX don't set the max_frame_size to larger
2454 	 * than the hardware can handle
2455 	 */
2456 	ctx->ifc_rx_mbuf_sz =
2457 	    iflib_get_mbuf_size_for(sctx->isc_max_frame_size);
2458 }
2459 
2460 uint32_t
iflib_get_rx_mbuf_sz(if_ctx_t ctx)2461 iflib_get_rx_mbuf_sz(if_ctx_t ctx)
2462 {
2463 
2464 	return (ctx->ifc_rx_mbuf_sz);
2465 }
2466 
2467 static void
iflib_init_locked(if_ctx_t ctx)2468 iflib_init_locked(if_ctx_t ctx)
2469 {
2470 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2471 	if_t ifp = ctx->ifc_ifp;
2472 	iflib_fl_t fl;
2473 	iflib_txq_t txq;
2474 	iflib_rxq_t rxq;
2475 	int i, j, tx_ip_csum_flags, tx_ip6_csum_flags;
2476 
2477 	if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
2478 	IFDI_INTR_DISABLE(ctx);
2479 
2480 	/*
2481 	 * See iflib_stop(). Useful in case iflib_init_locked() is
2482 	 * called without first calling iflib_stop().
2483 	 */
2484 	netmap_disable_all_rings(ifp);
2485 
2486 	tx_ip_csum_flags = scctx->isc_tx_csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP | CSUM_SCTP);
2487 	tx_ip6_csum_flags = scctx->isc_tx_csum_flags & (CSUM_IP6_TCP | CSUM_IP6_UDP | CSUM_IP6_SCTP);
2488 	/* Set hardware offload abilities */
2489 	if_clearhwassist(ifp);
2490 	if (if_getcapenable(ifp) & IFCAP_TXCSUM)
2491 		if_sethwassistbits(ifp, tx_ip_csum_flags, 0);
2492 	if (if_getcapenable(ifp) & IFCAP_TXCSUM_IPV6)
2493 		if_sethwassistbits(ifp,  tx_ip6_csum_flags, 0);
2494 	if (if_getcapenable(ifp) & IFCAP_TSO4)
2495 		if_sethwassistbits(ifp, CSUM_IP_TSO, 0);
2496 	if (if_getcapenable(ifp) & IFCAP_TSO6)
2497 		if_sethwassistbits(ifp, CSUM_IP6_TSO, 0);
2498 
2499 	for (i = 0, txq = ctx->ifc_txqs; i < scctx->isc_ntxqsets; i++, txq++) {
2500 		CALLOUT_LOCK(txq);
2501 		callout_stop(&txq->ift_timer);
2502 #ifdef DEV_NETMAP
2503 		callout_stop(&txq->ift_netmap_timer);
2504 #endif /* DEV_NETMAP */
2505 		CALLOUT_UNLOCK(txq);
2506 		(void)iflib_netmap_txq_init(ctx, txq);
2507 	}
2508 
2509 	/*
2510 	 * Calculate a suitable Rx mbuf size prior to calling IFDI_INIT, so
2511 	 * that drivers can use the value when setting up the hardware receive
2512 	 * buffers.
2513 	 */
2514 	iflib_calc_rx_mbuf_sz(ctx);
2515 
2516 #ifdef INVARIANTS
2517 	i = if_getdrvflags(ifp);
2518 #endif
2519 	IFDI_INIT(ctx);
2520 	MPASS(if_getdrvflags(ifp) == i);
2521 	for (i = 0, rxq = ctx->ifc_rxqs; i < scctx->isc_nrxqsets; i++, rxq++) {
2522 		if (iflib_netmap_rxq_init(ctx, rxq) > 0) {
2523 			/* This rxq is in netmap mode. Skip normal init. */
2524 			continue;
2525 		}
2526 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++) {
2527 			if (iflib_fl_setup(fl)) {
2528 				device_printf(ctx->ifc_dev,
2529 				    "setting up free list %d failed - "
2530 				    "check cluster settings\n", j);
2531 				goto done;
2532 			}
2533 		}
2534 	}
2535 done:
2536 	if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_RUNNING, IFF_DRV_OACTIVE);
2537 	IFDI_INTR_ENABLE(ctx);
2538 	txq = ctx->ifc_txqs;
2539 	for (i = 0; i < scctx->isc_ntxqsets; i++, txq++)
2540 		callout_reset_on(&txq->ift_timer, iflib_timer_default, iflib_timer, txq,
2541 			txq->ift_timer.c_cpu);
2542 
2543         /* Re-enable txsync/rxsync. */
2544 	netmap_enable_all_rings(ifp);
2545 }
2546 
2547 static int
iflib_media_change(if_t ifp)2548 iflib_media_change(if_t ifp)
2549 {
2550 	if_ctx_t ctx = if_getsoftc(ifp);
2551 	int err;
2552 
2553 	CTX_LOCK(ctx);
2554 	if ((err = IFDI_MEDIA_CHANGE(ctx)) == 0)
2555 		iflib_if_init_locked(ctx);
2556 	CTX_UNLOCK(ctx);
2557 	return (err);
2558 }
2559 
2560 static void
iflib_media_status(if_t ifp,struct ifmediareq * ifmr)2561 iflib_media_status(if_t ifp, struct ifmediareq *ifmr)
2562 {
2563 	if_ctx_t ctx = if_getsoftc(ifp);
2564 
2565 	CTX_LOCK(ctx);
2566 	IFDI_UPDATE_ADMIN_STATUS(ctx);
2567 	IFDI_MEDIA_STATUS(ctx, ifmr);
2568 	CTX_UNLOCK(ctx);
2569 }
2570 
2571 void
iflib_stop(if_ctx_t ctx)2572 iflib_stop(if_ctx_t ctx)
2573 {
2574 	iflib_txq_t txq = ctx->ifc_txqs;
2575 	iflib_rxq_t rxq = ctx->ifc_rxqs;
2576 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2577 	if_shared_ctx_t sctx = ctx->ifc_sctx;
2578 	iflib_dma_info_t di;
2579 	iflib_fl_t fl;
2580 	int i, j;
2581 
2582 	/* Tell the stack that the interface is no longer active */
2583 	if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
2584 
2585 	IFDI_INTR_DISABLE(ctx);
2586 	DELAY(1000);
2587 	IFDI_STOP(ctx);
2588 	DELAY(1000);
2589 
2590 	/*
2591 	 * Stop any pending txsync/rxsync and prevent new ones
2592 	 * form starting. Processes blocked in poll() will get
2593 	 * POLLERR.
2594 	 */
2595 	netmap_disable_all_rings(ctx->ifc_ifp);
2596 
2597 	iflib_debug_reset();
2598 	/* Wait for current tx queue users to exit to disarm watchdog timer. */
2599 	for (i = 0; i < scctx->isc_ntxqsets; i++, txq++) {
2600 		/* make sure all transmitters have completed before proceeding XXX */
2601 
2602 		CALLOUT_LOCK(txq);
2603 		callout_stop(&txq->ift_timer);
2604 #ifdef DEV_NETMAP
2605 		callout_stop(&txq->ift_netmap_timer);
2606 #endif /* DEV_NETMAP */
2607 		CALLOUT_UNLOCK(txq);
2608 
2609 		/* clean any enqueued buffers */
2610 		iflib_ifmp_purge(txq);
2611 		/* Free any existing tx buffers. */
2612 		for (j = 0; j < txq->ift_size; j++) {
2613 			iflib_txsd_free(ctx, txq, j);
2614 		}
2615 		txq->ift_processed = txq->ift_cleaned = txq->ift_cidx_processed = 0;
2616 		txq->ift_in_use = txq->ift_gen = txq->ift_cidx = txq->ift_pidx = txq->ift_no_desc_avail = 0;
2617 		txq->ift_closed = txq->ift_mbuf_defrag = txq->ift_mbuf_defrag_failed = 0;
2618 		txq->ift_no_tx_dma_setup = txq->ift_txd_encap_efbig = txq->ift_map_failed = 0;
2619 		txq->ift_pullups = 0;
2620 		ifmp_ring_reset_stats(txq->ift_br);
2621 		for (j = 0, di = txq->ift_ifdi; j < sctx->isc_ntxqs; j++, di++)
2622 			bzero((void *)di->idi_vaddr, di->idi_size);
2623 	}
2624 	for (i = 0; i < scctx->isc_nrxqsets; i++, rxq++) {
2625 		if (rxq->ifr_task.gt_taskqueue != NULL)
2626 			gtaskqueue_drain(rxq->ifr_task.gt_taskqueue,
2627 				 &rxq->ifr_task.gt_task);
2628 
2629 		rxq->ifr_cq_cidx = 0;
2630 		for (j = 0, di = rxq->ifr_ifdi; j < sctx->isc_nrxqs; j++, di++)
2631 			bzero((void *)di->idi_vaddr, di->idi_size);
2632 		/* also resets the free lists pidx/cidx */
2633 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++)
2634 			iflib_fl_bufs_free(fl);
2635 	}
2636 }
2637 
2638 static inline caddr_t
calc_next_rxd(iflib_fl_t fl,int cidx)2639 calc_next_rxd(iflib_fl_t fl, int cidx)
2640 {
2641 	qidx_t size;
2642 	int nrxd;
2643 	caddr_t start, end, cur, next;
2644 
2645 	nrxd = fl->ifl_size;
2646 	size = fl->ifl_rxd_size;
2647 	start = fl->ifl_ifdi->idi_vaddr;
2648 
2649 	if (__predict_false(size == 0))
2650 		return (start);
2651 	cur = start + size * cidx;
2652 	end = start + size * nrxd;
2653 	next = CACHE_PTR_NEXT(cur);
2654 	return (next < end ? next : start);
2655 }
2656 
2657 static inline void
prefetch_pkts(iflib_fl_t fl,int cidx)2658 prefetch_pkts(iflib_fl_t fl, int cidx)
2659 {
2660 	int nextptr;
2661 	int nrxd = fl->ifl_size;
2662 	caddr_t next_rxd;
2663 
2664 	nextptr = (cidx + CACHE_PTR_INCREMENT) & (nrxd - 1);
2665 	prefetch(&fl->ifl_sds.ifsd_m[nextptr]);
2666 	prefetch(&fl->ifl_sds.ifsd_cl[nextptr]);
2667 	next_rxd = calc_next_rxd(fl, cidx);
2668 	prefetch(next_rxd);
2669 	prefetch(fl->ifl_sds.ifsd_m[(cidx + 1) & (nrxd - 1)]);
2670 	prefetch(fl->ifl_sds.ifsd_m[(cidx + 2) & (nrxd - 1)]);
2671 	prefetch(fl->ifl_sds.ifsd_m[(cidx + 3) & (nrxd - 1)]);
2672 	prefetch(fl->ifl_sds.ifsd_m[(cidx + 4) & (nrxd - 1)]);
2673 	prefetch(fl->ifl_sds.ifsd_cl[(cidx + 1) & (nrxd - 1)]);
2674 	prefetch(fl->ifl_sds.ifsd_cl[(cidx + 2) & (nrxd - 1)]);
2675 	prefetch(fl->ifl_sds.ifsd_cl[(cidx + 3) & (nrxd - 1)]);
2676 	prefetch(fl->ifl_sds.ifsd_cl[(cidx + 4) & (nrxd - 1)]);
2677 }
2678 
2679 static struct mbuf *
rxd_frag_to_sd(iflib_rxq_t rxq,if_rxd_frag_t irf,bool unload,if_rxsd_t sd,int * pf_rv,if_rxd_info_t ri)2680 rxd_frag_to_sd(iflib_rxq_t rxq, if_rxd_frag_t irf, bool unload, if_rxsd_t sd,
2681     int *pf_rv, if_rxd_info_t ri)
2682 {
2683 	bus_dmamap_t map;
2684 	iflib_fl_t fl;
2685 	caddr_t payload;
2686 	struct mbuf *m;
2687 	int flid, cidx, len, next;
2688 
2689 	map = NULL;
2690 	flid = irf->irf_flid;
2691 	cidx = irf->irf_idx;
2692 	fl = &rxq->ifr_fl[flid];
2693 	sd->ifsd_fl = fl;
2694 	m = fl->ifl_sds.ifsd_m[cidx];
2695 	sd->ifsd_cl = &fl->ifl_sds.ifsd_cl[cidx];
2696 	fl->ifl_credits--;
2697 #if MEMORY_LOGGING
2698 	fl->ifl_m_dequeued++;
2699 #endif
2700 	if (rxq->ifr_ctx->ifc_flags & IFC_PREFETCH)
2701 		prefetch_pkts(fl, cidx);
2702 	next = (cidx + CACHE_PTR_INCREMENT) & (fl->ifl_size - 1);
2703 	prefetch(&fl->ifl_sds.ifsd_map[next]);
2704 	map = fl->ifl_sds.ifsd_map[cidx];
2705 
2706 	bus_dmamap_sync(fl->ifl_buf_tag, map, BUS_DMASYNC_POSTREAD);
2707 
2708 	if (rxq->pfil != NULL && PFIL_HOOKED_IN(rxq->pfil) && pf_rv != NULL &&
2709 	    irf->irf_len != 0) {
2710 		payload  = *sd->ifsd_cl;
2711 		payload +=  ri->iri_pad;
2712 		len = ri->iri_len - ri->iri_pad;
2713 		*pf_rv = pfil_run_hooks(rxq->pfil, payload, ri->iri_ifp,
2714 		    len | PFIL_MEMPTR | PFIL_IN, NULL);
2715 		switch (*pf_rv) {
2716 		case PFIL_DROPPED:
2717 		case PFIL_CONSUMED:
2718 			/*
2719 			 * The filter ate it.  Everything is recycled.
2720 			 */
2721 			m = NULL;
2722 			unload = 0;
2723 			break;
2724 		case PFIL_REALLOCED:
2725 			/*
2726 			 * The filter copied it.  Everything is recycled.
2727 			 */
2728 			m = pfil_mem2mbuf(payload);
2729 			unload = 0;
2730 			break;
2731 		case PFIL_PASS:
2732 			/*
2733 			 * Filter said it was OK, so receive like
2734 			 * normal
2735 			 */
2736 			fl->ifl_sds.ifsd_m[cidx] = NULL;
2737 			break;
2738 		default:
2739 			MPASS(0);
2740 		}
2741 	} else {
2742 		fl->ifl_sds.ifsd_m[cidx] = NULL;
2743 		if (pf_rv != NULL)
2744 			*pf_rv = PFIL_PASS;
2745 	}
2746 
2747 	if (unload && irf->irf_len != 0)
2748 		bus_dmamap_unload(fl->ifl_buf_tag, map);
2749 	fl->ifl_cidx = (fl->ifl_cidx + 1) & (fl->ifl_size - 1);
2750 	if (__predict_false(fl->ifl_cidx == 0))
2751 		fl->ifl_gen = 0;
2752 	bit_clear(fl->ifl_rx_bitmap, cidx);
2753 	return (m);
2754 }
2755 
2756 static struct mbuf *
assemble_segments(iflib_rxq_t rxq,if_rxd_info_t ri,if_rxsd_t sd,int * pf_rv)2757 assemble_segments(iflib_rxq_t rxq, if_rxd_info_t ri, if_rxsd_t sd, int *pf_rv)
2758 {
2759 	struct mbuf *m, *mh, *mt;
2760 	caddr_t cl;
2761 	int  *pf_rv_ptr, flags, i, padlen;
2762 	bool consumed;
2763 
2764 	i = 0;
2765 	mh = NULL;
2766 	consumed = false;
2767 	*pf_rv = PFIL_PASS;
2768 	pf_rv_ptr = pf_rv;
2769 	do {
2770 		m = rxd_frag_to_sd(rxq, &ri->iri_frags[i], !consumed, sd,
2771 		    pf_rv_ptr, ri);
2772 
2773 		MPASS(*sd->ifsd_cl != NULL);
2774 
2775 		/*
2776 		 * Exclude zero-length frags & frags from
2777 		 * packets the filter has consumed or dropped
2778 		 */
2779 		if (ri->iri_frags[i].irf_len == 0 || consumed ||
2780 		    *pf_rv == PFIL_CONSUMED || *pf_rv == PFIL_DROPPED) {
2781 			if (mh == NULL) {
2782 				/* everything saved here */
2783 				consumed = true;
2784 				pf_rv_ptr = NULL;
2785 				continue;
2786 			}
2787 			/* XXX we can save the cluster here, but not the mbuf */
2788 			m_init(m, M_NOWAIT, MT_DATA, 0);
2789 			m_free(m);
2790 			continue;
2791 		}
2792 		if (mh == NULL) {
2793 			flags = M_PKTHDR | M_EXT;
2794 			mh = mt = m;
2795 			padlen = ri->iri_pad;
2796 		} else {
2797 			flags = M_EXT;
2798 			mt->m_next = m;
2799 			mt = m;
2800 			/* assuming padding is only on the first fragment */
2801 			padlen = 0;
2802 		}
2803 		cl = *sd->ifsd_cl;
2804 		*sd->ifsd_cl = NULL;
2805 
2806 		/* Can these two be made one ? */
2807 		m_init(m, M_NOWAIT, MT_DATA, flags);
2808 		m_cljset(m, cl, sd->ifsd_fl->ifl_cltype);
2809 		/*
2810 		 * These must follow m_init and m_cljset
2811 		 */
2812 		m->m_data += padlen;
2813 		ri->iri_len -= padlen;
2814 		m->m_len = ri->iri_frags[i].irf_len;
2815 	} while (++i < ri->iri_nfrags);
2816 
2817 	return (mh);
2818 }
2819 
2820 /*
2821  * Process one software descriptor
2822  */
2823 static struct mbuf *
iflib_rxd_pkt_get(iflib_rxq_t rxq,if_rxd_info_t ri)2824 iflib_rxd_pkt_get(iflib_rxq_t rxq, if_rxd_info_t ri)
2825 {
2826 	struct if_rxsd sd;
2827 	struct mbuf *m;
2828 	int pf_rv;
2829 
2830 	/* should I merge this back in now that the two paths are basically duplicated? */
2831 	if (ri->iri_nfrags == 1 &&
2832 	    ri->iri_frags[0].irf_len != 0 &&
2833 	    ri->iri_frags[0].irf_len <= MIN(IFLIB_RX_COPY_THRESH, MHLEN)) {
2834 		m = rxd_frag_to_sd(rxq, &ri->iri_frags[0], false, &sd,
2835 		    &pf_rv, ri);
2836 		if (pf_rv != PFIL_PASS && pf_rv != PFIL_REALLOCED)
2837 			return (m);
2838 		if (pf_rv == PFIL_PASS) {
2839 			m_init(m, M_NOWAIT, MT_DATA, M_PKTHDR);
2840 #ifndef __NO_STRICT_ALIGNMENT
2841 			if (!IP_ALIGNED(m))
2842 				m->m_data += 2;
2843 #endif
2844 			memcpy(m->m_data, *sd.ifsd_cl, ri->iri_len);
2845 			m->m_len = ri->iri_frags[0].irf_len;
2846 		}
2847 	} else {
2848 		m = assemble_segments(rxq, ri, &sd, &pf_rv);
2849 		if (m == NULL)
2850 			return (NULL);
2851 		if (pf_rv != PFIL_PASS && pf_rv != PFIL_REALLOCED)
2852 			return (m);
2853 	}
2854 	m->m_pkthdr.len = ri->iri_len;
2855 	m->m_pkthdr.rcvif = ri->iri_ifp;
2856 	m->m_flags |= ri->iri_flags;
2857 	m->m_pkthdr.ether_vtag = ri->iri_vtag;
2858 	m->m_pkthdr.flowid = ri->iri_flowid;
2859 	M_HASHTYPE_SET(m, ri->iri_rsstype);
2860 	m->m_pkthdr.csum_flags = ri->iri_csum_flags;
2861 	m->m_pkthdr.csum_data = ri->iri_csum_data;
2862 	return (m);
2863 }
2864 
2865 #if defined(INET6) || defined(INET)
2866 static void
iflib_get_ip_forwarding(struct lro_ctrl * lc,bool * v4,bool * v6)2867 iflib_get_ip_forwarding(struct lro_ctrl *lc, bool *v4, bool *v6)
2868 {
2869 	CURVNET_SET(lc->ifp->if_vnet);
2870 #if defined(INET6)
2871 	*v6 = V_ip6_forwarding;
2872 #endif
2873 #if defined(INET)
2874 	*v4 = V_ipforwarding;
2875 #endif
2876 	CURVNET_RESTORE();
2877 }
2878 
2879 /*
2880  * Returns true if it's possible this packet could be LROed.
2881  * if it returns false, it is guaranteed that tcp_lro_rx()
2882  * would not return zero.
2883  */
2884 static bool
iflib_check_lro_possible(struct mbuf * m,bool v4_forwarding,bool v6_forwarding)2885 iflib_check_lro_possible(struct mbuf *m, bool v4_forwarding, bool v6_forwarding)
2886 {
2887 	struct ether_header *eh;
2888 
2889 	eh = mtod(m, struct ether_header *);
2890 	switch (eh->ether_type) {
2891 #if defined(INET6)
2892 	case htons(ETHERTYPE_IPV6):
2893 		return (!v6_forwarding);
2894 #endif
2895 #if defined(INET)
2896 	case htons(ETHERTYPE_IP):
2897 		return (!v4_forwarding);
2898 #endif
2899 	}
2900 
2901 	return (false);
2902 }
2903 #else
2904 static void
iflib_get_ip_forwarding(struct lro_ctrl * lc __unused,bool * v4 __unused,bool * v6 __unused)2905 iflib_get_ip_forwarding(struct lro_ctrl *lc __unused, bool *v4 __unused, bool *v6 __unused)
2906 {
2907 }
2908 #endif
2909 
2910 static void
_task_fn_rx_watchdog(void * context)2911 _task_fn_rx_watchdog(void *context)
2912 {
2913 	iflib_rxq_t rxq = context;
2914 
2915 	GROUPTASK_ENQUEUE(&rxq->ifr_task);
2916 }
2917 
2918 static uint8_t
iflib_rxeof(iflib_rxq_t rxq,qidx_t budget)2919 iflib_rxeof(iflib_rxq_t rxq, qidx_t budget)
2920 {
2921 	if_t ifp;
2922 	if_ctx_t ctx = rxq->ifr_ctx;
2923 	if_shared_ctx_t sctx = ctx->ifc_sctx;
2924 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2925 	int avail, i;
2926 	qidx_t *cidxp;
2927 	struct if_rxd_info ri;
2928 	int err, budget_left, rx_bytes, rx_pkts;
2929 	iflib_fl_t fl;
2930 	int lro_enabled;
2931 	bool v4_forwarding, v6_forwarding, lro_possible;
2932 	uint8_t retval = 0;
2933 
2934 	/*
2935 	 * XXX early demux data packets so that if_input processing only handles
2936 	 * acks in interrupt context
2937 	 */
2938 	struct mbuf *m, *mh, *mt, *mf;
2939 
2940 	NET_EPOCH_ASSERT();
2941 
2942 	lro_possible = v4_forwarding = v6_forwarding = false;
2943 	ifp = ctx->ifc_ifp;
2944 	mh = mt = NULL;
2945 	MPASS(budget > 0);
2946 	rx_pkts	= rx_bytes = 0;
2947 	if (sctx->isc_flags & IFLIB_HAS_RXCQ)
2948 		cidxp = &rxq->ifr_cq_cidx;
2949 	else
2950 		cidxp = &rxq->ifr_fl[0].ifl_cidx;
2951 	if ((avail = iflib_rxd_avail(ctx, rxq, *cidxp, budget)) == 0) {
2952 		for (i = 0, fl = &rxq->ifr_fl[0]; i < sctx->isc_nfl; i++, fl++)
2953 			retval |= iflib_fl_refill_all(ctx, fl);
2954 		DBG_COUNTER_INC(rx_unavail);
2955 		return (retval);
2956 	}
2957 
2958 	/* pfil needs the vnet to be set */
2959 	CURVNET_SET_QUIET(ifp->if_vnet);
2960 	for (budget_left = budget; budget_left > 0 && avail > 0;) {
2961 		if (__predict_false(!CTX_ACTIVE(ctx))) {
2962 			DBG_COUNTER_INC(rx_ctx_inactive);
2963 			break;
2964 		}
2965 		/*
2966 		 * Reset client set fields to their default values
2967 		 */
2968 		rxd_info_zero(&ri);
2969 		ri.iri_qsidx = rxq->ifr_id;
2970 		ri.iri_cidx = *cidxp;
2971 		ri.iri_ifp = ifp;
2972 		ri.iri_frags = rxq->ifr_frags;
2973 		err = ctx->isc_rxd_pkt_get(ctx->ifc_softc, &ri);
2974 
2975 		if (err)
2976 			goto err;
2977 		rx_pkts += 1;
2978 		rx_bytes += ri.iri_len;
2979 		if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
2980 			*cidxp = ri.iri_cidx;
2981 			/* Update our consumer index */
2982 			/* XXX NB: shurd - check if this is still safe */
2983 			while (rxq->ifr_cq_cidx >= scctx->isc_nrxd[0])
2984 				rxq->ifr_cq_cidx -= scctx->isc_nrxd[0];
2985 			/* was this only a completion queue message? */
2986 			if (__predict_false(ri.iri_nfrags == 0))
2987 				continue;
2988 		}
2989 		MPASS(ri.iri_nfrags != 0);
2990 		MPASS(ri.iri_len != 0);
2991 
2992 		/* will advance the cidx on the corresponding free lists */
2993 		m = iflib_rxd_pkt_get(rxq, &ri);
2994 		avail--;
2995 		budget_left--;
2996 		if (avail == 0 && budget_left)
2997 			avail = iflib_rxd_avail(ctx, rxq, *cidxp, budget_left);
2998 
2999 		if (__predict_false(m == NULL))
3000 			continue;
3001 
3002 		/* imm_pkt: -- cxgb */
3003 		if (mh == NULL)
3004 			mh = mt = m;
3005 		else {
3006 			mt->m_nextpkt = m;
3007 			mt = m;
3008 		}
3009 	}
3010 	CURVNET_RESTORE();
3011 	/* make sure that we can refill faster than drain */
3012 	for (i = 0, fl = &rxq->ifr_fl[0]; i < sctx->isc_nfl; i++, fl++)
3013 		retval |= iflib_fl_refill_all(ctx, fl);
3014 
3015 	lro_enabled = (if_getcapenable(ifp) & IFCAP_LRO);
3016 	if (lro_enabled)
3017 		iflib_get_ip_forwarding(&rxq->ifr_lc, &v4_forwarding, &v6_forwarding);
3018 	mt = mf = NULL;
3019 	while (mh != NULL) {
3020 		m = mh;
3021 		mh = mh->m_nextpkt;
3022 		m->m_nextpkt = NULL;
3023 #ifndef __NO_STRICT_ALIGNMENT
3024 		if (!IP_ALIGNED(m) && (m = iflib_fixup_rx(m)) == NULL)
3025 			continue;
3026 #endif
3027 #if defined(INET6) || defined(INET)
3028 		if (lro_enabled) {
3029 			if (!lro_possible) {
3030 				lro_possible = iflib_check_lro_possible(m, v4_forwarding, v6_forwarding);
3031 				if (lro_possible && mf != NULL) {
3032 					ifp->if_input(ifp, mf);
3033 					DBG_COUNTER_INC(rx_if_input);
3034 					mt = mf = NULL;
3035 				}
3036 			}
3037 			if ((m->m_pkthdr.csum_flags & (CSUM_L4_CALC | CSUM_L4_VALID)) ==
3038 			    (CSUM_L4_CALC | CSUM_L4_VALID)) {
3039 				if (lro_possible && tcp_lro_rx(&rxq->ifr_lc, m, 0) == 0)
3040 					continue;
3041 			}
3042 		}
3043 #endif
3044 		if (lro_possible) {
3045 			ifp->if_input(ifp, m);
3046 			DBG_COUNTER_INC(rx_if_input);
3047 			continue;
3048 		}
3049 
3050 		if (mf == NULL)
3051 			mf = m;
3052 		if (mt != NULL)
3053 			mt->m_nextpkt = m;
3054 		mt = m;
3055 	}
3056 	if (mf != NULL) {
3057 		ifp->if_input(ifp, mf);
3058 		DBG_COUNTER_INC(rx_if_input);
3059 	}
3060 
3061 	if_inc_counter(ifp, IFCOUNTER_IBYTES, rx_bytes);
3062 	if_inc_counter(ifp, IFCOUNTER_IPACKETS, rx_pkts);
3063 
3064 	/*
3065 	 * Flush any outstanding LRO work
3066 	 */
3067 #if defined(INET6) || defined(INET)
3068 	tcp_lro_flush_all(&rxq->ifr_lc);
3069 #endif
3070 	if (avail != 0 || iflib_rxd_avail(ctx, rxq, *cidxp, 1) != 0)
3071 		retval |= IFLIB_RXEOF_MORE;
3072 	return (retval);
3073 err:
3074 	STATE_LOCK(ctx);
3075 	ctx->ifc_flags |= IFC_DO_RESET;
3076 	iflib_admin_intr_deferred(ctx);
3077 	STATE_UNLOCK(ctx);
3078 	return (0);
3079 }
3080 
3081 #define TXD_NOTIFY_COUNT(txq) (((txq)->ift_size / (txq)->ift_update_freq) - 1)
3082 static inline qidx_t
txq_max_db_deferred(iflib_txq_t txq,qidx_t in_use)3083 txq_max_db_deferred(iflib_txq_t txq, qidx_t in_use)
3084 {
3085 	qidx_t notify_count = TXD_NOTIFY_COUNT(txq);
3086 	qidx_t minthresh = txq->ift_size / 8;
3087 	if (in_use > 4 * minthresh)
3088 		return (notify_count);
3089 	if (in_use > 2 * minthresh)
3090 		return (notify_count >> 1);
3091 	if (in_use > minthresh)
3092 		return (notify_count >> 3);
3093 	return (0);
3094 }
3095 
3096 static inline qidx_t
txq_max_rs_deferred(iflib_txq_t txq)3097 txq_max_rs_deferred(iflib_txq_t txq)
3098 {
3099 	qidx_t notify_count = TXD_NOTIFY_COUNT(txq);
3100 	qidx_t minthresh = txq->ift_size / 8;
3101 	if (txq->ift_in_use > 4 * minthresh)
3102 		return (notify_count);
3103 	if (txq->ift_in_use > 2 * minthresh)
3104 		return (notify_count >> 1);
3105 	if (txq->ift_in_use > minthresh)
3106 		return (notify_count >> 2);
3107 	return (2);
3108 }
3109 
3110 #define M_CSUM_FLAGS(m)		((m)->m_pkthdr.csum_flags)
3111 #define M_HAS_VLANTAG(m)	(m->m_flags & M_VLANTAG)
3112 
3113 #define TXQ_MAX_DB_DEFERRED(txq, in_use)	txq_max_db_deferred((txq), (in_use))
3114 #define TXQ_MAX_RS_DEFERRED(txq)	txq_max_rs_deferred(txq)
3115 #define TXQ_MAX_DB_CONSUMED(size)	(size >> 4)
3116 
3117 /* forward compatibility for cxgb */
3118 #define FIRST_QSET(ctx) 0
3119 #define NTXQSETS(ctx) ((ctx)->ifc_softc_ctx.isc_ntxqsets)
3120 #define NRXQSETS(ctx) ((ctx)->ifc_softc_ctx.isc_nrxqsets)
3121 #define QIDX(ctx, m) ((((m)->m_pkthdr.flowid & ctx->ifc_softc_ctx.isc_rss_table_mask) % NTXQSETS(ctx)) + FIRST_QSET(ctx))
3122 #define DESC_RECLAIMABLE(q) ((int)((q)->ift_processed - (q)->ift_cleaned - (q)->ift_ctx->ifc_softc_ctx.isc_tx_nsegments))
3123 
3124 /* XXX we should be setting this to something other than zero */
3125 #define RECLAIM_THRESH(ctx) ((ctx)->ifc_sctx->isc_tx_reclaim_thresh)
3126 #define	MAX_TX_DESC(ctx) MAX((ctx)->ifc_softc_ctx.isc_tx_tso_segments_max, \
3127     (ctx)->ifc_softc_ctx.isc_tx_nsegments)
3128 
3129 static inline bool
iflib_txd_db_check(iflib_txq_t txq,int ring)3130 iflib_txd_db_check(iflib_txq_t txq, int ring)
3131 {
3132 	if_ctx_t ctx = txq->ift_ctx;
3133 	qidx_t dbval, max;
3134 
3135 	max = TXQ_MAX_DB_DEFERRED(txq, txq->ift_in_use);
3136 
3137 	/* force || threshold exceeded || at the edge of the ring */
3138 	if (ring || (txq->ift_db_pending >= max) || (TXQ_AVAIL(txq) <= MAX_TX_DESC(ctx) + 2)) {
3139 
3140 		/*
3141 		 * 'npending' is used if the card's doorbell is in terms of the number of descriptors
3142 		 * pending flush (BRCM). 'pidx' is used in cases where the card's doorbeel uses the
3143 		 * producer index explicitly (INTC).
3144 		 */
3145 		dbval = txq->ift_npending ? txq->ift_npending : txq->ift_pidx;
3146 		bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
3147 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
3148 		ctx->isc_txd_flush(ctx->ifc_softc, txq->ift_id, dbval);
3149 
3150 		/*
3151 		 * Absent bugs there are zero packets pending so reset pending counts to zero.
3152 		 */
3153 		txq->ift_db_pending = txq->ift_npending = 0;
3154 		return (true);
3155 	}
3156 	return (false);
3157 }
3158 
3159 #ifdef PKT_DEBUG
3160 static void
print_pkt(if_pkt_info_t pi)3161 print_pkt(if_pkt_info_t pi)
3162 {
3163 	printf("pi len:  %d qsidx: %d nsegs: %d ndescs: %d flags: %x pidx: %d\n",
3164 	       pi->ipi_len, pi->ipi_qsidx, pi->ipi_nsegs, pi->ipi_ndescs, pi->ipi_flags, pi->ipi_pidx);
3165 	printf("pi new_pidx: %d csum_flags: %lx tso_segsz: %d mflags: %x vtag: %d\n",
3166 	       pi->ipi_new_pidx, pi->ipi_csum_flags, pi->ipi_tso_segsz, pi->ipi_mflags, pi->ipi_vtag);
3167 	printf("pi etype: %d ehdrlen: %d ip_hlen: %d ipproto: %d\n",
3168 	       pi->ipi_etype, pi->ipi_ehdrlen, pi->ipi_ip_hlen, pi->ipi_ipproto);
3169 }
3170 #endif
3171 
3172 #define IS_TSO4(pi) ((pi)->ipi_csum_flags & CSUM_IP_TSO)
3173 #define IS_TX_OFFLOAD4(pi) ((pi)->ipi_csum_flags & (CSUM_IP_TCP | CSUM_IP_TSO))
3174 #define IS_TSO6(pi) ((pi)->ipi_csum_flags & CSUM_IP6_TSO)
3175 #define IS_TX_OFFLOAD6(pi) ((pi)->ipi_csum_flags & (CSUM_IP6_TCP | CSUM_IP6_TSO))
3176 
3177 /**
3178  * Parses out ethernet header information in the given mbuf.
3179  * Returns in pi: ipi_etype (EtherType) and ipi_ehdrlen (Ethernet header length)
3180  *
3181  * This will account for the VLAN header if present.
3182  *
3183  * XXX: This doesn't handle QinQ, which could prevent TX offloads for those
3184  * types of packets.
3185  */
3186 static int
iflib_parse_ether_header(if_pkt_info_t pi,struct mbuf ** mp,uint64_t * pullups)3187 iflib_parse_ether_header(if_pkt_info_t pi, struct mbuf **mp, uint64_t *pullups)
3188 {
3189 	struct ether_vlan_header *eh;
3190 	struct mbuf *m;
3191 
3192 	m = *mp;
3193 	if (__predict_false(m->m_len < sizeof(*eh))) {
3194 		(*pullups)++;
3195 		if (__predict_false((m = m_pullup(m, sizeof(*eh))) == NULL))
3196 			return (ENOMEM);
3197 	}
3198 	eh = mtod(m, struct ether_vlan_header *);
3199 	if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
3200 		pi->ipi_etype = ntohs(eh->evl_proto);
3201 		pi->ipi_ehdrlen = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
3202 	} else {
3203 		pi->ipi_etype = ntohs(eh->evl_encap_proto);
3204 		pi->ipi_ehdrlen = ETHER_HDR_LEN;
3205 	}
3206 	*mp = m;
3207 
3208 	return (0);
3209 }
3210 
3211 /**
3212  * Parse up to the L3 header and extract IPv4/IPv6 header information into pi.
3213  * Currently this information includes: IP ToS value, IP header version/presence
3214  *
3215  * This is missing some checks and doesn't edit the packet content as it goes,
3216  * unlike iflib_parse_header(), in order to keep the amount of code here minimal.
3217  */
3218 static int
iflib_parse_header_partial(if_pkt_info_t pi,struct mbuf ** mp,uint64_t * pullups)3219 iflib_parse_header_partial(if_pkt_info_t pi, struct mbuf **mp, uint64_t *pullups)
3220 {
3221 	struct mbuf *m;
3222 	int err;
3223 
3224 	*pullups = 0;
3225 	m = *mp;
3226 	if (!M_WRITABLE(m)) {
3227 		if ((m = m_dup(m, M_NOWAIT)) == NULL) {
3228 			return (ENOMEM);
3229 		} else {
3230 			m_freem(*mp);
3231 			DBG_COUNTER_INC(tx_frees);
3232 			*mp = m;
3233 		}
3234 	}
3235 
3236 	/* Fills out pi->ipi_etype */
3237 	err = iflib_parse_ether_header(pi, mp, pullups);
3238 	if (err)
3239 		return (err);
3240 	m = *mp;
3241 
3242 	switch (pi->ipi_etype) {
3243 #ifdef INET
3244 	case ETHERTYPE_IP:
3245 	{
3246 		struct mbuf *n;
3247 		struct ip *ip = NULL;
3248 		int miniplen;
3249 
3250 		miniplen = min(m->m_pkthdr.len, pi->ipi_ehdrlen + sizeof(*ip));
3251 		if (__predict_false(m->m_len < miniplen)) {
3252 			/*
3253 			 * Check for common case where the first mbuf only contains
3254 			 * the Ethernet header
3255 			 */
3256 			if (m->m_len == pi->ipi_ehdrlen) {
3257 				n = m->m_next;
3258 				MPASS(n);
3259 				/* If next mbuf contains at least the minimal IP header, then stop */
3260 				if (n->m_len >= sizeof(*ip)) {
3261 					ip = (struct ip *)n->m_data;
3262 				} else {
3263 					(*pullups)++;
3264 					if (__predict_false((m = m_pullup(m, miniplen)) == NULL))
3265 						return (ENOMEM);
3266 					ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3267 				}
3268 			} else {
3269 				(*pullups)++;
3270 				if (__predict_false((m = m_pullup(m, miniplen)) == NULL))
3271 					return (ENOMEM);
3272 				ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3273 			}
3274 		} else {
3275 			ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3276 		}
3277 
3278 		/* Have the IPv4 header w/ no options here */
3279 		pi->ipi_ip_hlen = ip->ip_hl << 2;
3280 		pi->ipi_ipproto = ip->ip_p;
3281 		pi->ipi_ip_tos = ip->ip_tos;
3282 		pi->ipi_flags |= IPI_TX_IPV4;
3283 
3284 		break;
3285 	}
3286 #endif
3287 #ifdef INET6
3288 	case ETHERTYPE_IPV6:
3289 	{
3290 		struct ip6_hdr *ip6;
3291 
3292 		if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) {
3293 			(*pullups)++;
3294 			if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) == NULL))
3295 				return (ENOMEM);
3296 		}
3297 		ip6 = (struct ip6_hdr *)(m->m_data + pi->ipi_ehdrlen);
3298 
3299 		/* Have the IPv6 fixed header here */
3300 		pi->ipi_ip_hlen = sizeof(struct ip6_hdr);
3301 		pi->ipi_ipproto = ip6->ip6_nxt;
3302 		pi->ipi_ip_tos = IPV6_TRAFFIC_CLASS(ip6);
3303 		pi->ipi_flags |= IPI_TX_IPV6;
3304 
3305 		break;
3306 	}
3307 #endif
3308 	default:
3309 		pi->ipi_csum_flags &= ~CSUM_OFFLOAD;
3310 		pi->ipi_ip_hlen = 0;
3311 		break;
3312 	}
3313 	*mp = m;
3314 
3315 	return (0);
3316 
3317 }
3318 
3319 static int
iflib_parse_header(iflib_txq_t txq,if_pkt_info_t pi,struct mbuf ** mp)3320 iflib_parse_header(iflib_txq_t txq, if_pkt_info_t pi, struct mbuf **mp)
3321 {
3322 	if_shared_ctx_t sctx = txq->ift_ctx->ifc_sctx;
3323 	struct mbuf *m;
3324 	int err;
3325 
3326 	m = *mp;
3327 	if ((sctx->isc_flags & IFLIB_NEED_SCRATCH) &&
3328 	    M_WRITABLE(m) == 0) {
3329 		if ((m = m_dup(m, M_NOWAIT)) == NULL) {
3330 			return (ENOMEM);
3331 		} else {
3332 			m_freem(*mp);
3333 			DBG_COUNTER_INC(tx_frees);
3334 			*mp = m;
3335 		}
3336 	}
3337 
3338 	/* Fills out pi->ipi_etype */
3339 	err = iflib_parse_ether_header(pi, mp, &txq->ift_pullups);
3340 	if (__predict_false(err))
3341 		return (err);
3342 	m = *mp;
3343 
3344 	switch (pi->ipi_etype) {
3345 #ifdef INET
3346 	case ETHERTYPE_IP:
3347 	{
3348 		struct mbuf *n;
3349 		struct ip *ip = NULL;
3350 		struct tcphdr *th = NULL;
3351 		int minthlen;
3352 
3353 		minthlen = min(m->m_pkthdr.len, pi->ipi_ehdrlen + sizeof(*ip) + sizeof(*th));
3354 		if (__predict_false(m->m_len < minthlen)) {
3355 			/*
3356 			 * if this code bloat is causing too much of a hit
3357 			 * move it to a separate function and mark it noinline
3358 			 */
3359 			if (m->m_len == pi->ipi_ehdrlen) {
3360 				n = m->m_next;
3361 				MPASS(n);
3362 				if (n->m_len >= sizeof(*ip))  {
3363 					ip = (struct ip *)n->m_data;
3364 					if (n->m_len >= (ip->ip_hl << 2) + sizeof(*th))
3365 						th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
3366 				} else {
3367 					txq->ift_pullups++;
3368 					if (__predict_false((m = m_pullup(m, minthlen)) == NULL))
3369 						return (ENOMEM);
3370 					ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3371 				}
3372 			} else {
3373 				txq->ift_pullups++;
3374 				if (__predict_false((m = m_pullup(m, minthlen)) == NULL))
3375 					return (ENOMEM);
3376 				ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3377 				if (m->m_len >= (ip->ip_hl << 2) + sizeof(*th))
3378 					th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
3379 			}
3380 		} else {
3381 			ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3382 			if (m->m_len >= (ip->ip_hl << 2) + sizeof(*th))
3383 				th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
3384 		}
3385 		pi->ipi_ip_hlen = ip->ip_hl << 2;
3386 		pi->ipi_ipproto = ip->ip_p;
3387 		pi->ipi_ip_tos = ip->ip_tos;
3388 		pi->ipi_flags |= IPI_TX_IPV4;
3389 
3390 		/* TCP checksum offload may require TCP header length */
3391 		if (IS_TX_OFFLOAD4(pi)) {
3392 			if (__predict_true(pi->ipi_ipproto == IPPROTO_TCP)) {
3393 				if (__predict_false(th == NULL)) {
3394 					txq->ift_pullups++;
3395 					if (__predict_false((m = m_pullup(m, (ip->ip_hl << 2) + sizeof(*th))) == NULL))
3396 						return (ENOMEM);
3397 					th = (struct tcphdr *)((caddr_t)ip + pi->ipi_ip_hlen);
3398 				}
3399 				pi->ipi_tcp_hflags = th->th_flags;
3400 				pi->ipi_tcp_hlen = th->th_off << 2;
3401 				pi->ipi_tcp_seq = th->th_seq;
3402 			}
3403 			if (IS_TSO4(pi)) {
3404 				if (__predict_false(ip->ip_p != IPPROTO_TCP))
3405 					return (ENXIO);
3406 				/*
3407 				 * TSO always requires hardware checksum offload.
3408 				 */
3409 				pi->ipi_csum_flags |= (CSUM_IP_TCP | CSUM_IP);
3410 				th->th_sum = in_pseudo(ip->ip_src.s_addr,
3411 						       ip->ip_dst.s_addr, htons(IPPROTO_TCP));
3412 				pi->ipi_tso_segsz = m->m_pkthdr.tso_segsz;
3413 				if (sctx->isc_flags & IFLIB_TSO_INIT_IP) {
3414 					ip->ip_sum = 0;
3415 					ip->ip_len = htons(pi->ipi_ip_hlen + pi->ipi_tcp_hlen + pi->ipi_tso_segsz);
3416 				}
3417 			}
3418 		}
3419 		if ((sctx->isc_flags & IFLIB_NEED_ZERO_CSUM) && (pi->ipi_csum_flags & CSUM_IP))
3420 			ip->ip_sum = 0;
3421 
3422 		break;
3423 	}
3424 #endif
3425 #ifdef INET6
3426 	case ETHERTYPE_IPV6:
3427 	{
3428 		struct ip6_hdr *ip6 = (struct ip6_hdr *)(m->m_data + pi->ipi_ehdrlen);
3429 		struct tcphdr *th;
3430 		pi->ipi_ip_hlen = sizeof(struct ip6_hdr);
3431 
3432 		if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) {
3433 			txq->ift_pullups++;
3434 			if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) == NULL))
3435 				return (ENOMEM);
3436 		}
3437 		th = (struct tcphdr *)((caddr_t)ip6 + pi->ipi_ip_hlen);
3438 
3439 		/* XXX-BZ this will go badly in case of ext hdrs. */
3440 		pi->ipi_ipproto = ip6->ip6_nxt;
3441 		pi->ipi_ip_tos = IPV6_TRAFFIC_CLASS(ip6);
3442 		pi->ipi_flags |= IPI_TX_IPV6;
3443 
3444 		/* TCP checksum offload may require TCP header length */
3445 		if (IS_TX_OFFLOAD6(pi)) {
3446 			if (pi->ipi_ipproto == IPPROTO_TCP) {
3447 				if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr) + sizeof(struct tcphdr))) {
3448 					txq->ift_pullups++;
3449 					if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr) + sizeof(struct tcphdr))) == NULL))
3450 						return (ENOMEM);
3451 				}
3452 				pi->ipi_tcp_hflags = th->th_flags;
3453 				pi->ipi_tcp_hlen = th->th_off << 2;
3454 				pi->ipi_tcp_seq = th->th_seq;
3455 			}
3456 			if (IS_TSO6(pi)) {
3457 				if (__predict_false(ip6->ip6_nxt != IPPROTO_TCP))
3458 					return (ENXIO);
3459 				/*
3460 				 * TSO always requires hardware checksum offload.
3461 				 */
3462 				pi->ipi_csum_flags |= CSUM_IP6_TCP;
3463 				th->th_sum = in6_cksum_pseudo(ip6, 0, IPPROTO_TCP, 0);
3464 				pi->ipi_tso_segsz = m->m_pkthdr.tso_segsz;
3465 			}
3466 		}
3467 		break;
3468 	}
3469 #endif
3470 	default:
3471 		pi->ipi_csum_flags &= ~CSUM_OFFLOAD;
3472 		pi->ipi_ip_hlen = 0;
3473 		break;
3474 	}
3475 	*mp = m;
3476 
3477 	return (0);
3478 }
3479 
3480 /*
3481  * If dodgy hardware rejects the scatter gather chain we've handed it
3482  * we'll need to remove the mbuf chain from ifsg_m[] before we can add the
3483  * m_defrag'd mbufs
3484  */
3485 static __noinline struct mbuf *
iflib_remove_mbuf(iflib_txq_t txq)3486 iflib_remove_mbuf(iflib_txq_t txq)
3487 {
3488 	int ntxd, pidx;
3489 	struct mbuf *m, **ifsd_m;
3490 
3491 	ifsd_m = txq->ift_sds.ifsd_m;
3492 	ntxd = txq->ift_size;
3493 	pidx = txq->ift_pidx & (ntxd - 1);
3494 	ifsd_m = txq->ift_sds.ifsd_m;
3495 	m = ifsd_m[pidx];
3496 	ifsd_m[pidx] = NULL;
3497 	bus_dmamap_unload(txq->ift_buf_tag, txq->ift_sds.ifsd_map[pidx]);
3498 	if (txq->ift_sds.ifsd_tso_map != NULL)
3499 		bus_dmamap_unload(txq->ift_tso_buf_tag,
3500 		    txq->ift_sds.ifsd_tso_map[pidx]);
3501 #if MEMORY_LOGGING
3502 	txq->ift_dequeued++;
3503 #endif
3504 	return (m);
3505 }
3506 
3507 static inline caddr_t
calc_next_txd(iflib_txq_t txq,int cidx,uint8_t qid)3508 calc_next_txd(iflib_txq_t txq, int cidx, uint8_t qid)
3509 {
3510 	qidx_t size;
3511 	int ntxd;
3512 	caddr_t start, end, cur, next;
3513 
3514 	ntxd = txq->ift_size;
3515 	size = txq->ift_txd_size[qid];
3516 	start = txq->ift_ifdi[qid].idi_vaddr;
3517 
3518 	if (__predict_false(size == 0))
3519 		return (start);
3520 	cur = start + size * cidx;
3521 	end = start + size * ntxd;
3522 	next = CACHE_PTR_NEXT(cur);
3523 	return (next < end ? next : start);
3524 }
3525 
3526 /*
3527  * Pad an mbuf to ensure a minimum ethernet frame size.
3528  * min_frame_size is the frame size (less CRC) to pad the mbuf to
3529  */
3530 static __noinline int
iflib_ether_pad(device_t dev,struct mbuf ** m_head,uint16_t min_frame_size)3531 iflib_ether_pad(device_t dev, struct mbuf **m_head, uint16_t min_frame_size)
3532 {
3533 	/*
3534 	 * 18 is enough bytes to pad an ARP packet to 46 bytes, and
3535 	 * and ARP message is the smallest common payload I can think of
3536 	 */
3537 	static char pad[18];	/* just zeros */
3538 	int n;
3539 	struct mbuf *new_head;
3540 
3541 	if (!M_WRITABLE(*m_head)) {
3542 		new_head = m_dup(*m_head, M_NOWAIT);
3543 		if (new_head == NULL) {
3544 			m_freem(*m_head);
3545 			device_printf(dev, "cannot pad short frame, m_dup() failed");
3546 			DBG_COUNTER_INC(encap_pad_mbuf_fail);
3547 			DBG_COUNTER_INC(tx_frees);
3548 			return (ENOMEM);
3549 		}
3550 		m_freem(*m_head);
3551 		*m_head = new_head;
3552 	}
3553 
3554 	for (n = min_frame_size - (*m_head)->m_pkthdr.len;
3555 	     n > 0; n -= sizeof(pad))
3556 		if (!m_append(*m_head, min(n, sizeof(pad)), pad))
3557 			break;
3558 
3559 	if (n > 0) {
3560 		m_freem(*m_head);
3561 		device_printf(dev, "cannot pad short frame\n");
3562 		DBG_COUNTER_INC(encap_pad_mbuf_fail);
3563 		DBG_COUNTER_INC(tx_frees);
3564 		return (ENOBUFS);
3565 	}
3566 
3567 	return (0);
3568 }
3569 
3570 static int
iflib_encap(iflib_txq_t txq,struct mbuf ** m_headp)3571 iflib_encap(iflib_txq_t txq, struct mbuf **m_headp)
3572 {
3573 	if_ctx_t		ctx;
3574 	if_shared_ctx_t		sctx;
3575 	if_softc_ctx_t		scctx;
3576 	bus_dma_tag_t		buf_tag;
3577 	bus_dma_segment_t	*segs;
3578 	struct mbuf		*m_head, **ifsd_m;
3579 	void			*next_txd;
3580 	bus_dmamap_t		map;
3581 	struct if_pkt_info	pi;
3582 	int remap = 0;
3583 	int err, nsegs, ndesc, max_segs, pidx, cidx, next, ntxd;
3584 
3585 	ctx = txq->ift_ctx;
3586 	sctx = ctx->ifc_sctx;
3587 	scctx = &ctx->ifc_softc_ctx;
3588 	segs = txq->ift_segs;
3589 	ntxd = txq->ift_size;
3590 	m_head = *m_headp;
3591 	map = NULL;
3592 
3593 	/*
3594 	 * If we're doing TSO the next descriptor to clean may be quite far ahead
3595 	 */
3596 	cidx = txq->ift_cidx;
3597 	pidx = txq->ift_pidx;
3598 	if (ctx->ifc_flags & IFC_PREFETCH) {
3599 		next = (cidx + CACHE_PTR_INCREMENT) & (ntxd - 1);
3600 		if (!(ctx->ifc_flags & IFLIB_HAS_TXCQ)) {
3601 			next_txd = calc_next_txd(txq, cidx, 0);
3602 			prefetch(next_txd);
3603 		}
3604 
3605 		/* prefetch the next cache line of mbuf pointers and flags */
3606 		prefetch(&txq->ift_sds.ifsd_m[next]);
3607 		prefetch(&txq->ift_sds.ifsd_map[next]);
3608 		next = (cidx + CACHE_LINE_SIZE) & (ntxd - 1);
3609 	}
3610 	map = txq->ift_sds.ifsd_map[pidx];
3611 	ifsd_m = txq->ift_sds.ifsd_m;
3612 
3613 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
3614 		buf_tag = txq->ift_tso_buf_tag;
3615 		max_segs = scctx->isc_tx_tso_segments_max;
3616 		map = txq->ift_sds.ifsd_tso_map[pidx];
3617 		MPASS(buf_tag != NULL);
3618 		MPASS(max_segs > 0);
3619 	} else {
3620 		buf_tag = txq->ift_buf_tag;
3621 		max_segs = scctx->isc_tx_nsegments;
3622 		map = txq->ift_sds.ifsd_map[pidx];
3623 	}
3624 	if ((sctx->isc_flags & IFLIB_NEED_ETHER_PAD) &&
3625 	    __predict_false(m_head->m_pkthdr.len < scctx->isc_min_frame_size)) {
3626 		err = iflib_ether_pad(ctx->ifc_dev, m_headp, scctx->isc_min_frame_size);
3627 		if (err) {
3628 			DBG_COUNTER_INC(encap_txd_encap_fail);
3629 			return (err);
3630 		}
3631 	}
3632 	m_head = *m_headp;
3633 
3634 	pkt_info_zero(&pi);
3635 	pi.ipi_mflags = (m_head->m_flags & (M_VLANTAG | M_BCAST | M_MCAST));
3636 	pi.ipi_pidx = pidx;
3637 	pi.ipi_qsidx = txq->ift_id;
3638 	pi.ipi_len = m_head->m_pkthdr.len;
3639 	pi.ipi_csum_flags = m_head->m_pkthdr.csum_flags;
3640 	pi.ipi_vtag = M_HAS_VLANTAG(m_head) ? m_head->m_pkthdr.ether_vtag : 0;
3641 
3642 	/* deliberate bitwise OR to make one condition */
3643 	if (__predict_true((pi.ipi_csum_flags | pi.ipi_vtag))) {
3644 		if (__predict_false((err = iflib_parse_header(txq, &pi, m_headp)) != 0)) {
3645 			DBG_COUNTER_INC(encap_txd_encap_fail);
3646 			return (err);
3647 		}
3648 		m_head = *m_headp;
3649 	}
3650 
3651 retry:
3652 	err = bus_dmamap_load_mbuf_sg(buf_tag, map, m_head, segs, &nsegs,
3653 	    BUS_DMA_NOWAIT);
3654 defrag:
3655 	if (__predict_false(err)) {
3656 		switch (err) {
3657 		case EFBIG:
3658 			/* try collapse once and defrag once */
3659 			if (remap == 0) {
3660 				m_head = m_collapse(*m_headp, M_NOWAIT, max_segs);
3661 				/* try defrag if collapsing fails */
3662 				if (m_head == NULL)
3663 					remap++;
3664 			}
3665 			if (remap == 1) {
3666 				txq->ift_mbuf_defrag++;
3667 				m_head = m_defrag(*m_headp, M_NOWAIT);
3668 			}
3669 			/*
3670 			 * remap should never be >1 unless bus_dmamap_load_mbuf_sg
3671 			 * failed to map an mbuf that was run through m_defrag
3672 			 */
3673 			MPASS(remap <= 1);
3674 			if (__predict_false(m_head == NULL || remap > 1))
3675 				goto defrag_failed;
3676 			remap++;
3677 			*m_headp = m_head;
3678 			goto retry;
3679 			break;
3680 		case ENOMEM:
3681 			txq->ift_no_tx_dma_setup++;
3682 			break;
3683 		default:
3684 			txq->ift_no_tx_dma_setup++;
3685 			m_freem(*m_headp);
3686 			DBG_COUNTER_INC(tx_frees);
3687 			*m_headp = NULL;
3688 			break;
3689 		}
3690 		txq->ift_map_failed++;
3691 		DBG_COUNTER_INC(encap_load_mbuf_fail);
3692 		DBG_COUNTER_INC(encap_txd_encap_fail);
3693 		return (err);
3694 	}
3695 	ifsd_m[pidx] = m_head;
3696 	/*
3697 	 * XXX assumes a 1 to 1 relationship between segments and
3698 	 *        descriptors - this does not hold true on all drivers, e.g.
3699 	 *        cxgb
3700 	 */
3701 	if (__predict_false(nsegs + 2 > TXQ_AVAIL(txq))) {
3702 		txq->ift_no_desc_avail++;
3703 		bus_dmamap_unload(buf_tag, map);
3704 		DBG_COUNTER_INC(encap_txq_avail_fail);
3705 		DBG_COUNTER_INC(encap_txd_encap_fail);
3706 		if ((txq->ift_task.gt_task.ta_flags & TASK_ENQUEUED) == 0)
3707 			GROUPTASK_ENQUEUE(&txq->ift_task);
3708 		return (ENOBUFS);
3709 	}
3710 	/*
3711 	 * On Intel cards we can greatly reduce the number of TX interrupts
3712 	 * we see by only setting report status on every Nth descriptor.
3713 	 * However, this also means that the driver will need to keep track
3714 	 * of the descriptors that RS was set on to check them for the DD bit.
3715 	 */
3716 	txq->ift_rs_pending += nsegs + 1;
3717 	if (txq->ift_rs_pending > TXQ_MAX_RS_DEFERRED(txq) ||
3718 	     iflib_no_tx_batch || (TXQ_AVAIL(txq) - nsegs) <= MAX_TX_DESC(ctx) + 2) {
3719 		pi.ipi_flags |= IPI_TX_INTR;
3720 		txq->ift_rs_pending = 0;
3721 	}
3722 
3723 	pi.ipi_segs = segs;
3724 	pi.ipi_nsegs = nsegs;
3725 
3726 	MPASS(pidx >= 0 && pidx < txq->ift_size);
3727 #ifdef PKT_DEBUG
3728 	print_pkt(&pi);
3729 #endif
3730 	if ((err = ctx->isc_txd_encap(ctx->ifc_softc, &pi)) == 0) {
3731 		bus_dmamap_sync(buf_tag, map, BUS_DMASYNC_PREWRITE);
3732 		DBG_COUNTER_INC(tx_encap);
3733 		MPASS(pi.ipi_new_pidx < txq->ift_size);
3734 
3735 		ndesc = pi.ipi_new_pidx - pi.ipi_pidx;
3736 		if (pi.ipi_new_pidx < pi.ipi_pidx) {
3737 			ndesc += txq->ift_size;
3738 			txq->ift_gen = 1;
3739 		}
3740 		/*
3741 		 * drivers can need as many as
3742 		 * two sentinels
3743 		 */
3744 		MPASS(ndesc <= pi.ipi_nsegs + 2);
3745 		MPASS(pi.ipi_new_pidx != pidx);
3746 		MPASS(ndesc > 0);
3747 		txq->ift_in_use += ndesc;
3748 		txq->ift_db_pending += ndesc;
3749 
3750 		/*
3751 		 * We update the last software descriptor again here because there may
3752 		 * be a sentinel and/or there may be more mbufs than segments
3753 		 */
3754 		txq->ift_pidx = pi.ipi_new_pidx;
3755 		txq->ift_npending += pi.ipi_ndescs;
3756 	} else {
3757 		*m_headp = m_head = iflib_remove_mbuf(txq);
3758 		if (err == EFBIG) {
3759 			txq->ift_txd_encap_efbig++;
3760 			if (remap < 2) {
3761 				remap = 1;
3762 				goto defrag;
3763 			}
3764 		}
3765 		goto defrag_failed;
3766 	}
3767 	/*
3768 	 * err can't possibly be non-zero here, so we don't neet to test it
3769 	 * to see if we need to DBG_COUNTER_INC(encap_txd_encap_fail).
3770 	 */
3771 	return (err);
3772 
3773 defrag_failed:
3774 	txq->ift_mbuf_defrag_failed++;
3775 	txq->ift_map_failed++;
3776 	m_freem(*m_headp);
3777 	DBG_COUNTER_INC(tx_frees);
3778 	*m_headp = NULL;
3779 	DBG_COUNTER_INC(encap_txd_encap_fail);
3780 	return (ENOMEM);
3781 }
3782 
3783 static void
iflib_tx_desc_free(iflib_txq_t txq,int n)3784 iflib_tx_desc_free(iflib_txq_t txq, int n)
3785 {
3786 	uint32_t qsize, cidx, mask, gen;
3787 	struct mbuf *m, **ifsd_m;
3788 	bool do_prefetch;
3789 
3790 	cidx = txq->ift_cidx;
3791 	gen = txq->ift_gen;
3792 	qsize = txq->ift_size;
3793 	mask = qsize - 1;
3794 	ifsd_m = txq->ift_sds.ifsd_m;
3795 	do_prefetch = (txq->ift_ctx->ifc_flags & IFC_PREFETCH);
3796 
3797 	while (n-- > 0) {
3798 		if (do_prefetch) {
3799 			prefetch(ifsd_m[(cidx + 3) & mask]);
3800 			prefetch(ifsd_m[(cidx + 4) & mask]);
3801 		}
3802 		if ((m = ifsd_m[cidx]) != NULL) {
3803 			prefetch(&ifsd_m[(cidx + CACHE_PTR_INCREMENT) & mask]);
3804 			if (m->m_pkthdr.csum_flags & CSUM_TSO) {
3805 				bus_dmamap_sync(txq->ift_tso_buf_tag,
3806 				    txq->ift_sds.ifsd_tso_map[cidx],
3807 				    BUS_DMASYNC_POSTWRITE);
3808 				bus_dmamap_unload(txq->ift_tso_buf_tag,
3809 				    txq->ift_sds.ifsd_tso_map[cidx]);
3810 			} else {
3811 				bus_dmamap_sync(txq->ift_buf_tag,
3812 				    txq->ift_sds.ifsd_map[cidx],
3813 				    BUS_DMASYNC_POSTWRITE);
3814 				bus_dmamap_unload(txq->ift_buf_tag,
3815 				    txq->ift_sds.ifsd_map[cidx]);
3816 			}
3817 			/* XXX we don't support any drivers that batch packets yet */
3818 			MPASS(m->m_nextpkt == NULL);
3819 			m_freem(m);
3820 			ifsd_m[cidx] = NULL;
3821 #if MEMORY_LOGGING
3822 			txq->ift_dequeued++;
3823 #endif
3824 			DBG_COUNTER_INC(tx_frees);
3825 		}
3826 		if (__predict_false(++cidx == qsize)) {
3827 			cidx = 0;
3828 			gen = 0;
3829 		}
3830 	}
3831 	txq->ift_cidx = cidx;
3832 	txq->ift_gen = gen;
3833 }
3834 
3835 static __inline int
iflib_completed_tx_reclaim(iflib_txq_t txq,int thresh)3836 iflib_completed_tx_reclaim(iflib_txq_t txq, int thresh)
3837 {
3838 	int reclaim;
3839 	if_ctx_t ctx = txq->ift_ctx;
3840 
3841 	KASSERT(thresh >= 0, ("invalid threshold to reclaim"));
3842 	MPASS(thresh /*+ MAX_TX_DESC(txq->ift_ctx) */ < txq->ift_size);
3843 
3844 	/*
3845 	 * Need a rate-limiting check so that this isn't called every time
3846 	 */
3847 	iflib_tx_credits_update(ctx, txq);
3848 	reclaim = DESC_RECLAIMABLE(txq);
3849 
3850 	if (reclaim <= thresh /* + MAX_TX_DESC(txq->ift_ctx) */) {
3851 #ifdef INVARIANTS
3852 		if (iflib_verbose_debug) {
3853 			printf("%s processed=%ju cleaned=%ju tx_nsegments=%d reclaim=%d thresh=%d\n", __func__,
3854 			       txq->ift_processed, txq->ift_cleaned, txq->ift_ctx->ifc_softc_ctx.isc_tx_nsegments,
3855 			       reclaim, thresh);
3856 		}
3857 #endif
3858 		return (0);
3859 	}
3860 	iflib_tx_desc_free(txq, reclaim);
3861 	txq->ift_cleaned += reclaim;
3862 	txq->ift_in_use -= reclaim;
3863 
3864 	return (reclaim);
3865 }
3866 
3867 static struct mbuf **
_ring_peek_one(struct ifmp_ring * r,int cidx,int offset,int remaining)3868 _ring_peek_one(struct ifmp_ring *r, int cidx, int offset, int remaining)
3869 {
3870 	int next, size;
3871 	struct mbuf **items;
3872 
3873 	size = r->size;
3874 	next = (cidx + CACHE_PTR_INCREMENT) & (size - 1);
3875 	items = __DEVOLATILE(struct mbuf **, &r->items[0]);
3876 
3877 	prefetch(items[(cidx + offset) & (size - 1)]);
3878 	if (remaining > 1) {
3879 		prefetch2cachelines(&items[next]);
3880 		prefetch2cachelines(items[(cidx + offset + 1) & (size - 1)]);
3881 		prefetch2cachelines(items[(cidx + offset + 2) & (size - 1)]);
3882 		prefetch2cachelines(items[(cidx + offset + 3) & (size - 1)]);
3883 	}
3884 	return (__DEVOLATILE(struct mbuf **, &r->items[(cidx + offset) & (size - 1)]));
3885 }
3886 
3887 static void
iflib_txq_check_drain(iflib_txq_t txq,int budget)3888 iflib_txq_check_drain(iflib_txq_t txq, int budget)
3889 {
3890 
3891 	ifmp_ring_check_drainage(txq->ift_br, budget);
3892 }
3893 
3894 static uint32_t
iflib_txq_can_drain(struct ifmp_ring * r)3895 iflib_txq_can_drain(struct ifmp_ring *r)
3896 {
3897 	iflib_txq_t txq = r->cookie;
3898 	if_ctx_t ctx = txq->ift_ctx;
3899 
3900 	if (TXQ_AVAIL(txq) > MAX_TX_DESC(ctx) + 2)
3901 		return (1);
3902 	bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
3903 	    BUS_DMASYNC_POSTREAD);
3904 	return (ctx->isc_txd_credits_update(ctx->ifc_softc, txq->ift_id,
3905 	    false));
3906 }
3907 
3908 static uint32_t
iflib_txq_drain(struct ifmp_ring * r,uint32_t cidx,uint32_t pidx)3909 iflib_txq_drain(struct ifmp_ring *r, uint32_t cidx, uint32_t pidx)
3910 {
3911 	iflib_txq_t txq = r->cookie;
3912 	if_ctx_t ctx = txq->ift_ctx;
3913 	if_t ifp = ctx->ifc_ifp;
3914 	struct mbuf *m, **mp;
3915 	int avail, bytes_sent, skipped, count, err, i;
3916 	int mcast_sent, pkt_sent, reclaimed;
3917 	bool do_prefetch, rang, ring;
3918 
3919 	if (__predict_false(!(if_getdrvflags(ifp) & IFF_DRV_RUNNING) ||
3920 			    !LINK_ACTIVE(ctx))) {
3921 		DBG_COUNTER_INC(txq_drain_notready);
3922 		return (0);
3923 	}
3924 	reclaimed = iflib_completed_tx_reclaim(txq, RECLAIM_THRESH(ctx));
3925 	rang = iflib_txd_db_check(txq, reclaimed && txq->ift_db_pending);
3926 	avail = IDXDIFF(pidx, cidx, r->size);
3927 
3928 	if (__predict_false(ctx->ifc_flags & IFC_QFLUSH)) {
3929 		/*
3930 		 * The driver is unloading so we need to free all pending packets.
3931 		 */
3932 		DBG_COUNTER_INC(txq_drain_flushing);
3933 		for (i = 0; i < avail; i++) {
3934 			if (__predict_true(r->items[(cidx + i) & (r->size - 1)] != (void *)txq))
3935 				m_freem(r->items[(cidx + i) & (r->size - 1)]);
3936 			r->items[(cidx + i) & (r->size - 1)] = NULL;
3937 		}
3938 		return (avail);
3939 	}
3940 
3941 	if (__predict_false(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_OACTIVE)) {
3942 		txq->ift_qstatus = IFLIB_QUEUE_IDLE;
3943 		CALLOUT_LOCK(txq);
3944 		callout_stop(&txq->ift_timer);
3945 		CALLOUT_UNLOCK(txq);
3946 		DBG_COUNTER_INC(txq_drain_oactive);
3947 		return (0);
3948 	}
3949 
3950 	/*
3951 	 * If we've reclaimed any packets this queue cannot be hung.
3952 	 */
3953 	if (reclaimed)
3954 		txq->ift_qstatus = IFLIB_QUEUE_IDLE;
3955 	skipped = mcast_sent = bytes_sent = pkt_sent = 0;
3956 	count = MIN(avail, TX_BATCH_SIZE);
3957 #ifdef INVARIANTS
3958 	if (iflib_verbose_debug)
3959 		printf("%s avail=%d ifc_flags=%x txq_avail=%d ", __func__,
3960 		       avail, ctx->ifc_flags, TXQ_AVAIL(txq));
3961 #endif
3962 	do_prefetch = (ctx->ifc_flags & IFC_PREFETCH);
3963 	err = 0;
3964 	for (i = 0; i < count && TXQ_AVAIL(txq) >= MAX_TX_DESC(ctx) + 2; i++) {
3965 		int rem = do_prefetch ? count - i : 0;
3966 
3967 		mp = _ring_peek_one(r, cidx, i, rem);
3968 		MPASS(mp != NULL && *mp != NULL);
3969 
3970 		/*
3971 		 * Completion interrupts will use the address of the txq
3972 		 * as a sentinel to enqueue _something_ in order to acquire
3973 		 * the lock on the mp_ring (there's no direct lock call).
3974 		 * We obviously whave to check for these sentinel cases
3975 		 * and skip them.
3976 		 */
3977 		if (__predict_false(*mp == (struct mbuf *)txq)) {
3978 			skipped++;
3979 			continue;
3980 		}
3981 		err = iflib_encap(txq, mp);
3982 		if (__predict_false(err)) {
3983 			/* no room - bail out */
3984 			if (err == ENOBUFS)
3985 				break;
3986 			skipped++;
3987 			/* we can't send this packet - skip it */
3988 			continue;
3989 		}
3990 		pkt_sent++;
3991 		m = *mp;
3992 		DBG_COUNTER_INC(tx_sent);
3993 		bytes_sent += m->m_pkthdr.len;
3994 		mcast_sent += !!(m->m_flags & M_MCAST);
3995 
3996 		if (__predict_false(!(ifp->if_drv_flags & IFF_DRV_RUNNING)))
3997 			break;
3998 		ETHER_BPF_MTAP(ifp, m);
3999 		rang = iflib_txd_db_check(txq, false);
4000 	}
4001 
4002 	/* deliberate use of bitwise or to avoid gratuitous short-circuit */
4003 	ring = rang ? false  : (iflib_min_tx_latency | err);
4004 	iflib_txd_db_check(txq, ring);
4005 	if_inc_counter(ifp, IFCOUNTER_OBYTES, bytes_sent);
4006 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, pkt_sent);
4007 	if (mcast_sent)
4008 		if_inc_counter(ifp, IFCOUNTER_OMCASTS, mcast_sent);
4009 #ifdef INVARIANTS
4010 	if (iflib_verbose_debug)
4011 		printf("consumed=%d\n", skipped + pkt_sent);
4012 #endif
4013 	return (skipped + pkt_sent);
4014 }
4015 
4016 static uint32_t
iflib_txq_drain_always(struct ifmp_ring * r)4017 iflib_txq_drain_always(struct ifmp_ring *r)
4018 {
4019 	return (1);
4020 }
4021 
4022 static uint32_t
iflib_txq_drain_free(struct ifmp_ring * r,uint32_t cidx,uint32_t pidx)4023 iflib_txq_drain_free(struct ifmp_ring *r, uint32_t cidx, uint32_t pidx)
4024 {
4025 	int i, avail;
4026 	struct mbuf **mp;
4027 	iflib_txq_t txq;
4028 
4029 	txq = r->cookie;
4030 
4031 	txq->ift_qstatus = IFLIB_QUEUE_IDLE;
4032 	CALLOUT_LOCK(txq);
4033 	callout_stop(&txq->ift_timer);
4034 	CALLOUT_UNLOCK(txq);
4035 
4036 	avail = IDXDIFF(pidx, cidx, r->size);
4037 	for (i = 0; i < avail; i++) {
4038 		mp = _ring_peek_one(r, cidx, i, avail - i);
4039 		if (__predict_false(*mp == (struct mbuf *)txq))
4040 			continue;
4041 		m_freem(*mp);
4042 		DBG_COUNTER_INC(tx_frees);
4043 	}
4044 	MPASS(ifmp_ring_is_stalled(r) == 0);
4045 	return (avail);
4046 }
4047 
4048 static void
iflib_ifmp_purge(iflib_txq_t txq)4049 iflib_ifmp_purge(iflib_txq_t txq)
4050 {
4051 	struct ifmp_ring *r;
4052 
4053 	r = txq->ift_br;
4054 	r->drain = iflib_txq_drain_free;
4055 	r->can_drain = iflib_txq_drain_always;
4056 
4057 	ifmp_ring_check_drainage(r, r->size);
4058 
4059 	r->drain = iflib_txq_drain;
4060 	r->can_drain = iflib_txq_can_drain;
4061 }
4062 
4063 static void
_task_fn_tx(void * context)4064 _task_fn_tx(void *context)
4065 {
4066 	iflib_txq_t txq = context;
4067 	if_ctx_t ctx = txq->ift_ctx;
4068 	if_t ifp = ctx->ifc_ifp;
4069 	int abdicate = ctx->ifc_sysctl_tx_abdicate;
4070 
4071 #ifdef IFLIB_DIAGNOSTICS
4072 	txq->ift_cpu_exec_count[curcpu]++;
4073 #endif
4074 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
4075 		return;
4076 #ifdef DEV_NETMAP
4077 	if ((if_getcapenable(ifp) & IFCAP_NETMAP) &&
4078 	    netmap_tx_irq(ifp, txq->ift_id))
4079 		goto skip_ifmp;
4080 #endif
4081 #ifdef ALTQ
4082 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
4083 		iflib_altq_if_start(ifp);
4084 #endif
4085 	if (txq->ift_db_pending)
4086 		ifmp_ring_enqueue(txq->ift_br, (void **)&txq, 1, TX_BATCH_SIZE, abdicate);
4087 	else if (!abdicate)
4088 		ifmp_ring_check_drainage(txq->ift_br, TX_BATCH_SIZE);
4089 	/*
4090 	 * When abdicating, we always need to check drainage, not just when we don't enqueue
4091 	 */
4092 	if (abdicate)
4093 		ifmp_ring_check_drainage(txq->ift_br, TX_BATCH_SIZE);
4094 #ifdef DEV_NETMAP
4095 skip_ifmp:
4096 #endif
4097 	if (ctx->ifc_flags & IFC_LEGACY)
4098 		IFDI_INTR_ENABLE(ctx);
4099 	else
4100 		IFDI_TX_QUEUE_INTR_ENABLE(ctx, txq->ift_id);
4101 }
4102 
4103 static void
_task_fn_rx(void * context)4104 _task_fn_rx(void *context)
4105 {
4106 	iflib_rxq_t rxq = context;
4107 	if_ctx_t ctx = rxq->ifr_ctx;
4108 	uint8_t more;
4109 	uint16_t budget;
4110 #ifdef DEV_NETMAP
4111 	u_int work = 0;
4112 	int nmirq;
4113 #endif
4114 
4115 #ifdef IFLIB_DIAGNOSTICS
4116 	rxq->ifr_cpu_exec_count[curcpu]++;
4117 #endif
4118 	DBG_COUNTER_INC(task_fn_rxs);
4119 	if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
4120 		return;
4121 #ifdef DEV_NETMAP
4122 	nmirq = netmap_rx_irq(ctx->ifc_ifp, rxq->ifr_id, &work);
4123 	if (nmirq != NM_IRQ_PASS) {
4124 		more = (nmirq == NM_IRQ_RESCHED) ? IFLIB_RXEOF_MORE : 0;
4125 		goto skip_rxeof;
4126 	}
4127 #endif
4128 	budget = ctx->ifc_sysctl_rx_budget;
4129 	if (budget == 0)
4130 		budget = 16;	/* XXX */
4131 	more = iflib_rxeof(rxq, budget);
4132 #ifdef DEV_NETMAP
4133 skip_rxeof:
4134 #endif
4135 	if ((more & IFLIB_RXEOF_MORE) == 0) {
4136 		if (ctx->ifc_flags & IFC_LEGACY)
4137 			IFDI_INTR_ENABLE(ctx);
4138 		else
4139 			IFDI_RX_QUEUE_INTR_ENABLE(ctx, rxq->ifr_id);
4140 		DBG_COUNTER_INC(rx_intr_enables);
4141 	}
4142 	if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
4143 		return;
4144 
4145 	if (more & IFLIB_RXEOF_MORE)
4146 		GROUPTASK_ENQUEUE(&rxq->ifr_task);
4147 	else if (more & IFLIB_RXEOF_EMPTY)
4148 		callout_reset_curcpu(&rxq->ifr_watchdog, 1, &_task_fn_rx_watchdog, rxq);
4149 }
4150 
4151 static void
_task_fn_admin(void * context)4152 _task_fn_admin(void *context)
4153 {
4154 	if_ctx_t ctx = context;
4155 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
4156 	iflib_txq_t txq;
4157 	int i;
4158 	bool oactive, running, do_reset, do_watchdog, in_detach;
4159 
4160 	STATE_LOCK(ctx);
4161 	running = (if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING);
4162 	oactive = (if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_OACTIVE);
4163 	do_reset = (ctx->ifc_flags & IFC_DO_RESET);
4164 	do_watchdog = (ctx->ifc_flags & IFC_DO_WATCHDOG);
4165 	in_detach = (ctx->ifc_flags & IFC_IN_DETACH);
4166 	ctx->ifc_flags &= ~(IFC_DO_RESET | IFC_DO_WATCHDOG);
4167 	STATE_UNLOCK(ctx);
4168 
4169 	if ((!running && !oactive) && !(ctx->ifc_sctx->isc_flags & IFLIB_ADMIN_ALWAYS_RUN))
4170 		return;
4171 	if (in_detach)
4172 		return;
4173 
4174 	CTX_LOCK(ctx);
4175 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++) {
4176 		CALLOUT_LOCK(txq);
4177 		callout_stop(&txq->ift_timer);
4178 		CALLOUT_UNLOCK(txq);
4179 	}
4180 	if (do_watchdog) {
4181 		ctx->ifc_watchdog_events++;
4182 		IFDI_WATCHDOG_RESET(ctx);
4183 	}
4184 	IFDI_UPDATE_ADMIN_STATUS(ctx);
4185 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++) {
4186 		callout_reset_on(&txq->ift_timer, iflib_timer_default, iflib_timer, txq,
4187 		    txq->ift_timer.c_cpu);
4188 	}
4189 	IFDI_LINK_INTR_ENABLE(ctx);
4190 	if (do_reset)
4191 		iflib_if_init_locked(ctx);
4192 	CTX_UNLOCK(ctx);
4193 
4194 	if (LINK_ACTIVE(ctx) == 0)
4195 		return;
4196 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++)
4197 		iflib_txq_check_drain(txq, IFLIB_RESTART_BUDGET);
4198 }
4199 
4200 static void
_task_fn_iov(void * context)4201 _task_fn_iov(void *context)
4202 {
4203 	if_ctx_t ctx = context;
4204 
4205 	if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING) &&
4206 	    !(ctx->ifc_sctx->isc_flags & IFLIB_ADMIN_ALWAYS_RUN))
4207 		return;
4208 
4209 	CTX_LOCK(ctx);
4210 	IFDI_VFLR_HANDLE(ctx);
4211 	CTX_UNLOCK(ctx);
4212 }
4213 
4214 static int
iflib_sysctl_int_delay(SYSCTL_HANDLER_ARGS)4215 iflib_sysctl_int_delay(SYSCTL_HANDLER_ARGS)
4216 {
4217 	int err;
4218 	if_int_delay_info_t info;
4219 	if_ctx_t ctx;
4220 
4221 	info = (if_int_delay_info_t)arg1;
4222 	ctx = info->iidi_ctx;
4223 	info->iidi_req = req;
4224 	info->iidi_oidp = oidp;
4225 	CTX_LOCK(ctx);
4226 	err = IFDI_SYSCTL_INT_DELAY(ctx, info);
4227 	CTX_UNLOCK(ctx);
4228 	return (err);
4229 }
4230 
4231 /*********************************************************************
4232  *
4233  *  IFNET FUNCTIONS
4234  *
4235  **********************************************************************/
4236 
4237 static void
iflib_if_init_locked(if_ctx_t ctx)4238 iflib_if_init_locked(if_ctx_t ctx)
4239 {
4240 	iflib_stop(ctx);
4241 	iflib_init_locked(ctx);
4242 }
4243 
4244 static void
iflib_if_init(void * arg)4245 iflib_if_init(void *arg)
4246 {
4247 	if_ctx_t ctx = arg;
4248 
4249 	CTX_LOCK(ctx);
4250 	iflib_if_init_locked(ctx);
4251 	CTX_UNLOCK(ctx);
4252 }
4253 
4254 static int
iflib_if_transmit(if_t ifp,struct mbuf * m)4255 iflib_if_transmit(if_t ifp, struct mbuf *m)
4256 {
4257 	if_ctx_t ctx = if_getsoftc(ifp);
4258 	iflib_txq_t txq;
4259 	int err, qidx;
4260 	int abdicate;
4261 
4262 	if (__predict_false((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || !LINK_ACTIVE(ctx))) {
4263 		DBG_COUNTER_INC(tx_frees);
4264 		m_freem(m);
4265 		return (ENETDOWN);
4266 	}
4267 
4268 	MPASS(m->m_nextpkt == NULL);
4269 	/* ALTQ-enabled interfaces always use queue 0. */
4270 	qidx = 0;
4271 	/* Use driver-supplied queue selection method if it exists */
4272 	if (ctx->isc_txq_select_v2) {
4273 		struct if_pkt_info pi;
4274 		uint64_t early_pullups = 0;
4275 		pkt_info_zero(&pi);
4276 
4277 		err = iflib_parse_header_partial(&pi, &m, &early_pullups);
4278 		if (__predict_false(err != 0)) {
4279 			/* Assign pullups for bad pkts to default queue */
4280 			ctx->ifc_txqs[0].ift_pullups += early_pullups;
4281 			DBG_COUNTER_INC(encap_txd_encap_fail);
4282 			return (err);
4283 		}
4284 		/* Let driver make queueing decision */
4285 		qidx = ctx->isc_txq_select_v2(ctx->ifc_softc, m, &pi);
4286 		ctx->ifc_txqs[qidx].ift_pullups += early_pullups;
4287 	}
4288 	/* Backwards compatibility w/ simpler queue select */
4289 	else if (ctx->isc_txq_select)
4290 		qidx = ctx->isc_txq_select(ctx->ifc_softc, m);
4291 	/* If not, use iflib's standard method */
4292 	else if ((NTXQSETS(ctx) > 1) && M_HASHTYPE_GET(m) && !ALTQ_IS_ENABLED(&ifp->if_snd))
4293 		qidx = QIDX(ctx, m);
4294 
4295 	/* Set TX queue */
4296 	txq = &ctx->ifc_txqs[qidx];
4297 
4298 #ifdef DRIVER_BACKPRESSURE
4299 	if (txq->ift_closed) {
4300 		while (m != NULL) {
4301 			next = m->m_nextpkt;
4302 			m->m_nextpkt = NULL;
4303 			m_freem(m);
4304 			DBG_COUNTER_INC(tx_frees);
4305 			m = next;
4306 		}
4307 		return (ENOBUFS);
4308 	}
4309 #endif
4310 #ifdef notyet
4311 	qidx = count = 0;
4312 	mp = marr;
4313 	next = m;
4314 	do {
4315 		count++;
4316 		next = next->m_nextpkt;
4317 	} while (next != NULL);
4318 
4319 	if (count > nitems(marr))
4320 		if ((mp = malloc(count * sizeof(struct mbuf *), M_IFLIB, M_NOWAIT)) == NULL) {
4321 			/* XXX check nextpkt */
4322 			m_freem(m);
4323 			/* XXX simplify for now */
4324 			DBG_COUNTER_INC(tx_frees);
4325 			return (ENOBUFS);
4326 		}
4327 	for (next = m, i = 0; next != NULL; i++) {
4328 		mp[i] = next;
4329 		next = next->m_nextpkt;
4330 		mp[i]->m_nextpkt = NULL;
4331 	}
4332 #endif
4333 	DBG_COUNTER_INC(tx_seen);
4334 	abdicate = ctx->ifc_sysctl_tx_abdicate;
4335 
4336 	err = ifmp_ring_enqueue(txq->ift_br, (void **)&m, 1, TX_BATCH_SIZE, abdicate);
4337 
4338 	if (abdicate)
4339 		GROUPTASK_ENQUEUE(&txq->ift_task);
4340  	if (err) {
4341 		if (!abdicate)
4342 			GROUPTASK_ENQUEUE(&txq->ift_task);
4343 		/* support forthcoming later */
4344 #ifdef DRIVER_BACKPRESSURE
4345 		txq->ift_closed = TRUE;
4346 #endif
4347 		ifmp_ring_check_drainage(txq->ift_br, TX_BATCH_SIZE);
4348 		m_freem(m);
4349 		DBG_COUNTER_INC(tx_frees);
4350 	}
4351 
4352 	return (err);
4353 }
4354 
4355 #ifdef ALTQ
4356 /*
4357  * The overall approach to integrating iflib with ALTQ is to continue to use
4358  * the iflib mp_ring machinery between the ALTQ queue(s) and the hardware
4359  * ring.  Technically, when using ALTQ, queueing to an intermediate mp_ring
4360  * is redundant/unnecessary, but doing so minimizes the amount of
4361  * ALTQ-specific code required in iflib.  It is assumed that the overhead of
4362  * redundantly queueing to an intermediate mp_ring is swamped by the
4363  * performance limitations inherent in using ALTQ.
4364  *
4365  * When ALTQ support is compiled in, all iflib drivers will use a transmit
4366  * routine, iflib_altq_if_transmit(), that checks if ALTQ is enabled for the
4367  * given interface.  If ALTQ is enabled for an interface, then all
4368  * transmitted packets for that interface will be submitted to the ALTQ
4369  * subsystem via IFQ_ENQUEUE().  We don't use the legacy if_transmit()
4370  * implementation because it uses IFQ_HANDOFF(), which will duplicatively
4371  * update stats that the iflib machinery handles, and which is sensitve to
4372  * the disused IFF_DRV_OACTIVE flag.  Additionally, iflib_altq_if_start()
4373  * will be installed as the start routine for use by ALTQ facilities that
4374  * need to trigger queue drains on a scheduled basis.
4375  *
4376  */
4377 static void
iflib_altq_if_start(if_t ifp)4378 iflib_altq_if_start(if_t ifp)
4379 {
4380 	struct ifaltq *ifq = &ifp->if_snd;
4381 	struct mbuf *m;
4382 
4383 	IFQ_LOCK(ifq);
4384 	IFQ_DEQUEUE_NOLOCK(ifq, m);
4385 	while (m != NULL) {
4386 		iflib_if_transmit(ifp, m);
4387 		IFQ_DEQUEUE_NOLOCK(ifq, m);
4388 	}
4389 	IFQ_UNLOCK(ifq);
4390 }
4391 
4392 static int
iflib_altq_if_transmit(if_t ifp,struct mbuf * m)4393 iflib_altq_if_transmit(if_t ifp, struct mbuf *m)
4394 {
4395 	int err;
4396 
4397 	if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
4398 		IFQ_ENQUEUE(&ifp->if_snd, m, err);
4399 		if (err == 0)
4400 			iflib_altq_if_start(ifp);
4401 	} else
4402 		err = iflib_if_transmit(ifp, m);
4403 
4404 	return (err);
4405 }
4406 #endif /* ALTQ */
4407 
4408 static void
iflib_if_qflush(if_t ifp)4409 iflib_if_qflush(if_t ifp)
4410 {
4411 	if_ctx_t ctx = if_getsoftc(ifp);
4412 	iflib_txq_t txq = ctx->ifc_txqs;
4413 	int i;
4414 
4415 	STATE_LOCK(ctx);
4416 	ctx->ifc_flags |= IFC_QFLUSH;
4417 	STATE_UNLOCK(ctx);
4418 	for (i = 0; i < NTXQSETS(ctx); i++, txq++)
4419 		while (!(ifmp_ring_is_idle(txq->ift_br) || ifmp_ring_is_stalled(txq->ift_br)))
4420 			iflib_txq_check_drain(txq, 0);
4421 	STATE_LOCK(ctx);
4422 	ctx->ifc_flags &= ~IFC_QFLUSH;
4423 	STATE_UNLOCK(ctx);
4424 
4425 	/*
4426 	 * When ALTQ is enabled, this will also take care of purging the
4427 	 * ALTQ queue(s).
4428 	 */
4429 	if_qflush(ifp);
4430 }
4431 
4432 #define IFCAP_FLAGS (IFCAP_HWCSUM_IPV6 | IFCAP_HWCSUM | IFCAP_LRO | \
4433 		     IFCAP_TSO | IFCAP_VLAN_HWTAGGING | IFCAP_HWSTATS | \
4434 		     IFCAP_VLAN_MTU | IFCAP_VLAN_HWFILTER | \
4435 		     IFCAP_VLAN_HWTSO | IFCAP_VLAN_HWCSUM | IFCAP_MEXTPG)
4436 
4437 static int
iflib_if_ioctl(if_t ifp,u_long command,caddr_t data)4438 iflib_if_ioctl(if_t ifp, u_long command, caddr_t data)
4439 {
4440 	if_ctx_t ctx = if_getsoftc(ifp);
4441 	struct ifreq	*ifr = (struct ifreq *)data;
4442 #if defined(INET) || defined(INET6)
4443 	struct ifaddr	*ifa = (struct ifaddr *)data;
4444 #endif
4445 	bool		avoid_reset = false;
4446 	int		err = 0, reinit = 0, bits;
4447 
4448 	switch (command) {
4449 	case SIOCSIFADDR:
4450 #ifdef INET
4451 		if (ifa->ifa_addr->sa_family == AF_INET)
4452 			avoid_reset = true;
4453 #endif
4454 #ifdef INET6
4455 		if (ifa->ifa_addr->sa_family == AF_INET6)
4456 			avoid_reset = true;
4457 #endif
4458 		/*
4459 		 * Calling init results in link renegotiation,
4460 		 * so we avoid doing it when possible.
4461 		 */
4462 		if (avoid_reset) {
4463 			if_setflagbits(ifp, IFF_UP, 0);
4464 			if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
4465 				reinit = 1;
4466 #ifdef INET
4467 			if (!(if_getflags(ifp) & IFF_NOARP))
4468 				arp_ifinit(ifp, ifa);
4469 #endif
4470 		} else
4471 			err = ether_ioctl(ifp, command, data);
4472 		break;
4473 	case SIOCSIFMTU:
4474 		CTX_LOCK(ctx);
4475 		if (ifr->ifr_mtu == if_getmtu(ifp)) {
4476 			CTX_UNLOCK(ctx);
4477 			break;
4478 		}
4479 		bits = if_getdrvflags(ifp);
4480 		/* stop the driver and free any clusters before proceeding */
4481 		iflib_stop(ctx);
4482 
4483 		if ((err = IFDI_MTU_SET(ctx, ifr->ifr_mtu)) == 0) {
4484 			STATE_LOCK(ctx);
4485 			if (ifr->ifr_mtu > ctx->ifc_max_fl_buf_size)
4486 				ctx->ifc_flags |= IFC_MULTISEG;
4487 			else
4488 				ctx->ifc_flags &= ~IFC_MULTISEG;
4489 			STATE_UNLOCK(ctx);
4490 			err = if_setmtu(ifp, ifr->ifr_mtu);
4491 		}
4492 		iflib_init_locked(ctx);
4493 		STATE_LOCK(ctx);
4494 		if_setdrvflags(ifp, bits);
4495 		STATE_UNLOCK(ctx);
4496 		CTX_UNLOCK(ctx);
4497 		break;
4498 	case SIOCSIFFLAGS:
4499 		CTX_LOCK(ctx);
4500 		if (if_getflags(ifp) & IFF_UP) {
4501 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4502 				if ((if_getflags(ifp) ^ ctx->ifc_if_flags) &
4503 				    (IFF_PROMISC | IFF_ALLMULTI)) {
4504 					CTX_UNLOCK(ctx);
4505 					err = IFDI_PROMISC_SET(ctx, if_getflags(ifp));
4506 					CTX_LOCK(ctx);
4507 				}
4508 			} else
4509 				reinit = 1;
4510 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4511 			iflib_stop(ctx);
4512 		}
4513 		ctx->ifc_if_flags = if_getflags(ifp);
4514 		CTX_UNLOCK(ctx);
4515 		break;
4516 	case SIOCADDMULTI:
4517 	case SIOCDELMULTI:
4518 		if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4519 			CTX_LOCK(ctx);
4520 			IFDI_INTR_DISABLE(ctx);
4521 			IFDI_MULTI_SET(ctx);
4522 			IFDI_INTR_ENABLE(ctx);
4523 			CTX_UNLOCK(ctx);
4524 		}
4525 		break;
4526 	case SIOCSIFMEDIA:
4527 		CTX_LOCK(ctx);
4528 		IFDI_MEDIA_SET(ctx);
4529 		CTX_UNLOCK(ctx);
4530 		/* FALLTHROUGH */
4531 	case SIOCGIFMEDIA:
4532 	case SIOCGIFXMEDIA:
4533 		err = ifmedia_ioctl(ifp, ifr, ctx->ifc_mediap, command);
4534 		break;
4535 	case SIOCGI2C:
4536 	{
4537 		struct ifi2creq i2c;
4538 
4539 		err = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
4540 		if (err != 0)
4541 			break;
4542 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
4543 			err = EINVAL;
4544 			break;
4545 		}
4546 		if (i2c.len > sizeof(i2c.data)) {
4547 			err = EINVAL;
4548 			break;
4549 		}
4550 
4551 		if ((err = IFDI_I2C_REQ(ctx, &i2c)) == 0)
4552 			err = copyout(&i2c, ifr_data_get_ptr(ifr),
4553 			    sizeof(i2c));
4554 		break;
4555 	}
4556 	case SIOCSIFCAP:
4557 	{
4558 		int mask, setmask, oldmask;
4559 
4560 		oldmask = if_getcapenable(ifp);
4561 		mask = ifr->ifr_reqcap ^ oldmask;
4562 		mask &= ctx->ifc_softc_ctx.isc_capabilities | IFCAP_MEXTPG;
4563 		setmask = 0;
4564 #ifdef TCP_OFFLOAD
4565 		setmask |= mask & (IFCAP_TOE4 | IFCAP_TOE6);
4566 #endif
4567 		setmask |= (mask & IFCAP_FLAGS);
4568 		setmask |= (mask & IFCAP_WOL);
4569 
4570 		/*
4571 		 * If any RX csum has changed, change all the ones that
4572 		 * are supported by the driver.
4573 		 */
4574 		if (setmask & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6)) {
4575 			setmask |= ctx->ifc_softc_ctx.isc_capabilities &
4576 			    (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
4577 		}
4578 
4579 		/*
4580 		 * want to ensure that traffic has stopped before we change any of the flags
4581 		 */
4582 		if (setmask) {
4583 			CTX_LOCK(ctx);
4584 			bits = if_getdrvflags(ifp);
4585 			if (bits & IFF_DRV_RUNNING && setmask & ~IFCAP_WOL)
4586 				iflib_stop(ctx);
4587 			STATE_LOCK(ctx);
4588 			if_togglecapenable(ifp, setmask);
4589 			ctx->ifc_softc_ctx.isc_capenable ^= setmask;
4590 			STATE_UNLOCK(ctx);
4591 			if (bits & IFF_DRV_RUNNING && setmask & ~IFCAP_WOL)
4592 				iflib_init_locked(ctx);
4593 			STATE_LOCK(ctx);
4594 			if_setdrvflags(ifp, bits);
4595 			STATE_UNLOCK(ctx);
4596 			CTX_UNLOCK(ctx);
4597 		}
4598 		if_vlancap(ifp);
4599 		break;
4600 	}
4601 	case SIOCGPRIVATE_0:
4602 	case SIOCSDRVSPEC:
4603 	case SIOCGDRVSPEC:
4604 		CTX_LOCK(ctx);
4605 		err = IFDI_PRIV_IOCTL(ctx, command, data);
4606 		CTX_UNLOCK(ctx);
4607 		break;
4608 	default:
4609 		err = ether_ioctl(ifp, command, data);
4610 		break;
4611 	}
4612 	if (reinit)
4613 		iflib_if_init(ctx);
4614 	return (err);
4615 }
4616 
4617 static uint64_t
iflib_if_get_counter(if_t ifp,ift_counter cnt)4618 iflib_if_get_counter(if_t ifp, ift_counter cnt)
4619 {
4620 	if_ctx_t ctx = if_getsoftc(ifp);
4621 
4622 	return (IFDI_GET_COUNTER(ctx, cnt));
4623 }
4624 
4625 /*********************************************************************
4626  *
4627  *  OTHER FUNCTIONS EXPORTED TO THE STACK
4628  *
4629  **********************************************************************/
4630 
4631 static void
iflib_vlan_register(void * arg,if_t ifp,uint16_t vtag)4632 iflib_vlan_register(void *arg, if_t ifp, uint16_t vtag)
4633 {
4634 	if_ctx_t ctx = if_getsoftc(ifp);
4635 
4636 	if ((void *)ctx != arg)
4637 		return;
4638 
4639 	if ((vtag == 0) || (vtag > 4095))
4640 		return;
4641 
4642 	if (iflib_in_detach(ctx))
4643 		return;
4644 
4645 	CTX_LOCK(ctx);
4646 	/* Driver may need all untagged packets to be flushed */
4647 	if (IFDI_NEEDS_RESTART(ctx, IFLIB_RESTART_VLAN_CONFIG))
4648 		iflib_stop(ctx);
4649 	IFDI_VLAN_REGISTER(ctx, vtag);
4650 	/* Re-init to load the changes, if required */
4651 	if (IFDI_NEEDS_RESTART(ctx, IFLIB_RESTART_VLAN_CONFIG))
4652 		iflib_init_locked(ctx);
4653 	CTX_UNLOCK(ctx);
4654 }
4655 
4656 static void
iflib_vlan_unregister(void * arg,if_t ifp,uint16_t vtag)4657 iflib_vlan_unregister(void *arg, if_t ifp, uint16_t vtag)
4658 {
4659 	if_ctx_t ctx = if_getsoftc(ifp);
4660 
4661 	if ((void *)ctx != arg)
4662 		return;
4663 
4664 	if ((vtag == 0) || (vtag > 4095))
4665 		return;
4666 
4667 	CTX_LOCK(ctx);
4668 	/* Driver may need all tagged packets to be flushed */
4669 	if (IFDI_NEEDS_RESTART(ctx, IFLIB_RESTART_VLAN_CONFIG))
4670 		iflib_stop(ctx);
4671 	IFDI_VLAN_UNREGISTER(ctx, vtag);
4672 	/* Re-init to load the changes, if required */
4673 	if (IFDI_NEEDS_RESTART(ctx, IFLIB_RESTART_VLAN_CONFIG))
4674 		iflib_init_locked(ctx);
4675 	CTX_UNLOCK(ctx);
4676 }
4677 
4678 static void
iflib_led_func(void * arg,int onoff)4679 iflib_led_func(void *arg, int onoff)
4680 {
4681 	if_ctx_t ctx = arg;
4682 
4683 	CTX_LOCK(ctx);
4684 	IFDI_LED_FUNC(ctx, onoff);
4685 	CTX_UNLOCK(ctx);
4686 }
4687 
4688 /*********************************************************************
4689  *
4690  *  BUS FUNCTION DEFINITIONS
4691  *
4692  **********************************************************************/
4693 
4694 int
iflib_device_probe(device_t dev)4695 iflib_device_probe(device_t dev)
4696 {
4697 	const pci_vendor_info_t *ent;
4698 	if_shared_ctx_t sctx;
4699 	uint16_t pci_device_id, pci_rev_id, pci_subdevice_id, pci_subvendor_id;
4700 	uint16_t pci_vendor_id;
4701 
4702 	if ((sctx = DEVICE_REGISTER(dev)) == NULL || sctx->isc_magic != IFLIB_MAGIC)
4703 		return (ENOTSUP);
4704 
4705 	pci_vendor_id = pci_get_vendor(dev);
4706 	pci_device_id = pci_get_device(dev);
4707 	pci_subvendor_id = pci_get_subvendor(dev);
4708 	pci_subdevice_id = pci_get_subdevice(dev);
4709 	pci_rev_id = pci_get_revid(dev);
4710 	if (sctx->isc_parse_devinfo != NULL)
4711 		sctx->isc_parse_devinfo(&pci_device_id, &pci_subvendor_id, &pci_subdevice_id, &pci_rev_id);
4712 
4713 	ent = sctx->isc_vendor_info;
4714 	while (ent->pvi_vendor_id != 0) {
4715 		if (pci_vendor_id != ent->pvi_vendor_id) {
4716 			ent++;
4717 			continue;
4718 		}
4719 		if ((pci_device_id == ent->pvi_device_id) &&
4720 		    ((pci_subvendor_id == ent->pvi_subvendor_id) ||
4721 		     (ent->pvi_subvendor_id == 0)) &&
4722 		    ((pci_subdevice_id == ent->pvi_subdevice_id) ||
4723 		     (ent->pvi_subdevice_id == 0)) &&
4724 		    ((pci_rev_id == ent->pvi_rev_id) ||
4725 		     (ent->pvi_rev_id == 0))) {
4726 			device_set_desc_copy(dev, ent->pvi_name);
4727 			/* this needs to be changed to zero if the bus probing code
4728 			 * ever stops re-probing on best match because the sctx
4729 			 * may have its values over written by register calls
4730 			 * in subsequent probes
4731 			 */
4732 			return (BUS_PROBE_DEFAULT);
4733 		}
4734 		ent++;
4735 	}
4736 	return (ENXIO);
4737 }
4738 
4739 int
iflib_device_probe_vendor(device_t dev)4740 iflib_device_probe_vendor(device_t dev)
4741 {
4742 	int probe;
4743 
4744 	probe = iflib_device_probe(dev);
4745 	if (probe == BUS_PROBE_DEFAULT)
4746 		return (BUS_PROBE_VENDOR);
4747 	else
4748 		return (probe);
4749 }
4750 
4751 static void
iflib_reset_qvalues(if_ctx_t ctx)4752 iflib_reset_qvalues(if_ctx_t ctx)
4753 {
4754 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4755 	if_shared_ctx_t sctx = ctx->ifc_sctx;
4756 	device_t dev = ctx->ifc_dev;
4757 	int i;
4758 
4759 	if (ctx->ifc_sysctl_ntxqs != 0)
4760 		scctx->isc_ntxqsets = ctx->ifc_sysctl_ntxqs;
4761 	if (ctx->ifc_sysctl_nrxqs != 0)
4762 		scctx->isc_nrxqsets = ctx->ifc_sysctl_nrxqs;
4763 
4764 	for (i = 0; i < sctx->isc_ntxqs; i++) {
4765 		if (ctx->ifc_sysctl_ntxds[i] != 0)
4766 			scctx->isc_ntxd[i] = ctx->ifc_sysctl_ntxds[i];
4767 		else
4768 			scctx->isc_ntxd[i] = sctx->isc_ntxd_default[i];
4769 	}
4770 
4771 	for (i = 0; i < sctx->isc_nrxqs; i++) {
4772 		if (ctx->ifc_sysctl_nrxds[i] != 0)
4773 			scctx->isc_nrxd[i] = ctx->ifc_sysctl_nrxds[i];
4774 		else
4775 			scctx->isc_nrxd[i] = sctx->isc_nrxd_default[i];
4776 	}
4777 
4778 	for (i = 0; i < sctx->isc_nrxqs; i++) {
4779 		if (scctx->isc_nrxd[i] < sctx->isc_nrxd_min[i]) {
4780 			device_printf(dev, "nrxd%d: %d less than nrxd_min %d - resetting to min\n",
4781 				      i, scctx->isc_nrxd[i], sctx->isc_nrxd_min[i]);
4782 			scctx->isc_nrxd[i] = sctx->isc_nrxd_min[i];
4783 		}
4784 		if (scctx->isc_nrxd[i] > sctx->isc_nrxd_max[i]) {
4785 			device_printf(dev, "nrxd%d: %d greater than nrxd_max %d - resetting to max\n",
4786 				      i, scctx->isc_nrxd[i], sctx->isc_nrxd_max[i]);
4787 			scctx->isc_nrxd[i] = sctx->isc_nrxd_max[i];
4788 		}
4789 		if (!powerof2(scctx->isc_nrxd[i])) {
4790 			device_printf(dev, "nrxd%d: %d is not a power of 2 - using default value of %d\n",
4791 				      i, scctx->isc_nrxd[i], sctx->isc_nrxd_default[i]);
4792 			scctx->isc_nrxd[i] = sctx->isc_nrxd_default[i];
4793 		}
4794 	}
4795 
4796 	for (i = 0; i < sctx->isc_ntxqs; i++) {
4797 		if (scctx->isc_ntxd[i] < sctx->isc_ntxd_min[i]) {
4798 			device_printf(dev, "ntxd%d: %d less than ntxd_min %d - resetting to min\n",
4799 				      i, scctx->isc_ntxd[i], sctx->isc_ntxd_min[i]);
4800 			scctx->isc_ntxd[i] = sctx->isc_ntxd_min[i];
4801 		}
4802 		if (scctx->isc_ntxd[i] > sctx->isc_ntxd_max[i]) {
4803 			device_printf(dev, "ntxd%d: %d greater than ntxd_max %d - resetting to max\n",
4804 				      i, scctx->isc_ntxd[i], sctx->isc_ntxd_max[i]);
4805 			scctx->isc_ntxd[i] = sctx->isc_ntxd_max[i];
4806 		}
4807 		if (!powerof2(scctx->isc_ntxd[i])) {
4808 			device_printf(dev, "ntxd%d: %d is not a power of 2 - using default value of %d\n",
4809 				      i, scctx->isc_ntxd[i], sctx->isc_ntxd_default[i]);
4810 			scctx->isc_ntxd[i] = sctx->isc_ntxd_default[i];
4811 		}
4812 	}
4813 }
4814 
4815 static void
iflib_add_pfil(if_ctx_t ctx)4816 iflib_add_pfil(if_ctx_t ctx)
4817 {
4818 	struct pfil_head *pfil;
4819 	struct pfil_head_args pa;
4820 	iflib_rxq_t rxq;
4821 	int i;
4822 
4823 	pa.pa_version = PFIL_VERSION;
4824 	pa.pa_flags = PFIL_IN;
4825 	pa.pa_type = PFIL_TYPE_ETHERNET;
4826 	pa.pa_headname = ctx->ifc_ifp->if_xname;
4827 	pfil = pfil_head_register(&pa);
4828 
4829 	for (i = 0, rxq = ctx->ifc_rxqs; i < NRXQSETS(ctx); i++, rxq++) {
4830 		rxq->pfil = pfil;
4831 	}
4832 }
4833 
4834 static void
iflib_rem_pfil(if_ctx_t ctx)4835 iflib_rem_pfil(if_ctx_t ctx)
4836 {
4837 	struct pfil_head *pfil;
4838 	iflib_rxq_t rxq;
4839 	int i;
4840 
4841 	rxq = ctx->ifc_rxqs;
4842 	pfil = rxq->pfil;
4843 	for (i = 0; i < NRXQSETS(ctx); i++, rxq++) {
4844 		rxq->pfil = NULL;
4845 	}
4846 	pfil_head_unregister(pfil);
4847 }
4848 
4849 
4850 /*
4851  * Advance forward by n members of the cpuset ctx->ifc_cpus starting from
4852  * cpuid and wrapping as necessary.
4853  */
4854 static unsigned int
cpuid_advance(if_ctx_t ctx,unsigned int cpuid,unsigned int n)4855 cpuid_advance(if_ctx_t ctx, unsigned int cpuid, unsigned int n)
4856 {
4857 	unsigned int first_valid;
4858 	unsigned int last_valid;
4859 
4860 	/* cpuid should always be in the valid set */
4861 	MPASS(CPU_ISSET(cpuid, &ctx->ifc_cpus));
4862 
4863 	/* valid set should never be empty */
4864 	MPASS(!CPU_EMPTY(&ctx->ifc_cpus));
4865 
4866 	first_valid = CPU_FFS(&ctx->ifc_cpus) - 1;
4867 	last_valid = CPU_FLS(&ctx->ifc_cpus) - 1;
4868 	n = n % CPU_COUNT(&ctx->ifc_cpus);
4869 	while (n > 0) {
4870 		do {
4871 			cpuid++;
4872 			if (cpuid > last_valid)
4873 				cpuid = first_valid;
4874 		} while (!CPU_ISSET(cpuid, &ctx->ifc_cpus));
4875 		n--;
4876 	}
4877 
4878 	return (cpuid);
4879 }
4880 
4881 #if defined(SMP) && defined(SCHED_ULE)
4882 extern struct cpu_group *cpu_top;              /* CPU topology */
4883 
4884 static int
find_child_with_core(int cpu,struct cpu_group * grp)4885 find_child_with_core(int cpu, struct cpu_group *grp)
4886 {
4887 	int i;
4888 
4889 	if (grp->cg_children == 0)
4890 		return (-1);
4891 
4892 	MPASS(grp->cg_child);
4893 	for (i = 0; i < grp->cg_children; i++) {
4894 		if (CPU_ISSET(cpu, &grp->cg_child[i].cg_mask))
4895 			return (i);
4896 	}
4897 
4898 	return (-1);
4899 }
4900 
4901 
4902 /*
4903  * Find an L2 neighbor of the given CPU or return -1 if none found.  This
4904  * does not distinguish among multiple L2 neighbors if the given CPU has
4905  * more than one (it will always return the same result in that case).
4906  */
4907 static int
find_l2_neighbor(int cpu)4908 find_l2_neighbor(int cpu)
4909 {
4910 	struct cpu_group *grp;
4911 	int i;
4912 
4913 	grp = cpu_top;
4914 	if (grp == NULL)
4915 		return (-1);
4916 
4917 	/*
4918 	 * Find the smallest CPU group that contains the given core.
4919 	 */
4920 	i = 0;
4921 	while ((i = find_child_with_core(cpu, grp)) != -1) {
4922 		/*
4923 		 * If the smallest group containing the given CPU has less
4924 		 * than two members, we conclude the given CPU has no
4925 		 * L2 neighbor.
4926 		 */
4927 		if (grp->cg_child[i].cg_count <= 1)
4928 			return (-1);
4929 		grp = &grp->cg_child[i];
4930 	}
4931 
4932 	/* Must share L2. */
4933 	if (grp->cg_level > CG_SHARE_L2 || grp->cg_level == CG_SHARE_NONE)
4934 		return (-1);
4935 
4936 	/*
4937 	 * Select the first member of the set that isn't the reference
4938 	 * CPU, which at this point is guaranteed to exist.
4939 	 */
4940 	for (i = 0; i < CPU_SETSIZE; i++) {
4941 		if (CPU_ISSET(i, &grp->cg_mask) && i != cpu)
4942 			return (i);
4943 	}
4944 
4945 	/* Should never be reached */
4946 	return (-1);
4947 }
4948 
4949 #else
4950 static int
find_l2_neighbor(int cpu)4951 find_l2_neighbor(int cpu)
4952 {
4953 
4954 	return (-1);
4955 }
4956 #endif
4957 
4958 /*
4959  * CPU mapping behaviors
4960  * ---------------------
4961  * 'separate txrx' refers to the separate_txrx sysctl
4962  * 'use logical' refers to the use_logical_cores sysctl
4963  * 'INTR CPUS' indicates whether bus_get_cpus(INTR_CPUS) succeeded
4964  *
4965  *  separate     use     INTR
4966  *    txrx     logical   CPUS   result
4967  * ---------- --------- ------ ------------------------------------------------
4968  *     -          -       X     RX and TX queues mapped to consecutive physical
4969  *                              cores with RX/TX pairs on same core and excess
4970  *                              of either following
4971  *     -          X       X     RX and TX queues mapped to consecutive cores
4972  *                              of any type with RX/TX pairs on same core and
4973  *                              excess of either following
4974  *     X          -       X     RX and TX queues mapped to consecutive physical
4975  *                              cores; all RX then all TX
4976  *     X          X       X     RX queues mapped to consecutive physical cores
4977  *                              first, then TX queues mapped to L2 neighbor of
4978  *                              the corresponding RX queue if one exists,
4979  *                              otherwise to consecutive physical cores
4980  *     -         n/a      -     RX and TX queues mapped to consecutive cores of
4981  *                              any type with RX/TX pairs on same core and excess
4982  *                              of either following
4983  *     X         n/a      -     RX and TX queues mapped to consecutive cores of
4984  *                              any type; all RX then all TX
4985  */
4986 static unsigned int
get_cpuid_for_queue(if_ctx_t ctx,unsigned int base_cpuid,unsigned int qid,bool is_tx)4987 get_cpuid_for_queue(if_ctx_t ctx, unsigned int base_cpuid, unsigned int qid,
4988     bool is_tx)
4989 {
4990 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4991 	unsigned int core_index;
4992 
4993 	if (ctx->ifc_sysctl_separate_txrx) {
4994 		/*
4995 		 * When using separate CPUs for TX and RX, the assignment
4996 		 * will always be of a consecutive CPU out of the set of
4997 		 * context CPUs, except for the specific case where the
4998 		 * context CPUs are phsyical cores, the use of logical cores
4999 		 * has been enabled, the assignment is for TX, the TX qid
5000 		 * corresponds to an RX qid, and the CPU assigned to the
5001 		 * corresponding RX queue has an L2 neighbor.
5002 		 */
5003 		if (ctx->ifc_sysctl_use_logical_cores &&
5004 		    ctx->ifc_cpus_are_physical_cores &&
5005 		    is_tx && qid < scctx->isc_nrxqsets) {
5006 			int l2_neighbor;
5007 			unsigned int rx_cpuid;
5008 
5009 			rx_cpuid = cpuid_advance(ctx, base_cpuid, qid);
5010 			l2_neighbor = find_l2_neighbor(rx_cpuid);
5011 			if (l2_neighbor != -1) {
5012 				return (l2_neighbor);
5013 			}
5014 			/*
5015 			 * ... else fall through to the normal
5016 			 * consecutive-after-RX assignment scheme.
5017 			 *
5018 			 * Note that we are assuming that all RX queue CPUs
5019 			 * have an L2 neighbor, or all do not.  If a mixed
5020 			 * scenario is possible, we will have to keep track
5021 			 * separately of how many queues prior to this one
5022 			 * were not able to be assigned to an L2 neighbor.
5023 			 */
5024 		}
5025 		if (is_tx)
5026 			core_index = scctx->isc_nrxqsets + qid;
5027 		else
5028 			core_index = qid;
5029 	} else {
5030 		core_index = qid;
5031 	}
5032 
5033 	return (cpuid_advance(ctx, base_cpuid, core_index));
5034 }
5035 
5036 static uint16_t
get_ctx_core_offset(if_ctx_t ctx)5037 get_ctx_core_offset(if_ctx_t ctx)
5038 {
5039 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
5040 	struct cpu_offset *op;
5041 	cpuset_t assigned_cpus;
5042 	unsigned int cores_consumed;
5043 	unsigned int base_cpuid = ctx->ifc_sysctl_core_offset;
5044 	unsigned int first_valid;
5045 	unsigned int last_valid;
5046 	unsigned int i;
5047 
5048 	first_valid = CPU_FFS(&ctx->ifc_cpus) - 1;
5049 	last_valid = CPU_FLS(&ctx->ifc_cpus) - 1;
5050 
5051 	if (base_cpuid != CORE_OFFSET_UNSPECIFIED) {
5052 		/*
5053 		 * Align the user-chosen base CPU ID to the next valid CPU
5054 		 * for this device.  If the chosen base CPU ID is smaller
5055 		 * than the first valid CPU or larger than the last valid
5056 		 * CPU, we assume the user does not know what the valid
5057 		 * range is for this device and is thinking in terms of a
5058 		 * zero-based reference frame, and so we shift the given
5059 		 * value into the valid range (and wrap accordingly) so the
5060 		 * intent is translated to the proper frame of reference.
5061 		 * If the base CPU ID is within the valid first/last, but
5062 		 * does not correspond to a valid CPU, it is advanced to the
5063 		 * next valid CPU (wrapping if necessary).
5064 		 */
5065 		if (base_cpuid < first_valid || base_cpuid > last_valid) {
5066 			/* shift from zero-based to first_valid-based */
5067 			base_cpuid += first_valid;
5068 			/* wrap to range [first_valid, last_valid] */
5069 			base_cpuid = (base_cpuid - first_valid) %
5070 			    (last_valid - first_valid + 1);
5071 		}
5072 		if (!CPU_ISSET(base_cpuid, &ctx->ifc_cpus)) {
5073 			/*
5074 			 * base_cpuid is in [first_valid, last_valid], but
5075 			 * not a member of the valid set.  In this case,
5076 			 * there will always be a member of the valid set
5077 			 * with a CPU ID that is greater than base_cpuid,
5078 			 * and we simply advance to it.
5079 			 */
5080 			while (!CPU_ISSET(base_cpuid, &ctx->ifc_cpus))
5081 				base_cpuid++;
5082 		}
5083 		return (base_cpuid);
5084 	}
5085 
5086 	/*
5087 	 * Determine how many cores will be consumed by performing the CPU
5088 	 * assignments and counting how many of the assigned CPUs correspond
5089 	 * to CPUs in the set of context CPUs.  This is done using the CPU
5090 	 * ID first_valid as the base CPU ID, as the base CPU must be within
5091 	 * the set of context CPUs.
5092 	 *
5093 	 * Note not all assigned CPUs will be in the set of context CPUs
5094 	 * when separate CPUs are being allocated to TX and RX queues,
5095 	 * assignment to logical cores has been enabled, the set of context
5096 	 * CPUs contains only physical CPUs, and TX queues are mapped to L2
5097 	 * neighbors of CPUs that RX queues have been mapped to - in this
5098 	 * case we do only want to count how many CPUs in the set of context
5099 	 * CPUs have been consumed, as that determines the next CPU in that
5100 	 * set to start allocating at for the next device for which
5101 	 * core_offset is not set.
5102 	 */
5103 	CPU_ZERO(&assigned_cpus);
5104 	for (i = 0; i < scctx->isc_ntxqsets; i++)
5105 		CPU_SET(get_cpuid_for_queue(ctx, first_valid, i, true),
5106 		    &assigned_cpus);
5107 	for (i = 0; i < scctx->isc_nrxqsets; i++)
5108 		CPU_SET(get_cpuid_for_queue(ctx, first_valid, i, false),
5109 		    &assigned_cpus);
5110 	CPU_AND(&assigned_cpus, &assigned_cpus, &ctx->ifc_cpus);
5111 	cores_consumed = CPU_COUNT(&assigned_cpus);
5112 
5113 	mtx_lock(&cpu_offset_mtx);
5114 	SLIST_FOREACH(op, &cpu_offsets, entries) {
5115 		if (CPU_CMP(&ctx->ifc_cpus, &op->set) == 0) {
5116 			base_cpuid = op->next_cpuid;
5117 			op->next_cpuid = cpuid_advance(ctx, op->next_cpuid,
5118 			    cores_consumed);
5119 			MPASS(op->refcount < UINT_MAX);
5120 			op->refcount++;
5121 			break;
5122 		}
5123 	}
5124 	if (base_cpuid == CORE_OFFSET_UNSPECIFIED) {
5125 		base_cpuid = first_valid;
5126 		op = malloc(sizeof(struct cpu_offset), M_IFLIB,
5127 		    M_NOWAIT | M_ZERO);
5128 		if (op == NULL) {
5129 			device_printf(ctx->ifc_dev,
5130 			    "allocation for cpu offset failed.\n");
5131 		} else {
5132 			op->next_cpuid = cpuid_advance(ctx, base_cpuid,
5133 			    cores_consumed);
5134 			op->refcount = 1;
5135 			CPU_COPY(&ctx->ifc_cpus, &op->set);
5136 			SLIST_INSERT_HEAD(&cpu_offsets, op, entries);
5137 		}
5138 	}
5139 	mtx_unlock(&cpu_offset_mtx);
5140 
5141 	return (base_cpuid);
5142 }
5143 
5144 static void
unref_ctx_core_offset(if_ctx_t ctx)5145 unref_ctx_core_offset(if_ctx_t ctx)
5146 {
5147 	struct cpu_offset *op, *top;
5148 
5149 	mtx_lock(&cpu_offset_mtx);
5150 	SLIST_FOREACH_SAFE(op, &cpu_offsets, entries, top) {
5151 		if (CPU_CMP(&ctx->ifc_cpus, &op->set) == 0) {
5152 			MPASS(op->refcount > 0);
5153 			op->refcount--;
5154 			if (op->refcount == 0) {
5155 				SLIST_REMOVE(&cpu_offsets, op, cpu_offset, entries);
5156 				free(op, M_IFLIB);
5157 			}
5158 			break;
5159 		}
5160 	}
5161 	mtx_unlock(&cpu_offset_mtx);
5162 }
5163 
5164 int
iflib_device_register(device_t dev,void * sc,if_shared_ctx_t sctx,if_ctx_t * ctxp)5165 iflib_device_register(device_t dev, void *sc, if_shared_ctx_t sctx, if_ctx_t *ctxp)
5166 {
5167 	if_ctx_t ctx;
5168 	if_t ifp;
5169 	if_softc_ctx_t scctx;
5170 	kobjop_desc_t kobj_desc;
5171 	kobj_method_t *kobj_method;
5172 	int err, msix, rid;
5173 	int num_txd, num_rxd;
5174 
5175 	ctx = malloc(sizeof(*ctx), M_IFLIB, M_WAITOK | M_ZERO);
5176 
5177 	if (sc == NULL) {
5178 		sc = malloc(sctx->isc_driver->size, M_IFLIB, M_WAITOK | M_ZERO);
5179 		device_set_softc(dev, ctx);
5180 		ctx->ifc_flags |= IFC_SC_ALLOCATED;
5181 	}
5182 
5183 	ctx->ifc_sctx = sctx;
5184 	ctx->ifc_dev = dev;
5185 	ctx->ifc_softc = sc;
5186 
5187 	if ((err = iflib_register(ctx)) != 0) {
5188 		device_printf(dev, "iflib_register failed %d\n", err);
5189 		goto fail_ctx_free;
5190 	}
5191 	iflib_add_device_sysctl_pre(ctx);
5192 
5193 	scctx = &ctx->ifc_softc_ctx;
5194 	ifp = ctx->ifc_ifp;
5195 
5196 	iflib_reset_qvalues(ctx);
5197 	IFNET_WLOCK();
5198 	CTX_LOCK(ctx);
5199 	if ((err = IFDI_ATTACH_PRE(ctx)) != 0) {
5200 		device_printf(dev, "IFDI_ATTACH_PRE failed %d\n", err);
5201 		goto fail_unlock;
5202 	}
5203 	_iflib_pre_assert(scctx);
5204 	ctx->ifc_txrx = *scctx->isc_txrx;
5205 
5206 	if (sctx->isc_flags & IFLIB_DRIVER_MEDIA)
5207 		ctx->ifc_mediap = scctx->isc_media;
5208 
5209 #ifdef INVARIANTS
5210 	if (scctx->isc_capabilities & IFCAP_TXCSUM)
5211 		MPASS(scctx->isc_tx_csum_flags);
5212 #endif
5213 
5214 	if_setcapabilities(ifp,
5215 	    scctx->isc_capabilities | IFCAP_HWSTATS | IFCAP_MEXTPG);
5216 	if_setcapenable(ifp,
5217 	    scctx->isc_capenable | IFCAP_HWSTATS | IFCAP_MEXTPG);
5218 
5219 	if (scctx->isc_ntxqsets == 0 || (scctx->isc_ntxqsets_max && scctx->isc_ntxqsets_max < scctx->isc_ntxqsets))
5220 		scctx->isc_ntxqsets = scctx->isc_ntxqsets_max;
5221 	if (scctx->isc_nrxqsets == 0 || (scctx->isc_nrxqsets_max && scctx->isc_nrxqsets_max < scctx->isc_nrxqsets))
5222 		scctx->isc_nrxqsets = scctx->isc_nrxqsets_max;
5223 
5224 	num_txd = iflib_num_tx_descs(ctx);
5225 	num_rxd = iflib_num_rx_descs(ctx);
5226 
5227 	/* XXX change for per-queue sizes */
5228 	device_printf(dev, "Using %d TX descriptors and %d RX descriptors\n",
5229 	    num_txd, num_rxd);
5230 
5231 	if (scctx->isc_tx_nsegments > num_txd / MAX_SINGLE_PACKET_FRACTION)
5232 		scctx->isc_tx_nsegments = max(1, num_txd /
5233 		    MAX_SINGLE_PACKET_FRACTION);
5234 	if (scctx->isc_tx_tso_segments_max > num_txd /
5235 	    MAX_SINGLE_PACKET_FRACTION)
5236 		scctx->isc_tx_tso_segments_max = max(1,
5237 		    num_txd / MAX_SINGLE_PACKET_FRACTION);
5238 
5239 	/* TSO parameters - dig these out of the data sheet - simply correspond to tag setup */
5240 	if (if_getcapabilities(ifp) & IFCAP_TSO) {
5241 		/*
5242 		 * The stack can't handle a TSO size larger than IP_MAXPACKET,
5243 		 * but some MACs do.
5244 		 */
5245 		if_sethwtsomax(ifp, min(scctx->isc_tx_tso_size_max,
5246 		    IP_MAXPACKET));
5247 		/*
5248 		 * Take maximum number of m_pullup(9)'s in iflib_parse_header()
5249 		 * into account.  In the worst case, each of these calls will
5250 		 * add another mbuf and, thus, the requirement for another DMA
5251 		 * segment.  So for best performance, it doesn't make sense to
5252 		 * advertize a maximum of TSO segments that typically will
5253 		 * require defragmentation in iflib_encap().
5254 		 */
5255 		if_sethwtsomaxsegcount(ifp, scctx->isc_tx_tso_segments_max - 3);
5256 		if_sethwtsomaxsegsize(ifp, scctx->isc_tx_tso_segsize_max);
5257 	}
5258 	if (scctx->isc_rss_table_size == 0)
5259 		scctx->isc_rss_table_size = 64;
5260 	scctx->isc_rss_table_mask = scctx->isc_rss_table_size - 1;
5261 
5262 	GROUPTASK_INIT(&ctx->ifc_admin_task, 0, _task_fn_admin, ctx);
5263 	/* XXX format name */
5264 	taskqgroup_attach(qgroup_if_config_tqg, &ctx->ifc_admin_task, ctx,
5265 	    NULL, NULL, "admin");
5266 
5267 	/* Set up cpu set.  If it fails, use the set of all CPUs. */
5268 	if (bus_get_cpus(dev, INTR_CPUS, sizeof(ctx->ifc_cpus), &ctx->ifc_cpus) != 0) {
5269 		device_printf(dev, "Unable to fetch CPU list\n");
5270 		CPU_COPY(&all_cpus, &ctx->ifc_cpus);
5271 		ctx->ifc_cpus_are_physical_cores = false;
5272 	} else
5273 		ctx->ifc_cpus_are_physical_cores = true;
5274 	MPASS(CPU_COUNT(&ctx->ifc_cpus) > 0);
5275 
5276 	/*
5277 	 * Now set up MSI or MSI-X, should return us the number of supported
5278 	 * vectors (will be 1 for a legacy interrupt and MSI).
5279 	 */
5280 	if (sctx->isc_flags & IFLIB_SKIP_MSIX) {
5281 		msix = scctx->isc_vectors;
5282 	} else if (scctx->isc_msix_bar != 0)
5283 		/*
5284 		 * The simple fact that isc_msix_bar is not 0 does not mean we
5285 		 * we have a good value there that is known to work.
5286 		 */
5287 		msix = iflib_msix_init(ctx);
5288 	else {
5289 		scctx->isc_vectors = 1;
5290 		scctx->isc_ntxqsets = 1;
5291 		scctx->isc_nrxqsets = 1;
5292 		scctx->isc_intr = IFLIB_INTR_LEGACY;
5293 		msix = 0;
5294 	}
5295 	/* Get memory for the station queues */
5296 	if ((err = iflib_queues_alloc(ctx))) {
5297 		device_printf(dev, "Unable to allocate queue memory\n");
5298 		goto fail_intr_free;
5299 	}
5300 
5301 	if ((err = iflib_qset_structures_setup(ctx)))
5302 		goto fail_queues;
5303 
5304 	/*
5305 	 * Now that we know how many queues there are, get the core offset.
5306 	 */
5307 	ctx->ifc_sysctl_core_offset = get_ctx_core_offset(ctx);
5308 
5309 	if (msix > 1) {
5310 		/*
5311 		 * When using MSI-X, ensure that ifdi_{r,t}x_queue_intr_enable
5312 		 * aren't the default NULL implementation.
5313 		 */
5314 		kobj_desc = &ifdi_rx_queue_intr_enable_desc;
5315 		kobj_method = kobj_lookup_method(((kobj_t)ctx)->ops->cls, NULL,
5316 		    kobj_desc);
5317 		if (kobj_method == &kobj_desc->deflt) {
5318 			device_printf(dev,
5319 			    "MSI-X requires ifdi_rx_queue_intr_enable method");
5320 			err = EOPNOTSUPP;
5321 			goto fail_queues;
5322 		}
5323 		kobj_desc = &ifdi_tx_queue_intr_enable_desc;
5324 		kobj_method = kobj_lookup_method(((kobj_t)ctx)->ops->cls, NULL,
5325 		    kobj_desc);
5326 		if (kobj_method == &kobj_desc->deflt) {
5327 			device_printf(dev,
5328 			    "MSI-X requires ifdi_tx_queue_intr_enable method");
5329 			err = EOPNOTSUPP;
5330 			goto fail_queues;
5331 		}
5332 
5333 		/*
5334 		 * Assign the MSI-X vectors.
5335 		 * Note that the default NULL ifdi_msix_intr_assign method will
5336 		 * fail here, too.
5337 		 */
5338 		err = IFDI_MSIX_INTR_ASSIGN(ctx, msix);
5339 		if (err != 0) {
5340 			device_printf(dev, "IFDI_MSIX_INTR_ASSIGN failed %d\n",
5341 			    err);
5342 			goto fail_queues;
5343 		}
5344 	} else if (scctx->isc_intr != IFLIB_INTR_MSIX) {
5345 		rid = 0;
5346 		if (scctx->isc_intr == IFLIB_INTR_MSI) {
5347 			MPASS(msix == 1);
5348 			rid = 1;
5349 		}
5350 		if ((err = iflib_legacy_setup(ctx, ctx->isc_legacy_intr, ctx->ifc_softc, &rid, "irq0")) != 0) {
5351 			device_printf(dev, "iflib_legacy_setup failed %d\n", err);
5352 			goto fail_queues;
5353 		}
5354 	} else {
5355 		device_printf(dev,
5356 		    "Cannot use iflib with only 1 MSI-X interrupt!\n");
5357 		err = ENODEV;
5358 		goto fail_queues;
5359 	}
5360 
5361 	/*
5362 	 * It prevents a double-locking panic with iflib_media_status when
5363 	 * the driver loads.
5364 	 */
5365 	CTX_UNLOCK(ctx);
5366 	ether_ifattach(ctx->ifc_ifp, ctx->ifc_mac.octet);
5367 	CTX_LOCK(ctx);
5368 
5369 	if ((err = IFDI_ATTACH_POST(ctx)) != 0) {
5370 		device_printf(dev, "IFDI_ATTACH_POST failed %d\n", err);
5371 		goto fail_detach;
5372 	}
5373 
5374 	/*
5375 	 * Tell the upper layer(s) if IFCAP_VLAN_MTU is supported.
5376 	 * This must appear after the call to ether_ifattach() because
5377 	 * ether_ifattach() sets if_hdrlen to the default value.
5378 	 */
5379 	if (if_getcapabilities(ifp) & IFCAP_VLAN_MTU)
5380 		if_setifheaderlen(ifp, sizeof(struct ether_vlan_header));
5381 
5382 	if ((err = iflib_netmap_attach(ctx))) {
5383 		device_printf(ctx->ifc_dev, "netmap attach failed: %d\n", err);
5384 		goto fail_detach;
5385 	}
5386 	*ctxp = ctx;
5387 
5388 	DEBUGNET_SET(ctx->ifc_ifp, iflib);
5389 
5390 	if_setgetcounterfn(ctx->ifc_ifp, iflib_if_get_counter);
5391 	iflib_add_device_sysctl_post(ctx);
5392 	iflib_add_pfil(ctx);
5393 	ctx->ifc_flags |= IFC_INIT_DONE;
5394 	CTX_UNLOCK(ctx);
5395 	IFNET_WUNLOCK();
5396 
5397 	return (0);
5398 
5399 fail_detach:
5400 	ether_ifdetach(ctx->ifc_ifp);
5401 fail_queues:
5402 	iflib_tqg_detach(ctx);
5403 	iflib_tx_structures_free(ctx);
5404 	iflib_rx_structures_free(ctx);
5405 	IFDI_DETACH(ctx);
5406 	IFDI_QUEUES_FREE(ctx);
5407 fail_intr_free:
5408 	iflib_free_intr_mem(ctx);
5409 fail_unlock:
5410 	CTX_UNLOCK(ctx);
5411 	IFNET_WUNLOCK();
5412 	iflib_deregister(ctx);
5413 fail_ctx_free:
5414 	device_set_softc(ctx->ifc_dev, NULL);
5415         if (ctx->ifc_flags & IFC_SC_ALLOCATED)
5416                 free(ctx->ifc_softc, M_IFLIB);
5417         free(ctx, M_IFLIB);
5418 	return (err);
5419 }
5420 
5421 int
iflib_pseudo_register(device_t dev,if_shared_ctx_t sctx,if_ctx_t * ctxp,struct iflib_cloneattach_ctx * clctx)5422 iflib_pseudo_register(device_t dev, if_shared_ctx_t sctx, if_ctx_t *ctxp,
5423 					  struct iflib_cloneattach_ctx *clctx)
5424 {
5425 	int num_txd, num_rxd;
5426 	int err;
5427 	if_ctx_t ctx;
5428 	if_t ifp;
5429 	if_softc_ctx_t scctx;
5430 	int i;
5431 	void *sc;
5432 
5433 	ctx = malloc(sizeof(*ctx), M_IFLIB, M_WAITOK|M_ZERO);
5434 	sc = malloc(sctx->isc_driver->size, M_IFLIB, M_WAITOK|M_ZERO);
5435 	ctx->ifc_flags |= IFC_SC_ALLOCATED;
5436 	if (sctx->isc_flags & (IFLIB_PSEUDO|IFLIB_VIRTUAL))
5437 		ctx->ifc_flags |= IFC_PSEUDO;
5438 
5439 	ctx->ifc_sctx = sctx;
5440 	ctx->ifc_softc = sc;
5441 	ctx->ifc_dev = dev;
5442 
5443 	if ((err = iflib_register(ctx)) != 0) {
5444 		device_printf(dev, "%s: iflib_register failed %d\n", __func__, err);
5445 		goto fail_ctx_free;
5446 	}
5447 	iflib_add_device_sysctl_pre(ctx);
5448 
5449 	scctx = &ctx->ifc_softc_ctx;
5450 	ifp = ctx->ifc_ifp;
5451 
5452 	iflib_reset_qvalues(ctx);
5453 	CTX_LOCK(ctx);
5454 	if ((err = IFDI_ATTACH_PRE(ctx)) != 0) {
5455 		device_printf(dev, "IFDI_ATTACH_PRE failed %d\n", err);
5456 		goto fail_unlock;
5457 	}
5458 	if (sctx->isc_flags & IFLIB_GEN_MAC)
5459 		ether_gen_addr(ifp, &ctx->ifc_mac);
5460 	if ((err = IFDI_CLONEATTACH(ctx, clctx->cc_ifc, clctx->cc_name,
5461 								clctx->cc_params)) != 0) {
5462 		device_printf(dev, "IFDI_CLONEATTACH failed %d\n", err);
5463 		goto fail_unlock;
5464 	}
5465 #ifdef INVARIANTS
5466 	if (scctx->isc_capabilities & IFCAP_TXCSUM)
5467 		MPASS(scctx->isc_tx_csum_flags);
5468 #endif
5469 
5470 	if_setcapabilities(ifp, scctx->isc_capabilities | IFCAP_HWSTATS | IFCAP_LINKSTATE);
5471 	if_setcapenable(ifp, scctx->isc_capenable | IFCAP_HWSTATS | IFCAP_LINKSTATE);
5472 
5473 	ifp->if_flags |= IFF_NOGROUP;
5474 	if (sctx->isc_flags & IFLIB_PSEUDO) {
5475 		ifmedia_add(ctx->ifc_mediap, IFM_ETHER | IFM_AUTO, 0, NULL);
5476 		ifmedia_set(ctx->ifc_mediap, IFM_ETHER | IFM_AUTO);
5477 		if (sctx->isc_flags & IFLIB_PSEUDO_ETHER) {
5478 			ether_ifattach(ctx->ifc_ifp, ctx->ifc_mac.octet);
5479 		} else {
5480 			if_attach(ctx->ifc_ifp);
5481 			bpfattach(ctx->ifc_ifp, DLT_NULL, sizeof(u_int32_t));
5482 		}
5483 
5484 		if ((err = IFDI_ATTACH_POST(ctx)) != 0) {
5485 			device_printf(dev, "IFDI_ATTACH_POST failed %d\n", err);
5486 			goto fail_detach;
5487 		}
5488 		*ctxp = ctx;
5489 
5490 		/*
5491 		 * Tell the upper layer(s) if IFCAP_VLAN_MTU is supported.
5492 		 * This must appear after the call to ether_ifattach() because
5493 		 * ether_ifattach() sets if_hdrlen to the default value.
5494 		 */
5495 		if (if_getcapabilities(ifp) & IFCAP_VLAN_MTU)
5496 			if_setifheaderlen(ifp,
5497 			    sizeof(struct ether_vlan_header));
5498 
5499 		if_setgetcounterfn(ctx->ifc_ifp, iflib_if_get_counter);
5500 		iflib_add_device_sysctl_post(ctx);
5501 		ctx->ifc_flags |= IFC_INIT_DONE;
5502 		CTX_UNLOCK(ctx);
5503 		return (0);
5504 	}
5505 	ifmedia_add(ctx->ifc_mediap, IFM_ETHER | IFM_1000_T | IFM_FDX, 0, NULL);
5506 	ifmedia_add(ctx->ifc_mediap, IFM_ETHER | IFM_AUTO, 0, NULL);
5507 	ifmedia_set(ctx->ifc_mediap, IFM_ETHER | IFM_AUTO);
5508 
5509 	_iflib_pre_assert(scctx);
5510 	ctx->ifc_txrx = *scctx->isc_txrx;
5511 
5512 	if (scctx->isc_ntxqsets == 0 || (scctx->isc_ntxqsets_max && scctx->isc_ntxqsets_max < scctx->isc_ntxqsets))
5513 		scctx->isc_ntxqsets = scctx->isc_ntxqsets_max;
5514 	if (scctx->isc_nrxqsets == 0 || (scctx->isc_nrxqsets_max && scctx->isc_nrxqsets_max < scctx->isc_nrxqsets))
5515 		scctx->isc_nrxqsets = scctx->isc_nrxqsets_max;
5516 
5517 	num_txd = iflib_num_tx_descs(ctx);
5518 	num_rxd = iflib_num_rx_descs(ctx);
5519 
5520 	/* XXX change for per-queue sizes */
5521 	device_printf(dev, "Using %d TX descriptors and %d RX descriptors\n",
5522 	    num_txd, num_rxd);
5523 
5524 	if (scctx->isc_tx_nsegments > num_txd / MAX_SINGLE_PACKET_FRACTION)
5525 		scctx->isc_tx_nsegments = max(1, num_txd /
5526 		    MAX_SINGLE_PACKET_FRACTION);
5527 	if (scctx->isc_tx_tso_segments_max > num_txd /
5528 	    MAX_SINGLE_PACKET_FRACTION)
5529 		scctx->isc_tx_tso_segments_max = max(1,
5530 		    num_txd / MAX_SINGLE_PACKET_FRACTION);
5531 
5532 	/* TSO parameters - dig these out of the data sheet - simply correspond to tag setup */
5533 	if (if_getcapabilities(ifp) & IFCAP_TSO) {
5534 		/*
5535 		 * The stack can't handle a TSO size larger than IP_MAXPACKET,
5536 		 * but some MACs do.
5537 		 */
5538 		if_sethwtsomax(ifp, min(scctx->isc_tx_tso_size_max,
5539 		    IP_MAXPACKET));
5540 		/*
5541 		 * Take maximum number of m_pullup(9)'s in iflib_parse_header()
5542 		 * into account.  In the worst case, each of these calls will
5543 		 * add another mbuf and, thus, the requirement for another DMA
5544 		 * segment.  So for best performance, it doesn't make sense to
5545 		 * advertize a maximum of TSO segments that typically will
5546 		 * require defragmentation in iflib_encap().
5547 		 */
5548 		if_sethwtsomaxsegcount(ifp, scctx->isc_tx_tso_segments_max - 3);
5549 		if_sethwtsomaxsegsize(ifp, scctx->isc_tx_tso_segsize_max);
5550 	}
5551 	if (scctx->isc_rss_table_size == 0)
5552 		scctx->isc_rss_table_size = 64;
5553 	scctx->isc_rss_table_mask = scctx->isc_rss_table_size-1;
5554 
5555 	GROUPTASK_INIT(&ctx->ifc_admin_task, 0, _task_fn_admin, ctx);
5556 	/* XXX format name */
5557 	taskqgroup_attach(qgroup_if_config_tqg, &ctx->ifc_admin_task, ctx,
5558 	    NULL, NULL, "admin");
5559 
5560 	/* XXX --- can support > 1 -- but keep it simple for now */
5561 	scctx->isc_intr = IFLIB_INTR_LEGACY;
5562 
5563 	/* Get memory for the station queues */
5564 	if ((err = iflib_queues_alloc(ctx))) {
5565 		device_printf(dev, "Unable to allocate queue memory\n");
5566 		goto fail_iflib_detach;
5567 	}
5568 
5569 	if ((err = iflib_qset_structures_setup(ctx))) {
5570 		device_printf(dev, "qset structure setup failed %d\n", err);
5571 		goto fail_queues;
5572 	}
5573 
5574 	/*
5575 	 * XXX What if anything do we want to do about interrupts?
5576 	 */
5577 	ether_ifattach(ctx->ifc_ifp, ctx->ifc_mac.octet);
5578 	if ((err = IFDI_ATTACH_POST(ctx)) != 0) {
5579 		device_printf(dev, "IFDI_ATTACH_POST failed %d\n", err);
5580 		goto fail_detach;
5581 	}
5582 
5583 	/*
5584 	 * Tell the upper layer(s) if IFCAP_VLAN_MTU is supported.
5585 	 * This must appear after the call to ether_ifattach() because
5586 	 * ether_ifattach() sets if_hdrlen to the default value.
5587 	 */
5588 	if (if_getcapabilities(ifp) & IFCAP_VLAN_MTU)
5589 		if_setifheaderlen(ifp, sizeof(struct ether_vlan_header));
5590 
5591 	/* XXX handle more than one queue */
5592 	for (i = 0; i < scctx->isc_nrxqsets; i++)
5593 		IFDI_RX_CLSET(ctx, 0, i, ctx->ifc_rxqs[i].ifr_fl[0].ifl_sds.ifsd_cl);
5594 
5595 	*ctxp = ctx;
5596 
5597 	if_setgetcounterfn(ctx->ifc_ifp, iflib_if_get_counter);
5598 	iflib_add_device_sysctl_post(ctx);
5599 	ctx->ifc_flags |= IFC_INIT_DONE;
5600 	CTX_UNLOCK(ctx);
5601 
5602 	return (0);
5603 fail_detach:
5604 	ether_ifdetach(ctx->ifc_ifp);
5605 fail_queues:
5606 	iflib_tqg_detach(ctx);
5607 	iflib_tx_structures_free(ctx);
5608 	iflib_rx_structures_free(ctx);
5609 fail_iflib_detach:
5610 	IFDI_DETACH(ctx);
5611 	IFDI_QUEUES_FREE(ctx);
5612 fail_unlock:
5613 	CTX_UNLOCK(ctx);
5614 	iflib_deregister(ctx);
5615 fail_ctx_free:
5616 	free(ctx->ifc_softc, M_IFLIB);
5617 	free(ctx, M_IFLIB);
5618 	return (err);
5619 }
5620 
5621 int
iflib_pseudo_deregister(if_ctx_t ctx)5622 iflib_pseudo_deregister(if_ctx_t ctx)
5623 {
5624 	if_t ifp = ctx->ifc_ifp;
5625 	if_shared_ctx_t sctx = ctx->ifc_sctx;
5626 
5627 	/* Unregister VLAN event handlers early */
5628 	iflib_unregister_vlan_handlers(ctx);
5629 
5630 	if ((sctx->isc_flags & IFLIB_PSEUDO)  &&
5631 		(sctx->isc_flags & IFLIB_PSEUDO_ETHER) == 0) {
5632 		bpfdetach(ifp);
5633 		if_detach(ifp);
5634 	} else {
5635 		ether_ifdetach(ifp);
5636 	}
5637 
5638 	iflib_tqg_detach(ctx);
5639 	iflib_tx_structures_free(ctx);
5640 	iflib_rx_structures_free(ctx);
5641 	IFDI_DETACH(ctx);
5642 	IFDI_QUEUES_FREE(ctx);
5643 
5644 	iflib_deregister(ctx);
5645 
5646 	if (ctx->ifc_flags & IFC_SC_ALLOCATED)
5647 		free(ctx->ifc_softc, M_IFLIB);
5648 	free(ctx, M_IFLIB);
5649 	return (0);
5650 }
5651 
5652 int
iflib_device_attach(device_t dev)5653 iflib_device_attach(device_t dev)
5654 {
5655 	if_ctx_t ctx;
5656 	if_shared_ctx_t sctx;
5657 
5658 	if ((sctx = DEVICE_REGISTER(dev)) == NULL || sctx->isc_magic != IFLIB_MAGIC)
5659 		return (ENOTSUP);
5660 
5661 	pci_enable_busmaster(dev);
5662 
5663 	return (iflib_device_register(dev, NULL, sctx, &ctx));
5664 }
5665 
5666 int
iflib_device_deregister(if_ctx_t ctx)5667 iflib_device_deregister(if_ctx_t ctx)
5668 {
5669 	if_t ifp = ctx->ifc_ifp;
5670 	device_t dev = ctx->ifc_dev;
5671 
5672 	/* Make sure VLANS are not using driver */
5673 	if (if_vlantrunkinuse(ifp)) {
5674 		device_printf(dev, "Vlan in use, detach first\n");
5675 		return (EBUSY);
5676 	}
5677 #ifdef PCI_IOV
5678 	if (!CTX_IS_VF(ctx) && pci_iov_detach(dev) != 0) {
5679 		device_printf(dev, "SR-IOV in use; detach first.\n");
5680 		return (EBUSY);
5681 	}
5682 #endif
5683 
5684 	STATE_LOCK(ctx);
5685 	ctx->ifc_flags |= IFC_IN_DETACH;
5686 	STATE_UNLOCK(ctx);
5687 
5688 	/* Unregister VLAN handlers before calling iflib_stop() */
5689 	iflib_unregister_vlan_handlers(ctx);
5690 
5691 	iflib_netmap_detach(ifp);
5692 	ether_ifdetach(ifp);
5693 
5694 	CTX_LOCK(ctx);
5695 	iflib_stop(ctx);
5696 	CTX_UNLOCK(ctx);
5697 
5698 	iflib_rem_pfil(ctx);
5699 	if (ctx->ifc_led_dev != NULL)
5700 		led_destroy(ctx->ifc_led_dev);
5701 
5702 	iflib_tqg_detach(ctx);
5703 	iflib_tx_structures_free(ctx);
5704 	iflib_rx_structures_free(ctx);
5705 
5706 	CTX_LOCK(ctx);
5707 	IFDI_DETACH(ctx);
5708 	IFDI_QUEUES_FREE(ctx);
5709 	CTX_UNLOCK(ctx);
5710 
5711 	/* ether_ifdetach calls if_qflush - lock must be destroy afterwards*/
5712 	iflib_free_intr_mem(ctx);
5713 
5714 	bus_generic_detach(dev);
5715 
5716 	iflib_deregister(ctx);
5717 
5718 	device_set_softc(ctx->ifc_dev, NULL);
5719 	if (ctx->ifc_flags & IFC_SC_ALLOCATED)
5720 		free(ctx->ifc_softc, M_IFLIB);
5721 	unref_ctx_core_offset(ctx);
5722 	free(ctx, M_IFLIB);
5723 	return (0);
5724 }
5725 
5726 static void
iflib_tqg_detach(if_ctx_t ctx)5727 iflib_tqg_detach(if_ctx_t ctx)
5728 {
5729 	iflib_txq_t txq;
5730 	iflib_rxq_t rxq;
5731 	int i;
5732 	struct taskqgroup *tqg;
5733 
5734 	/* XXX drain any dependent tasks */
5735 	tqg = qgroup_if_io_tqg;
5736 	for (txq = ctx->ifc_txqs, i = 0; i < NTXQSETS(ctx); i++, txq++) {
5737 		callout_drain(&txq->ift_timer);
5738 #ifdef DEV_NETMAP
5739 		callout_drain(&txq->ift_netmap_timer);
5740 #endif /* DEV_NETMAP */
5741 		if (txq->ift_task.gt_uniq != NULL)
5742 			taskqgroup_detach(tqg, &txq->ift_task);
5743 	}
5744 	for (i = 0, rxq = ctx->ifc_rxqs; i < NRXQSETS(ctx); i++, rxq++) {
5745 		if (rxq->ifr_task.gt_uniq != NULL)
5746 			taskqgroup_detach(tqg, &rxq->ifr_task);
5747 	}
5748 	tqg = qgroup_if_config_tqg;
5749 	if (ctx->ifc_admin_task.gt_uniq != NULL)
5750 		taskqgroup_detach(tqg, &ctx->ifc_admin_task);
5751 	if (ctx->ifc_vflr_task.gt_uniq != NULL)
5752 		taskqgroup_detach(tqg, &ctx->ifc_vflr_task);
5753 }
5754 
5755 static void
iflib_free_intr_mem(if_ctx_t ctx)5756 iflib_free_intr_mem(if_ctx_t ctx)
5757 {
5758 
5759 	if (ctx->ifc_softc_ctx.isc_intr != IFLIB_INTR_MSIX) {
5760 		iflib_irq_free(ctx, &ctx->ifc_legacy_irq);
5761 	}
5762 	if (ctx->ifc_softc_ctx.isc_intr != IFLIB_INTR_LEGACY) {
5763 		pci_release_msi(ctx->ifc_dev);
5764 	}
5765 	if (ctx->ifc_msix_mem != NULL) {
5766 		bus_release_resource(ctx->ifc_dev, SYS_RES_MEMORY,
5767 		    rman_get_rid(ctx->ifc_msix_mem), ctx->ifc_msix_mem);
5768 		ctx->ifc_msix_mem = NULL;
5769 	}
5770 }
5771 
5772 int
iflib_device_detach(device_t dev)5773 iflib_device_detach(device_t dev)
5774 {
5775 	if_ctx_t ctx = device_get_softc(dev);
5776 
5777 	return (iflib_device_deregister(ctx));
5778 }
5779 
5780 int
iflib_device_suspend(device_t dev)5781 iflib_device_suspend(device_t dev)
5782 {
5783 	if_ctx_t ctx = device_get_softc(dev);
5784 
5785 	CTX_LOCK(ctx);
5786 	IFDI_SUSPEND(ctx);
5787 	CTX_UNLOCK(ctx);
5788 
5789 	return (bus_generic_suspend(dev));
5790 }
5791 int
iflib_device_shutdown(device_t dev)5792 iflib_device_shutdown(device_t dev)
5793 {
5794 	if_ctx_t ctx = device_get_softc(dev);
5795 
5796 	CTX_LOCK(ctx);
5797 	IFDI_SHUTDOWN(ctx);
5798 	CTX_UNLOCK(ctx);
5799 
5800 	return (bus_generic_suspend(dev));
5801 }
5802 
5803 int
iflib_device_resume(device_t dev)5804 iflib_device_resume(device_t dev)
5805 {
5806 	if_ctx_t ctx = device_get_softc(dev);
5807 	iflib_txq_t txq = ctx->ifc_txqs;
5808 
5809 	CTX_LOCK(ctx);
5810 	IFDI_RESUME(ctx);
5811 	iflib_if_init_locked(ctx);
5812 	CTX_UNLOCK(ctx);
5813 	for (int i = 0; i < NTXQSETS(ctx); i++, txq++)
5814 		iflib_txq_check_drain(txq, IFLIB_RESTART_BUDGET);
5815 
5816 	return (bus_generic_resume(dev));
5817 }
5818 
5819 int
iflib_device_iov_init(device_t dev,uint16_t num_vfs,const nvlist_t * params)5820 iflib_device_iov_init(device_t dev, uint16_t num_vfs, const nvlist_t *params)
5821 {
5822 	int error;
5823 	if_ctx_t ctx = device_get_softc(dev);
5824 
5825 	CTX_LOCK(ctx);
5826 	error = IFDI_IOV_INIT(ctx, num_vfs, params);
5827 	CTX_UNLOCK(ctx);
5828 
5829 	return (error);
5830 }
5831 
5832 void
iflib_device_iov_uninit(device_t dev)5833 iflib_device_iov_uninit(device_t dev)
5834 {
5835 	if_ctx_t ctx = device_get_softc(dev);
5836 
5837 	CTX_LOCK(ctx);
5838 	IFDI_IOV_UNINIT(ctx);
5839 	CTX_UNLOCK(ctx);
5840 }
5841 
5842 int
iflib_device_iov_add_vf(device_t dev,uint16_t vfnum,const nvlist_t * params)5843 iflib_device_iov_add_vf(device_t dev, uint16_t vfnum, const nvlist_t *params)
5844 {
5845 	int error;
5846 	if_ctx_t ctx = device_get_softc(dev);
5847 
5848 	CTX_LOCK(ctx);
5849 	error = IFDI_IOV_VF_ADD(ctx, vfnum, params);
5850 	CTX_UNLOCK(ctx);
5851 
5852 	return (error);
5853 }
5854 
5855 /*********************************************************************
5856  *
5857  *  MODULE FUNCTION DEFINITIONS
5858  *
5859  **********************************************************************/
5860 
5861 /*
5862  * - Start a fast taskqueue thread for each core
5863  * - Start a taskqueue for control operations
5864  */
5865 static int
iflib_module_init(void)5866 iflib_module_init(void)
5867 {
5868 	iflib_timer_default = hz / 2;
5869 	return (0);
5870 }
5871 
5872 static int
iflib_module_event_handler(module_t mod,int what,void * arg)5873 iflib_module_event_handler(module_t mod, int what, void *arg)
5874 {
5875 	int err;
5876 
5877 	switch (what) {
5878 	case MOD_LOAD:
5879 		if ((err = iflib_module_init()) != 0)
5880 			return (err);
5881 		break;
5882 	case MOD_UNLOAD:
5883 		return (EBUSY);
5884 	default:
5885 		return (EOPNOTSUPP);
5886 	}
5887 
5888 	return (0);
5889 }
5890 
5891 /*********************************************************************
5892  *
5893  *  PUBLIC FUNCTION DEFINITIONS
5894  *     ordered as in iflib.h
5895  *
5896  **********************************************************************/
5897 
5898 static void
_iflib_assert(if_shared_ctx_t sctx)5899 _iflib_assert(if_shared_ctx_t sctx)
5900 {
5901 	int i;
5902 
5903 	MPASS(sctx->isc_tx_maxsize);
5904 	MPASS(sctx->isc_tx_maxsegsize);
5905 
5906 	MPASS(sctx->isc_rx_maxsize);
5907 	MPASS(sctx->isc_rx_nsegments);
5908 	MPASS(sctx->isc_rx_maxsegsize);
5909 
5910 	MPASS(sctx->isc_nrxqs >= 1 && sctx->isc_nrxqs <= 8);
5911 	for (i = 0; i < sctx->isc_nrxqs; i++) {
5912 		MPASS(sctx->isc_nrxd_min[i]);
5913 		MPASS(powerof2(sctx->isc_nrxd_min[i]));
5914 		MPASS(sctx->isc_nrxd_max[i]);
5915 		MPASS(powerof2(sctx->isc_nrxd_max[i]));
5916 		MPASS(sctx->isc_nrxd_default[i]);
5917 		MPASS(powerof2(sctx->isc_nrxd_default[i]));
5918 	}
5919 
5920 	MPASS(sctx->isc_ntxqs >= 1 && sctx->isc_ntxqs <= 8);
5921 	for (i = 0; i < sctx->isc_ntxqs; i++) {
5922 		MPASS(sctx->isc_ntxd_min[i]);
5923 		MPASS(powerof2(sctx->isc_ntxd_min[i]));
5924 		MPASS(sctx->isc_ntxd_max[i]);
5925 		MPASS(powerof2(sctx->isc_ntxd_max[i]));
5926 		MPASS(sctx->isc_ntxd_default[i]);
5927 		MPASS(powerof2(sctx->isc_ntxd_default[i]));
5928 	}
5929 }
5930 
5931 static void
_iflib_pre_assert(if_softc_ctx_t scctx)5932 _iflib_pre_assert(if_softc_ctx_t scctx)
5933 {
5934 
5935 	MPASS(scctx->isc_txrx->ift_txd_encap);
5936 	MPASS(scctx->isc_txrx->ift_txd_flush);
5937 	MPASS(scctx->isc_txrx->ift_txd_credits_update);
5938 	MPASS(scctx->isc_txrx->ift_rxd_available);
5939 	MPASS(scctx->isc_txrx->ift_rxd_pkt_get);
5940 	MPASS(scctx->isc_txrx->ift_rxd_refill);
5941 	MPASS(scctx->isc_txrx->ift_rxd_flush);
5942 }
5943 
5944 static int
iflib_register(if_ctx_t ctx)5945 iflib_register(if_ctx_t ctx)
5946 {
5947 	if_shared_ctx_t sctx = ctx->ifc_sctx;
5948 	driver_t *driver = sctx->isc_driver;
5949 	device_t dev = ctx->ifc_dev;
5950 	if_t ifp;
5951 	u_char type;
5952 	int iflags;
5953 
5954 	if ((sctx->isc_flags & IFLIB_PSEUDO) == 0)
5955 		_iflib_assert(sctx);
5956 
5957 	CTX_LOCK_INIT(ctx);
5958 	STATE_LOCK_INIT(ctx, device_get_nameunit(ctx->ifc_dev));
5959 	if (sctx->isc_flags & IFLIB_PSEUDO) {
5960 		if (sctx->isc_flags & IFLIB_PSEUDO_ETHER)
5961 			type = IFT_ETHER;
5962 		else
5963 			type = IFT_PPP;
5964 	} else
5965 		type = IFT_ETHER;
5966 	ifp = ctx->ifc_ifp = if_alloc(type);
5967 
5968 	/*
5969 	 * Initialize our context's device specific methods
5970 	 */
5971 	kobj_init((kobj_t) ctx, (kobj_class_t) driver);
5972 	kobj_class_compile((kobj_class_t) driver);
5973 
5974 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
5975 	if_setsoftc(ifp, ctx);
5976 	if_setdev(ifp, dev);
5977 	if_setinitfn(ifp, iflib_if_init);
5978 	if_setioctlfn(ifp, iflib_if_ioctl);
5979 #ifdef ALTQ
5980 	if_setstartfn(ifp, iflib_altq_if_start);
5981 	if_settransmitfn(ifp, iflib_altq_if_transmit);
5982 	if_setsendqready(ifp);
5983 #else
5984 	if_settransmitfn(ifp, iflib_if_transmit);
5985 #endif
5986 	if_setqflushfn(ifp, iflib_if_qflush);
5987 	iflags = IFF_MULTICAST | IFF_KNOWSEPOCH;
5988 
5989 	if ((sctx->isc_flags & IFLIB_PSEUDO) &&
5990 		(sctx->isc_flags & IFLIB_PSEUDO_ETHER) == 0)
5991 		iflags |= IFF_POINTOPOINT;
5992 	else
5993 		iflags |= IFF_BROADCAST | IFF_SIMPLEX;
5994 	if_setflags(ifp, iflags);
5995 	ctx->ifc_vlan_attach_event =
5996 		EVENTHANDLER_REGISTER(vlan_config, iflib_vlan_register, ctx,
5997 							  EVENTHANDLER_PRI_FIRST);
5998 	ctx->ifc_vlan_detach_event =
5999 		EVENTHANDLER_REGISTER(vlan_unconfig, iflib_vlan_unregister, ctx,
6000 							  EVENTHANDLER_PRI_FIRST);
6001 
6002 	if ((sctx->isc_flags & IFLIB_DRIVER_MEDIA) == 0) {
6003 		ctx->ifc_mediap = &ctx->ifc_media;
6004 		ifmedia_init(ctx->ifc_mediap, IFM_IMASK,
6005 		    iflib_media_change, iflib_media_status);
6006 	}
6007 	return (0);
6008 }
6009 
6010 static void
iflib_unregister_vlan_handlers(if_ctx_t ctx)6011 iflib_unregister_vlan_handlers(if_ctx_t ctx)
6012 {
6013 	/* Unregister VLAN events */
6014 	if (ctx->ifc_vlan_attach_event != NULL) {
6015 		EVENTHANDLER_DEREGISTER(vlan_config, ctx->ifc_vlan_attach_event);
6016 		ctx->ifc_vlan_attach_event = NULL;
6017 	}
6018 	if (ctx->ifc_vlan_detach_event != NULL) {
6019 		EVENTHANDLER_DEREGISTER(vlan_unconfig, ctx->ifc_vlan_detach_event);
6020 		ctx->ifc_vlan_detach_event = NULL;
6021 	}
6022 
6023 }
6024 
6025 static void
iflib_deregister(if_ctx_t ctx)6026 iflib_deregister(if_ctx_t ctx)
6027 {
6028 	if_t ifp = ctx->ifc_ifp;
6029 
6030 	/* Remove all media */
6031 	ifmedia_removeall(&ctx->ifc_media);
6032 
6033 	/* Ensure that VLAN event handlers are unregistered */
6034 	iflib_unregister_vlan_handlers(ctx);
6035 
6036 	/* Release kobject reference */
6037 	kobj_delete((kobj_t) ctx, NULL);
6038 
6039 	/* Free the ifnet structure */
6040 	if_free(ifp);
6041 
6042 	STATE_LOCK_DESTROY(ctx);
6043 
6044 	/* ether_ifdetach calls if_qflush - lock must be destroy afterwards*/
6045 	CTX_LOCK_DESTROY(ctx);
6046 }
6047 
6048 static int
iflib_queues_alloc(if_ctx_t ctx)6049 iflib_queues_alloc(if_ctx_t ctx)
6050 {
6051 	if_shared_ctx_t sctx = ctx->ifc_sctx;
6052 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
6053 	device_t dev = ctx->ifc_dev;
6054 	int nrxqsets = scctx->isc_nrxqsets;
6055 	int ntxqsets = scctx->isc_ntxqsets;
6056 	iflib_txq_t txq;
6057 	iflib_rxq_t rxq;
6058 	iflib_fl_t fl = NULL;
6059 	int i, j, cpu, err, txconf, rxconf;
6060 	iflib_dma_info_t ifdip;
6061 	uint32_t *rxqsizes = scctx->isc_rxqsizes;
6062 	uint32_t *txqsizes = scctx->isc_txqsizes;
6063 	uint8_t nrxqs = sctx->isc_nrxqs;
6064 	uint8_t ntxqs = sctx->isc_ntxqs;
6065 	int nfree_lists = sctx->isc_nfl ? sctx->isc_nfl : 1;
6066 	int fl_offset = (sctx->isc_flags & IFLIB_HAS_RXCQ ? 1 : 0);
6067 	caddr_t *vaddrs;
6068 	uint64_t *paddrs;
6069 
6070 	KASSERT(ntxqs > 0, ("number of queues per qset must be at least 1"));
6071 	KASSERT(nrxqs > 0, ("number of queues per qset must be at least 1"));
6072 	KASSERT(nrxqs >= fl_offset + nfree_lists,
6073            ("there must be at least a rxq for each free list"));
6074 
6075 	/* Allocate the TX ring struct memory */
6076 	if (!(ctx->ifc_txqs =
6077 	    (iflib_txq_t) malloc(sizeof(struct iflib_txq) *
6078 	    ntxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
6079 		device_printf(dev, "Unable to allocate TX ring memory\n");
6080 		err = ENOMEM;
6081 		goto fail;
6082 	}
6083 
6084 	/* Now allocate the RX */
6085 	if (!(ctx->ifc_rxqs =
6086 	    (iflib_rxq_t) malloc(sizeof(struct iflib_rxq) *
6087 	    nrxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
6088 		device_printf(dev, "Unable to allocate RX ring memory\n");
6089 		err = ENOMEM;
6090 		goto rx_fail;
6091 	}
6092 
6093 	txq = ctx->ifc_txqs;
6094 	rxq = ctx->ifc_rxqs;
6095 
6096 	/*
6097 	 * XXX handle allocation failure
6098 	 */
6099 	for (txconf = i = 0, cpu = CPU_FIRST(); i < ntxqsets; i++, txconf++, txq++, cpu = CPU_NEXT(cpu)) {
6100 		/* Set up some basics */
6101 
6102 		if ((ifdip = malloc(sizeof(struct iflib_dma_info) * ntxqs,
6103 		    M_IFLIB, M_NOWAIT | M_ZERO)) == NULL) {
6104 			device_printf(dev,
6105 			    "Unable to allocate TX DMA info memory\n");
6106 			err = ENOMEM;
6107 			goto err_tx_desc;
6108 		}
6109 		txq->ift_ifdi = ifdip;
6110 		for (j = 0; j < ntxqs; j++, ifdip++) {
6111 			if (iflib_dma_alloc(ctx, txqsizes[j], ifdip, 0)) {
6112 				device_printf(dev,
6113 				    "Unable to allocate TX descriptors\n");
6114 				err = ENOMEM;
6115 				goto err_tx_desc;
6116 			}
6117 			txq->ift_txd_size[j] = scctx->isc_txd_size[j];
6118 			bzero((void *)ifdip->idi_vaddr, txqsizes[j]);
6119 		}
6120 		txq->ift_ctx = ctx;
6121 		txq->ift_id = i;
6122 		if (sctx->isc_flags & IFLIB_HAS_TXCQ) {
6123 			txq->ift_br_offset = 1;
6124 		} else {
6125 			txq->ift_br_offset = 0;
6126 		}
6127 
6128 		if (iflib_txsd_alloc(txq)) {
6129 			device_printf(dev, "Critical Failure setting up TX buffers\n");
6130 			err = ENOMEM;
6131 			goto err_tx_desc;
6132 		}
6133 
6134 		/* Initialize the TX lock */
6135 		snprintf(txq->ift_mtx_name, MTX_NAME_LEN, "%s:TX(%d):callout",
6136 		    device_get_nameunit(dev), txq->ift_id);
6137 		mtx_init(&txq->ift_mtx, txq->ift_mtx_name, NULL, MTX_DEF);
6138 		callout_init_mtx(&txq->ift_timer, &txq->ift_mtx, 0);
6139 		txq->ift_timer.c_cpu = cpu;
6140 #ifdef DEV_NETMAP
6141 		callout_init_mtx(&txq->ift_netmap_timer, &txq->ift_mtx, 0);
6142 		txq->ift_netmap_timer.c_cpu = cpu;
6143 #endif /* DEV_NETMAP */
6144 
6145 		err = ifmp_ring_alloc(&txq->ift_br, 2048, txq, iflib_txq_drain,
6146 				      iflib_txq_can_drain, M_IFLIB, M_WAITOK);
6147 		if (err) {
6148 			/* XXX free any allocated rings */
6149 			device_printf(dev, "Unable to allocate buf_ring\n");
6150 			goto err_tx_desc;
6151 		}
6152 	}
6153 
6154 	for (rxconf = i = 0; i < nrxqsets; i++, rxconf++, rxq++) {
6155 		/* Set up some basics */
6156 		callout_init(&rxq->ifr_watchdog, 1);
6157 
6158 		if ((ifdip = malloc(sizeof(struct iflib_dma_info) * nrxqs,
6159 		   M_IFLIB, M_NOWAIT | M_ZERO)) == NULL) {
6160 			device_printf(dev,
6161 			    "Unable to allocate RX DMA info memory\n");
6162 			err = ENOMEM;
6163 			goto err_tx_desc;
6164 		}
6165 
6166 		rxq->ifr_ifdi = ifdip;
6167 		/* XXX this needs to be changed if #rx queues != #tx queues */
6168 		rxq->ifr_ntxqirq = 1;
6169 		rxq->ifr_txqid[0] = i;
6170 		for (j = 0; j < nrxqs; j++, ifdip++) {
6171 			if (iflib_dma_alloc(ctx, rxqsizes[j], ifdip, 0)) {
6172 				device_printf(dev,
6173 				    "Unable to allocate RX descriptors\n");
6174 				err = ENOMEM;
6175 				goto err_tx_desc;
6176 			}
6177 			bzero((void *)ifdip->idi_vaddr, rxqsizes[j]);
6178 		}
6179 		rxq->ifr_ctx = ctx;
6180 		rxq->ifr_id = i;
6181 		rxq->ifr_fl_offset = fl_offset;
6182 		rxq->ifr_nfl = nfree_lists;
6183 		if (!(fl =
6184 			  (iflib_fl_t) malloc(sizeof(struct iflib_fl) * nfree_lists, M_IFLIB, M_NOWAIT | M_ZERO))) {
6185 			device_printf(dev, "Unable to allocate free list memory\n");
6186 			err = ENOMEM;
6187 			goto err_tx_desc;
6188 		}
6189 		rxq->ifr_fl = fl;
6190 		for (j = 0; j < nfree_lists; j++) {
6191 			fl[j].ifl_rxq = rxq;
6192 			fl[j].ifl_id = j;
6193 			fl[j].ifl_ifdi = &rxq->ifr_ifdi[j + rxq->ifr_fl_offset];
6194 			fl[j].ifl_rxd_size = scctx->isc_rxd_size[j];
6195 		}
6196 		/* Allocate receive buffers for the ring */
6197 		if (iflib_rxsd_alloc(rxq)) {
6198 			device_printf(dev,
6199 			    "Critical Failure setting up receive buffers\n");
6200 			err = ENOMEM;
6201 			goto err_rx_desc;
6202 		}
6203 
6204 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++)
6205 			fl->ifl_rx_bitmap = bit_alloc(fl->ifl_size, M_IFLIB,
6206 			    M_WAITOK);
6207 	}
6208 
6209 	/* TXQs */
6210 	vaddrs = malloc(sizeof(caddr_t)  * ntxqsets * ntxqs, M_IFLIB, M_WAITOK);
6211 	paddrs = malloc(sizeof(uint64_t) * ntxqsets * ntxqs, M_IFLIB, M_WAITOK);
6212 	for (i = 0; i < ntxqsets; i++) {
6213 		iflib_dma_info_t di = ctx->ifc_txqs[i].ift_ifdi;
6214 
6215 		for (j = 0; j < ntxqs; j++, di++) {
6216 			vaddrs[i * ntxqs + j] = di->idi_vaddr;
6217 			paddrs[i * ntxqs + j] = di->idi_paddr;
6218 		}
6219 	}
6220 	if ((err = IFDI_TX_QUEUES_ALLOC(ctx, vaddrs, paddrs, ntxqs, ntxqsets)) != 0) {
6221 		device_printf(ctx->ifc_dev,
6222 		    "Unable to allocate device TX queue\n");
6223 		iflib_tx_structures_free(ctx);
6224 		free(vaddrs, M_IFLIB);
6225 		free(paddrs, M_IFLIB);
6226 		goto err_rx_desc;
6227 	}
6228 	free(vaddrs, M_IFLIB);
6229 	free(paddrs, M_IFLIB);
6230 
6231 	/* RXQs */
6232 	vaddrs = malloc(sizeof(caddr_t)  * nrxqsets * nrxqs, M_IFLIB, M_WAITOK);
6233 	paddrs = malloc(sizeof(uint64_t) * nrxqsets * nrxqs, M_IFLIB, M_WAITOK);
6234 	for (i = 0; i < nrxqsets; i++) {
6235 		iflib_dma_info_t di = ctx->ifc_rxqs[i].ifr_ifdi;
6236 
6237 		for (j = 0; j < nrxqs; j++, di++) {
6238 			vaddrs[i * nrxqs + j] = di->idi_vaddr;
6239 			paddrs[i * nrxqs + j] = di->idi_paddr;
6240 		}
6241 	}
6242 	if ((err = IFDI_RX_QUEUES_ALLOC(ctx, vaddrs, paddrs, nrxqs, nrxqsets)) != 0) {
6243 		device_printf(ctx->ifc_dev,
6244 		    "Unable to allocate device RX queue\n");
6245 		iflib_tx_structures_free(ctx);
6246 		free(vaddrs, M_IFLIB);
6247 		free(paddrs, M_IFLIB);
6248 		goto err_rx_desc;
6249 	}
6250 	free(vaddrs, M_IFLIB);
6251 	free(paddrs, M_IFLIB);
6252 
6253 	return (0);
6254 
6255 /* XXX handle allocation failure changes */
6256 err_rx_desc:
6257 err_tx_desc:
6258 rx_fail:
6259 	if (ctx->ifc_rxqs != NULL)
6260 		free(ctx->ifc_rxqs, M_IFLIB);
6261 	ctx->ifc_rxqs = NULL;
6262 	if (ctx->ifc_txqs != NULL)
6263 		free(ctx->ifc_txqs, M_IFLIB);
6264 	ctx->ifc_txqs = NULL;
6265 fail:
6266 	return (err);
6267 }
6268 
6269 static int
iflib_tx_structures_setup(if_ctx_t ctx)6270 iflib_tx_structures_setup(if_ctx_t ctx)
6271 {
6272 	iflib_txq_t txq = ctx->ifc_txqs;
6273 	int i;
6274 
6275 	for (i = 0; i < NTXQSETS(ctx); i++, txq++)
6276 		iflib_txq_setup(txq);
6277 
6278 	return (0);
6279 }
6280 
6281 static void
iflib_tx_structures_free(if_ctx_t ctx)6282 iflib_tx_structures_free(if_ctx_t ctx)
6283 {
6284 	iflib_txq_t txq = ctx->ifc_txqs;
6285 	if_shared_ctx_t sctx = ctx->ifc_sctx;
6286 	int i, j;
6287 
6288 	for (i = 0; i < NTXQSETS(ctx); i++, txq++) {
6289 		for (j = 0; j < sctx->isc_ntxqs; j++)
6290 			iflib_dma_free(&txq->ift_ifdi[j]);
6291 		iflib_txq_destroy(txq);
6292 	}
6293 	free(ctx->ifc_txqs, M_IFLIB);
6294 	ctx->ifc_txqs = NULL;
6295 }
6296 
6297 /*********************************************************************
6298  *
6299  *  Initialize all receive rings.
6300  *
6301  **********************************************************************/
6302 static int
iflib_rx_structures_setup(if_ctx_t ctx)6303 iflib_rx_structures_setup(if_ctx_t ctx)
6304 {
6305 	iflib_rxq_t rxq = ctx->ifc_rxqs;
6306 	int q;
6307 #if defined(INET6) || defined(INET)
6308 	int err, i;
6309 #endif
6310 
6311 	for (q = 0; q < ctx->ifc_softc_ctx.isc_nrxqsets; q++, rxq++) {
6312 #if defined(INET6) || defined(INET)
6313 		if (if_getcapabilities(ctx->ifc_ifp) & IFCAP_LRO) {
6314 			err = tcp_lro_init_args(&rxq->ifr_lc, ctx->ifc_ifp,
6315 			    TCP_LRO_ENTRIES, min(1024,
6316 			    ctx->ifc_softc_ctx.isc_nrxd[rxq->ifr_fl_offset]));
6317 			if (err != 0) {
6318 				device_printf(ctx->ifc_dev,
6319 				    "LRO Initialization failed!\n");
6320 				goto fail;
6321 			}
6322 		}
6323 #endif
6324 		IFDI_RXQ_SETUP(ctx, rxq->ifr_id);
6325 	}
6326 	return (0);
6327 #if defined(INET6) || defined(INET)
6328 fail:
6329 	/*
6330 	 * Free LRO resources allocated so far, we will only handle
6331 	 * the rings that completed, the failing case will have
6332 	 * cleaned up for itself.  'q' failed, so its the terminus.
6333 	 */
6334 	rxq = ctx->ifc_rxqs;
6335 	for (i = 0; i < q; ++i, rxq++) {
6336 		if (if_getcapabilities(ctx->ifc_ifp) & IFCAP_LRO)
6337 			tcp_lro_free(&rxq->ifr_lc);
6338 	}
6339 	return (err);
6340 #endif
6341 }
6342 
6343 /*********************************************************************
6344  *
6345  *  Free all receive rings.
6346  *
6347  **********************************************************************/
6348 static void
iflib_rx_structures_free(if_ctx_t ctx)6349 iflib_rx_structures_free(if_ctx_t ctx)
6350 {
6351 	iflib_rxq_t rxq = ctx->ifc_rxqs;
6352 	if_shared_ctx_t sctx = ctx->ifc_sctx;
6353 	int i, j;
6354 
6355 	for (i = 0; i < ctx->ifc_softc_ctx.isc_nrxqsets; i++, rxq++) {
6356 		for (j = 0; j < sctx->isc_nrxqs; j++)
6357 			iflib_dma_free(&rxq->ifr_ifdi[j]);
6358 		iflib_rx_sds_free(rxq);
6359 #if defined(INET6) || defined(INET)
6360 		if (if_getcapabilities(ctx->ifc_ifp) & IFCAP_LRO)
6361 			tcp_lro_free(&rxq->ifr_lc);
6362 #endif
6363 	}
6364 	free(ctx->ifc_rxqs, M_IFLIB);
6365 	ctx->ifc_rxqs = NULL;
6366 }
6367 
6368 static int
iflib_qset_structures_setup(if_ctx_t ctx)6369 iflib_qset_structures_setup(if_ctx_t ctx)
6370 {
6371 	int err;
6372 
6373 	/*
6374 	 * It is expected that the caller takes care of freeing queues if this
6375 	 * fails.
6376 	 */
6377 	if ((err = iflib_tx_structures_setup(ctx)) != 0) {
6378 		device_printf(ctx->ifc_dev, "iflib_tx_structures_setup failed: %d\n", err);
6379 		return (err);
6380 	}
6381 
6382 	if ((err = iflib_rx_structures_setup(ctx)) != 0)
6383 		device_printf(ctx->ifc_dev, "iflib_rx_structures_setup failed: %d\n", err);
6384 
6385 	return (err);
6386 }
6387 
6388 int
iflib_irq_alloc(if_ctx_t ctx,if_irq_t irq,int rid,driver_filter_t filter,void * filter_arg,driver_intr_t handler,void * arg,const char * name)6389 iflib_irq_alloc(if_ctx_t ctx, if_irq_t irq, int rid,
6390 		driver_filter_t filter, void *filter_arg, driver_intr_t handler, void *arg, const char *name)
6391 {
6392 
6393 	return (_iflib_irq_alloc(ctx, irq, rid, filter, handler, arg, name));
6394 }
6395 
6396 /* Just to avoid copy/paste */
6397 static inline int
iflib_irq_set_affinity(if_ctx_t ctx,if_irq_t irq,iflib_intr_type_t type,int qid,struct grouptask * gtask,struct taskqgroup * tqg,void * uniq,const char * name)6398 iflib_irq_set_affinity(if_ctx_t ctx, if_irq_t irq, iflib_intr_type_t type,
6399     int qid, struct grouptask *gtask, struct taskqgroup *tqg, void *uniq,
6400     const char *name)
6401 {
6402 	device_t dev;
6403 	unsigned int base_cpuid, cpuid;
6404 	int err;
6405 
6406 	dev = ctx->ifc_dev;
6407 	base_cpuid = ctx->ifc_sysctl_core_offset;
6408 	cpuid = get_cpuid_for_queue(ctx, base_cpuid, qid, type == IFLIB_INTR_TX);
6409 	err = taskqgroup_attach_cpu(tqg, gtask, uniq, cpuid, dev,
6410 	    irq ? irq->ii_res : NULL, name);
6411 	if (err) {
6412 		device_printf(dev, "taskqgroup_attach_cpu failed %d\n", err);
6413 		return (err);
6414 	}
6415 #ifdef notyet
6416 	if (cpuid > ctx->ifc_cpuid_highest)
6417 		ctx->ifc_cpuid_highest = cpuid;
6418 #endif
6419 	return (0);
6420 }
6421 
6422 /*
6423  * Allocate a hardware interrupt for subctx using the parent (ctx)'s hardware
6424  * resources.
6425  *
6426  * Similar to iflib_irq_alloc_generic(), but for interrupt type IFLIB_INTR_RXTX
6427  * only.
6428  *
6429  * XXX: Could be removed if subctx's dev has its intr resource allocation
6430  * methods replaced with custom ones?
6431  */
6432 int
iflib_irq_alloc_generic_subctx(if_ctx_t ctx,if_ctx_t subctx,if_irq_t irq,int rid,iflib_intr_type_t type,driver_filter_t * filter,void * filter_arg,int qid,const char * name)6433 iflib_irq_alloc_generic_subctx(if_ctx_t ctx, if_ctx_t subctx, if_irq_t irq,
6434 			       int rid, iflib_intr_type_t type,
6435 			       driver_filter_t *filter, void *filter_arg,
6436 			       int qid, const char *name)
6437 {
6438 	device_t dev, subdev;
6439 	struct grouptask *gtask;
6440 	struct taskqgroup *tqg;
6441 	iflib_filter_info_t info;
6442 	gtask_fn_t *fn;
6443 	int tqrid, err;
6444 	driver_filter_t *intr_fast;
6445 	void *q;
6446 
6447 	MPASS(ctx != NULL);
6448 	MPASS(subctx != NULL);
6449 
6450 	tqrid = rid;
6451 	dev = ctx->ifc_dev;
6452 	subdev = subctx->ifc_dev;
6453 
6454 	switch (type) {
6455 	case IFLIB_INTR_RXTX:
6456 		q = &subctx->ifc_rxqs[qid];
6457 		info = &subctx->ifc_rxqs[qid].ifr_filter_info;
6458 		gtask = &subctx->ifc_rxqs[qid].ifr_task;
6459 		tqg = qgroup_if_io_tqg;
6460 		fn = _task_fn_rx;
6461 		intr_fast = iflib_fast_intr_rxtx;
6462 		NET_GROUPTASK_INIT(gtask, 0, fn, q);
6463 		break;
6464 	default:
6465 		device_printf(dev, "%s: unknown net intr type for subctx %s (%d)\n",
6466 		    __func__, device_get_nameunit(subdev), type);
6467 		return (EINVAL);
6468 	}
6469 
6470 	info->ifi_filter = filter;
6471 	info->ifi_filter_arg = filter_arg;
6472 	info->ifi_task = gtask;
6473 	info->ifi_ctx = q;
6474 
6475 	NET_GROUPTASK_INIT(gtask, 0, fn, q);
6476 
6477 	/* Allocate interrupts from hardware using parent context */
6478 	err = _iflib_irq_alloc(ctx, irq, rid, intr_fast, NULL, info, name);
6479 	if (err != 0) {
6480 		device_printf(dev, "_iflib_irq_alloc failed for subctx %s: %d\n",
6481 		    device_get_nameunit(subdev), err);
6482 		return (err);
6483 	}
6484 
6485 	if (tqrid != -1) {
6486 		err = iflib_irq_set_affinity(ctx, irq, type, qid, gtask, tqg, q,
6487 		    name);
6488 		if (err)
6489 			return (err);
6490 	} else {
6491 		taskqgroup_attach(tqg, gtask, q, dev, irq->ii_res, name);
6492 	}
6493 
6494 	return (0);
6495 }
6496 
6497 int
iflib_irq_alloc_generic(if_ctx_t ctx,if_irq_t irq,int rid,iflib_intr_type_t type,driver_filter_t * filter,void * filter_arg,int qid,const char * name)6498 iflib_irq_alloc_generic(if_ctx_t ctx, if_irq_t irq, int rid,
6499 			iflib_intr_type_t type, driver_filter_t *filter,
6500 			void *filter_arg, int qid, const char *name)
6501 {
6502 	device_t dev;
6503 	struct grouptask *gtask;
6504 	struct taskqgroup *tqg;
6505 	iflib_filter_info_t info;
6506 	gtask_fn_t *fn;
6507 	int tqrid, err;
6508 	driver_filter_t *intr_fast;
6509 	void *q;
6510 
6511 	info = &ctx->ifc_filter_info;
6512 	tqrid = rid;
6513 
6514 	switch (type) {
6515 	/* XXX merge tx/rx for netmap? */
6516 	case IFLIB_INTR_TX:
6517 		q = &ctx->ifc_txqs[qid];
6518 		info = &ctx->ifc_txqs[qid].ift_filter_info;
6519 		gtask = &ctx->ifc_txqs[qid].ift_task;
6520 		tqg = qgroup_if_io_tqg;
6521 		fn = _task_fn_tx;
6522 		intr_fast = iflib_fast_intr;
6523 		GROUPTASK_INIT(gtask, 0, fn, q);
6524 		ctx->ifc_flags |= IFC_NETMAP_TX_IRQ;
6525 		break;
6526 	case IFLIB_INTR_RX:
6527 		q = &ctx->ifc_rxqs[qid];
6528 		info = &ctx->ifc_rxqs[qid].ifr_filter_info;
6529 		gtask = &ctx->ifc_rxqs[qid].ifr_task;
6530 		tqg = qgroup_if_io_tqg;
6531 		fn = _task_fn_rx;
6532 		intr_fast = iflib_fast_intr;
6533 		NET_GROUPTASK_INIT(gtask, 0, fn, q);
6534 		break;
6535 	case IFLIB_INTR_RXTX:
6536 		q = &ctx->ifc_rxqs[qid];
6537 		info = &ctx->ifc_rxqs[qid].ifr_filter_info;
6538 		gtask = &ctx->ifc_rxqs[qid].ifr_task;
6539 		tqg = qgroup_if_io_tqg;
6540 		fn = _task_fn_rx;
6541 		intr_fast = iflib_fast_intr_rxtx;
6542 		NET_GROUPTASK_INIT(gtask, 0, fn, q);
6543 		break;
6544 	case IFLIB_INTR_ADMIN:
6545 		q = ctx;
6546 		tqrid = -1;
6547 		info = &ctx->ifc_filter_info;
6548 		gtask = &ctx->ifc_admin_task;
6549 		tqg = qgroup_if_config_tqg;
6550 		fn = _task_fn_admin;
6551 		intr_fast = iflib_fast_intr_ctx;
6552 		break;
6553 	default:
6554 		device_printf(ctx->ifc_dev, "%s: unknown net intr type\n",
6555 		    __func__);
6556 		return (EINVAL);
6557 	}
6558 
6559 	info->ifi_filter = filter;
6560 	info->ifi_filter_arg = filter_arg;
6561 	info->ifi_task = gtask;
6562 	info->ifi_ctx = q;
6563 
6564 	dev = ctx->ifc_dev;
6565 	err = _iflib_irq_alloc(ctx, irq, rid, intr_fast, NULL, info,  name);
6566 	if (err != 0) {
6567 		device_printf(dev, "_iflib_irq_alloc failed %d\n", err);
6568 		return (err);
6569 	}
6570 	if (type == IFLIB_INTR_ADMIN)
6571 		return (0);
6572 
6573 	if (tqrid != -1) {
6574 		err = iflib_irq_set_affinity(ctx, irq, type, qid, gtask, tqg, q,
6575 		    name);
6576 		if (err)
6577 			return (err);
6578 	} else {
6579 		taskqgroup_attach(tqg, gtask, q, dev, irq->ii_res, name);
6580 	}
6581 
6582 	return (0);
6583 }
6584 
6585 void
iflib_softirq_alloc_generic(if_ctx_t ctx,if_irq_t irq,iflib_intr_type_t type,void * arg,int qid,const char * name)6586 iflib_softirq_alloc_generic(if_ctx_t ctx, if_irq_t irq, iflib_intr_type_t type,
6587 			    void *arg, int qid, const char *name)
6588 {
6589 	device_t dev;
6590 	struct grouptask *gtask;
6591 	struct taskqgroup *tqg;
6592 	gtask_fn_t *fn;
6593 	void *q;
6594 	int err;
6595 
6596 	switch (type) {
6597 	case IFLIB_INTR_TX:
6598 		q = &ctx->ifc_txqs[qid];
6599 		gtask = &ctx->ifc_txqs[qid].ift_task;
6600 		tqg = qgroup_if_io_tqg;
6601 		fn = _task_fn_tx;
6602 		GROUPTASK_INIT(gtask, 0, fn, q);
6603 		break;
6604 	case IFLIB_INTR_RX:
6605 		q = &ctx->ifc_rxqs[qid];
6606 		gtask = &ctx->ifc_rxqs[qid].ifr_task;
6607 		tqg = qgroup_if_io_tqg;
6608 		fn = _task_fn_rx;
6609 		NET_GROUPTASK_INIT(gtask, 0, fn, q);
6610 		break;
6611 	case IFLIB_INTR_IOV:
6612 		q = ctx;
6613 		gtask = &ctx->ifc_vflr_task;
6614 		tqg = qgroup_if_config_tqg;
6615 		fn = _task_fn_iov;
6616 		GROUPTASK_INIT(gtask, 0, fn, q);
6617 		break;
6618 	default:
6619 		panic("unknown net intr type");
6620 	}
6621 	err = iflib_irq_set_affinity(ctx, irq, type, qid, gtask, tqg, q, name);
6622 	if (err) {
6623 		dev = ctx->ifc_dev;
6624 		taskqgroup_attach(tqg, gtask, q, dev, irq ? irq->ii_res : NULL,
6625 		    name);
6626 	}
6627 }
6628 
6629 void
iflib_irq_free(if_ctx_t ctx,if_irq_t irq)6630 iflib_irq_free(if_ctx_t ctx, if_irq_t irq)
6631 {
6632 
6633 	if (irq->ii_tag)
6634 		bus_teardown_intr(ctx->ifc_dev, irq->ii_res, irq->ii_tag);
6635 
6636 	if (irq->ii_res)
6637 		bus_release_resource(ctx->ifc_dev, SYS_RES_IRQ,
6638 		    rman_get_rid(irq->ii_res), irq->ii_res);
6639 }
6640 
6641 static int
iflib_legacy_setup(if_ctx_t ctx,driver_filter_t filter,void * filter_arg,int * rid,const char * name)6642 iflib_legacy_setup(if_ctx_t ctx, driver_filter_t filter, void *filter_arg, int *rid, const char *name)
6643 {
6644 	iflib_txq_t txq = ctx->ifc_txqs;
6645 	iflib_rxq_t rxq = ctx->ifc_rxqs;
6646 	if_irq_t irq = &ctx->ifc_legacy_irq;
6647 	iflib_filter_info_t info;
6648 	device_t dev;
6649 	struct grouptask *gtask;
6650 	struct resource *res;
6651 	int err, tqrid;
6652 	bool rx_only;
6653 
6654 	info = &rxq->ifr_filter_info;
6655 	gtask = &rxq->ifr_task;
6656 	tqrid = *rid;
6657 	rx_only = (ctx->ifc_sctx->isc_flags & IFLIB_SINGLE_IRQ_RX_ONLY) != 0;
6658 
6659 	ctx->ifc_flags |= IFC_LEGACY;
6660 	info->ifi_filter = filter;
6661 	info->ifi_filter_arg = filter_arg;
6662 	info->ifi_task = gtask;
6663 	info->ifi_ctx = rxq;
6664 
6665 	dev = ctx->ifc_dev;
6666 	/* We allocate a single interrupt resource */
6667 	err = _iflib_irq_alloc(ctx, irq, tqrid, rx_only ? iflib_fast_intr :
6668 	    iflib_fast_intr_rxtx, NULL, info, name);
6669 	if (err != 0)
6670 		return (err);
6671 	NET_GROUPTASK_INIT(gtask, 0, _task_fn_rx, rxq);
6672 	res = irq->ii_res;
6673 	taskqgroup_attach(qgroup_if_io_tqg, gtask, rxq, dev, res, name);
6674 
6675 	GROUPTASK_INIT(&txq->ift_task, 0, _task_fn_tx, txq);
6676 	taskqgroup_attach(qgroup_if_io_tqg, &txq->ift_task, txq, dev, res,
6677 	    "tx");
6678 	return (0);
6679 }
6680 
6681 void
iflib_led_create(if_ctx_t ctx)6682 iflib_led_create(if_ctx_t ctx)
6683 {
6684 
6685 	ctx->ifc_led_dev = led_create(iflib_led_func, ctx,
6686 	    device_get_nameunit(ctx->ifc_dev));
6687 }
6688 
6689 void
iflib_tx_intr_deferred(if_ctx_t ctx,int txqid)6690 iflib_tx_intr_deferred(if_ctx_t ctx, int txqid)
6691 {
6692 
6693 	GROUPTASK_ENQUEUE(&ctx->ifc_txqs[txqid].ift_task);
6694 }
6695 
6696 void
iflib_rx_intr_deferred(if_ctx_t ctx,int rxqid)6697 iflib_rx_intr_deferred(if_ctx_t ctx, int rxqid)
6698 {
6699 
6700 	GROUPTASK_ENQUEUE(&ctx->ifc_rxqs[rxqid].ifr_task);
6701 }
6702 
6703 void
iflib_admin_intr_deferred(if_ctx_t ctx)6704 iflib_admin_intr_deferred(if_ctx_t ctx)
6705 {
6706 
6707 	MPASS(ctx->ifc_admin_task.gt_taskqueue != NULL);
6708 	GROUPTASK_ENQUEUE(&ctx->ifc_admin_task);
6709 }
6710 
6711 void
iflib_iov_intr_deferred(if_ctx_t ctx)6712 iflib_iov_intr_deferred(if_ctx_t ctx)
6713 {
6714 
6715 	GROUPTASK_ENQUEUE(&ctx->ifc_vflr_task);
6716 }
6717 
6718 void
iflib_io_tqg_attach(struct grouptask * gt,void * uniq,int cpu,const char * name)6719 iflib_io_tqg_attach(struct grouptask *gt, void *uniq, int cpu, const char *name)
6720 {
6721 
6722 	taskqgroup_attach_cpu(qgroup_if_io_tqg, gt, uniq, cpu, NULL, NULL,
6723 	    name);
6724 }
6725 
6726 void
iflib_config_gtask_init(void * ctx,struct grouptask * gtask,gtask_fn_t * fn,const char * name)6727 iflib_config_gtask_init(void *ctx, struct grouptask *gtask, gtask_fn_t *fn,
6728 	const char *name)
6729 {
6730 
6731 	GROUPTASK_INIT(gtask, 0, fn, ctx);
6732 	taskqgroup_attach(qgroup_if_config_tqg, gtask, gtask, NULL, NULL,
6733 	    name);
6734 }
6735 
6736 void
iflib_config_gtask_deinit(struct grouptask * gtask)6737 iflib_config_gtask_deinit(struct grouptask *gtask)
6738 {
6739 
6740 	taskqgroup_detach(qgroup_if_config_tqg, gtask);
6741 }
6742 
6743 void
iflib_link_state_change(if_ctx_t ctx,int link_state,uint64_t baudrate)6744 iflib_link_state_change(if_ctx_t ctx, int link_state, uint64_t baudrate)
6745 {
6746 	if_t ifp = ctx->ifc_ifp;
6747 	iflib_txq_t txq = ctx->ifc_txqs;
6748 
6749 	if_setbaudrate(ifp, baudrate);
6750 	if (baudrate >= IF_Gbps(10)) {
6751 		STATE_LOCK(ctx);
6752 		ctx->ifc_flags |= IFC_PREFETCH;
6753 		STATE_UNLOCK(ctx);
6754 	}
6755 	/* If link down, disable watchdog */
6756 	if ((ctx->ifc_link_state == LINK_STATE_UP) && (link_state == LINK_STATE_DOWN)) {
6757 		for (int i = 0; i < ctx->ifc_softc_ctx.isc_ntxqsets; i++, txq++)
6758 			txq->ift_qstatus = IFLIB_QUEUE_IDLE;
6759 	}
6760 	ctx->ifc_link_state = link_state;
6761 	if_link_state_change(ifp, link_state);
6762 }
6763 
6764 static int
iflib_tx_credits_update(if_ctx_t ctx,iflib_txq_t txq)6765 iflib_tx_credits_update(if_ctx_t ctx, iflib_txq_t txq)
6766 {
6767 	int credits;
6768 #ifdef INVARIANTS
6769 	int credits_pre = txq->ift_cidx_processed;
6770 #endif
6771 
6772 	bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
6773 	    BUS_DMASYNC_POSTREAD);
6774 	if ((credits = ctx->isc_txd_credits_update(ctx->ifc_softc, txq->ift_id, true)) == 0)
6775 		return (0);
6776 
6777 	txq->ift_processed += credits;
6778 	txq->ift_cidx_processed += credits;
6779 
6780 	MPASS(credits_pre + credits == txq->ift_cidx_processed);
6781 	if (txq->ift_cidx_processed >= txq->ift_size)
6782 		txq->ift_cidx_processed -= txq->ift_size;
6783 	return (credits);
6784 }
6785 
6786 static int
iflib_rxd_avail(if_ctx_t ctx,iflib_rxq_t rxq,qidx_t cidx,qidx_t budget)6787 iflib_rxd_avail(if_ctx_t ctx, iflib_rxq_t rxq, qidx_t cidx, qidx_t budget)
6788 {
6789 	iflib_fl_t fl;
6790 	u_int i;
6791 
6792 	for (i = 0, fl = &rxq->ifr_fl[0]; i < rxq->ifr_nfl; i++, fl++)
6793 		bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
6794 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
6795 	return (ctx->isc_rxd_available(ctx->ifc_softc, rxq->ifr_id, cidx,
6796 	    budget));
6797 }
6798 
6799 void
iflib_add_int_delay_sysctl(if_ctx_t ctx,const char * name,const char * description,if_int_delay_info_t info,int offset,int value)6800 iflib_add_int_delay_sysctl(if_ctx_t ctx, const char *name,
6801 	const char *description, if_int_delay_info_t info,
6802 	int offset, int value)
6803 {
6804 	info->iidi_ctx = ctx;
6805 	info->iidi_offset = offset;
6806 	info->iidi_value = value;
6807 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(ctx->ifc_dev),
6808 	    SYSCTL_CHILDREN(device_get_sysctl_tree(ctx->ifc_dev)),
6809 	    OID_AUTO, name, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
6810 	    info, 0, iflib_sysctl_int_delay, "I", description);
6811 }
6812 
6813 struct sx *
iflib_ctx_lock_get(if_ctx_t ctx)6814 iflib_ctx_lock_get(if_ctx_t ctx)
6815 {
6816 
6817 	return (&ctx->ifc_ctx_sx);
6818 }
6819 
6820 static int
iflib_msix_init(if_ctx_t ctx)6821 iflib_msix_init(if_ctx_t ctx)
6822 {
6823 	device_t dev = ctx->ifc_dev;
6824 	if_shared_ctx_t sctx = ctx->ifc_sctx;
6825 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
6826 	int admincnt, bar, err, iflib_num_rx_queues, iflib_num_tx_queues;
6827 	int msgs, queuemsgs, queues, rx_queues, tx_queues, vectors;
6828 
6829 	iflib_num_tx_queues = ctx->ifc_sysctl_ntxqs;
6830 	iflib_num_rx_queues = ctx->ifc_sysctl_nrxqs;
6831 
6832 	if (bootverbose)
6833 		device_printf(dev, "msix_init qsets capped at %d\n",
6834 		    imax(scctx->isc_ntxqsets, scctx->isc_nrxqsets));
6835 
6836 	/* Override by tuneable */
6837 	if (scctx->isc_disable_msix)
6838 		goto msi;
6839 
6840 	/* First try MSI-X */
6841 	if ((msgs = pci_msix_count(dev)) == 0) {
6842 		if (bootverbose)
6843 			device_printf(dev, "MSI-X not supported or disabled\n");
6844 		goto msi;
6845 	}
6846 
6847 	bar = ctx->ifc_softc_ctx.isc_msix_bar;
6848 	/*
6849 	 * bar == -1 => "trust me I know what I'm doing"
6850 	 * Some drivers are for hardware that is so shoddily
6851 	 * documented that no one knows which bars are which
6852 	 * so the developer has to map all bars. This hack
6853 	 * allows shoddy garbage to use MSI-X in this framework.
6854 	 */
6855 	if (bar != -1) {
6856 		ctx->ifc_msix_mem = bus_alloc_resource_any(dev,
6857 	            SYS_RES_MEMORY, &bar, RF_ACTIVE);
6858 		if (ctx->ifc_msix_mem == NULL) {
6859 			device_printf(dev, "Unable to map MSI-X table\n");
6860 			goto msi;
6861 		}
6862 	}
6863 
6864 	admincnt = sctx->isc_admin_intrcnt;
6865 #if IFLIB_DEBUG
6866 	/* use only 1 qset in debug mode */
6867 	queuemsgs = min(msgs - admincnt, 1);
6868 #else
6869 	queuemsgs = msgs - admincnt;
6870 #endif
6871 #ifdef RSS
6872 	queues = imin(queuemsgs, rss_getnumbuckets());
6873 #else
6874 	queues = queuemsgs;
6875 #endif
6876 	queues = imin(CPU_COUNT(&ctx->ifc_cpus), queues);
6877 	if (bootverbose)
6878 		device_printf(dev,
6879 		    "intr CPUs: %d queue msgs: %d admincnt: %d\n",
6880 		    CPU_COUNT(&ctx->ifc_cpus), queuemsgs, admincnt);
6881 #ifdef  RSS
6882 	/* If we're doing RSS, clamp at the number of RSS buckets */
6883 	if (queues > rss_getnumbuckets())
6884 		queues = rss_getnumbuckets();
6885 #endif
6886 	if (iflib_num_rx_queues > 0 && iflib_num_rx_queues < queuemsgs - admincnt)
6887 		rx_queues = iflib_num_rx_queues;
6888 	else
6889 		rx_queues = queues;
6890 
6891 	if (rx_queues > scctx->isc_nrxqsets)
6892 		rx_queues = scctx->isc_nrxqsets;
6893 
6894 	/*
6895 	 * We want this to be all logical CPUs by default
6896 	 */
6897 	if (iflib_num_tx_queues > 0 && iflib_num_tx_queues < queues)
6898 		tx_queues = iflib_num_tx_queues;
6899 	else
6900 		tx_queues = mp_ncpus;
6901 
6902 	if (tx_queues > scctx->isc_ntxqsets)
6903 		tx_queues = scctx->isc_ntxqsets;
6904 
6905 	if (ctx->ifc_sysctl_qs_eq_override == 0) {
6906 #ifdef INVARIANTS
6907 		if (tx_queues != rx_queues)
6908 			device_printf(dev,
6909 			    "queue equality override not set, capping rx_queues at %d and tx_queues at %d\n",
6910 			    min(rx_queues, tx_queues), min(rx_queues, tx_queues));
6911 #endif
6912 		tx_queues = min(rx_queues, tx_queues);
6913 		rx_queues = min(rx_queues, tx_queues);
6914 	}
6915 
6916 	vectors = rx_queues + admincnt;
6917 	if (msgs < vectors) {
6918 		device_printf(dev,
6919 		    "insufficient number of MSI-X vectors "
6920 		    "(supported %d, need %d)\n", msgs, vectors);
6921 		goto msi;
6922 	}
6923 
6924 	device_printf(dev, "Using %d RX queues %d TX queues\n", rx_queues,
6925 	    tx_queues);
6926 	msgs = vectors;
6927 	if ((err = pci_alloc_msix(dev, &vectors)) == 0) {
6928 		if (vectors != msgs) {
6929 			device_printf(dev,
6930 			    "Unable to allocate sufficient MSI-X vectors "
6931 			    "(got %d, need %d)\n", vectors, msgs);
6932 			pci_release_msi(dev);
6933 			if (bar != -1) {
6934 				bus_release_resource(dev, SYS_RES_MEMORY, bar,
6935 				    ctx->ifc_msix_mem);
6936 				ctx->ifc_msix_mem = NULL;
6937 			}
6938 			goto msi;
6939 		}
6940 		device_printf(dev, "Using MSI-X interrupts with %d vectors\n",
6941 		    vectors);
6942 		scctx->isc_vectors = vectors;
6943 		scctx->isc_nrxqsets = rx_queues;
6944 		scctx->isc_ntxqsets = tx_queues;
6945 		scctx->isc_intr = IFLIB_INTR_MSIX;
6946 
6947 		return (vectors);
6948 	} else {
6949 		device_printf(dev,
6950 		    "failed to allocate %d MSI-X vectors, err: %d\n", vectors,
6951 		    err);
6952 		if (bar != -1) {
6953 			bus_release_resource(dev, SYS_RES_MEMORY, bar,
6954 			    ctx->ifc_msix_mem);
6955 			ctx->ifc_msix_mem = NULL;
6956 		}
6957 	}
6958 
6959 msi:
6960 	vectors = pci_msi_count(dev);
6961 	scctx->isc_nrxqsets = 1;
6962 	scctx->isc_ntxqsets = 1;
6963 	scctx->isc_vectors = vectors;
6964 	if (vectors == 1 && pci_alloc_msi(dev, &vectors) == 0) {
6965 		device_printf(dev, "Using an MSI interrupt\n");
6966 		scctx->isc_intr = IFLIB_INTR_MSI;
6967 	} else {
6968 		scctx->isc_vectors = 1;
6969 		device_printf(dev, "Using a Legacy interrupt\n");
6970 		scctx->isc_intr = IFLIB_INTR_LEGACY;
6971 	}
6972 
6973 	return (vectors);
6974 }
6975 
6976 static const char *ring_states[] = { "IDLE", "BUSY", "STALLED", "ABDICATED" };
6977 
6978 static int
mp_ring_state_handler(SYSCTL_HANDLER_ARGS)6979 mp_ring_state_handler(SYSCTL_HANDLER_ARGS)
6980 {
6981 	int rc;
6982 	uint16_t *state = ((uint16_t *)oidp->oid_arg1);
6983 	struct sbuf *sb;
6984 	const char *ring_state = "UNKNOWN";
6985 
6986 	/* XXX needed ? */
6987 	rc = sysctl_wire_old_buffer(req, 0);
6988 	MPASS(rc == 0);
6989 	if (rc != 0)
6990 		return (rc);
6991 	sb = sbuf_new_for_sysctl(NULL, NULL, 80, req);
6992 	MPASS(sb != NULL);
6993 	if (sb == NULL)
6994 		return (ENOMEM);
6995 	if (state[3] <= 3)
6996 		ring_state = ring_states[state[3]];
6997 
6998 	sbuf_printf(sb, "pidx_head: %04hd pidx_tail: %04hd cidx: %04hd state: %s",
6999 		    state[0], state[1], state[2], ring_state);
7000 	rc = sbuf_finish(sb);
7001 	sbuf_delete(sb);
7002         return (rc);
7003 }
7004 
7005 enum iflib_ndesc_handler {
7006 	IFLIB_NTXD_HANDLER,
7007 	IFLIB_NRXD_HANDLER,
7008 };
7009 
7010 static int
mp_ndesc_handler(SYSCTL_HANDLER_ARGS)7011 mp_ndesc_handler(SYSCTL_HANDLER_ARGS)
7012 {
7013 	if_ctx_t ctx = (void *)arg1;
7014 	enum iflib_ndesc_handler type = arg2;
7015 	char buf[256] = {0};
7016 	qidx_t *ndesc;
7017 	char *p, *next;
7018 	int nqs, rc, i;
7019 
7020 	nqs = 8;
7021 	switch (type) {
7022 	case IFLIB_NTXD_HANDLER:
7023 		ndesc = ctx->ifc_sysctl_ntxds;
7024 		if (ctx->ifc_sctx)
7025 			nqs = ctx->ifc_sctx->isc_ntxqs;
7026 		break;
7027 	case IFLIB_NRXD_HANDLER:
7028 		ndesc = ctx->ifc_sysctl_nrxds;
7029 		if (ctx->ifc_sctx)
7030 			nqs = ctx->ifc_sctx->isc_nrxqs;
7031 		break;
7032 	default:
7033 		printf("%s: unhandled type\n", __func__);
7034 		return (EINVAL);
7035 	}
7036 	if (nqs == 0)
7037 		nqs = 8;
7038 
7039 	for (i = 0; i < 8; i++) {
7040 		if (i >= nqs)
7041 			break;
7042 		if (i)
7043 			strcat(buf, ",");
7044 		sprintf(strchr(buf, 0), "%d", ndesc[i]);
7045 	}
7046 
7047 	rc = sysctl_handle_string(oidp, buf, sizeof(buf), req);
7048 	if (rc || req->newptr == NULL)
7049 		return (rc);
7050 
7051 	for (i = 0, next = buf, p = strsep(&next, " ,"); i < 8 && p;
7052 	    i++, p = strsep(&next, " ,")) {
7053 		ndesc[i] = strtoul(p, NULL, 10);
7054 	}
7055 
7056 	return (rc);
7057 }
7058 
7059 #define NAME_BUFLEN 32
7060 static void
iflib_add_device_sysctl_pre(if_ctx_t ctx)7061 iflib_add_device_sysctl_pre(if_ctx_t ctx)
7062 {
7063         device_t dev = iflib_get_dev(ctx);
7064 	struct sysctl_oid_list *child, *oid_list;
7065 	struct sysctl_ctx_list *ctx_list;
7066 	struct sysctl_oid *node;
7067 
7068 	ctx_list = device_get_sysctl_ctx(dev);
7069 	child = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
7070 	ctx->ifc_sysctl_node = node = SYSCTL_ADD_NODE(ctx_list, child,
7071 	    OID_AUTO, "iflib", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7072 	    "IFLIB fields");
7073 	oid_list = SYSCTL_CHILDREN(node);
7074 
7075 	SYSCTL_ADD_CONST_STRING(ctx_list, oid_list, OID_AUTO, "driver_version",
7076 	    CTLFLAG_RD, ctx->ifc_sctx->isc_driver_version, "driver version");
7077 
7078 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_ntxqs",
7079 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_ntxqs, 0,
7080 	    "# of txqs to use, 0 => use default #");
7081 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_nrxqs",
7082 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_nrxqs, 0,
7083 	    "# of rxqs to use, 0 => use default #");
7084 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_qs_enable",
7085 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_qs_eq_override, 0,
7086 	    "permit #txq != #rxq");
7087 	SYSCTL_ADD_INT(ctx_list, oid_list, OID_AUTO, "disable_msix",
7088 	    CTLFLAG_RWTUN, &ctx->ifc_softc_ctx.isc_disable_msix, 0,
7089 	    "disable MSI-X (default 0)");
7090 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "rx_budget",
7091 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_rx_budget, 0, "set the RX budget");
7092 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "tx_abdicate",
7093 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_tx_abdicate, 0,
7094 	    "cause TX to abdicate instead of running to completion");
7095 	ctx->ifc_sysctl_core_offset = CORE_OFFSET_UNSPECIFIED;
7096 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "core_offset",
7097 	    CTLFLAG_RDTUN, &ctx->ifc_sysctl_core_offset, 0,
7098 	    "offset to start using cores at");
7099 	SYSCTL_ADD_U8(ctx_list, oid_list, OID_AUTO, "separate_txrx",
7100 	    CTLFLAG_RDTUN, &ctx->ifc_sysctl_separate_txrx, 0,
7101 	    "use separate cores for TX and RX");
7102 	SYSCTL_ADD_U8(ctx_list, oid_list, OID_AUTO, "use_logical_cores",
7103 	    CTLFLAG_RDTUN, &ctx->ifc_sysctl_use_logical_cores, 0,
7104 	    "try to make use of logical cores for TX and RX");
7105 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "use_extra_msix_vectors",
7106 	    CTLFLAG_RDTUN, &ctx->ifc_sysctl_extra_msix_vectors, 0,
7107 	    "attempt to reserve the given number of extra MSI-X vectors during driver load for the creation of additional interfaces later");
7108 	SYSCTL_ADD_INT(ctx_list, oid_list, OID_AUTO, "allocated_msix_vectors",
7109        	    CTLFLAG_RDTUN, &ctx->ifc_softc_ctx.isc_vectors, 0,
7110 	    "total # of MSI-X vectors allocated by driver");
7111 
7112 	/* XXX change for per-queue sizes */
7113 	SYSCTL_ADD_PROC(ctx_list, oid_list, OID_AUTO, "override_ntxds",
7114 	    CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT, ctx,
7115 	    IFLIB_NTXD_HANDLER, mp_ndesc_handler, "A",
7116 	    "list of # of TX descriptors to use, 0 = use default #");
7117 	SYSCTL_ADD_PROC(ctx_list, oid_list, OID_AUTO, "override_nrxds",
7118 	    CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT, ctx,
7119 	    IFLIB_NRXD_HANDLER, mp_ndesc_handler, "A",
7120 	    "list of # of RX descriptors to use, 0 = use default #");
7121 }
7122 
7123 static void
iflib_add_device_sysctl_post(if_ctx_t ctx)7124 iflib_add_device_sysctl_post(if_ctx_t ctx)
7125 {
7126 	if_shared_ctx_t sctx = ctx->ifc_sctx;
7127 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
7128         device_t dev = iflib_get_dev(ctx);
7129 	struct sysctl_oid_list *child;
7130 	struct sysctl_ctx_list *ctx_list;
7131 	iflib_fl_t fl;
7132 	iflib_txq_t txq;
7133 	iflib_rxq_t rxq;
7134 	int i, j;
7135 	char namebuf[NAME_BUFLEN];
7136 	char *qfmt;
7137 	struct sysctl_oid *queue_node, *fl_node, *node;
7138 	struct sysctl_oid_list *queue_list, *fl_list;
7139 	ctx_list = device_get_sysctl_ctx(dev);
7140 
7141 	node = ctx->ifc_sysctl_node;
7142 	child = SYSCTL_CHILDREN(node);
7143 
7144 	if (scctx->isc_ntxqsets > 100)
7145 		qfmt = "txq%03d";
7146 	else if (scctx->isc_ntxqsets > 10)
7147 		qfmt = "txq%02d";
7148 	else
7149 		qfmt = "txq%d";
7150 	for (i = 0, txq = ctx->ifc_txqs; i < scctx->isc_ntxqsets; i++, txq++) {
7151 		snprintf(namebuf, NAME_BUFLEN, qfmt, i);
7152 		queue_node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, namebuf,
7153 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "Queue Name");
7154 		queue_list = SYSCTL_CHILDREN(queue_node);
7155 		SYSCTL_ADD_INT(ctx_list, queue_list, OID_AUTO, "cpu",
7156 		    CTLFLAG_RD, &txq->ift_task.gt_cpu, 0,
7157 		    "cpu this queue is bound to");
7158 #if MEMORY_LOGGING
7159 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "txq_dequeued",
7160 		    CTLFLAG_RD, &txq->ift_dequeued, "total mbufs freed");
7161 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "txq_enqueued",
7162 		    CTLFLAG_RD, &txq->ift_enqueued, "total mbufs enqueued");
7163 #endif
7164 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "mbuf_defrag",
7165 		    CTLFLAG_RD, &txq->ift_mbuf_defrag,
7166 		    "# of times m_defrag was called");
7167 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "m_pullups",
7168 		    CTLFLAG_RD, &txq->ift_pullups,
7169 		    "# of times m_pullup was called");
7170 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
7171 		    "mbuf_defrag_failed", CTLFLAG_RD,
7172 		    &txq->ift_mbuf_defrag_failed, "# of times m_defrag failed");
7173 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
7174 		    "no_desc_avail", CTLFLAG_RD, &txq->ift_no_desc_avail,
7175 		    "# of times no descriptors were available");
7176 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
7177 		    "tx_map_failed", CTLFLAG_RD, &txq->ift_map_failed,
7178 		    "# of times DMA map failed");
7179 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
7180 		    "txd_encap_efbig", CTLFLAG_RD, &txq->ift_txd_encap_efbig,
7181 		    "# of times txd_encap returned EFBIG");
7182 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
7183 		    "no_tx_dma_setup", CTLFLAG_RD, &txq->ift_no_tx_dma_setup,
7184 		    "# of times map failed for other than EFBIG");
7185 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_pidx",
7186 		    CTLFLAG_RD, &txq->ift_pidx, 1, "Producer Index");
7187 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_cidx",
7188 		    CTLFLAG_RD, &txq->ift_cidx, 1, "Consumer Index");
7189 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO,
7190 		    "txq_cidx_processed", CTLFLAG_RD, &txq->ift_cidx_processed,
7191 		    1, "Consumer Index seen by credit update");
7192 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_in_use",
7193 		    CTLFLAG_RD, &txq->ift_in_use, 1, "descriptors in use");
7194 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
7195 		    "txq_processed", CTLFLAG_RD, &txq->ift_processed,
7196 		    "descriptors procesed for clean");
7197 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "txq_cleaned",
7198 		    CTLFLAG_RD, &txq->ift_cleaned, "total cleaned");
7199 		SYSCTL_ADD_PROC(ctx_list, queue_list, OID_AUTO, "ring_state",
7200 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
7201 		    __DEVOLATILE(uint64_t *, &txq->ift_br->state), 0,
7202 		    mp_ring_state_handler, "A", "soft ring state");
7203 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
7204 		    "r_enqueues", CTLFLAG_RD, &txq->ift_br->enqueues,
7205 		    "# of enqueues to the mp_ring for this queue");
7206 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
7207 		    "r_drops", CTLFLAG_RD, &txq->ift_br->drops,
7208 		    "# of drops in the mp_ring for this queue");
7209 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
7210 		    "r_starts", CTLFLAG_RD, &txq->ift_br->starts,
7211 		    "# of normal consumer starts in mp_ring for this queue");
7212 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
7213 		    "r_stalls", CTLFLAG_RD, &txq->ift_br->stalls,
7214 		    "# of consumer stalls in the mp_ring for this queue");
7215 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
7216 		    "r_restarts", CTLFLAG_RD, &txq->ift_br->restarts,
7217 		    "# of consumer restarts in the mp_ring for this queue");
7218 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
7219 		    "r_abdications", CTLFLAG_RD, &txq->ift_br->abdications,
7220 		    "# of consumer abdications in the mp_ring for this queue");
7221 	}
7222 
7223 	if (scctx->isc_nrxqsets > 100)
7224 		qfmt = "rxq%03d";
7225 	else if (scctx->isc_nrxqsets > 10)
7226 		qfmt = "rxq%02d";
7227 	else
7228 		qfmt = "rxq%d";
7229 	for (i = 0, rxq = ctx->ifc_rxqs; i < scctx->isc_nrxqsets; i++, rxq++) {
7230 		snprintf(namebuf, NAME_BUFLEN, qfmt, i);
7231 		queue_node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, namebuf,
7232 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "Queue Name");
7233 		queue_list = SYSCTL_CHILDREN(queue_node);
7234 		SYSCTL_ADD_INT(ctx_list, queue_list, OID_AUTO, "cpu",
7235 		    CTLFLAG_RD, &rxq->ifr_task.gt_cpu, 0,
7236 		    "cpu this queue is bound to");
7237 		if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
7238 			SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO,
7239 			    "rxq_cq_cidx", CTLFLAG_RD, &rxq->ifr_cq_cidx, 1,
7240 			    "Consumer Index");
7241 		}
7242 
7243 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++) {
7244 			snprintf(namebuf, NAME_BUFLEN, "rxq_fl%d", j);
7245 			fl_node = SYSCTL_ADD_NODE(ctx_list, queue_list,
7246 			    OID_AUTO, namebuf, CTLFLAG_RD | CTLFLAG_MPSAFE,
7247 			    NULL, "freelist Name");
7248 			fl_list = SYSCTL_CHILDREN(fl_node);
7249 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "pidx",
7250 			    CTLFLAG_RD, &fl->ifl_pidx, 1, "Producer Index");
7251 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "cidx",
7252 			    CTLFLAG_RD, &fl->ifl_cidx, 1, "Consumer Index");
7253 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "credits",
7254 			    CTLFLAG_RD, &fl->ifl_credits, 1,
7255 			    "credits available");
7256 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "buf_size",
7257 			    CTLFLAG_RD, &fl->ifl_buf_size, 1, "buffer size");
7258 #if MEMORY_LOGGING
7259 			SYSCTL_ADD_UQUAD(ctx_list, fl_list, OID_AUTO,
7260 			    "fl_m_enqueued", CTLFLAG_RD, &fl->ifl_m_enqueued,
7261 			    "mbufs allocated");
7262 			SYSCTL_ADD_UQUAD(ctx_list, fl_list, OID_AUTO,
7263 			    "fl_m_dequeued", CTLFLAG_RD, &fl->ifl_m_dequeued,
7264 			    "mbufs freed");
7265 			SYSCTL_ADD_UQUAD(ctx_list, fl_list, OID_AUTO,
7266 			    "fl_cl_enqueued", CTLFLAG_RD, &fl->ifl_cl_enqueued,
7267 			    "clusters allocated");
7268 			SYSCTL_ADD_UQUAD(ctx_list, fl_list, OID_AUTO,
7269 			    "fl_cl_dequeued", CTLFLAG_RD, &fl->ifl_cl_dequeued,
7270 			    "clusters freed");
7271 #endif
7272 		}
7273 	}
7274 
7275 }
7276 
7277 void
iflib_request_reset(if_ctx_t ctx)7278 iflib_request_reset(if_ctx_t ctx)
7279 {
7280 
7281 	STATE_LOCK(ctx);
7282 	ctx->ifc_flags |= IFC_DO_RESET;
7283 	STATE_UNLOCK(ctx);
7284 }
7285 
7286 #ifndef __NO_STRICT_ALIGNMENT
7287 static struct mbuf *
iflib_fixup_rx(struct mbuf * m)7288 iflib_fixup_rx(struct mbuf *m)
7289 {
7290 	struct mbuf *n;
7291 
7292 	if (m->m_len <= (MCLBYTES - ETHER_HDR_LEN)) {
7293 		bcopy(m->m_data, m->m_data + ETHER_HDR_LEN, m->m_len);
7294 		m->m_data += ETHER_HDR_LEN;
7295 		n = m;
7296 	} else {
7297 		MGETHDR(n, M_NOWAIT, MT_DATA);
7298 		if (n == NULL) {
7299 			m_freem(m);
7300 			return (NULL);
7301 		}
7302 		bcopy(m->m_data, n->m_data, ETHER_HDR_LEN);
7303 		m->m_data += ETHER_HDR_LEN;
7304 		m->m_len -= ETHER_HDR_LEN;
7305 		n->m_len = ETHER_HDR_LEN;
7306 		M_MOVE_PKTHDR(n, m);
7307 		n->m_next = m;
7308 	}
7309 	return (n);
7310 }
7311 #endif
7312 
7313 #ifdef DEBUGNET
7314 static void
iflib_debugnet_init(if_t ifp,int * nrxr,int * ncl,int * clsize)7315 iflib_debugnet_init(if_t ifp, int *nrxr, int *ncl, int *clsize)
7316 {
7317 	if_ctx_t ctx;
7318 
7319 	ctx = if_getsoftc(ifp);
7320 	CTX_LOCK(ctx);
7321 	*nrxr = NRXQSETS(ctx);
7322 	*ncl = ctx->ifc_rxqs[0].ifr_fl->ifl_size;
7323 	*clsize = ctx->ifc_rxqs[0].ifr_fl->ifl_buf_size;
7324 	CTX_UNLOCK(ctx);
7325 }
7326 
7327 static void
iflib_debugnet_event(if_t ifp,enum debugnet_ev event)7328 iflib_debugnet_event(if_t ifp, enum debugnet_ev event)
7329 {
7330 	if_ctx_t ctx;
7331 	if_softc_ctx_t scctx;
7332 	iflib_fl_t fl;
7333 	iflib_rxq_t rxq;
7334 	int i, j;
7335 
7336 	ctx = if_getsoftc(ifp);
7337 	scctx = &ctx->ifc_softc_ctx;
7338 
7339 	switch (event) {
7340 	case DEBUGNET_START:
7341 		for (i = 0; i < scctx->isc_nrxqsets; i++) {
7342 			rxq = &ctx->ifc_rxqs[i];
7343 			for (j = 0; j < rxq->ifr_nfl; j++) {
7344 				fl = rxq->ifr_fl;
7345 				fl->ifl_zone = m_getzone(fl->ifl_buf_size);
7346 			}
7347 		}
7348 		iflib_no_tx_batch = 1;
7349 		break;
7350 	default:
7351 		break;
7352 	}
7353 }
7354 
7355 static int
iflib_debugnet_transmit(if_t ifp,struct mbuf * m)7356 iflib_debugnet_transmit(if_t ifp, struct mbuf *m)
7357 {
7358 	if_ctx_t ctx;
7359 	iflib_txq_t txq;
7360 	int error;
7361 
7362 	ctx = if_getsoftc(ifp);
7363 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
7364 	    IFF_DRV_RUNNING)
7365 		return (EBUSY);
7366 
7367 	txq = &ctx->ifc_txqs[0];
7368 	error = iflib_encap(txq, &m);
7369 	if (error == 0)
7370 		(void)iflib_txd_db_check(txq, true);
7371 	return (error);
7372 }
7373 
7374 static int
iflib_debugnet_poll(if_t ifp,int count)7375 iflib_debugnet_poll(if_t ifp, int count)
7376 {
7377 	struct epoch_tracker et;
7378 	if_ctx_t ctx;
7379 	if_softc_ctx_t scctx;
7380 	iflib_txq_t txq;
7381 	int i;
7382 
7383 	ctx = if_getsoftc(ifp);
7384 	scctx = &ctx->ifc_softc_ctx;
7385 
7386 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
7387 	    IFF_DRV_RUNNING)
7388 		return (EBUSY);
7389 
7390 	txq = &ctx->ifc_txqs[0];
7391 	(void)iflib_completed_tx_reclaim(txq, RECLAIM_THRESH(ctx));
7392 
7393 	NET_EPOCH_ENTER(et);
7394 	for (i = 0; i < scctx->isc_nrxqsets; i++)
7395 		(void)iflib_rxeof(&ctx->ifc_rxqs[i], 16 /* XXX */);
7396 	NET_EPOCH_EXIT(et);
7397 	return (0);
7398 }
7399 #endif /* DEBUGNET */
7400