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