xref: /illumos-gate/usr/src/uts/common/io/i40e/i40e_main.c (revision 2f79f42c9137bbeebe83c431ed2623985c554679)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2015 OmniTI Computer Consulting, Inc. All rights reserved.
14  * Copyright 2019 Joyent, Inc.
15  * Copyright 2017 Tegile Systems, Inc.  All rights reserved.
16  */
17 
18 /*
19  * i40e - Intel 10/40 Gb Ethernet driver
20  *
21  * The i40e driver is the main software device driver for the Intel 40 Gb family
22  * of devices. Note that these devices come in many flavors with both 40 GbE
23  * ports and 10 GbE ports. This device is the successor to the 82599 family of
24  * devices (ixgbe).
25  *
26  * Unlike previous generations of Intel 1 GbE and 10 GbE devices, the 40 GbE
27  * devices defined in the XL710 controller (previously known as Fortville) are a
28  * rather different beast and have a small switch embedded inside of them. In
29  * addition, the way that most of the programming is done has been overhauled.
30  * As opposed to just using PCIe memory mapped registers, it also has an
31  * administrative queue which is used to communicate with firmware running on
32  * the chip.
33  *
34  * Each physical function in the hardware shows up as a device that this driver
35  * will bind to. The hardware splits many resources evenly across all of the
36  * physical functions present on the device, while other resources are instead
37  * shared across the entire card and its up to the device driver to
38  * intelligently partition them.
39  *
40  * ------------
41  * Organization
42  * ------------
43  *
44  * This driver is made up of several files which have their own theory
45  * statements spread across them. We'll touch on the high level purpose of each
46  * file here, and then we'll get into more discussion on how the device is
47  * generally modelled with respect to the interfaces in illumos.
48  *
49  * i40e_gld.c: This file contains all of the bindings to MAC and the networking
50  *             stack.
51  *
52  * i40e_intr.c: This file contains all of the interrupt service routines and
53  *              contains logic to enable and disable interrupts on the hardware.
54  *              It also contains the logic to map hardware resources such as the
55  *              rings to and from interrupts and controls their ability to fire.
56  *
57  *              There is a big theory statement on interrupts present there.
58  *
59  * i40e_main.c: The file that you're currently in. It interfaces with the
60  *              traditional OS DDI interfaces and is in charge of configuring
61  *              the device.
62  *
63  * i40e_osdep.[ch]: These files contain interfaces and definitions needed to
64  *                  work with Intel's common code for the device.
65  *
66  * i40e_stats.c: This file contains the general work and logic around our
67  *               kstats. A theory statement on their organization and use of the
68  *               hardware exists there.
69  *
70  * i40e_sw.h: This header file contains all of the primary structure definitions
71  *            and constants that are used across the entire driver.
72  *
73  * i40e_transceiver.c: This file contains all of the logic for sending and
74  *                     receiving data. It contains all of the ring and DMA
75  *                     allocation logic, as well as, the actual interfaces to
76  *                     send and receive data.
77  *
78  *                     A big theory statement on ring management, descriptors,
79  *                     and how it ties into the OS is present there.
80  *
81  * --------------
82  * General Design
83  * --------------
84  *
85  * Before we go too far into the general way we've laid out data structures and
86  * the like, it's worth taking some time to explain how the hardware is
87  * organized. This organization informs a lot of how we do things at this time
88  * in the driver.
89  *
90  * Each physical device consists of a number of one or more ports, which are
91  * considered physical functions in the PCI sense and thus each get enumerated
92  * by the system, resulting in an instance being created and attached to. While
93  * there are many resources that are unique to each physical function eg.
94  * instance of the device, there are many that are shared across all of them.
95  * Several resources have an amount reserved for each Virtual Station Interface
96  * (VSI) and then a static pool of resources, available for all functions on the
97  * card.
98  *
99  * The most important resource in hardware are its transmit and receive queue
100  * pairs (i40e_trqpair_t). These should be thought of as rings in GLDv3
101  * parlance. There are a set number of these on each device; however, they are
102  * statically partitioned among all of the different physical functions.
103  *
104  * 'Fortville' (the code name for this device family) is basically a switch. To
105  * map MAC addresses and other things to queues, we end up having to create
106  * Virtual Station Interfaces (VSIs) and establish forwarding rules that direct
107  * traffic to a queue. A VSI owns a collection of queues and has a series of
108  * forwarding rules that point to it. One way to think of this is to treat it
109  * like MAC does a VNIC. When MAC refers to a group, a collection of rings and
110  * classification resources, that is a VSI in i40e.
111  *
112  * The sets of VSIs is shared across the entire device, though there may be some
113  * amount that are reserved to each PF. Because the GLDv3 does not let us change
114  * the number of groups dynamically, we instead statically divide this amount
115  * evenly between all the functions that exist. In addition, we have the same
116  * problem with the mac address forwarding rules. There are a static number that
117  * exist shared across all the functions.
118  *
119  * To handle both of these resources, what we end up doing is going through and
120  * determining which functions belong to the same device. Nominally one might do
121  * this by having a nexus driver; however, a prime requirement for a nexus
122  * driver is identifying the various children and activating them. While it is
123  * possible to get this information from NVRAM, we would end up duplicating a
124  * lot of the PCI enumeration logic. Really, at the end of the day, the device
125  * doesn't give us the traditional identification properties we want from a
126  * nexus driver.
127  *
128  * Instead, we rely on some properties that are guaranteed to be unique. While
129  * it might be tempting to leverage the PBA or serial number of the device from
130  * NVRAM, there is nothing that says that two devices can't be mis-programmed to
131  * have the same values in NVRAM. Instead, we uniquely identify a group of
132  * functions based on their parent in the /devices tree, their PCI bus and PCI
133  * function identifiers. Using either on their own may not be sufficient.
134  *
135  * For each unique PCI device that we encounter, we'll create a i40e_device_t.
136  * From there, because we don't have a good way to tell the GLDv3 about sharing
137  * resources between everything, we'll end up just dividing the resources
138  * evenly between all of the functions. Longer term, if we don't have to declare
139  * to the GLDv3 that these resources are shared, then we'll maintain a pool and
140  * have each PF allocate from the pool in the device, thus if only two of four
141  * ports are being used, for example, then all of the resources can still be
142  * used.
143  *
144  * -------------------------------------------
145  * Transmit and Receive Queue Pair Allocations
146  * -------------------------------------------
147  *
148  * NVRAM ends up assigning each PF its own share of the transmit and receive LAN
149  * queue pairs, we have no way of modifying it, only observing it. From there,
150  * it's up to us to map these queues to VSIs and VFs. Since we don't support any
151  * VFs at this time, we only focus on assignments to VSIs.
152  *
153  * At the moment, we used a static mapping of transmit/receive queue pairs to a
154  * given VSI (eg. rings to a group). Though in the fullness of time, we want to
155  * make this something which is fully dynamic and take advantage of documented,
156  * but not yet available functionality for adding filters based on VXLAN and
157  * other encapsulation technologies.
158  *
159  * -------------------------------------
160  * Broadcast, Multicast, and Promiscuous
161  * -------------------------------------
162  *
163  * As part of the GLDv3, we need to make sure that we can handle receiving
164  * broadcast and multicast traffic. As well as enabling promiscuous mode when
165  * requested. GLDv3 requires that all broadcast and multicast traffic be
166  * retrieved by the default group, eg. the first one. This is the same thing as
167  * the default VSI.
168  *
169  * To receieve broadcast traffic, we enable it through the admin queue, rather
170  * than use one of our filters for it. For multicast traffic, we reserve a
171  * certain number of the hash filters and assign them to a given PF. When we
172  * exceed those, we then switch to using promiscuous mode for multicast traffic.
173  *
174  * More specifically, once we exceed the number of filters (indicated because
175  * the i40e_t`i40e_resources.ifr_nmcastfilt ==
176  * i40e_t`i40e_resources.ifr_nmcastfilt_used), we then instead need to toggle
177  * promiscuous mode. If promiscuous mode is toggled then we keep track of the
178  * number of MACs added to it by incrementing i40e_t`i40e_mcast_promisc_count.
179  * That will stay enabled until that count reaches zero indicating that we have
180  * only added multicast addresses that we have a corresponding entry for.
181  *
182  * Because MAC itself wants to toggle promiscuous mode, which includes both
183  * unicast and multicast traffic, we go through and keep track of that
184  * ourselves. That is maintained through the use of the i40e_t`i40e_promisc_on
185  * member.
186  *
187  * --------------
188  * VSI Management
189  * --------------
190  *
191  * The PFs share 384 VSIs. The firmware creates one VSI per PF by default.
192  * During chip start we retrieve the SEID of this VSI and assign it as the
193  * default VSI for our VEB (one VEB per PF). We then add additional VSIs to
194  * the VEB up to the determined number of rx groups: i40e_t`i40e_num_rx_groups.
195  * We currently cap this number to I40E_GROUP_MAX to a) make sure all PFs can
196  * allocate the same number of VSIs, and b) to keep the interrupt multiplexing
197  * under control. In the future, when we improve the interrupt allocation, we
198  * may want to revisit this cap to make better use of the available VSIs. The
199  * VSI allocation and configuration can be found in i40e_chip_start().
200  *
201  * ----------------
202  * Structure Layout
203  * ----------------
204  *
205  * The following images relates the core data structures together. The primary
206  * structure in the system is the i40e_t. It itself contains multiple rings,
207  * i40e_trqpair_t's which contain the various transmit and receive data. The
208  * receive data is stored outside of the i40e_trqpair_t and instead in the
209  * i40e_rx_data_t. The i40e_t has a corresponding i40e_device_t which keeps
210  * track of per-physical device state. Finally, for every active descriptor,
211  * there is a corresponding control block, which is where the
212  * i40e_rx_control_block_t and the i40e_tx_control_block_t come from.
213  *
214  *   +-----------------------+       +-----------------------+
215  *   | Global i40e_t list    |       | Global Device list    |
216  *   |                       |    +--|                       |
217  *   | i40e_glist            |    |  | i40e_dlist            |
218  *   +-----------------------+    |  +-----------------------+
219  *       |                        v
220  *       |      +------------------------+      +-----------------------+
221  *       |      | Device-wide Structure  |----->| Device-wide Structure |--> ...
222  *       |      | i40e_device_t          |      | i40e_device_t         |
223  *       |      |                        |      +-----------------------+
224  *       |      | dev_info_t *     ------+--> Parent in devices tree.
225  *       |      | uint_t           ------+--> PCI bus number
226  *       |      | uint_t           ------+--> PCI device number
227  *       |      | uint_t           ------+--> Number of functions
228  *       |      | i40e_switch_rsrcs_t ---+--> Captured total switch resources
229  *       |      | list_t           ------+-------------+
230  *       |      +------------------------+             |
231  *       |                           ^                 |
232  *       |                           +--------+        |
233  *       |                                    |        v
234  *       |  +---------------------------+     |   +-------------------+
235  *       +->| GLDv3 Device, per PF      |-----|-->| GLDv3 Device (PF) |--> ...
236  *          | i40e_t                    |     |   | i40e_t            |
237  *          | **Primary Structure**     |     |   +-------------------+
238  *          |                           |     |
239  *          | i40e_device_t *         --+-----+
240  *          | i40e_state_t            --+---> Device State
241  *          | i40e_hw_t               --+---> Intel common code structure
242  *          | mac_handle_t            --+---> GLDv3 handle to MAC
243  *          | ddi_periodic_t          --+---> Link activity timer
244  *          | i40e_vsi_t *            --+---> Array of VSIs
245  *          | i40e_func_rsrc_t        --+---> Available hardware resources
246  *          | i40e_switch_rsrc_t *    --+---> Switch resource snapshot
247  *          | i40e_sdu                --+---> Current MTU
248  *          | i40e_frame_max          --+---> Current HW frame size
249  *          | i40e_uaddr_t *          --+---> Array of assigned unicast MACs
250  *          | i40e_maddr_t *          --+---> Array of assigned multicast MACs
251  *          | i40e_mcast_promisccount --+---> Active multicast state
252  *          | i40e_promisc_on         --+---> Current promiscuous mode state
253  *          | uint_t                  --+---> Number of transmit/receive pairs
254  *          | i40e_rx_group_t *       --+---> Array of Rx groups
255  *          | kstat_t *               --+---> PF kstats
256  *          | i40e_pf_stats_t         --+---> PF kstat backing data
257  *          | i40e_trqpair_t *        --+---------+
258  *          +---------------------------+         |
259  *                                                |
260  *                                                v
261  *  +-------------------------------+       +-----------------------------+
262  *  | Transmit/Receive Queue Pair   |-------| Transmit/Receive Queue Pair |->...
263  *  | i40e_trqpair_t                |       | i40e_trqpair_t              |
264  *  + Ring Data Structure           |       +-----------------------------+
265  *  |                               |
266  *  | mac_ring_handle_t             +--> MAC RX ring handle
267  *  | mac_ring_handle_t             +--> MAC TX ring handle
268  *  | i40e_rxq_stat_t             --+--> RX Queue stats
269  *  | i40e_txq_stat_t             --+--> TX Queue stats
270  *  | uint32_t (tx ring size)       +--> TX Ring Size
271  *  | uint32_t (tx free list size)  +--> TX Free List Size
272  *  | i40e_dma_buffer_t     --------+--> TX Descriptor ring DMA
273  *  | i40e_tx_desc_t *      --------+--> TX descriptor ring
274  *  | volatile unt32_t *            +--> TX Write back head
275  *  | uint32_t               -------+--> TX ring head
276  *  | uint32_t               -------+--> TX ring tail
277  *  | uint32_t               -------+--> Num TX desc free
278  *  | i40e_tx_control_block_t *   --+--> TX control block array  ---+
279  *  | i40e_tx_control_block_t **  --+--> TCB work list          ----+
280  *  | i40e_tx_control_block_t **  --+--> TCB free list           ---+
281  *  | uint32_t               -------+--> Free TCB count             |
282  *  | i40e_rx_data_t *       -------+--+                            v
283  *  +-------------------------------+  |          +---------------------------+
284  *                                     |          | Per-TX Frame Metadata     |
285  *                                     |          | i40e_tx_control_block_t   |
286  *                +--------------------+          |                           |
287  *                |           mblk to transmit <--+---      mblk_t *          |
288  *                |           type of transmit <--+---      i40e_tx_type_t    |
289  *                |              TX DMA handle <--+---      ddi_dma_handle_t  |
290  *                v              TX DMA buffer <--+---      i40e_dma_buffer_t |
291  *    +------------------------------+            +---------------------------+
292  *    | Core Receive Data            |
293  *    | i40e_rx_data_t               |
294  *    |                              |
295  *    | i40e_dma_buffer_t          --+--> RX descriptor DMA Data
296  *    | i40e_rx_desc_t             --+--> RX descriptor ring
297  *    | uint32_t                   --+--> Next free desc.
298  *    | i40e_rx_control_block_t *  --+--> RX Control Block Array  ---+
299  *    | i40e_rx_control_block_t ** --+--> RCB work list           ---+
300  *    | i40e_rx_control_block_t ** --+--> RCB free list           ---+
301  *    +------------------------------+                               |
302  *                ^                                                  |
303  *                |     +---------------------------+                |
304  *                |     | Per-RX Frame Metadata     |<---------------+
305  *                |     | i40e_rx_control_block_t   |
306  *                |     |                           |
307  *                |     | mblk_t *              ----+--> Received mblk_t data
308  *                |     | uint32_t              ----+--> Reference count
309  *                |     | i40e_dma_buffer_t     ----+--> Receive data DMA info
310  *                |     | frtn_t                ----+--> mblk free function info
311  *                +-----+-- i40e_rx_data_t *        |
312  *                      +---------------------------+
313  *
314  * -------------
315  * Lock Ordering
316  * -------------
317  *
318  * In order to ensure that we don't deadlock, the following represents the
319  * lock order being used. When grabbing locks, follow the following order. Lower
320  * numbers are more important. Thus, the i40e_glock which is number 0, must be
321  * taken before any other locks in the driver. On the other hand, the
322  * i40e_t`i40e_stat_lock, has the highest number because it's the least
323  * important lock. Note, that just because one lock is higher than another does
324  * not mean that all intermediary locks are required.
325  *
326  * 0) i40e_glock
327  * 1) i40e_t`i40e_general_lock
328  *
329  * 2) i40e_trqpair_t`itrq_rx_lock
330  * 3) i40e_trqpair_t`itrq_tx_lock
331  * 4) i40e_t`i40e_rx_pending_lock
332  * 5) i40e_trqpair_t`itrq_tcb_lock
333  *
334  * 6) i40e_t`i40e_stat_lock
335  *
336  * Rules and expectations:
337  *
338  * 1) A thread holding locks belong to one PF should not hold locks belonging to
339  * a second. If for some reason this becomes necessary, locks should be grabbed
340  * based on the list order in the i40e_device_t, which implies that the
341  * i40e_glock is held.
342  *
343  * 2) When grabbing locks between multiple transmit and receive queues, the
344  * locks for the lowest number transmit/receive queue should be grabbed first.
345  *
346  * 3) When grabbing both the transmit and receive lock for a given queue, always
347  * grab i40e_trqpair_t`itrq_rx_lock before the i40e_trqpair_t`itrq_tx_lock.
348  *
349  * 4) The following pairs of locks are not expected to be held at the same time:
350  *
351  * o i40e_t`i40e_rx_pending_lock and i40e_trqpair_t`itrq_tcb_lock
352  *
353  * -----------
354  * Future Work
355  * -----------
356  *
357  * At the moment the i40e_t driver is rather bare bones, allowing us to start
358  * getting data flowing and folks using it while we develop additional features.
359  * While bugs have been filed to cover this future work, the following gives an
360  * overview of expected work:
361  *
362  *  o DMA binding and breaking up the locking in ring recycling.
363  *  o Enhanced detection of device errors
364  *  o Participation in IRM
365  *  o FMA device reset
366  *  o Stall detection, temperature error detection, etc.
367  *  o More dynamic resource pools
368  */
369 
370 #include "i40e_sw.h"
371 
372 static char i40e_ident[] = "Intel 10/40Gb Ethernet v1.0.3";
373 
374 /*
375  * The i40e_glock primarily protects the lists below and the i40e_device_t
376  * structures.
377  */
378 static kmutex_t i40e_glock;
379 static list_t i40e_glist;
380 static list_t i40e_dlist;
381 
382 /*
383  * Access attributes for register mapping.
384  */
385 static ddi_device_acc_attr_t i40e_regs_acc_attr = {
386 	DDI_DEVICE_ATTR_V1,
387 	DDI_STRUCTURE_LE_ACC,
388 	DDI_STRICTORDER_ACC,
389 	DDI_FLAGERR_ACC
390 };
391 
392 /*
393  * Logging function for this driver.
394  */
395 static void
396 i40e_dev_err(i40e_t *i40e, int level, boolean_t console, const char *fmt,
397     va_list ap)
398 {
399 	char buf[1024];
400 
401 	(void) vsnprintf(buf, sizeof (buf), fmt, ap);
402 
403 	if (i40e == NULL) {
404 		cmn_err(level, (console) ? "%s: %s" : "!%s: %s",
405 		    I40E_MODULE_NAME, buf);
406 	} else {
407 		dev_err(i40e->i40e_dip, level, (console) ? "%s" : "!%s",
408 		    buf);
409 	}
410 }
411 
412 /*
413  * Because there's the stupid trailing-comma problem with the C preprocessor
414  * and variable arguments, I need to instantiate these.	 Pardon the redundant
415  * code.
416  */
417 /*PRINTFLIKE2*/
418 void
419 i40e_error(i40e_t *i40e, const char *fmt, ...)
420 {
421 	va_list ap;
422 
423 	va_start(ap, fmt);
424 	i40e_dev_err(i40e, CE_WARN, B_FALSE, fmt, ap);
425 	va_end(ap);
426 }
427 
428 /*PRINTFLIKE2*/
429 void
430 i40e_log(i40e_t *i40e, const char *fmt, ...)
431 {
432 	va_list ap;
433 
434 	va_start(ap, fmt);
435 	i40e_dev_err(i40e, CE_NOTE, B_FALSE, fmt, ap);
436 	va_end(ap);
437 }
438 
439 /*PRINTFLIKE2*/
440 void
441 i40e_notice(i40e_t *i40e, const char *fmt, ...)
442 {
443 	va_list ap;
444 
445 	va_start(ap, fmt);
446 	i40e_dev_err(i40e, CE_NOTE, B_TRUE, fmt, ap);
447 	va_end(ap);
448 }
449 
450 /*
451  * Various parts of the driver need to know if the controller is from the X722
452  * family, which has a few additional capabilities and different programming
453  * means. We don't consider virtual functions as part of this as they are quite
454  * different and will require substantially more work.
455  */
456 static boolean_t
457 i40e_is_x722(i40e_t *i40e)
458 {
459 	return (i40e->i40e_hw_space.mac.type == I40E_MAC_X722);
460 }
461 
462 static void
463 i40e_device_rele(i40e_t *i40e)
464 {
465 	i40e_device_t *idp = i40e->i40e_device;
466 
467 	if (idp == NULL)
468 		return;
469 
470 	mutex_enter(&i40e_glock);
471 	VERIFY(idp->id_nreg > 0);
472 	list_remove(&idp->id_i40e_list, i40e);
473 	idp->id_nreg--;
474 	if (idp->id_nreg == 0) {
475 		list_remove(&i40e_dlist, idp);
476 		list_destroy(&idp->id_i40e_list);
477 		kmem_free(idp->id_rsrcs, sizeof (i40e_switch_rsrc_t) *
478 		    idp->id_rsrcs_alloc);
479 		kmem_free(idp, sizeof (i40e_device_t));
480 	}
481 	i40e->i40e_device = NULL;
482 	mutex_exit(&i40e_glock);
483 }
484 
485 static i40e_device_t *
486 i40e_device_find(i40e_t *i40e, dev_info_t *parent, uint_t bus, uint_t device)
487 {
488 	i40e_device_t *idp;
489 	mutex_enter(&i40e_glock);
490 	for (idp = list_head(&i40e_dlist); idp != NULL;
491 	    idp = list_next(&i40e_dlist, idp)) {
492 		if (idp->id_parent == parent && idp->id_pci_bus == bus &&
493 		    idp->id_pci_device == device) {
494 			break;
495 		}
496 	}
497 
498 	if (idp != NULL) {
499 		VERIFY(idp->id_nreg < idp->id_nfuncs);
500 		idp->id_nreg++;
501 	} else {
502 		i40e_hw_t *hw = &i40e->i40e_hw_space;
503 		ASSERT(hw->num_ports > 0);
504 		ASSERT(hw->num_partitions > 0);
505 
506 		/*
507 		 * The Intel common code doesn't exactly keep the number of PCI
508 		 * functions. But it calculates it during discovery of
509 		 * partitions and ports. So what we do is undo the calculation
510 		 * that it does originally, as functions are evenly spread
511 		 * across ports in the rare case of partitions.
512 		 */
513 		idp = kmem_alloc(sizeof (i40e_device_t), KM_SLEEP);
514 		idp->id_parent = parent;
515 		idp->id_pci_bus = bus;
516 		idp->id_pci_device = device;
517 		idp->id_nfuncs = hw->num_ports * hw->num_partitions;
518 		idp->id_nreg = 1;
519 		idp->id_rsrcs_alloc = i40e->i40e_switch_rsrc_alloc;
520 		idp->id_rsrcs_act = i40e->i40e_switch_rsrc_actual;
521 		idp->id_rsrcs = kmem_alloc(sizeof (i40e_switch_rsrc_t) *
522 		    idp->id_rsrcs_alloc, KM_SLEEP);
523 		bcopy(i40e->i40e_switch_rsrcs, idp->id_rsrcs,
524 		    sizeof (i40e_switch_rsrc_t) * idp->id_rsrcs_alloc);
525 		list_create(&idp->id_i40e_list, sizeof (i40e_t),
526 		    offsetof(i40e_t, i40e_dlink));
527 
528 		list_insert_tail(&i40e_dlist, idp);
529 	}
530 
531 	list_insert_tail(&idp->id_i40e_list, i40e);
532 	mutex_exit(&i40e_glock);
533 
534 	return (idp);
535 }
536 
537 static void
538 i40e_link_state_set(i40e_t *i40e, link_state_t state)
539 {
540 	if (i40e->i40e_link_state == state)
541 		return;
542 
543 	i40e->i40e_link_state = state;
544 	mac_link_update(i40e->i40e_mac_hdl, i40e->i40e_link_state);
545 }
546 
547 /*
548  * This is a basic link check routine. Mostly we're using this just to see
549  * if we can get any accurate information about the state of the link being
550  * up or down, as well as updating the link state, speed, etc. information.
551  */
552 void
553 i40e_link_check(i40e_t *i40e)
554 {
555 	i40e_hw_t *hw = &i40e->i40e_hw_space;
556 	boolean_t ls;
557 	int ret;
558 
559 	ASSERT(MUTEX_HELD(&i40e->i40e_general_lock));
560 
561 	hw->phy.get_link_info = B_TRUE;
562 	if ((ret = i40e_get_link_status(hw, &ls)) != I40E_SUCCESS) {
563 		i40e->i40e_s_link_status_errs++;
564 		i40e->i40e_s_link_status_lasterr = ret;
565 		return;
566 	}
567 
568 	/*
569 	 * Firmware abstracts all of the mac and phy information for us, so we
570 	 * can use i40e_get_link_status to determine the current state.
571 	 */
572 	if (ls == B_TRUE) {
573 		enum i40e_aq_link_speed speed;
574 
575 		speed = i40e_get_link_speed(hw);
576 
577 		/*
578 		 * Translate from an i40e value to a value in Mbits/s.
579 		 */
580 		switch (speed) {
581 		case I40E_LINK_SPEED_100MB:
582 			i40e->i40e_link_speed = 100;
583 			break;
584 		case I40E_LINK_SPEED_1GB:
585 			i40e->i40e_link_speed = 1000;
586 			break;
587 		case I40E_LINK_SPEED_10GB:
588 			i40e->i40e_link_speed = 10000;
589 			break;
590 		case I40E_LINK_SPEED_20GB:
591 			i40e->i40e_link_speed = 20000;
592 			break;
593 		case I40E_LINK_SPEED_40GB:
594 			i40e->i40e_link_speed = 40000;
595 			break;
596 		case I40E_LINK_SPEED_25GB:
597 			i40e->i40e_link_speed = 25000;
598 			break;
599 		default:
600 			i40e->i40e_link_speed = 0;
601 			break;
602 		}
603 
604 		/*
605 		 * At this time, hardware does not support half-duplex
606 		 * operation, hence why we don't ask the hardware about our
607 		 * current speed.
608 		 */
609 		i40e->i40e_link_duplex = LINK_DUPLEX_FULL;
610 		i40e_link_state_set(i40e, LINK_STATE_UP);
611 	} else {
612 		i40e->i40e_link_speed = 0;
613 		i40e->i40e_link_duplex = 0;
614 		i40e_link_state_set(i40e, LINK_STATE_DOWN);
615 	}
616 }
617 
618 static void
619 i40e_rem_intrs(i40e_t *i40e)
620 {
621 	int i, rc;
622 
623 	for (i = 0; i < i40e->i40e_intr_count; i++) {
624 		rc = ddi_intr_free(i40e->i40e_intr_handles[i]);
625 		if (rc != DDI_SUCCESS) {
626 			i40e_log(i40e, "failed to free interrupt %d: %d",
627 			    i, rc);
628 		}
629 	}
630 
631 	kmem_free(i40e->i40e_intr_handles, i40e->i40e_intr_size);
632 	i40e->i40e_intr_handles = NULL;
633 }
634 
635 static void
636 i40e_rem_intr_handlers(i40e_t *i40e)
637 {
638 	int i, rc;
639 
640 	for (i = 0; i < i40e->i40e_intr_count; i++) {
641 		rc = ddi_intr_remove_handler(i40e->i40e_intr_handles[i]);
642 		if (rc != DDI_SUCCESS) {
643 			i40e_log(i40e, "failed to remove interrupt %d: %d",
644 			    i, rc);
645 		}
646 	}
647 }
648 
649 /*
650  * illumos Fault Management Architecture (FMA) support.
651  */
652 
653 int
654 i40e_check_acc_handle(ddi_acc_handle_t handle)
655 {
656 	ddi_fm_error_t de;
657 
658 	ddi_fm_acc_err_get(handle, &de, DDI_FME_VERSION);
659 	ddi_fm_acc_err_clear(handle, DDI_FME_VERSION);
660 	return (de.fme_status);
661 }
662 
663 int
664 i40e_check_dma_handle(ddi_dma_handle_t handle)
665 {
666 	ddi_fm_error_t de;
667 
668 	ddi_fm_dma_err_get(handle, &de, DDI_FME_VERSION);
669 	return (de.fme_status);
670 }
671 
672 /*
673  * Fault service error handling callback function.
674  */
675 /* ARGSUSED */
676 static int
677 i40e_fm_error_cb(dev_info_t *dip, ddi_fm_error_t *err, const void *impl_data)
678 {
679 	pci_ereport_post(dip, err, NULL);
680 	return (err->fme_status);
681 }
682 
683 static void
684 i40e_fm_init(i40e_t *i40e)
685 {
686 	ddi_iblock_cookie_t iblk;
687 
688 	i40e->i40e_fm_capabilities = ddi_prop_get_int(DDI_DEV_T_ANY,
689 	    i40e->i40e_dip, DDI_PROP_DONTPASS, "fm_capable",
690 	    DDI_FM_EREPORT_CAPABLE | DDI_FM_ACCCHK_CAPABLE |
691 	    DDI_FM_DMACHK_CAPABLE | DDI_FM_ERRCB_CAPABLE);
692 
693 	if (i40e->i40e_fm_capabilities < 0) {
694 		i40e->i40e_fm_capabilities = 0;
695 	} else if (i40e->i40e_fm_capabilities > 0xf) {
696 		i40e->i40e_fm_capabilities = DDI_FM_EREPORT_CAPABLE |
697 		    DDI_FM_ACCCHK_CAPABLE | DDI_FM_DMACHK_CAPABLE |
698 		    DDI_FM_ERRCB_CAPABLE;
699 	}
700 
701 	/*
702 	 * Only register with IO Fault Services if we have some capability
703 	 */
704 	if (i40e->i40e_fm_capabilities & DDI_FM_ACCCHK_CAPABLE) {
705 		i40e_regs_acc_attr.devacc_attr_access = DDI_FLAGERR_ACC;
706 	} else {
707 		i40e_regs_acc_attr.devacc_attr_access = DDI_DEFAULT_ACC;
708 	}
709 
710 	if (i40e->i40e_fm_capabilities) {
711 		ddi_fm_init(i40e->i40e_dip, &i40e->i40e_fm_capabilities, &iblk);
712 
713 		if (DDI_FM_EREPORT_CAP(i40e->i40e_fm_capabilities) ||
714 		    DDI_FM_ERRCB_CAP(i40e->i40e_fm_capabilities)) {
715 			pci_ereport_setup(i40e->i40e_dip);
716 		}
717 
718 		if (DDI_FM_ERRCB_CAP(i40e->i40e_fm_capabilities)) {
719 			ddi_fm_handler_register(i40e->i40e_dip,
720 			    i40e_fm_error_cb, (void*)i40e);
721 		}
722 	}
723 
724 	if (i40e->i40e_fm_capabilities & DDI_FM_DMACHK_CAPABLE) {
725 		i40e_init_dma_attrs(i40e, B_TRUE);
726 	} else {
727 		i40e_init_dma_attrs(i40e, B_FALSE);
728 	}
729 }
730 
731 static void
732 i40e_fm_fini(i40e_t *i40e)
733 {
734 	if (i40e->i40e_fm_capabilities) {
735 
736 		if (DDI_FM_EREPORT_CAP(i40e->i40e_fm_capabilities) ||
737 		    DDI_FM_ERRCB_CAP(i40e->i40e_fm_capabilities))
738 			pci_ereport_teardown(i40e->i40e_dip);
739 
740 		if (DDI_FM_ERRCB_CAP(i40e->i40e_fm_capabilities))
741 			ddi_fm_handler_unregister(i40e->i40e_dip);
742 
743 		ddi_fm_fini(i40e->i40e_dip);
744 	}
745 }
746 
747 void
748 i40e_fm_ereport(i40e_t *i40e, char *detail)
749 {
750 	uint64_t ena;
751 	char buf[FM_MAX_CLASS];
752 
753 	(void) snprintf(buf, FM_MAX_CLASS, "%s.%s", DDI_FM_DEVICE, detail);
754 	ena = fm_ena_generate(0, FM_ENA_FMT1);
755 	if (DDI_FM_EREPORT_CAP(i40e->i40e_fm_capabilities)) {
756 		ddi_fm_ereport_post(i40e->i40e_dip, buf, ena, DDI_NOSLEEP,
757 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0, NULL);
758 	}
759 }
760 
761 /*
762  * Here we're trying to set the SEID of the default VSI. In general,
763  * when we come through and look at this shortly after attach, we
764  * expect there to only be a single element present, which is the
765  * default VSI. Importantly, each PF seems to not see any other
766  * devices, in part because of the simple switch mode that we're
767  * using. If for some reason, we see more artifacts, we'll need to
768  * revisit what we're doing here.
769  */
770 static boolean_t
771 i40e_set_def_vsi_seid(i40e_t *i40e)
772 {
773 	i40e_hw_t *hw = &i40e->i40e_hw_space;
774 	struct i40e_aqc_get_switch_config_resp *sw_config;
775 	uint8_t aq_buf[I40E_AQ_LARGE_BUF];
776 	uint16_t next = 0;
777 	int rc;
778 
779 	/* LINTED: E_BAD_PTR_CAST_ALIGN */
780 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
781 	rc = i40e_aq_get_switch_config(hw, sw_config, sizeof (aq_buf), &next,
782 	    NULL);
783 	if (rc != I40E_SUCCESS) {
784 		i40e_error(i40e, "i40e_aq_get_switch_config() failed %d: %d",
785 		    rc, hw->aq.asq_last_status);
786 		return (B_FALSE);
787 	}
788 
789 	if (LE_16(sw_config->header.num_reported) != 1) {
790 		i40e_error(i40e, "encountered multiple (%d) switching units "
791 		    "during attach, not proceeding",
792 		    LE_16(sw_config->header.num_reported));
793 		return (B_FALSE);
794 	}
795 
796 	I40E_DEF_VSI_SEID(i40e) = sw_config->element[0].seid;
797 	return (B_TRUE);
798 }
799 
800 /*
801  * Get the SEID of the uplink MAC.
802  */
803 static int
804 i40e_get_mac_seid(i40e_t *i40e)
805 {
806 	i40e_hw_t *hw = &i40e->i40e_hw_space;
807 	struct i40e_aqc_get_switch_config_resp *sw_config;
808 	uint8_t aq_buf[I40E_AQ_LARGE_BUF];
809 	uint16_t next = 0;
810 	int rc;
811 
812 	/* LINTED: E_BAD_PTR_CAST_ALIGN */
813 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
814 	rc = i40e_aq_get_switch_config(hw, sw_config, sizeof (aq_buf), &next,
815 	    NULL);
816 	if (rc != I40E_SUCCESS) {
817 		i40e_error(i40e, "i40e_aq_get_switch_config() failed %d: %d",
818 		    rc, hw->aq.asq_last_status);
819 		return (-1);
820 	}
821 
822 	return (LE_16(sw_config->element[0].uplink_seid));
823 }
824 
825 /*
826  * We need to fill the i40e_hw_t structure with the capabilities of this PF. We
827  * must also provide the memory for it; however, we don't need to keep it around
828  * to the call to the common code. It takes it and parses it into an internal
829  * structure.
830  */
831 static boolean_t
832 i40e_get_hw_capabilities(i40e_t *i40e, i40e_hw_t *hw)
833 {
834 	struct i40e_aqc_list_capabilities_element_resp *buf;
835 	int rc;
836 	size_t len;
837 	uint16_t needed;
838 	int nelems = I40E_HW_CAP_DEFAULT;
839 
840 	len = nelems * sizeof (*buf);
841 
842 	for (;;) {
843 		ASSERT(len > 0);
844 		buf = kmem_alloc(len, KM_SLEEP);
845 		rc = i40e_aq_discover_capabilities(hw, buf, len,
846 		    &needed, i40e_aqc_opc_list_func_capabilities, NULL);
847 		kmem_free(buf, len);
848 
849 		if (hw->aq.asq_last_status == I40E_AQ_RC_ENOMEM &&
850 		    nelems == I40E_HW_CAP_DEFAULT) {
851 			if (nelems == needed) {
852 				i40e_error(i40e, "Capability discovery failed "
853 				    "due to byzantine common code");
854 				return (B_FALSE);
855 			}
856 			len = needed;
857 			continue;
858 		} else if (rc != I40E_SUCCESS ||
859 		    hw->aq.asq_last_status != I40E_AQ_RC_OK) {
860 			i40e_error(i40e, "Capability discovery failed: %d", rc);
861 			return (B_FALSE);
862 		}
863 
864 		break;
865 	}
866 
867 	return (B_TRUE);
868 }
869 
870 /*
871  * Obtain the switch's capabilities as seen by this PF and keep it around for
872  * our later use.
873  */
874 static boolean_t
875 i40e_get_switch_resources(i40e_t *i40e)
876 {
877 	i40e_hw_t *hw = &i40e->i40e_hw_space;
878 	uint8_t cnt = 2;
879 	uint8_t act;
880 	size_t size;
881 	i40e_switch_rsrc_t *buf;
882 
883 	for (;;) {
884 		enum i40e_status_code ret;
885 		size = cnt * sizeof (i40e_switch_rsrc_t);
886 		ASSERT(size > 0);
887 		if (size > UINT16_MAX)
888 			return (B_FALSE);
889 		buf = kmem_alloc(size, KM_SLEEP);
890 
891 		ret = i40e_aq_get_switch_resource_alloc(hw, &act, buf,
892 		    cnt, NULL);
893 		if (ret == I40E_ERR_ADMIN_QUEUE_ERROR &&
894 		    hw->aq.asq_last_status == I40E_AQ_RC_EINVAL) {
895 			kmem_free(buf, size);
896 			cnt += I40E_SWITCH_CAP_DEFAULT;
897 			continue;
898 		} else if (ret != I40E_SUCCESS) {
899 			kmem_free(buf, size);
900 			i40e_error(i40e,
901 			    "failed to retrieve switch statistics: %d", ret);
902 			return (B_FALSE);
903 		}
904 
905 		break;
906 	}
907 
908 	i40e->i40e_switch_rsrc_alloc = cnt;
909 	i40e->i40e_switch_rsrc_actual = act;
910 	i40e->i40e_switch_rsrcs = buf;
911 
912 	return (B_TRUE);
913 }
914 
915 static void
916 i40e_cleanup_resources(i40e_t *i40e)
917 {
918 	if (i40e->i40e_uaddrs != NULL) {
919 		kmem_free(i40e->i40e_uaddrs, sizeof (i40e_uaddr_t) *
920 		    i40e->i40e_resources.ifr_nmacfilt);
921 		i40e->i40e_uaddrs = NULL;
922 	}
923 
924 	if (i40e->i40e_maddrs != NULL) {
925 		kmem_free(i40e->i40e_maddrs, sizeof (i40e_maddr_t) *
926 		    i40e->i40e_resources.ifr_nmcastfilt);
927 		i40e->i40e_maddrs = NULL;
928 	}
929 
930 	if (i40e->i40e_switch_rsrcs != NULL) {
931 		size_t sz = sizeof (i40e_switch_rsrc_t) *
932 		    i40e->i40e_switch_rsrc_alloc;
933 		ASSERT(sz > 0);
934 		kmem_free(i40e->i40e_switch_rsrcs, sz);
935 		i40e->i40e_switch_rsrcs = NULL;
936 	}
937 
938 	if (i40e->i40e_device != NULL)
939 		i40e_device_rele(i40e);
940 }
941 
942 static boolean_t
943 i40e_get_available_resources(i40e_t *i40e)
944 {
945 	dev_info_t *parent;
946 	uint16_t bus, device, func;
947 	uint_t nregs;
948 	int *regs, i;
949 	i40e_device_t *idp;
950 	i40e_hw_t *hw = &i40e->i40e_hw_space;
951 
952 	parent = ddi_get_parent(i40e->i40e_dip);
953 
954 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, i40e->i40e_dip, 0, "reg",
955 	    &regs, &nregs) != DDI_PROP_SUCCESS) {
956 		return (B_FALSE);
957 	}
958 
959 	if (nregs < 1) {
960 		ddi_prop_free(regs);
961 		return (B_FALSE);
962 	}
963 
964 	bus = PCI_REG_BUS_G(regs[0]);
965 	device = PCI_REG_DEV_G(regs[0]);
966 	func = PCI_REG_FUNC_G(regs[0]);
967 	ddi_prop_free(regs);
968 
969 	i40e->i40e_hw_space.bus.func = func;
970 	i40e->i40e_hw_space.bus.device = device;
971 
972 	if (i40e_get_switch_resources(i40e) == B_FALSE) {
973 		return (B_FALSE);
974 	}
975 
976 	/*
977 	 * To calculate the total amount of a resource we have available, we
978 	 * need to add how many our i40e_t thinks it has guaranteed, if any, and
979 	 * then we need to go through and divide the number of available on the
980 	 * device, which was snapshotted before anyone should have allocated
981 	 * anything, and use that to derive how many are available from the
982 	 * pool. Longer term, we may want to turn this into something that's
983 	 * more of a pool-like resource that everything can share (though that
984 	 * may require some more assistance from MAC).
985 	 *
986 	 * Though for transmit and receive queue pairs, we just have to ask
987 	 * firmware instead.
988 	 */
989 	idp = i40e_device_find(i40e, parent, bus, device);
990 	i40e->i40e_device = idp;
991 	i40e->i40e_resources.ifr_nvsis = 0;
992 	i40e->i40e_resources.ifr_nvsis_used = 0;
993 	i40e->i40e_resources.ifr_nmacfilt = 0;
994 	i40e->i40e_resources.ifr_nmacfilt_used = 0;
995 	i40e->i40e_resources.ifr_nmcastfilt = 0;
996 	i40e->i40e_resources.ifr_nmcastfilt_used = 0;
997 
998 	for (i = 0; i < i40e->i40e_switch_rsrc_actual; i++) {
999 		i40e_switch_rsrc_t *srp = &i40e->i40e_switch_rsrcs[i];
1000 
1001 		switch (srp->resource_type) {
1002 		case I40E_AQ_RESOURCE_TYPE_VSI:
1003 			i40e->i40e_resources.ifr_nvsis +=
1004 			    LE_16(srp->guaranteed);
1005 			i40e->i40e_resources.ifr_nvsis_used = LE_16(srp->used);
1006 			break;
1007 		case I40E_AQ_RESOURCE_TYPE_MACADDR:
1008 			i40e->i40e_resources.ifr_nmacfilt +=
1009 			    LE_16(srp->guaranteed);
1010 			i40e->i40e_resources.ifr_nmacfilt_used =
1011 			    LE_16(srp->used);
1012 			break;
1013 		case I40E_AQ_RESOURCE_TYPE_MULTICAST_HASH:
1014 			i40e->i40e_resources.ifr_nmcastfilt +=
1015 			    LE_16(srp->guaranteed);
1016 			i40e->i40e_resources.ifr_nmcastfilt_used =
1017 			    LE_16(srp->used);
1018 			break;
1019 		default:
1020 			break;
1021 		}
1022 	}
1023 
1024 	for (i = 0; i < idp->id_rsrcs_act; i++) {
1025 		i40e_switch_rsrc_t *srp = &i40e->i40e_switch_rsrcs[i];
1026 		switch (srp->resource_type) {
1027 		case I40E_AQ_RESOURCE_TYPE_VSI:
1028 			i40e->i40e_resources.ifr_nvsis +=
1029 			    LE_16(srp->total_unalloced) / idp->id_nfuncs;
1030 			break;
1031 		case I40E_AQ_RESOURCE_TYPE_MACADDR:
1032 			i40e->i40e_resources.ifr_nmacfilt +=
1033 			    LE_16(srp->total_unalloced) / idp->id_nfuncs;
1034 			break;
1035 		case I40E_AQ_RESOURCE_TYPE_MULTICAST_HASH:
1036 			i40e->i40e_resources.ifr_nmcastfilt +=
1037 			    LE_16(srp->total_unalloced) / idp->id_nfuncs;
1038 		default:
1039 			break;
1040 		}
1041 	}
1042 
1043 	i40e->i40e_resources.ifr_nrx_queue = hw->func_caps.num_rx_qp;
1044 	i40e->i40e_resources.ifr_ntx_queue = hw->func_caps.num_tx_qp;
1045 
1046 	i40e->i40e_uaddrs = kmem_zalloc(sizeof (i40e_uaddr_t) *
1047 	    i40e->i40e_resources.ifr_nmacfilt, KM_SLEEP);
1048 	i40e->i40e_maddrs = kmem_zalloc(sizeof (i40e_maddr_t) *
1049 	    i40e->i40e_resources.ifr_nmcastfilt, KM_SLEEP);
1050 
1051 	/*
1052 	 * Initialize these as multicast addresses to indicate it's invalid for
1053 	 * sanity purposes. Think of it like 0xdeadbeef.
1054 	 */
1055 	for (i = 0; i < i40e->i40e_resources.ifr_nmacfilt; i++)
1056 		i40e->i40e_uaddrs[i].iua_mac[0] = 0x01;
1057 
1058 	return (B_TRUE);
1059 }
1060 
1061 static boolean_t
1062 i40e_enable_interrupts(i40e_t *i40e)
1063 {
1064 	int i, rc;
1065 
1066 	if (i40e->i40e_intr_cap & DDI_INTR_FLAG_BLOCK) {
1067 		rc = ddi_intr_block_enable(i40e->i40e_intr_handles,
1068 		    i40e->i40e_intr_count);
1069 		if (rc != DDI_SUCCESS) {
1070 			i40e_error(i40e, "Interrupt block-enable failed: %d",
1071 			    rc);
1072 			return (B_FALSE);
1073 		}
1074 	} else {
1075 		for (i = 0; i < i40e->i40e_intr_count; i++) {
1076 			rc = ddi_intr_enable(i40e->i40e_intr_handles[i]);
1077 			if (rc != DDI_SUCCESS) {
1078 				i40e_error(i40e,
1079 				    "Failed to enable interrupt %d: %d", i, rc);
1080 				while (--i >= 0) {
1081 					(void) ddi_intr_disable(
1082 					    i40e->i40e_intr_handles[i]);
1083 				}
1084 				return (B_FALSE);
1085 			}
1086 		}
1087 	}
1088 
1089 	return (B_TRUE);
1090 }
1091 
1092 static boolean_t
1093 i40e_disable_interrupts(i40e_t *i40e)
1094 {
1095 	int i, rc;
1096 
1097 	if (i40e->i40e_intr_cap & DDI_INTR_FLAG_BLOCK) {
1098 		rc = ddi_intr_block_disable(i40e->i40e_intr_handles,
1099 		    i40e->i40e_intr_count);
1100 		if (rc != DDI_SUCCESS) {
1101 			i40e_error(i40e,
1102 			    "Interrupt block-disabled failed: %d", rc);
1103 			return (B_FALSE);
1104 		}
1105 	} else {
1106 		for (i = 0; i < i40e->i40e_intr_count; i++) {
1107 			rc = ddi_intr_disable(i40e->i40e_intr_handles[i]);
1108 			if (rc != DDI_SUCCESS) {
1109 				i40e_error(i40e,
1110 				    "Failed to disable interrupt %d: %d",
1111 				    i, rc);
1112 				return (B_FALSE);
1113 			}
1114 		}
1115 	}
1116 
1117 	return (B_TRUE);
1118 }
1119 
1120 /*
1121  * Free receive & transmit rings.
1122  */
1123 static void
1124 i40e_free_trqpairs(i40e_t *i40e)
1125 {
1126 	i40e_trqpair_t *itrq;
1127 
1128 	if (i40e->i40e_rx_groups != NULL) {
1129 		kmem_free(i40e->i40e_rx_groups,
1130 		    sizeof (i40e_rx_group_t) * i40e->i40e_num_rx_groups);
1131 		i40e->i40e_rx_groups = NULL;
1132 	}
1133 
1134 	if (i40e->i40e_trqpairs != NULL) {
1135 		for (uint_t i = 0; i < i40e->i40e_num_trqpairs; i++) {
1136 			itrq = &i40e->i40e_trqpairs[i];
1137 			mutex_destroy(&itrq->itrq_rx_lock);
1138 			mutex_destroy(&itrq->itrq_tx_lock);
1139 			mutex_destroy(&itrq->itrq_tcb_lock);
1140 
1141 			/*
1142 			 * Should have already been cleaned up by start/stop,
1143 			 * etc.
1144 			 */
1145 			ASSERT(itrq->itrq_txkstat == NULL);
1146 			ASSERT(itrq->itrq_rxkstat == NULL);
1147 		}
1148 
1149 		kmem_free(i40e->i40e_trqpairs,
1150 		    sizeof (i40e_trqpair_t) * i40e->i40e_num_trqpairs);
1151 		i40e->i40e_trqpairs = NULL;
1152 	}
1153 
1154 	cv_destroy(&i40e->i40e_rx_pending_cv);
1155 	mutex_destroy(&i40e->i40e_rx_pending_lock);
1156 	mutex_destroy(&i40e->i40e_general_lock);
1157 }
1158 
1159 /*
1160  * Allocate transmit and receive rings, as well as other data structures that we
1161  * need.
1162  */
1163 static boolean_t
1164 i40e_alloc_trqpairs(i40e_t *i40e)
1165 {
1166 	void *mutexpri = DDI_INTR_PRI(i40e->i40e_intr_pri);
1167 
1168 	/*
1169 	 * Now that we have the priority for the interrupts, initialize
1170 	 * all relevant locks.
1171 	 */
1172 	mutex_init(&i40e->i40e_general_lock, NULL, MUTEX_DRIVER, mutexpri);
1173 	mutex_init(&i40e->i40e_rx_pending_lock, NULL, MUTEX_DRIVER, mutexpri);
1174 	cv_init(&i40e->i40e_rx_pending_cv, NULL, CV_DRIVER, NULL);
1175 
1176 	i40e->i40e_trqpairs = kmem_zalloc(sizeof (i40e_trqpair_t) *
1177 	    i40e->i40e_num_trqpairs, KM_SLEEP);
1178 	for (uint_t i = 0; i < i40e->i40e_num_trqpairs; i++) {
1179 		i40e_trqpair_t *itrq = &i40e->i40e_trqpairs[i];
1180 
1181 		itrq->itrq_i40e = i40e;
1182 		mutex_init(&itrq->itrq_rx_lock, NULL, MUTEX_DRIVER, mutexpri);
1183 		mutex_init(&itrq->itrq_tx_lock, NULL, MUTEX_DRIVER, mutexpri);
1184 		mutex_init(&itrq->itrq_tcb_lock, NULL, MUTEX_DRIVER, mutexpri);
1185 		itrq->itrq_index = i;
1186 	}
1187 
1188 	i40e->i40e_rx_groups = kmem_zalloc(sizeof (i40e_rx_group_t) *
1189 	    i40e->i40e_num_rx_groups, KM_SLEEP);
1190 
1191 	for (uint_t i = 0; i < i40e->i40e_num_rx_groups; i++) {
1192 		i40e_rx_group_t *rxg = &i40e->i40e_rx_groups[i];
1193 
1194 		rxg->irg_index = i;
1195 		rxg->irg_i40e = i40e;
1196 	}
1197 
1198 	return (B_TRUE);
1199 }
1200 
1201 
1202 
1203 /*
1204  * Unless a .conf file already overrode i40e_t structure values, they will
1205  * be 0, and need to be set in conjunction with the now-available HW report.
1206  */
1207 /* ARGSUSED */
1208 static void
1209 i40e_hw_to_instance(i40e_t *i40e, i40e_hw_t *hw)
1210 {
1211 	if (i40e->i40e_num_trqpairs_per_vsi == 0) {
1212 		if (i40e_is_x722(i40e)) {
1213 			i40e->i40e_num_trqpairs_per_vsi =
1214 			    I40E_722_MAX_TC_QUEUES;
1215 		} else {
1216 			i40e->i40e_num_trqpairs_per_vsi =
1217 			    I40E_710_MAX_TC_QUEUES;
1218 		}
1219 	}
1220 
1221 	if (i40e->i40e_num_rx_groups == 0) {
1222 		i40e->i40e_num_rx_groups = I40E_GROUP_MAX;
1223 	}
1224 }
1225 
1226 /*
1227  * Free any resources required by, or setup by, the Intel common code.
1228  */
1229 static void
1230 i40e_common_code_fini(i40e_t *i40e)
1231 {
1232 	i40e_hw_t *hw = &i40e->i40e_hw_space;
1233 	int rc;
1234 
1235 	rc = i40e_shutdown_lan_hmc(hw);
1236 	if (rc != I40E_SUCCESS)
1237 		i40e_error(i40e, "failed to shutdown LAN hmc: %d", rc);
1238 
1239 	rc = i40e_shutdown_adminq(hw);
1240 	if (rc != I40E_SUCCESS)
1241 		i40e_error(i40e, "failed to shutdown admin queue: %d", rc);
1242 }
1243 
1244 /*
1245  * Initialize and call Intel common-code routines, includes some setup
1246  * the common code expects from the driver.  Also prints on failure, so
1247  * the caller doesn't have to.
1248  */
1249 static boolean_t
1250 i40e_common_code_init(i40e_t *i40e, i40e_hw_t *hw)
1251 {
1252 	int rc;
1253 
1254 	i40e_clear_hw(hw);
1255 	rc = i40e_pf_reset(hw);
1256 	if (rc != 0) {
1257 		i40e_error(i40e, "failed to reset hardware: %d", rc);
1258 		i40e_fm_ereport(i40e, DDI_FM_DEVICE_NO_RESPONSE);
1259 		return (B_FALSE);
1260 	}
1261 
1262 	rc = i40e_init_shared_code(hw);
1263 	if (rc != 0) {
1264 		i40e_error(i40e, "failed to initialize i40e core: %d", rc);
1265 		return (B_FALSE);
1266 	}
1267 
1268 	hw->aq.num_arq_entries = I40E_DEF_ADMINQ_SIZE;
1269 	hw->aq.num_asq_entries =  I40E_DEF_ADMINQ_SIZE;
1270 	hw->aq.arq_buf_size = I40E_ADMINQ_BUFSZ;
1271 	hw->aq.asq_buf_size = I40E_ADMINQ_BUFSZ;
1272 
1273 	rc = i40e_init_adminq(hw);
1274 	if (rc != 0) {
1275 		i40e_error(i40e, "failed to initialize firmware admin queue: "
1276 		    "%d, potential firmware version mismatch", rc);
1277 		i40e_fm_ereport(i40e, DDI_FM_DEVICE_INVAL_STATE);
1278 		return (B_FALSE);
1279 	}
1280 
1281 	if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
1282 	    hw->aq.api_min_ver > I40E_FW_API_VERSION_MINOR) {
1283 		i40e_log(i40e, "The driver for the device detected a newer "
1284 		    "version of the NVM image (%d.%d) than expected (%d.%d).\n"
1285 		    "Please install the most recent version of the network "
1286 		    "driver.\n", hw->aq.api_maj_ver, hw->aq.api_min_ver,
1287 		    I40E_FW_API_VERSION_MAJOR, I40E_FW_API_VERSION_MINOR);
1288 	} else if (hw->aq.api_maj_ver < I40E_FW_API_VERSION_MAJOR ||
1289 	    hw->aq.api_min_ver < (I40E_FW_API_VERSION_MINOR - 1)) {
1290 		i40e_log(i40e, "The driver for the device detected an older"
1291 		    " version of the NVM image (%d.%d) than expected (%d.%d)."
1292 		    "\nPlease update the NVM image.\n",
1293 		    hw->aq.api_maj_ver, hw->aq.api_min_ver,
1294 		    I40E_FW_API_VERSION_MAJOR, I40E_FW_API_VERSION_MINOR - 1);
1295 	}
1296 
1297 	i40e_clear_pxe_mode(hw);
1298 
1299 	/*
1300 	 * We need to call this so that the common code can discover
1301 	 * capabilities of the hardware, which it uses throughout the rest.
1302 	 */
1303 	if (!i40e_get_hw_capabilities(i40e, hw)) {
1304 		i40e_error(i40e, "failed to obtain hardware capabilities");
1305 		return (B_FALSE);
1306 	}
1307 
1308 	if (i40e_get_available_resources(i40e) == B_FALSE) {
1309 		i40e_error(i40e, "failed to obtain hardware resources");
1310 		return (B_FALSE);
1311 	}
1312 
1313 	i40e_hw_to_instance(i40e, hw);
1314 
1315 	rc = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
1316 	    hw->func_caps.num_rx_qp, 0, 0);
1317 	if (rc != 0) {
1318 		i40e_error(i40e, "failed to initialize hardware memory cache: "
1319 		    "%d", rc);
1320 		return (B_FALSE);
1321 	}
1322 
1323 	rc = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
1324 	if (rc != 0) {
1325 		i40e_error(i40e, "failed to configure hardware memory cache: "
1326 		    "%d", rc);
1327 		return (B_FALSE);
1328 	}
1329 
1330 	(void) i40e_aq_stop_lldp(hw, TRUE, NULL);
1331 
1332 	rc = i40e_get_mac_addr(hw, hw->mac.addr);
1333 	if (rc != I40E_SUCCESS) {
1334 		i40e_error(i40e, "failed to retrieve hardware mac address: %d",
1335 		    rc);
1336 		return (B_FALSE);
1337 	}
1338 
1339 	rc = i40e_validate_mac_addr(hw->mac.addr);
1340 	if (rc != 0) {
1341 		i40e_error(i40e, "failed to validate internal mac address: "
1342 		    "%d", rc);
1343 		return (B_FALSE);
1344 	}
1345 	bcopy(hw->mac.addr, hw->mac.perm_addr, ETHERADDRL);
1346 	if ((rc = i40e_get_port_mac_addr(hw, hw->mac.port_addr)) !=
1347 	    I40E_SUCCESS) {
1348 		i40e_error(i40e, "failed to retrieve port mac address: %d",
1349 		    rc);
1350 		return (B_FALSE);
1351 	}
1352 
1353 	/*
1354 	 * We need to obtain the Default Virtual Station SEID (VSI)
1355 	 * before we can perform other operations on the device.
1356 	 */
1357 	if (!i40e_set_def_vsi_seid(i40e)) {
1358 		i40e_error(i40e, "failed to obtain Default VSI SEID");
1359 		return (B_FALSE);
1360 	}
1361 
1362 	return (B_TRUE);
1363 }
1364 
1365 static void
1366 i40e_unconfigure(dev_info_t *devinfo, i40e_t *i40e)
1367 {
1368 	int rc;
1369 
1370 	if (i40e->i40e_attach_progress & I40E_ATTACH_ENABLE_INTR)
1371 		(void) i40e_disable_interrupts(i40e);
1372 
1373 	if ((i40e->i40e_attach_progress & I40E_ATTACH_LINK_TIMER) &&
1374 	    i40e->i40e_periodic_id != 0) {
1375 		ddi_periodic_delete(i40e->i40e_periodic_id);
1376 		i40e->i40e_periodic_id = 0;
1377 	}
1378 
1379 	if (i40e->i40e_attach_progress & I40E_ATTACH_MAC) {
1380 		rc = mac_unregister(i40e->i40e_mac_hdl);
1381 		if (rc != 0) {
1382 			i40e_error(i40e, "failed to unregister from mac: %d",
1383 			    rc);
1384 		}
1385 	}
1386 
1387 	if (i40e->i40e_attach_progress & I40E_ATTACH_STATS) {
1388 		i40e_stats_fini(i40e);
1389 	}
1390 
1391 	if (i40e->i40e_attach_progress & I40E_ATTACH_ADD_INTR)
1392 		i40e_rem_intr_handlers(i40e);
1393 
1394 	if (i40e->i40e_attach_progress & I40E_ATTACH_ALLOC_RINGSLOCKS)
1395 		i40e_free_trqpairs(i40e);
1396 
1397 	if (i40e->i40e_attach_progress & I40E_ATTACH_ALLOC_INTR)
1398 		i40e_rem_intrs(i40e);
1399 
1400 	if (i40e->i40e_attach_progress & I40E_ATTACH_COMMON_CODE)
1401 		i40e_common_code_fini(i40e);
1402 
1403 	i40e_cleanup_resources(i40e);
1404 
1405 	if (i40e->i40e_attach_progress & I40E_ATTACH_PROPS)
1406 		(void) ddi_prop_remove_all(devinfo);
1407 
1408 	if (i40e->i40e_attach_progress & I40E_ATTACH_REGS_MAP &&
1409 	    i40e->i40e_osdep_space.ios_reg_handle != NULL) {
1410 		ddi_regs_map_free(&i40e->i40e_osdep_space.ios_reg_handle);
1411 		i40e->i40e_osdep_space.ios_reg_handle = NULL;
1412 	}
1413 
1414 	if ((i40e->i40e_attach_progress & I40E_ATTACH_PCI_CONFIG) &&
1415 	    i40e->i40e_osdep_space.ios_cfg_handle != NULL) {
1416 		pci_config_teardown(&i40e->i40e_osdep_space.ios_cfg_handle);
1417 		i40e->i40e_osdep_space.ios_cfg_handle = NULL;
1418 	}
1419 
1420 	if (i40e->i40e_attach_progress & I40E_ATTACH_FM_INIT)
1421 		i40e_fm_fini(i40e);
1422 
1423 	kmem_free(i40e->i40e_aqbuf, I40E_ADMINQ_BUFSZ);
1424 	kmem_free(i40e, sizeof (i40e_t));
1425 
1426 	ddi_set_driver_private(devinfo, NULL);
1427 }
1428 
1429 static boolean_t
1430 i40e_final_init(i40e_t *i40e)
1431 {
1432 	i40e_hw_t *hw = &i40e->i40e_hw_space;
1433 	struct i40e_osdep *osdep = OS_DEP(hw);
1434 	uint8_t pbanum[I40E_PBANUM_STRLEN];
1435 	enum i40e_status_code irc;
1436 	char buf[I40E_DDI_PROP_LEN];
1437 
1438 	pbanum[0] = '\0';
1439 	irc = i40e_read_pba_string(hw, pbanum, sizeof (pbanum));
1440 	if (irc != I40E_SUCCESS) {
1441 		i40e_log(i40e, "failed to read PBA string: %d", irc);
1442 	} else {
1443 		(void) ddi_prop_update_string(DDI_DEV_T_NONE, i40e->i40e_dip,
1444 		    "printed-board-assembly", (char *)pbanum);
1445 	}
1446 
1447 #ifdef	DEBUG
1448 	ASSERT(snprintf(NULL, 0, "%d.%d", hw->aq.fw_maj_ver,
1449 	    hw->aq.fw_min_ver) < sizeof (buf));
1450 	ASSERT(snprintf(NULL, 0, "%x", hw->aq.fw_build) < sizeof (buf));
1451 	ASSERT(snprintf(NULL, 0, "%d.%d", hw->aq.api_maj_ver,
1452 	    hw->aq.api_min_ver) < sizeof (buf));
1453 #endif
1454 
1455 	(void) snprintf(buf, sizeof (buf), "%d.%d", hw->aq.fw_maj_ver,
1456 	    hw->aq.fw_min_ver);
1457 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, i40e->i40e_dip,
1458 	    "firmware-version", buf);
1459 	(void) snprintf(buf, sizeof (buf), "%x", hw->aq.fw_build);
1460 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, i40e->i40e_dip,
1461 	    "firmware-build", buf);
1462 	(void) snprintf(buf, sizeof (buf), "%d.%d", hw->aq.api_maj_ver,
1463 	    hw->aq.api_min_ver);
1464 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, i40e->i40e_dip,
1465 	    "api-version", buf);
1466 
1467 	if (!i40e_set_hw_bus_info(hw))
1468 		return (B_FALSE);
1469 
1470 	if (i40e_check_acc_handle(osdep->ios_reg_handle) != DDI_FM_OK) {
1471 		ddi_fm_service_impact(i40e->i40e_dip, DDI_SERVICE_LOST);
1472 		return (B_FALSE);
1473 	}
1474 
1475 	return (B_TRUE);
1476 }
1477 
1478 static void
1479 i40e_identify_hardware(i40e_t *i40e)
1480 {
1481 	i40e_hw_t *hw = &i40e->i40e_hw_space;
1482 	struct i40e_osdep *osdep = &i40e->i40e_osdep_space;
1483 
1484 	hw->vendor_id = pci_config_get16(osdep->ios_cfg_handle, PCI_CONF_VENID);
1485 	hw->device_id = pci_config_get16(osdep->ios_cfg_handle, PCI_CONF_DEVID);
1486 	hw->revision_id = pci_config_get8(osdep->ios_cfg_handle,
1487 	    PCI_CONF_REVID);
1488 	hw->subsystem_device_id =
1489 	    pci_config_get16(osdep->ios_cfg_handle, PCI_CONF_SUBSYSID);
1490 	hw->subsystem_vendor_id =
1491 	    pci_config_get16(osdep->ios_cfg_handle, PCI_CONF_SUBVENID);
1492 
1493 	/*
1494 	 * Note that we set the hardware's bus information later on, in
1495 	 * i40e_get_available_resources(). The common code doesn't seem to
1496 	 * require that it be set in any ways, it seems to be mostly for
1497 	 * book-keeping.
1498 	 */
1499 }
1500 
1501 static boolean_t
1502 i40e_regs_map(i40e_t *i40e)
1503 {
1504 	dev_info_t *devinfo = i40e->i40e_dip;
1505 	i40e_hw_t *hw = &i40e->i40e_hw_space;
1506 	struct i40e_osdep *osdep = &i40e->i40e_osdep_space;
1507 	off_t memsize;
1508 	int ret;
1509 
1510 	if (ddi_dev_regsize(devinfo, I40E_ADAPTER_REGSET, &memsize) !=
1511 	    DDI_SUCCESS) {
1512 		i40e_error(i40e, "Used invalid register set to map PCIe regs");
1513 		return (B_FALSE);
1514 	}
1515 
1516 	if ((ret = ddi_regs_map_setup(devinfo, I40E_ADAPTER_REGSET,
1517 	    (caddr_t *)&hw->hw_addr, 0, memsize, &i40e_regs_acc_attr,
1518 	    &osdep->ios_reg_handle)) != DDI_SUCCESS) {
1519 		i40e_error(i40e, "failed to map device registers: %d", ret);
1520 		return (B_FALSE);
1521 	}
1522 
1523 	osdep->ios_reg_size = memsize;
1524 	return (B_TRUE);
1525 }
1526 
1527 /*
1528  * Update parameters required when a new MTU has been configured.  Calculate the
1529  * maximum frame size, as well as, size our DMA buffers which we size in
1530  * increments of 1K.
1531  */
1532 void
1533 i40e_update_mtu(i40e_t *i40e)
1534 {
1535 	uint32_t rx, tx;
1536 
1537 	i40e->i40e_frame_max = i40e->i40e_sdu +
1538 	    sizeof (struct ether_vlan_header) + ETHERFCSL;
1539 
1540 	rx = i40e->i40e_frame_max + I40E_BUF_IPHDR_ALIGNMENT;
1541 	i40e->i40e_rx_buf_size = ((rx >> 10) +
1542 	    ((rx & (((uint32_t)1 << 10) -1)) > 0 ? 1 : 0)) << 10;
1543 
1544 	tx = i40e->i40e_frame_max;
1545 	i40e->i40e_tx_buf_size = ((tx >> 10) +
1546 	    ((tx & (((uint32_t)1 << 10) -1)) > 0 ? 1 : 0)) << 10;
1547 }
1548 
1549 static int
1550 i40e_get_prop(i40e_t *i40e, char *prop, int min, int max, int def)
1551 {
1552 	int val;
1553 
1554 	val = ddi_prop_get_int(DDI_DEV_T_ANY, i40e->i40e_dip, DDI_PROP_DONTPASS,
1555 	    prop, def);
1556 	if (val > max)
1557 		val = max;
1558 	if (val < min)
1559 		val = min;
1560 	return (val);
1561 }
1562 
1563 static void
1564 i40e_init_properties(i40e_t *i40e)
1565 {
1566 	i40e->i40e_sdu = i40e_get_prop(i40e, "default_mtu",
1567 	    I40E_MIN_MTU, I40E_MAX_MTU, I40E_DEF_MTU);
1568 
1569 	i40e->i40e_intr_force = i40e_get_prop(i40e, "intr_force",
1570 	    I40E_INTR_NONE, I40E_INTR_LEGACY, I40E_INTR_NONE);
1571 
1572 	i40e->i40e_mr_enable = i40e_get_prop(i40e, "mr_enable",
1573 	    B_FALSE, B_TRUE, B_TRUE);
1574 
1575 	i40e->i40e_tx_ring_size = i40e_get_prop(i40e, "tx_ring_size",
1576 	    I40E_MIN_TX_RING_SIZE, I40E_MAX_TX_RING_SIZE,
1577 	    I40E_DEF_TX_RING_SIZE);
1578 	if ((i40e->i40e_tx_ring_size % I40E_DESC_ALIGN) != 0) {
1579 		i40e->i40e_tx_ring_size = P2ROUNDUP(i40e->i40e_tx_ring_size,
1580 		    I40E_DESC_ALIGN);
1581 	}
1582 
1583 	i40e->i40e_tx_block_thresh = i40e_get_prop(i40e, "tx_resched_threshold",
1584 	    I40E_MIN_TX_BLOCK_THRESH,
1585 	    i40e->i40e_tx_ring_size - I40E_TX_MAX_COOKIE,
1586 	    I40E_DEF_TX_BLOCK_THRESH);
1587 
1588 	i40e->i40e_rx_ring_size = i40e_get_prop(i40e, "rx_ring_size",
1589 	    I40E_MIN_RX_RING_SIZE, I40E_MAX_RX_RING_SIZE,
1590 	    I40E_DEF_RX_RING_SIZE);
1591 	if ((i40e->i40e_rx_ring_size % I40E_DESC_ALIGN) != 0) {
1592 		i40e->i40e_rx_ring_size = P2ROUNDUP(i40e->i40e_rx_ring_size,
1593 		    I40E_DESC_ALIGN);
1594 	}
1595 
1596 	i40e->i40e_rx_limit_per_intr = i40e_get_prop(i40e, "rx_limit_per_intr",
1597 	    I40E_MIN_RX_LIMIT_PER_INTR,	I40E_MAX_RX_LIMIT_PER_INTR,
1598 	    I40E_DEF_RX_LIMIT_PER_INTR);
1599 
1600 	i40e->i40e_tx_hcksum_enable = i40e_get_prop(i40e, "tx_hcksum_enable",
1601 	    B_FALSE, B_TRUE, B_TRUE);
1602 
1603 	i40e->i40e_tx_lso_enable = i40e_get_prop(i40e, "tx_lso_enable",
1604 	    B_FALSE, B_TRUE, B_TRUE);
1605 
1606 	i40e->i40e_rx_hcksum_enable = i40e_get_prop(i40e, "rx_hcksum_enable",
1607 	    B_FALSE, B_TRUE, B_TRUE);
1608 
1609 	i40e->i40e_rx_dma_min = i40e_get_prop(i40e, "rx_dma_threshold",
1610 	    I40E_MIN_RX_DMA_THRESH, I40E_MAX_RX_DMA_THRESH,
1611 	    I40E_DEF_RX_DMA_THRESH);
1612 
1613 	i40e->i40e_tx_dma_min = i40e_get_prop(i40e, "tx_dma_threshold",
1614 	    I40E_MIN_TX_DMA_THRESH, I40E_MAX_TX_DMA_THRESH,
1615 	    I40E_DEF_TX_DMA_THRESH);
1616 
1617 	i40e->i40e_tx_itr = i40e_get_prop(i40e, "tx_intr_throttle",
1618 	    I40E_MIN_ITR, I40E_MAX_ITR, I40E_DEF_TX_ITR);
1619 
1620 	i40e->i40e_rx_itr = i40e_get_prop(i40e, "rx_intr_throttle",
1621 	    I40E_MIN_ITR, I40E_MAX_ITR, I40E_DEF_RX_ITR);
1622 
1623 	i40e->i40e_other_itr = i40e_get_prop(i40e, "other_intr_throttle",
1624 	    I40E_MIN_ITR, I40E_MAX_ITR, I40E_DEF_OTHER_ITR);
1625 
1626 	if (!i40e->i40e_mr_enable) {
1627 		i40e->i40e_num_trqpairs = I40E_TRQPAIR_NOMSIX;
1628 		i40e->i40e_num_rx_groups = I40E_GROUP_NOMSIX;
1629 	}
1630 
1631 	i40e_update_mtu(i40e);
1632 }
1633 
1634 /*
1635  * There are a few constraints on interrupts that we're currently imposing, some
1636  * of which are restrictions from hardware. For a fuller treatment, see
1637  * i40e_intr.c.
1638  *
1639  * Currently, to use MSI-X we require two interrupts be available though in
1640  * theory we should participate in IRM and happily use more interrupts.
1641  *
1642  * Hardware only supports a single MSI being programmed and therefore if we
1643  * don't have MSI-X interrupts available at this time, then we ratchet down the
1644  * number of rings and groups available. Obviously, we only bother with a single
1645  * fixed interrupt.
1646  */
1647 static boolean_t
1648 i40e_alloc_intr_handles(i40e_t *i40e, dev_info_t *devinfo, int intr_type)
1649 {
1650 	i40e_hw_t *hw = &i40e->i40e_hw_space;
1651 	ddi_acc_handle_t rh = i40e->i40e_osdep_space.ios_reg_handle;
1652 	int request, count, actual, rc, min;
1653 	uint32_t reg;
1654 
1655 	switch (intr_type) {
1656 	case DDI_INTR_TYPE_FIXED:
1657 	case DDI_INTR_TYPE_MSI:
1658 		request = 1;
1659 		min = 1;
1660 		break;
1661 	case DDI_INTR_TYPE_MSIX:
1662 		min = 2;
1663 		if (!i40e->i40e_mr_enable) {
1664 			request = 2;
1665 			break;
1666 		}
1667 		reg = I40E_READ_REG(hw, I40E_GLPCI_CNF2);
1668 		/*
1669 		 * Should this read fail, we will drop back to using
1670 		 * MSI or fixed interrupts.
1671 		 */
1672 		if (i40e_check_acc_handle(rh) != DDI_FM_OK) {
1673 			ddi_fm_service_impact(i40e->i40e_dip,
1674 			    DDI_SERVICE_DEGRADED);
1675 			return (B_FALSE);
1676 		}
1677 		request = (reg & I40E_GLPCI_CNF2_MSI_X_PF_N_MASK) >>
1678 		    I40E_GLPCI_CNF2_MSI_X_PF_N_SHIFT;
1679 		request++;	/* the register value is n - 1 */
1680 		break;
1681 	default:
1682 		panic("bad interrupt type passed to i40e_alloc_intr_handles: "
1683 		    "%d", intr_type);
1684 		return (B_FALSE);
1685 	}
1686 
1687 	rc = ddi_intr_get_nintrs(devinfo, intr_type, &count);
1688 	if (rc != DDI_SUCCESS || count < min) {
1689 		i40e_log(i40e, "Get interrupt number failed, "
1690 		    "returned %d, count %d", rc, count);
1691 		return (B_FALSE);
1692 	}
1693 
1694 	rc = ddi_intr_get_navail(devinfo, intr_type, &count);
1695 	if (rc != DDI_SUCCESS || count < min) {
1696 		i40e_log(i40e, "Get AVAILABLE interrupt number failed, "
1697 		    "returned %d, count %d", rc, count);
1698 		return (B_FALSE);
1699 	}
1700 
1701 	actual = 0;
1702 	i40e->i40e_intr_count = 0;
1703 	i40e->i40e_intr_count_max = 0;
1704 	i40e->i40e_intr_count_min = 0;
1705 
1706 	i40e->i40e_intr_size = request * sizeof (ddi_intr_handle_t);
1707 	ASSERT(i40e->i40e_intr_size != 0);
1708 	i40e->i40e_intr_handles = kmem_alloc(i40e->i40e_intr_size, KM_SLEEP);
1709 
1710 	rc = ddi_intr_alloc(devinfo, i40e->i40e_intr_handles, intr_type, 0,
1711 	    min(request, count), &actual, DDI_INTR_ALLOC_NORMAL);
1712 	if (rc != DDI_SUCCESS) {
1713 		i40e_log(i40e, "Interrupt allocation failed with %d.", rc);
1714 		goto alloc_handle_fail;
1715 	}
1716 
1717 	i40e->i40e_intr_count = actual;
1718 	i40e->i40e_intr_count_max = request;
1719 	i40e->i40e_intr_count_min = min;
1720 
1721 	if (actual < min) {
1722 		i40e_log(i40e, "actual (%d) is less than minimum (%d).",
1723 		    actual, min);
1724 		goto alloc_handle_fail;
1725 	}
1726 
1727 	/*
1728 	 * Record the priority and capabilities for our first vector.  Once
1729 	 * we have it, that's our priority until detach time.  Even if we
1730 	 * eventually participate in IRM, our priority shouldn't change.
1731 	 */
1732 	rc = ddi_intr_get_pri(i40e->i40e_intr_handles[0], &i40e->i40e_intr_pri);
1733 	if (rc != DDI_SUCCESS) {
1734 		i40e_log(i40e,
1735 		    "Getting interrupt priority failed with %d.", rc);
1736 		goto alloc_handle_fail;
1737 	}
1738 
1739 	rc = ddi_intr_get_cap(i40e->i40e_intr_handles[0], &i40e->i40e_intr_cap);
1740 	if (rc != DDI_SUCCESS) {
1741 		i40e_log(i40e,
1742 		    "Getting interrupt capabilities failed with %d.", rc);
1743 		goto alloc_handle_fail;
1744 	}
1745 
1746 	i40e->i40e_intr_type = intr_type;
1747 	return (B_TRUE);
1748 
1749 alloc_handle_fail:
1750 
1751 	i40e_rem_intrs(i40e);
1752 	return (B_FALSE);
1753 }
1754 
1755 static boolean_t
1756 i40e_alloc_intrs(i40e_t *i40e, dev_info_t *devinfo)
1757 {
1758 	int intr_types, rc;
1759 	uint_t max_trqpairs;
1760 
1761 	if (i40e_is_x722(i40e)) {
1762 		max_trqpairs = I40E_722_MAX_TC_QUEUES;
1763 	} else {
1764 		max_trqpairs = I40E_710_MAX_TC_QUEUES;
1765 	}
1766 
1767 	rc = ddi_intr_get_supported_types(devinfo, &intr_types);
1768 	if (rc != DDI_SUCCESS) {
1769 		i40e_error(i40e, "failed to get supported interrupt types: %d",
1770 		    rc);
1771 		return (B_FALSE);
1772 	}
1773 
1774 	i40e->i40e_intr_type = 0;
1775 	i40e->i40e_num_rx_groups = I40E_GROUP_MAX;
1776 
1777 	/*
1778 	 * We need to determine the number of queue pairs per traffic
1779 	 * class. We only have one traffic class (TC0), so we'll base
1780 	 * this off the number of interrupts provided. Furthermore,
1781 	 * since we only use one traffic class, the number of queues
1782 	 * per traffic class and per VSI are the same.
1783 	 */
1784 	if ((intr_types & DDI_INTR_TYPE_MSIX) &&
1785 	    (i40e->i40e_intr_force <= I40E_INTR_MSIX) &&
1786 	    (i40e_alloc_intr_handles(i40e, devinfo, DDI_INTR_TYPE_MSIX))) {
1787 		uint32_t n;
1788 
1789 		/*
1790 		 * While we want the number of queue pairs to match
1791 		 * the number of interrupts, we must keep stay in
1792 		 * bounds of the maximum number of queues per traffic
1793 		 * class. We subtract one from i40e_intr_count to
1794 		 * account for interrupt zero; which is currently
1795 		 * restricted to admin queue commands and other
1796 		 * interrupt causes.
1797 		 */
1798 		n = MIN(i40e->i40e_intr_count - 1, max_trqpairs);
1799 		ASSERT3U(n, >, 0);
1800 
1801 		/*
1802 		 * Round up to the nearest power of two to ensure that
1803 		 * the QBASE aligns with the TC size which must be
1804 		 * programmed as a power of two. See the queue mapping
1805 		 * description in section 7.4.9.5.5.1.
1806 		 *
1807 		 * If i40e_intr_count - 1 is not a power of two then
1808 		 * some queue pairs on the same VSI will have to share
1809 		 * an interrupt.
1810 		 *
1811 		 * We may want to revisit this logic in a future where
1812 		 * we have more interrupts and more VSIs. Otherwise,
1813 		 * each VSI will use as many interrupts as possible.
1814 		 * Using more QPs per VSI means better RSS for each
1815 		 * group, but at the same time may require more
1816 		 * sharing of interrupts across VSIs. This may be a
1817 		 * good candidate for a .conf tunable.
1818 		 */
1819 		n = 0x1 << ddi_fls(n);
1820 		i40e->i40e_num_trqpairs_per_vsi = n;
1821 		ASSERT3U(i40e->i40e_num_rx_groups, >, 0);
1822 		i40e->i40e_num_trqpairs = i40e->i40e_num_trqpairs_per_vsi *
1823 		    i40e->i40e_num_rx_groups;
1824 		return (B_TRUE);
1825 	}
1826 
1827 	/*
1828 	 * We only use multiple transmit/receive pairs when MSI-X interrupts are
1829 	 * available due to the fact that the device basically only supports a
1830 	 * single MSI interrupt.
1831 	 */
1832 	i40e->i40e_num_trqpairs = I40E_TRQPAIR_NOMSIX;
1833 	i40e->i40e_num_trqpairs_per_vsi = i40e->i40e_num_trqpairs;
1834 	i40e->i40e_num_rx_groups = I40E_GROUP_NOMSIX;
1835 
1836 	if ((intr_types & DDI_INTR_TYPE_MSI) &&
1837 	    (i40e->i40e_intr_force <= I40E_INTR_MSI)) {
1838 		if (i40e_alloc_intr_handles(i40e, devinfo, DDI_INTR_TYPE_MSI))
1839 			return (B_TRUE);
1840 	}
1841 
1842 	if (intr_types & DDI_INTR_TYPE_FIXED) {
1843 		if (i40e_alloc_intr_handles(i40e, devinfo, DDI_INTR_TYPE_FIXED))
1844 			return (B_TRUE);
1845 	}
1846 
1847 	return (B_FALSE);
1848 }
1849 
1850 /*
1851  * Map different interrupts to MSI-X vectors.
1852  */
1853 static boolean_t
1854 i40e_map_intrs_to_vectors(i40e_t *i40e)
1855 {
1856 	if (i40e->i40e_intr_type != DDI_INTR_TYPE_MSIX) {
1857 		return (B_TRUE);
1858 	}
1859 
1860 	/*
1861 	 * Each queue pair is mapped to a single interrupt, so
1862 	 * transmit and receive interrupts for a given queue share the
1863 	 * same vector. Vector zero is reserved for the admin queue.
1864 	 */
1865 	for (uint_t i = 0; i < i40e->i40e_num_trqpairs; i++) {
1866 		uint_t vector = i % (i40e->i40e_intr_count - 1);
1867 
1868 		i40e->i40e_trqpairs[i].itrq_rx_intrvec = vector + 1;
1869 		i40e->i40e_trqpairs[i].itrq_tx_intrvec = vector + 1;
1870 	}
1871 
1872 	return (B_TRUE);
1873 }
1874 
1875 static boolean_t
1876 i40e_add_intr_handlers(i40e_t *i40e)
1877 {
1878 	int rc, vector;
1879 
1880 	switch (i40e->i40e_intr_type) {
1881 	case DDI_INTR_TYPE_MSIX:
1882 		for (vector = 0; vector < i40e->i40e_intr_count; vector++) {
1883 			rc = ddi_intr_add_handler(
1884 			    i40e->i40e_intr_handles[vector],
1885 			    (ddi_intr_handler_t *)i40e_intr_msix, i40e,
1886 			    (void *)(uintptr_t)vector);
1887 			if (rc != DDI_SUCCESS) {
1888 				i40e_log(i40e, "Add interrupt handler (MSI-X) "
1889 				    "failed: return %d, vector %d", rc, vector);
1890 				for (vector--; vector >= 0; vector--) {
1891 					(void) ddi_intr_remove_handler(
1892 					    i40e->i40e_intr_handles[vector]);
1893 				}
1894 				return (B_FALSE);
1895 			}
1896 		}
1897 		break;
1898 	case DDI_INTR_TYPE_MSI:
1899 		rc = ddi_intr_add_handler(i40e->i40e_intr_handles[0],
1900 		    (ddi_intr_handler_t *)i40e_intr_msi, i40e, NULL);
1901 		if (rc != DDI_SUCCESS) {
1902 			i40e_log(i40e, "Add interrupt handler (MSI) failed: "
1903 			    "return %d", rc);
1904 			return (B_FALSE);
1905 		}
1906 		break;
1907 	case DDI_INTR_TYPE_FIXED:
1908 		rc = ddi_intr_add_handler(i40e->i40e_intr_handles[0],
1909 		    (ddi_intr_handler_t *)i40e_intr_legacy, i40e, NULL);
1910 		if (rc != DDI_SUCCESS) {
1911 			i40e_log(i40e, "Add interrupt handler (legacy) failed:"
1912 			    " return %d", rc);
1913 			return (B_FALSE);
1914 		}
1915 		break;
1916 	default:
1917 		/* Cast to pacify lint */
1918 		panic("i40e_intr_type %p contains an unknown type: %d",
1919 		    (void *)i40e, i40e->i40e_intr_type);
1920 	}
1921 
1922 	return (B_TRUE);
1923 }
1924 
1925 /*
1926  * Perform periodic checks. Longer term, we should be thinking about additional
1927  * things here:
1928  *
1929  * o Stall Detection
1930  * o Temperature sensor detection
1931  * o Device resetting
1932  * o Statistics updating to avoid wraparound
1933  */
1934 static void
1935 i40e_timer(void *arg)
1936 {
1937 	i40e_t *i40e = arg;
1938 
1939 	mutex_enter(&i40e->i40e_general_lock);
1940 	i40e_link_check(i40e);
1941 	mutex_exit(&i40e->i40e_general_lock);
1942 }
1943 
1944 /*
1945  * Get the hardware state, and scribble away anything that needs scribbling.
1946  */
1947 static void
1948 i40e_get_hw_state(i40e_t *i40e, i40e_hw_t *hw)
1949 {
1950 	int rc;
1951 
1952 	ASSERT(MUTEX_HELD(&i40e->i40e_general_lock));
1953 
1954 	(void) i40e_aq_get_link_info(hw, TRUE, NULL, NULL);
1955 	i40e_link_check(i40e);
1956 
1957 	/*
1958 	 * Try and determine our PHY. Note that we may have to retry to and
1959 	 * delay to detect fiber correctly.
1960 	 */
1961 	rc = i40e_aq_get_phy_capabilities(hw, B_FALSE, B_TRUE, &i40e->i40e_phy,
1962 	    NULL);
1963 	if (rc == I40E_ERR_UNKNOWN_PHY) {
1964 		i40e_msec_delay(200);
1965 		rc = i40e_aq_get_phy_capabilities(hw, B_FALSE, B_TRUE,
1966 		    &i40e->i40e_phy, NULL);
1967 	}
1968 
1969 	if (rc != I40E_SUCCESS) {
1970 		if (rc == I40E_ERR_UNKNOWN_PHY) {
1971 			i40e_error(i40e, "encountered unknown PHY type, "
1972 			    "not attaching.");
1973 		} else {
1974 			i40e_error(i40e, "error getting physical capabilities: "
1975 			    "%d, %d", rc, hw->aq.asq_last_status);
1976 		}
1977 	}
1978 
1979 	rc = i40e_update_link_info(hw);
1980 	if (rc != I40E_SUCCESS) {
1981 		i40e_error(i40e, "failed to update link information: %d", rc);
1982 	}
1983 
1984 	/*
1985 	 * In general, we don't want to mask off (as in stop from being a cause)
1986 	 * any of the interrupts that the phy might be able to generate.
1987 	 */
1988 	rc = i40e_aq_set_phy_int_mask(hw, 0, NULL);
1989 	if (rc != I40E_SUCCESS) {
1990 		i40e_error(i40e, "failed to update phy link mask: %d", rc);
1991 	}
1992 }
1993 
1994 /*
1995  * Go through and re-initialize any existing filters that we may have set up for
1996  * this device. Note that we would only expect them to exist if hardware had
1997  * already been initialized and we had just reset it. While we're not
1998  * implementing this yet, we're keeping this around for when we add reset
1999  * capabilities, so this isn't forgotten.
2000  */
2001 /* ARGSUSED */
2002 static void
2003 i40e_init_macaddrs(i40e_t *i40e, i40e_hw_t *hw)
2004 {
2005 }
2006 
2007 /*
2008  * Set the properties which have common values across all the VSIs.
2009  * Consult the "Add VSI" command section (7.4.9.5.5.1) for a
2010  * complete description of these properties.
2011  */
2012 static void
2013 i40e_set_shared_vsi_props(i40e_t *i40e,
2014     struct i40e_aqc_vsi_properties_data *info, uint_t vsi_idx)
2015 {
2016 	uint_t tc_queues;
2017 	uint16_t vsi_qp_base;
2018 
2019 	/*
2020 	 * It's important that we use bitwise-OR here; callers to this
2021 	 * function might enable other sections before calling this
2022 	 * function.
2023 	 */
2024 	info->valid_sections |= LE_16(I40E_AQ_VSI_PROP_QUEUE_MAP_VALID |
2025 	    I40E_AQ_VSI_PROP_VLAN_VALID);
2026 
2027 	/*
2028 	 * Calculate the starting QP index for this VSI. This base is
2029 	 * relative to the PF queue space; so a value of 0 for PF#1
2030 	 * represents the absolute index PFLAN_QALLOC_FIRSTQ for PF#1.
2031 	 */
2032 	vsi_qp_base = vsi_idx * i40e->i40e_num_trqpairs_per_vsi;
2033 	info->mapping_flags = LE_16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2034 	info->queue_mapping[0] =
2035 	    LE_16((vsi_qp_base << I40E_AQ_VSI_QUEUE_SHIFT) &
2036 		I40E_AQ_VSI_QUEUE_MASK);
2037 
2038 	/*
2039 	 * tc_queues determines the size of the traffic class, where
2040 	 * the size is 2^^tc_queues to a maximum of 64 for the X710
2041 	 * and 128 for the X722.
2042 	 *
2043 	 * Some examples:
2044 	 * 	i40e_num_trqpairs_per_vsi == 1 =>  tc_queues = 0, 2^^0 = 1.
2045 	 * 	i40e_num_trqpairs_per_vsi == 7 =>  tc_queues = 3, 2^^3 = 8.
2046 	 * 	i40e_num_trqpairs_per_vsi == 8 =>  tc_queues = 3, 2^^3 = 8.
2047 	 * 	i40e_num_trqpairs_per_vsi == 9 =>  tc_queues = 4, 2^^4 = 16.
2048 	 * 	i40e_num_trqpairs_per_vsi == 17 => tc_queues = 5, 2^^5 = 32.
2049 	 * 	i40e_num_trqpairs_per_vsi == 64 => tc_queues = 6, 2^^6 = 64.
2050 	 */
2051 	tc_queues = ddi_fls(i40e->i40e_num_trqpairs_per_vsi - 1);
2052 
2053 	/*
2054 	 * The TC queue mapping is in relation to the VSI queue space.
2055 	 * Since we are only using one traffic class (TC0) we always
2056 	 * start at queue offset 0.
2057 	 */
2058 	info->tc_mapping[0] =
2059 	    LE_16(((0 << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) &
2060 		    I40E_AQ_VSI_TC_QUE_OFFSET_MASK) |
2061 		((tc_queues << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT) &
2062 		    I40E_AQ_VSI_TC_QUE_NUMBER_MASK));
2063 
2064 	/*
2065 	 * I40E_AQ_VSI_PVLAN_MODE_ALL ("VLAN driver insertion mode")
2066 	 *
2067 	 *	Allow tagged and untagged packets to be sent to this
2068 	 *	VSI from the host.
2069 	 *
2070 	 * I40E_AQ_VSI_PVLAN_EMOD_NOTHING ("VLAN and UP expose mode")
2071 	 *
2072 	 *	Leave the tag on the frame and place no VLAN
2073 	 *	information in the descriptor. We want this mode
2074 	 *	because our MAC layer will take care of the VLAN tag,
2075 	 *	if there is one.
2076 	 */
2077 	info->port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2078 	    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
2079 }
2080 
2081 /*
2082  * Delete the VSI at this index, if one exists. We assume there is no
2083  * action we can take if this command fails but to log the failure.
2084  */
2085 static void
2086 i40e_delete_vsi(i40e_t *i40e, uint_t idx)
2087 {
2088 	i40e_hw_t	*hw = &i40e->i40e_hw_space;
2089 	uint16_t	seid = i40e->i40e_vsis[idx].iv_seid;
2090 
2091 	if (seid != 0) {
2092 		int rc;
2093 
2094 		rc = i40e_aq_delete_element(hw, seid, NULL);
2095 
2096 		if (rc != I40E_SUCCESS) {
2097 			i40e_error(i40e, "Failed to delete VSI %d: %d",
2098 			    rc, hw->aq.asq_last_status);
2099 		}
2100 
2101 		i40e->i40e_vsis[idx].iv_seid = 0;
2102 	}
2103 }
2104 
2105 /*
2106  * Add a new VSI.
2107  */
2108 static boolean_t
2109 i40e_add_vsi(i40e_t *i40e, i40e_hw_t *hw, uint_t idx)
2110 {
2111 	struct i40e_vsi_context	ctx;
2112 	i40e_rx_group_t		*rxg;
2113 	int			rc;
2114 
2115 	/*
2116 	 * The default VSI is created by the controller. This function
2117 	 * creates new, non-defualt VSIs only.
2118 	 */
2119 	ASSERT3U(idx, !=, 0);
2120 
2121 	bzero(&ctx, sizeof (struct i40e_vsi_context));
2122 	ctx.uplink_seid = i40e->i40e_veb_seid;
2123 	ctx.pf_num = hw->pf_id;
2124 	ctx.flags = I40E_AQ_VSI_TYPE_PF;
2125 	ctx.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
2126 	i40e_set_shared_vsi_props(i40e, &ctx.info, idx);
2127 
2128 	rc = i40e_aq_add_vsi(hw, &ctx, NULL);
2129 	if (rc != I40E_SUCCESS) {
2130 		i40e_error(i40e, "i40e_aq_add_vsi() failed %d: %d", rc,
2131 		    hw->aq.asq_last_status);
2132 		return (B_FALSE);
2133 	}
2134 
2135 	rxg = &i40e->i40e_rx_groups[idx];
2136 	rxg->irg_vsi_seid = ctx.seid;
2137 	i40e->i40e_vsis[idx].iv_number = ctx.vsi_number;
2138 	i40e->i40e_vsis[idx].iv_seid = ctx.seid;
2139 	i40e->i40e_vsis[idx].iv_stats_id = LE_16(ctx.info.stat_counter_idx);
2140 
2141 	if (i40e_stat_vsi_init(i40e, idx) == B_FALSE)
2142 		return (B_FALSE);
2143 
2144 	return (B_TRUE);
2145 }
2146 
2147 /*
2148  * Configure the hardware for the Default Virtual Station Interface (VSI).
2149  */
2150 static boolean_t
2151 i40e_config_def_vsi(i40e_t *i40e, i40e_hw_t *hw)
2152 {
2153 	struct i40e_vsi_context	ctx;
2154 	i40e_rx_group_t *def_rxg;
2155 	int err;
2156 	struct i40e_aqc_remove_macvlan_element_data filt;
2157 
2158 	bzero(&ctx, sizeof (struct i40e_vsi_context));
2159 	ctx.seid = I40E_DEF_VSI_SEID(i40e);
2160 	ctx.pf_num = hw->pf_id;
2161 	err = i40e_aq_get_vsi_params(hw, &ctx, NULL);
2162 	if (err != I40E_SUCCESS) {
2163 		i40e_error(i40e, "get VSI params failed with %d", err);
2164 		return (B_FALSE);
2165 	}
2166 
2167 	ctx.info.valid_sections = 0;
2168 	i40e->i40e_vsis[0].iv_number = ctx.vsi_number;
2169 	i40e->i40e_vsis[0].iv_stats_id = LE_16(ctx.info.stat_counter_idx);
2170 	if (i40e_stat_vsi_init(i40e, 0) == B_FALSE)
2171 		return (B_FALSE);
2172 
2173 	i40e_set_shared_vsi_props(i40e, &ctx.info, I40E_DEF_VSI_IDX);
2174 
2175 	err = i40e_aq_update_vsi_params(hw, &ctx, NULL);
2176 	if (err != I40E_SUCCESS) {
2177 		i40e_error(i40e, "Update VSI params failed with %d", err);
2178 		return (B_FALSE);
2179 	}
2180 
2181 	def_rxg = &i40e->i40e_rx_groups[0];
2182 	def_rxg->irg_vsi_seid = I40E_DEF_VSI_SEID(i40e);
2183 
2184 	/*
2185 	 * The controller places an implicit L2 filter for the primary
2186 	 * MAC pointing to the default VSI. We remove this filter to
2187 	 * prevent duplicate delivery of packets destined for the
2188 	 * primary MAC address as DLS will create the same filter on a
2189 	 * non-default VSI for the primary MAC client.
2190 	 */
2191 	bzero(&filt, sizeof (filt));
2192 	bcopy(hw->mac.port_addr, filt.mac_addr, ETHERADDRL);
2193 	filt.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2194 	filt.vlan_tag = 0;
2195 
2196 
2197 	ASSERT3U(i40e->i40e_resources.ifr_nmacfilt_used, <=, 1);
2198 
2199 	err = i40e_aq_remove_macvlan(hw, I40E_DEF_VSI_SEID(i40e), &filt, 1,
2200 	    NULL);
2201 	if (err != I40E_SUCCESS) {
2202 		i40e_error(i40e, "Failed to remove primary MAC from default VSI"
2203 		    ":  %d (%d)", err, hw->aq.asq_last_status);
2204 		return (B_FALSE);
2205 	}
2206 
2207 	/*
2208 	 *  As mentioned above, the controller created an implicit L2
2209 	 *  filter for the primary MAC. We want to remove both the
2210 	 *  filter and decrement the filter count. However, not all
2211 	 *  controllers count this implicit filter against the total
2212 	 *  MAC filter count. So here we are making sure it is either
2213 	 *  one or zero. If it is one, then we know it is for the
2214 	 *  implicit filter and we should decrement since we just
2215 	 *  removed the filter above. If it is zero then we know the
2216 	 *  controller that does not count the implicit filter, and it
2217 	 *  was enough to just remove it; we leave the count alone.
2218 	 *  But if it is neither, then we have never seen a controller
2219 	 *  like this before and we should fail to attach.
2220 	 *
2221 	 *  It is unfortunate that this code must exist but the
2222 	 *  behavior of this implicit L2 filter and its corresponding
2223 	 *  count were dicovered through empirical testing. The
2224 	 *  programming manuals hint at this filter but do not
2225 	 *  explicitly call out the exact behavior.
2226 	 */
2227 	if (i40e->i40e_resources.ifr_nmacfilt_used == 1) {
2228 		i40e->i40e_resources.ifr_nmacfilt_used--;
2229 	} else {
2230 		if (i40e->i40e_resources.ifr_nmacfilt_used != 0) {
2231 			i40e_error(i40e, "Unexpected MAC filter count: %u"
2232 			    " (expected 0)",
2233 			    i40e->i40e_resources.ifr_nmacfilt_used);
2234 			    return (B_FALSE);
2235 		}
2236 	}
2237 
2238 	return (B_TRUE);
2239 }
2240 
2241 static boolean_t
2242 i40e_config_rss_key_x722(i40e_t *i40e, i40e_hw_t *hw)
2243 {
2244 	for (uint_t i = 0; i < i40e->i40e_num_rx_groups; i++) {
2245 		uint32_t seed[I40E_PFQF_HKEY_MAX_INDEX + 1];
2246 		struct i40e_aqc_get_set_rss_key_data key;
2247 		const char *u8seed;
2248 		enum i40e_status_code status;
2249 		uint16_t vsi_number = i40e->i40e_vsis[i].iv_number;
2250 
2251 		(void) random_get_pseudo_bytes((uint8_t *)seed, sizeof (seed));
2252 		u8seed = (char *)seed;
2253 
2254 		CTASSERT(sizeof (key) >= (sizeof (key.standard_rss_key) +
2255 		    sizeof (key.extended_hash_key)));
2256 
2257 		bcopy(u8seed, key.standard_rss_key,
2258 		    sizeof (key.standard_rss_key));
2259 		bcopy(&u8seed[sizeof (key.standard_rss_key)],
2260 		    key.extended_hash_key, sizeof (key.extended_hash_key));
2261 
2262 		ASSERT3U(vsi_number, !=, 0);
2263 		status = i40e_aq_set_rss_key(hw, vsi_number, &key);
2264 
2265 		if (status != I40E_SUCCESS) {
2266 			i40e_error(i40e, "failed to set RSS key for VSI %u: %d",
2267 			    vsi_number, status);
2268 			return (B_FALSE);
2269 		}
2270 	}
2271 
2272 	return (B_TRUE);
2273 }
2274 
2275 /*
2276  * Configure the RSS key. For the X710 controller family, this is set on a
2277  * per-PF basis via registers. For the X722, this is done on a per-VSI basis
2278  * through the admin queue.
2279  */
2280 static boolean_t
2281 i40e_config_rss_key(i40e_t *i40e, i40e_hw_t *hw)
2282 {
2283 	if (i40e_is_x722(i40e)) {
2284 		if (!i40e_config_rss_key_x722(i40e, hw))
2285 			return (B_FALSE);
2286 	} else {
2287 		uint32_t seed[I40E_PFQF_HKEY_MAX_INDEX + 1];
2288 
2289 		(void) random_get_pseudo_bytes((uint8_t *)seed, sizeof (seed));
2290 		for (uint_t i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
2291 			i40e_write_rx_ctl(hw, I40E_PFQF_HKEY(i), seed[i]);
2292 	}
2293 
2294 	return (B_TRUE);
2295 }
2296 
2297 /*
2298  * Populate the LUT. The size of each entry in the LUT depends on the controller
2299  * family, with the X722 using a known 7-bit width. On the X710 controller, this
2300  * is programmed through its control registers where as on the X722 this is
2301  * configured through the admin queue. Also of note, the X722 allows the LUT to
2302  * be set on a per-PF or VSI basis. At this time we use the PF setting. If we
2303  * decide to use the per-VSI LUT in the future, then we will need to modify the
2304  * i40e_add_vsi() function to set the RSS LUT bits in the queueing section.
2305  *
2306  * We populate the LUT in a round robin fashion with the rx queue indices from 0
2307  * to i40e_num_trqpairs_per_vsi - 1.
2308  */
2309 static boolean_t
2310 i40e_config_rss_hlut(i40e_t *i40e, i40e_hw_t *hw)
2311 {
2312 	uint32_t *hlut;
2313 	uint8_t lut_mask;
2314 	uint_t i;
2315 	boolean_t ret = B_FALSE;
2316 
2317 	/*
2318 	 * We always configure the PF with a table size of 512 bytes in
2319 	 * i40e_chip_start().
2320 	 */
2321 	hlut = kmem_alloc(I40E_HLUT_TABLE_SIZE, KM_NOSLEEP);
2322 	if (hlut == NULL) {
2323 		i40e_error(i40e, "i40e_config_rss() buffer allocation failed");
2324 		return (B_FALSE);
2325 	}
2326 
2327 	/*
2328 	 * The width of the X722 is apparently defined to be 7 bits, regardless
2329 	 * of the capability.
2330 	 */
2331 	if (i40e_is_x722(i40e)) {
2332 		lut_mask = (1 << 7) - 1;
2333 	} else {
2334 		lut_mask = (1 << hw->func_caps.rss_table_entry_width) - 1;
2335 	}
2336 
2337 	for (i = 0; i < I40E_HLUT_TABLE_SIZE; i++) {
2338 		((uint8_t *)hlut)[i] =
2339 		    (i % i40e->i40e_num_trqpairs_per_vsi) & lut_mask;
2340 	}
2341 
2342 	if (i40e_is_x722(i40e)) {
2343 		enum i40e_status_code status;
2344 
2345 		status = i40e_aq_set_rss_lut(hw, 0, B_TRUE, (uint8_t *)hlut,
2346 		    I40E_HLUT_TABLE_SIZE);
2347 
2348 		if (status != I40E_SUCCESS) {
2349 			i40e_error(i40e, "failed to set RSS LUT %d: %d",
2350 			    status, hw->aq.asq_last_status);
2351 			goto out;
2352 		}
2353 	} else {
2354 		for (i = 0; i < I40E_HLUT_TABLE_SIZE >> 2; i++) {
2355 			I40E_WRITE_REG(hw, I40E_PFQF_HLUT(i), hlut[i]);
2356 		}
2357 	}
2358 	ret = B_TRUE;
2359 out:
2360 	kmem_free(hlut, I40E_HLUT_TABLE_SIZE);
2361 	return (ret);
2362 }
2363 
2364 /*
2365  * Set up RSS.
2366  * 	1. Seed the hash key.
2367  *	2. Enable PCTYPEs for the hash filter.
2368  *	3. Populate the LUT.
2369  */
2370 static boolean_t
2371 i40e_config_rss(i40e_t *i40e, i40e_hw_t *hw)
2372 {
2373 	uint64_t hena;
2374 
2375 	/*
2376 	 * 1. Seed the hash key
2377 	 */
2378 	if (!i40e_config_rss_key(i40e, hw))
2379 		return (B_FALSE);
2380 
2381 	/*
2382 	 * 2. Configure PCTYPES
2383 	 */
2384 	hena = (1ULL << I40E_FILTER_PCTYPE_NONF_IPV4_OTHER) |
2385 	    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV4_TCP) |
2386 	    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV4_SCTP) |
2387 	    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV4_UDP) |
2388 	    (1ULL << I40E_FILTER_PCTYPE_FRAG_IPV4) |
2389 	    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV6_OTHER) |
2390 	    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV6_TCP) |
2391 	    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV6_SCTP) |
2392 	    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV6_UDP) |
2393 	    (1ULL << I40E_FILTER_PCTYPE_FRAG_IPV6) |
2394 	    (1ULL << I40E_FILTER_PCTYPE_L2_PAYLOAD);
2395 
2396 	/*
2397 	 * Add additional types supported by the X722 controller.
2398 	 */
2399 	if (i40e_is_x722(i40e)) {
2400 		hena |= (1ULL << I40E_FILTER_PCTYPE_NONF_UNICAST_IPV4_UDP) |
2401 		    (1ULL << I40E_FILTER_PCTYPE_NONF_MULTICAST_IPV4_UDP) |
2402 		    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV4_TCP_SYN_NO_ACK) |
2403 		    (1ULL << I40E_FILTER_PCTYPE_NONF_UNICAST_IPV6_UDP) |
2404 		    (1ULL << I40E_FILTER_PCTYPE_NONF_MULTICAST_IPV6_UDP) |
2405 		    (1ULL << I40E_FILTER_PCTYPE_NONF_IPV6_TCP_SYN_NO_ACK);
2406 	}
2407 
2408 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (uint32_t)hena);
2409 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (uint32_t)(hena >> 32));
2410 
2411 	/*
2412 	 * 3. Populate LUT
2413 	 */
2414 	return (i40e_config_rss_hlut(i40e, hw));
2415 }
2416 
2417 /*
2418  * Wrapper to kick the chipset on.
2419  */
2420 static boolean_t
2421 i40e_chip_start(i40e_t *i40e)
2422 {
2423 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2424 	struct i40e_filter_control_settings filter;
2425 	int rc;
2426 	uint8_t err;
2427 
2428 	if (((hw->aq.fw_maj_ver == 4) && (hw->aq.fw_min_ver < 33)) ||
2429 	    (hw->aq.fw_maj_ver < 4)) {
2430 		i40e_msec_delay(75);
2431 		if (i40e_aq_set_link_restart_an(hw, TRUE, NULL) !=
2432 		    I40E_SUCCESS) {
2433 			i40e_error(i40e, "failed to restart link: admin queue "
2434 			    "error: %d", hw->aq.asq_last_status);
2435 			return (B_FALSE);
2436 		}
2437 	}
2438 
2439 	/* Determine hardware state */
2440 	i40e_get_hw_state(i40e, hw);
2441 
2442 	/* For now, we always disable Ethernet Flow Control. */
2443 	hw->fc.requested_mode = I40E_FC_NONE;
2444 	rc = i40e_set_fc(hw, &err, B_TRUE);
2445 	if (rc != I40E_SUCCESS) {
2446 		i40e_error(i40e, "Setting flow control failed, returned %d"
2447 		    " with error: 0x%x", rc, err);
2448 		return (B_FALSE);
2449 	}
2450 
2451 	/* Initialize mac addresses. */
2452 	i40e_init_macaddrs(i40e, hw);
2453 
2454 	/*
2455 	 * Set up the filter control. If the hash lut size is changed from
2456 	 * I40E_HASH_LUT_SIZE_512 then I40E_HLUT_TABLE_SIZE and
2457 	 * i40e_config_rss_hlut() will need to be updated.
2458 	 */
2459 	bzero(&filter, sizeof (filter));
2460 	filter.enable_ethtype = TRUE;
2461 	filter.enable_macvlan = TRUE;
2462 	filter.hash_lut_size = I40E_HASH_LUT_SIZE_512;
2463 
2464 	rc = i40e_set_filter_control(hw, &filter);
2465 	if (rc != I40E_SUCCESS) {
2466 		i40e_error(i40e, "i40e_set_filter_control() returned %d", rc);
2467 		return (B_FALSE);
2468 	}
2469 
2470 	i40e_intr_chip_init(i40e);
2471 
2472 	rc = i40e_get_mac_seid(i40e);
2473 	if (rc == -1) {
2474 		i40e_error(i40e, "failed to obtain MAC Uplink SEID");
2475 		return (B_FALSE);
2476 	}
2477 	i40e->i40e_mac_seid = (uint16_t)rc;
2478 
2479 	/*
2480 	 * Create a VEB in order to support multiple VSIs. Each VSI
2481 	 * functions as a MAC group. This call sets the PF's MAC as
2482 	 * the uplink port and the PF's default VSI as the default
2483 	 * downlink port.
2484 	 */
2485 	rc = i40e_aq_add_veb(hw, i40e->i40e_mac_seid, I40E_DEF_VSI_SEID(i40e),
2486 	    0x1, B_TRUE, &i40e->i40e_veb_seid, B_FALSE, NULL);
2487 	if (rc != I40E_SUCCESS) {
2488 		i40e_error(i40e, "i40e_aq_add_veb() failed %d: %d", rc,
2489 		    hw->aq.asq_last_status);
2490 		return (B_FALSE);
2491 	}
2492 
2493 	if (!i40e_config_def_vsi(i40e, hw))
2494 		return (B_FALSE);
2495 
2496 	for (uint_t i = 1; i < i40e->i40e_num_rx_groups; i++) {
2497 		if (!i40e_add_vsi(i40e, hw, i))
2498 			return (B_FALSE);
2499 	}
2500 
2501 	if (!i40e_config_rss(i40e, hw))
2502 		return (B_FALSE);
2503 
2504 	i40e_flush(hw);
2505 
2506 	return (B_TRUE);
2507 }
2508 
2509 /*
2510  * Take care of tearing down the rx ring. See 8.3.3.1.2 for more information.
2511  */
2512 static void
2513 i40e_shutdown_rx_rings(i40e_t *i40e)
2514 {
2515 	int i;
2516 	uint32_t reg;
2517 
2518 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2519 
2520 	/*
2521 	 * Step 1. The interrupt linked list (see i40e_intr.c for more
2522 	 * information) should have already been cleared before calling this
2523 	 * function.
2524 	 */
2525 #ifdef	DEBUG
2526 	if (i40e->i40e_intr_type == DDI_INTR_TYPE_MSIX) {
2527 		for (i = 1; i < i40e->i40e_intr_count; i++) {
2528 			reg = I40E_READ_REG(hw, I40E_PFINT_LNKLSTN(i - 1));
2529 			VERIFY3U(reg, ==, I40E_QUEUE_TYPE_EOL);
2530 		}
2531 	} else {
2532 		reg = I40E_READ_REG(hw, I40E_PFINT_LNKLST0);
2533 		VERIFY3U(reg, ==, I40E_QUEUE_TYPE_EOL);
2534 	}
2535 
2536 #endif	/* DEBUG */
2537 
2538 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
2539 		/*
2540 		 * Step 1. Request the queue by clearing QENA_REQ. It may not be
2541 		 * set due to unwinding from failures and a partially enabled
2542 		 * ring set.
2543 		 */
2544 		reg = I40E_READ_REG(hw, I40E_QRX_ENA(i));
2545 		if (!(reg & I40E_QRX_ENA_QENA_REQ_MASK))
2546 			continue;
2547 		VERIFY((reg & I40E_QRX_ENA_QENA_REQ_MASK) ==
2548 		    I40E_QRX_ENA_QENA_REQ_MASK);
2549 		reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
2550 		I40E_WRITE_REG(hw, I40E_QRX_ENA(i), reg);
2551 	}
2552 
2553 	/*
2554 	 * Step 2. Wait for the disable to take, by having QENA_STAT in the FPM
2555 	 * be cleared. Note that we could still receive data in the queue during
2556 	 * this time. We don't actually wait for this now and instead defer this
2557 	 * to i40e_shutdown_rings_wait(), after we've interleaved disabling the
2558 	 * TX queues as well.
2559 	 */
2560 }
2561 
2562 static void
2563 i40e_shutdown_tx_rings(i40e_t *i40e)
2564 {
2565 	int i;
2566 	uint32_t reg;
2567 
2568 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2569 
2570 	/*
2571 	 * Step 1. The interrupt linked list should already have been cleared.
2572 	 */
2573 #ifdef DEBUG
2574 	if (i40e->i40e_intr_type == DDI_INTR_TYPE_MSIX) {
2575 		for (i = 1; i < i40e->i40e_intr_count; i++) {
2576 			reg = I40E_READ_REG(hw, I40E_PFINT_LNKLSTN(i - 1));
2577 			VERIFY3U(reg, ==, I40E_QUEUE_TYPE_EOL);
2578 		}
2579 	} else {
2580 		reg = I40E_READ_REG(hw, I40E_PFINT_LNKLST0);
2581 		VERIFY3U(reg, ==, I40E_QUEUE_TYPE_EOL);
2582 
2583 	}
2584 #endif	/* DEBUG */
2585 
2586 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
2587 		/*
2588 		 * Step 2. Set the SET_QDIS flag for every queue.
2589 		 */
2590 		i40e_pre_tx_queue_cfg(hw, i, B_FALSE);
2591 	}
2592 
2593 	/*
2594 	 * Step 3. Wait at least 400 usec (can be done once for all queues).
2595 	 */
2596 	drv_usecwait(500);
2597 
2598 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
2599 		/*
2600 		 * Step 4. Clear the QENA_REQ flag which tells hardware to
2601 		 * quiesce. If QENA_REQ is not already set then that means that
2602 		 * we likely already tried to disable this queue.
2603 		 */
2604 		reg = I40E_READ_REG(hw, I40E_QTX_ENA(i));
2605 		if (!(reg & I40E_QTX_ENA_QENA_REQ_MASK))
2606 			continue;
2607 		reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
2608 		I40E_WRITE_REG(hw, I40E_QTX_ENA(i), reg);
2609 	}
2610 
2611 	/*
2612 	 * Step 5. Wait for all drains to finish. This will be done by the
2613 	 * hardware removing the QENA_STAT flag from the queue. Rather than
2614 	 * waiting here, we interleave it with all the others in
2615 	 * i40e_shutdown_rings_wait().
2616 	 */
2617 }
2618 
2619 /*
2620  * Wait for all the rings to be shut down. e.g. Steps 2 and 5 from the above
2621  * functions.
2622  */
2623 static boolean_t
2624 i40e_shutdown_rings_wait(i40e_t *i40e)
2625 {
2626 	int i, try;
2627 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2628 
2629 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
2630 		uint32_t reg;
2631 
2632 		for (try = 0; try < I40E_RING_WAIT_NTRIES; try++) {
2633 			reg = I40E_READ_REG(hw, I40E_QRX_ENA(i));
2634 			if ((reg & I40E_QRX_ENA_QENA_STAT_MASK) == 0)
2635 				break;
2636 			i40e_msec_delay(I40E_RING_WAIT_PAUSE);
2637 		}
2638 
2639 		if ((reg & I40E_QRX_ENA_QENA_STAT_MASK) != 0) {
2640 			i40e_error(i40e, "timed out disabling rx queue %d",
2641 			    i);
2642 			return (B_FALSE);
2643 		}
2644 
2645 		for (try = 0; try < I40E_RING_WAIT_NTRIES; try++) {
2646 			reg = I40E_READ_REG(hw, I40E_QTX_ENA(i));
2647 			if ((reg & I40E_QTX_ENA_QENA_STAT_MASK) == 0)
2648 				break;
2649 			i40e_msec_delay(I40E_RING_WAIT_PAUSE);
2650 		}
2651 
2652 		if ((reg & I40E_QTX_ENA_QENA_STAT_MASK) != 0) {
2653 			i40e_error(i40e, "timed out disabling tx queue %d",
2654 			    i);
2655 			return (B_FALSE);
2656 		}
2657 	}
2658 
2659 	return (B_TRUE);
2660 }
2661 
2662 static boolean_t
2663 i40e_shutdown_rings(i40e_t *i40e)
2664 {
2665 	i40e_shutdown_rx_rings(i40e);
2666 	i40e_shutdown_tx_rings(i40e);
2667 	return (i40e_shutdown_rings_wait(i40e));
2668 }
2669 
2670 static void
2671 i40e_setup_rx_descs(i40e_trqpair_t *itrq)
2672 {
2673 	int i;
2674 	i40e_rx_data_t *rxd = itrq->itrq_rxdata;
2675 
2676 	for (i = 0; i < rxd->rxd_ring_size; i++) {
2677 		i40e_rx_control_block_t *rcb;
2678 		i40e_rx_desc_t *rdesc;
2679 
2680 		rcb = rxd->rxd_work_list[i];
2681 		rdesc = &rxd->rxd_desc_ring[i];
2682 
2683 		rdesc->read.pkt_addr =
2684 		    CPU_TO_LE64((uintptr_t)rcb->rcb_dma.dmab_dma_address);
2685 		rdesc->read.hdr_addr = 0;
2686 	}
2687 }
2688 
2689 static boolean_t
2690 i40e_setup_rx_hmc(i40e_trqpair_t *itrq)
2691 {
2692 	i40e_rx_data_t *rxd = itrq->itrq_rxdata;
2693 	i40e_t *i40e = itrq->itrq_i40e;
2694 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2695 
2696 	struct i40e_hmc_obj_rxq rctx;
2697 	int err;
2698 
2699 	bzero(&rctx, sizeof (struct i40e_hmc_obj_rxq));
2700 	rctx.base = rxd->rxd_desc_area.dmab_dma_address /
2701 	    I40E_HMC_RX_CTX_UNIT;
2702 	rctx.qlen = rxd->rxd_ring_size;
2703 	VERIFY(i40e->i40e_rx_buf_size >= I40E_HMC_RX_DBUFF_MIN);
2704 	VERIFY(i40e->i40e_rx_buf_size <= I40E_HMC_RX_DBUFF_MAX);
2705 	rctx.dbuff = i40e->i40e_rx_buf_size >> I40E_RXQ_CTX_DBUFF_SHIFT;
2706 	rctx.hbuff = 0 >> I40E_RXQ_CTX_HBUFF_SHIFT;
2707 	rctx.dtype = I40E_HMC_RX_DTYPE_NOSPLIT;
2708 	rctx.dsize = I40E_HMC_RX_DSIZE_32BYTE;
2709 	rctx.crcstrip = I40E_HMC_RX_CRCSTRIP_ENABLE;
2710 	rctx.fc_ena = I40E_HMC_RX_FC_DISABLE;
2711 	rctx.l2tsel = I40E_HMC_RX_L2TAGORDER;
2712 	rctx.hsplit_0 = I40E_HMC_RX_HDRSPLIT_DISABLE;
2713 	rctx.hsplit_1 = I40E_HMC_RX_HDRSPLIT_DISABLE;
2714 	rctx.showiv = I40E_HMC_RX_INVLAN_DONTSTRIP;
2715 	rctx.rxmax = i40e->i40e_frame_max;
2716 	rctx.tphrdesc_ena = I40E_HMC_RX_TPH_DISABLE;
2717 	rctx.tphwdesc_ena = I40E_HMC_RX_TPH_DISABLE;
2718 	rctx.tphdata_ena = I40E_HMC_RX_TPH_DISABLE;
2719 	rctx.tphhead_ena = I40E_HMC_RX_TPH_DISABLE;
2720 	rctx.lrxqthresh = I40E_HMC_RX_LOWRXQ_NOINTR;
2721 
2722 	/*
2723 	 * This must be set to 0x1, see Table 8-12 in section 8.3.3.2.2.
2724 	 */
2725 	rctx.prefena = I40E_HMC_RX_PREFENA;
2726 
2727 	err = i40e_clear_lan_rx_queue_context(hw, itrq->itrq_index);
2728 	if (err != I40E_SUCCESS) {
2729 		i40e_error(i40e, "failed to clear rx queue %d context: %d",
2730 		    itrq->itrq_index, err);
2731 		return (B_FALSE);
2732 	}
2733 
2734 	err = i40e_set_lan_rx_queue_context(hw, itrq->itrq_index, &rctx);
2735 	if (err != I40E_SUCCESS) {
2736 		i40e_error(i40e, "failed to set rx queue %d context: %d",
2737 		    itrq->itrq_index, err);
2738 		return (B_FALSE);
2739 	}
2740 
2741 	return (B_TRUE);
2742 }
2743 
2744 /*
2745  * Take care of setting up the descriptor rings and actually programming the
2746  * device. See 8.3.3.1.1 for the full list of steps we need to do to enable the
2747  * rx rings.
2748  */
2749 static boolean_t
2750 i40e_setup_rx_rings(i40e_t *i40e)
2751 {
2752 	int i;
2753 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2754 
2755 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
2756 		i40e_trqpair_t *itrq = &i40e->i40e_trqpairs[i];
2757 		i40e_rx_data_t *rxd = itrq->itrq_rxdata;
2758 		uint32_t reg;
2759 
2760 		/*
2761 		 * Step 1. Program all receive ring descriptors.
2762 		 */
2763 		i40e_setup_rx_descs(itrq);
2764 
2765 		/*
2766 		 * Step 2. Program the queue's FPM/HMC context.
2767 		 */
2768 		if (i40e_setup_rx_hmc(itrq) == B_FALSE)
2769 			return (B_FALSE);
2770 
2771 		/*
2772 		 * Step 3. Clear the queue's tail pointer and set it to the end
2773 		 * of the space.
2774 		 */
2775 		I40E_WRITE_REG(hw, I40E_QRX_TAIL(i), 0);
2776 		I40E_WRITE_REG(hw, I40E_QRX_TAIL(i), rxd->rxd_ring_size - 1);
2777 
2778 		/*
2779 		 * Step 4. Enable the queue via the QENA_REQ.
2780 		 */
2781 		reg = I40E_READ_REG(hw, I40E_QRX_ENA(i));
2782 		VERIFY0(reg & (I40E_QRX_ENA_QENA_REQ_MASK |
2783 		    I40E_QRX_ENA_QENA_STAT_MASK));
2784 		reg |= I40E_QRX_ENA_QENA_REQ_MASK;
2785 		I40E_WRITE_REG(hw, I40E_QRX_ENA(i), reg);
2786 	}
2787 
2788 	/*
2789 	 * Note, we wait for every queue to be enabled before we start checking.
2790 	 * This will hopefully cause most queues to be enabled at this point.
2791 	 */
2792 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
2793 		uint32_t j, reg;
2794 
2795 		/*
2796 		 * Step 5. Verify that QENA_STAT has been set. It's promised
2797 		 * that this should occur within about 10 us, but like other
2798 		 * systems, we give the card a bit more time.
2799 		 */
2800 		for (j = 0; j < I40E_RING_WAIT_NTRIES; j++) {
2801 			reg = I40E_READ_REG(hw, I40E_QRX_ENA(i));
2802 
2803 			if (reg & I40E_QRX_ENA_QENA_STAT_MASK)
2804 				break;
2805 			i40e_msec_delay(I40E_RING_WAIT_PAUSE);
2806 		}
2807 
2808 		if ((reg & I40E_QRX_ENA_QENA_STAT_MASK) == 0) {
2809 			i40e_error(i40e, "failed to enable rx queue %d, timed "
2810 			    "out.", i);
2811 			return (B_FALSE);
2812 		}
2813 	}
2814 
2815 	return (B_TRUE);
2816 }
2817 
2818 static boolean_t
2819 i40e_setup_tx_hmc(i40e_trqpair_t *itrq)
2820 {
2821 	i40e_t *i40e = itrq->itrq_i40e;
2822 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2823 
2824 	struct i40e_hmc_obj_txq tctx;
2825 	struct i40e_vsi_context	context;
2826 	int err;
2827 
2828 	bzero(&tctx, sizeof (struct i40e_hmc_obj_txq));
2829 	tctx.new_context = I40E_HMC_TX_NEW_CONTEXT;
2830 	tctx.base = itrq->itrq_desc_area.dmab_dma_address /
2831 	    I40E_HMC_TX_CTX_UNIT;
2832 	tctx.fc_ena = I40E_HMC_TX_FC_DISABLE;
2833 	tctx.timesync_ena = I40E_HMC_TX_TS_DISABLE;
2834 	tctx.fd_ena = I40E_HMC_TX_FD_DISABLE;
2835 	tctx.alt_vlan_ena = I40E_HMC_TX_ALT_VLAN_DISABLE;
2836 	tctx.head_wb_ena = I40E_HMC_TX_WB_ENABLE;
2837 	tctx.qlen = itrq->itrq_tx_ring_size;
2838 	tctx.tphrdesc_ena = I40E_HMC_TX_TPH_DISABLE;
2839 	tctx.tphrpacket_ena = I40E_HMC_TX_TPH_DISABLE;
2840 	tctx.tphwdesc_ena = I40E_HMC_TX_TPH_DISABLE;
2841 	tctx.head_wb_addr = itrq->itrq_desc_area.dmab_dma_address +
2842 	    sizeof (i40e_tx_desc_t) * itrq->itrq_tx_ring_size;
2843 
2844 	/*
2845 	 * This field isn't actually documented, like crc, but it suggests that
2846 	 * it should be zeroed. We leave both of these here because of that for
2847 	 * now. We should check with Intel on why these are here even.
2848 	 */
2849 	tctx.crc = 0;
2850 	tctx.rdylist_act = 0;
2851 
2852 	/*
2853 	 * We're supposed to assign the rdylist field with the value of the
2854 	 * traffic class index for the first device. We query the VSI parameters
2855 	 * again to get what the handle is. Note that every queue is always
2856 	 * assigned to traffic class zero, because we don't actually use them.
2857 	 */
2858 	bzero(&context, sizeof (struct i40e_vsi_context));
2859 	context.seid = I40E_DEF_VSI_SEID(i40e);
2860 	context.pf_num = hw->pf_id;
2861 	err = i40e_aq_get_vsi_params(hw, &context, NULL);
2862 	if (err != I40E_SUCCESS) {
2863 		i40e_error(i40e, "get VSI params failed with %d", err);
2864 		return (B_FALSE);
2865 	}
2866 	tctx.rdylist = LE_16(context.info.qs_handle[0]);
2867 
2868 	err = i40e_clear_lan_tx_queue_context(hw, itrq->itrq_index);
2869 	if (err != I40E_SUCCESS) {
2870 		i40e_error(i40e, "failed to clear tx queue %d context: %d",
2871 		    itrq->itrq_index, err);
2872 		return (B_FALSE);
2873 	}
2874 
2875 	err = i40e_set_lan_tx_queue_context(hw, itrq->itrq_index, &tctx);
2876 	if (err != I40E_SUCCESS) {
2877 		i40e_error(i40e, "failed to set tx queue %d context: %d",
2878 		    itrq->itrq_index, err);
2879 		return (B_FALSE);
2880 	}
2881 
2882 	return (B_TRUE);
2883 }
2884 
2885 /*
2886  * Take care of setting up the descriptor rings and actually programming the
2887  * device. See 8.4.3.1.1 for what we need to do here.
2888  */
2889 static boolean_t
2890 i40e_setup_tx_rings(i40e_t *i40e)
2891 {
2892 	int i;
2893 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2894 
2895 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
2896 		i40e_trqpair_t *itrq = &i40e->i40e_trqpairs[i];
2897 		uint32_t reg;
2898 
2899 		/*
2900 		 * Step 1. Clear the queue disable flag and verify that the
2901 		 * index is set correctly.
2902 		 */
2903 		i40e_pre_tx_queue_cfg(hw, i, B_TRUE);
2904 
2905 		/*
2906 		 * Step 2. Prepare the queue's FPM/HMC context.
2907 		 */
2908 		if (i40e_setup_tx_hmc(itrq) == B_FALSE)
2909 			return (B_FALSE);
2910 
2911 		/*
2912 		 * Step 3. Verify that it's clear that this PF owns this queue.
2913 		 */
2914 		reg = I40E_QTX_CTL_PF_QUEUE;
2915 		reg |= (hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
2916 		    I40E_QTX_CTL_PF_INDX_MASK;
2917 		I40E_WRITE_REG(hw, I40E_QTX_CTL(itrq->itrq_index), reg);
2918 		i40e_flush(hw);
2919 
2920 		/*
2921 		 * Step 4. Set the QENA_REQ flag.
2922 		 */
2923 		reg = I40E_READ_REG(hw, I40E_QTX_ENA(i));
2924 		VERIFY0(reg & (I40E_QTX_ENA_QENA_REQ_MASK |
2925 		    I40E_QTX_ENA_QENA_STAT_MASK));
2926 		reg |= I40E_QTX_ENA_QENA_REQ_MASK;
2927 		I40E_WRITE_REG(hw, I40E_QTX_ENA(i), reg);
2928 	}
2929 
2930 	/*
2931 	 * Note, we wait for every queue to be enabled before we start checking.
2932 	 * This will hopefully cause most queues to be enabled at this point.
2933 	 */
2934 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
2935 		uint32_t j, reg;
2936 
2937 		/*
2938 		 * Step 5. Verify that QENA_STAT has been set. It's promised
2939 		 * that this should occur within about 10 us, but like BSD,
2940 		 * we'll try for up to 100 ms for this queue.
2941 		 */
2942 		for (j = 0; j < I40E_RING_WAIT_NTRIES; j++) {
2943 			reg = I40E_READ_REG(hw, I40E_QTX_ENA(i));
2944 
2945 			if (reg & I40E_QTX_ENA_QENA_STAT_MASK)
2946 				break;
2947 			i40e_msec_delay(I40E_RING_WAIT_PAUSE);
2948 		}
2949 
2950 		if ((reg & I40E_QTX_ENA_QENA_STAT_MASK) == 0) {
2951 			i40e_error(i40e, "failed to enable tx queue %d, timed "
2952 			    "out", i);
2953 			return (B_FALSE);
2954 		}
2955 	}
2956 
2957 	return (B_TRUE);
2958 }
2959 
2960 void
2961 i40e_stop(i40e_t *i40e, boolean_t free_allocations)
2962 {
2963 	uint_t i;
2964 	i40e_hw_t *hw = &i40e->i40e_hw_space;
2965 
2966 	ASSERT(MUTEX_HELD(&i40e->i40e_general_lock));
2967 
2968 	/*
2969 	 * Shutdown and drain the tx and rx pipeline. We do this using the
2970 	 * following steps.
2971 	 *
2972 	 * 1) Shutdown interrupts to all the queues (trying to keep the admin
2973 	 *    queue alive).
2974 	 *
2975 	 * 2) Remove all of the interrupt tx and rx causes by setting the
2976 	 *    interrupt linked lists to zero.
2977 	 *
2978 	 * 2) Shutdown the tx and rx rings. Because i40e_shutdown_rings() should
2979 	 *    wait for all the queues to be disabled, once we reach that point
2980 	 *    it should be safe to free associated data.
2981 	 *
2982 	 * 4) Wait 50ms after all that is done. This ensures that the rings are
2983 	 *    ready for programming again and we don't have to think about this
2984 	 *    in other parts of the driver.
2985 	 *
2986 	 * 5) Disable remaining chip interrupts, (admin queue, etc.)
2987 	 *
2988 	 * 6) Verify that FM is happy with all the register accesses we
2989 	 *    performed.
2990 	 */
2991 	i40e_intr_io_disable_all(i40e);
2992 	i40e_intr_io_clear_cause(i40e);
2993 
2994 	if (i40e_shutdown_rings(i40e) == B_FALSE) {
2995 		ddi_fm_service_impact(i40e->i40e_dip, DDI_SERVICE_LOST);
2996 	}
2997 
2998 	delay(50 * drv_usectohz(1000));
2999 
3000 	/*
3001 	 * We don't delete the default VSI because it replaces the VEB
3002 	 * after VEB deletion (see the "Delete Element" section).
3003 	 * Furthermore, since the default VSI is provided by the
3004 	 * firmware, we never attempt to delete it.
3005 	 */
3006 	for (i = 1; i < i40e->i40e_num_rx_groups; i++) {
3007 		i40e_delete_vsi(i40e, i);
3008 	}
3009 
3010 	if (i40e->i40e_veb_seid != 0) {
3011 		int rc = i40e_aq_delete_element(hw, i40e->i40e_veb_seid, NULL);
3012 
3013 		if (rc != I40E_SUCCESS) {
3014 			i40e_error(i40e, "Failed to delete VEB %d: %d", rc,
3015 			    hw->aq.asq_last_status);
3016 		}
3017 
3018 		i40e->i40e_veb_seid = 0;
3019 	}
3020 
3021 	i40e_intr_chip_fini(i40e);
3022 
3023 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
3024 		mutex_enter(&i40e->i40e_trqpairs[i].itrq_rx_lock);
3025 		mutex_enter(&i40e->i40e_trqpairs[i].itrq_tx_lock);
3026 	}
3027 
3028 	/*
3029 	 * We should consider refactoring this to be part of the ring start /
3030 	 * stop routines at some point.
3031 	 */
3032 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
3033 		i40e_stats_trqpair_fini(&i40e->i40e_trqpairs[i]);
3034 	}
3035 
3036 	if (i40e_check_acc_handle(i40e->i40e_osdep_space.ios_cfg_handle) !=
3037 	    DDI_FM_OK) {
3038 		ddi_fm_service_impact(i40e->i40e_dip, DDI_SERVICE_LOST);
3039 	}
3040 
3041 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
3042 		i40e_tx_cleanup_ring(&i40e->i40e_trqpairs[i]);
3043 	}
3044 
3045 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
3046 		mutex_exit(&i40e->i40e_trqpairs[i].itrq_rx_lock);
3047 		mutex_exit(&i40e->i40e_trqpairs[i].itrq_tx_lock);
3048 	}
3049 
3050 	for (i = 0; i < i40e->i40e_num_rx_groups; i++) {
3051 		i40e_stat_vsi_fini(i40e, i);
3052 	}
3053 
3054 	i40e->i40e_link_speed = 0;
3055 	i40e->i40e_link_duplex = 0;
3056 	i40e_link_state_set(i40e, LINK_STATE_UNKNOWN);
3057 
3058 	if (free_allocations) {
3059 		i40e_free_ring_mem(i40e, B_FALSE);
3060 	}
3061 }
3062 
3063 boolean_t
3064 i40e_start(i40e_t *i40e, boolean_t alloc)
3065 {
3066 	i40e_hw_t *hw = &i40e->i40e_hw_space;
3067 	boolean_t rc = B_TRUE;
3068 	int i, err;
3069 
3070 	ASSERT(MUTEX_HELD(&i40e->i40e_general_lock));
3071 
3072 	if (alloc) {
3073 		if (i40e_alloc_ring_mem(i40e) == B_FALSE) {
3074 			i40e_error(i40e,
3075 			    "Failed to allocate ring memory");
3076 			return (B_FALSE);
3077 		}
3078 	}
3079 
3080 	/*
3081 	 * This should get refactored to be part of ring start and stop at
3082 	 * some point, along with most of the logic here.
3083 	 */
3084 	for (i = 0; i < i40e->i40e_num_trqpairs; i++) {
3085 		if (i40e_stats_trqpair_init(&i40e->i40e_trqpairs[i]) ==
3086 		    B_FALSE) {
3087 			int j;
3088 
3089 			for (j = 0; j < i; j++) {
3090 				i40e_trqpair_t *itrq = &i40e->i40e_trqpairs[j];
3091 				i40e_stats_trqpair_fini(itrq);
3092 			}
3093 			return (B_FALSE);
3094 		}
3095 	}
3096 
3097 	if (!i40e_chip_start(i40e)) {
3098 		i40e_fm_ereport(i40e, DDI_FM_DEVICE_INVAL_STATE);
3099 		rc = B_FALSE;
3100 		goto done;
3101 	}
3102 
3103 	if (i40e_setup_rx_rings(i40e) == B_FALSE) {
3104 		rc = B_FALSE;
3105 		goto done;
3106 	}
3107 
3108 	if (i40e_setup_tx_rings(i40e) == B_FALSE) {
3109 		rc = B_FALSE;
3110 		goto done;
3111 	}
3112 
3113 	/*
3114 	 * Enable broadcast traffic; however, do not enable multicast traffic.
3115 	 * That's handle exclusively through MAC's mc_multicst routines.
3116 	 */
3117 	err = i40e_aq_set_vsi_broadcast(hw, I40E_DEF_VSI_SEID(i40e), B_TRUE,
3118 	    NULL);
3119 	if (err != I40E_SUCCESS) {
3120 		i40e_error(i40e, "failed to set default VSI: %d", err);
3121 		rc = B_FALSE;
3122 		goto done;
3123 	}
3124 
3125 	err = i40e_aq_set_mac_config(hw, i40e->i40e_frame_max, B_TRUE, 0, NULL);
3126 	if (err != I40E_SUCCESS) {
3127 		i40e_error(i40e, "failed to set MAC config: %d", err);
3128 		rc = B_FALSE;
3129 		goto done;
3130 	}
3131 
3132 	/*
3133 	 * Finally, make sure that we're happy from an FM perspective.
3134 	 */
3135 	if (i40e_check_acc_handle(i40e->i40e_osdep_space.ios_reg_handle) !=
3136 	    DDI_FM_OK) {
3137 		rc = B_FALSE;
3138 		goto done;
3139 	}
3140 
3141 	/* Clear state bits prior to final interrupt enabling. */
3142 	atomic_and_32(&i40e->i40e_state,
3143 	    ~(I40E_ERROR | I40E_STALL | I40E_OVERTEMP));
3144 
3145 	i40e_intr_io_enable_all(i40e);
3146 
3147 done:
3148 	if (rc == B_FALSE) {
3149 		i40e_stop(i40e, B_FALSE);
3150 		if (alloc == B_TRUE) {
3151 			i40e_free_ring_mem(i40e, B_TRUE);
3152 		}
3153 		ddi_fm_service_impact(i40e->i40e_dip, DDI_SERVICE_LOST);
3154 	}
3155 
3156 	return (rc);
3157 }
3158 
3159 /*
3160  * We may have loaned up descriptors to the stack. As such, if we still have
3161  * them outstanding, then we will not continue with detach.
3162  */
3163 static boolean_t
3164 i40e_drain_rx(i40e_t *i40e)
3165 {
3166 	mutex_enter(&i40e->i40e_rx_pending_lock);
3167 	while (i40e->i40e_rx_pending > 0) {
3168 		if (cv_reltimedwait(&i40e->i40e_rx_pending_cv,
3169 		    &i40e->i40e_rx_pending_lock,
3170 		    drv_usectohz(I40E_DRAIN_RX_WAIT), TR_CLOCK_TICK) == -1) {
3171 			mutex_exit(&i40e->i40e_rx_pending_lock);
3172 			return (B_FALSE);
3173 		}
3174 	}
3175 	mutex_exit(&i40e->i40e_rx_pending_lock);
3176 
3177 	return (B_TRUE);
3178 }
3179 
3180 static int
3181 i40e_attach(dev_info_t *devinfo, ddi_attach_cmd_t cmd)
3182 {
3183 	i40e_t *i40e;
3184 	struct i40e_osdep *osdep;
3185 	i40e_hw_t *hw;
3186 	int instance;
3187 
3188 	if (cmd != DDI_ATTACH)
3189 		return (DDI_FAILURE);
3190 
3191 	instance = ddi_get_instance(devinfo);
3192 	i40e = kmem_zalloc(sizeof (i40e_t), KM_SLEEP);
3193 
3194 	i40e->i40e_aqbuf = kmem_zalloc(I40E_ADMINQ_BUFSZ, KM_SLEEP);
3195 	i40e->i40e_instance = instance;
3196 	i40e->i40e_dip = devinfo;
3197 
3198 	hw = &i40e->i40e_hw_space;
3199 	osdep = &i40e->i40e_osdep_space;
3200 	hw->back = osdep;
3201 	osdep->ios_i40e = i40e;
3202 
3203 	ddi_set_driver_private(devinfo, i40e);
3204 
3205 	i40e_fm_init(i40e);
3206 	i40e->i40e_attach_progress |= I40E_ATTACH_FM_INIT;
3207 
3208 	if (pci_config_setup(devinfo, &osdep->ios_cfg_handle) != DDI_SUCCESS) {
3209 		i40e_error(i40e, "Failed to map PCI configurations.");
3210 		goto attach_fail;
3211 	}
3212 	i40e->i40e_attach_progress |= I40E_ATTACH_PCI_CONFIG;
3213 
3214 	i40e_identify_hardware(i40e);
3215 
3216 	if (!i40e_regs_map(i40e)) {
3217 		i40e_error(i40e, "Failed to map device registers.");
3218 		goto attach_fail;
3219 	}
3220 	i40e->i40e_attach_progress |= I40E_ATTACH_REGS_MAP;
3221 
3222 	i40e_init_properties(i40e);
3223 	i40e->i40e_attach_progress |= I40E_ATTACH_PROPS;
3224 
3225 	if (!i40e_common_code_init(i40e, hw))
3226 		goto attach_fail;
3227 	i40e->i40e_attach_progress |= I40E_ATTACH_COMMON_CODE;
3228 
3229 	/*
3230 	 * When we participate in IRM, we should make sure that we register
3231 	 * ourselves with it before callbacks.
3232 	 */
3233 	if (!i40e_alloc_intrs(i40e, devinfo)) {
3234 		i40e_error(i40e, "Failed to allocate interrupts.");
3235 		goto attach_fail;
3236 	}
3237 	i40e->i40e_attach_progress |= I40E_ATTACH_ALLOC_INTR;
3238 
3239 	if (!i40e_alloc_trqpairs(i40e)) {
3240 		i40e_error(i40e,
3241 		    "Failed to allocate receive & transmit rings.");
3242 		goto attach_fail;
3243 	}
3244 	i40e->i40e_attach_progress |= I40E_ATTACH_ALLOC_RINGSLOCKS;
3245 
3246 	if (!i40e_map_intrs_to_vectors(i40e)) {
3247 		i40e_error(i40e, "Failed to map interrupts to vectors.");
3248 		goto attach_fail;
3249 	}
3250 
3251 	if (!i40e_add_intr_handlers(i40e)) {
3252 		i40e_error(i40e, "Failed to add the interrupt handlers.");
3253 		goto attach_fail;
3254 	}
3255 	i40e->i40e_attach_progress |= I40E_ATTACH_ADD_INTR;
3256 
3257 	if (!i40e_final_init(i40e)) {
3258 		i40e_error(i40e, "Final initialization failed.");
3259 		goto attach_fail;
3260 	}
3261 	i40e->i40e_attach_progress |= I40E_ATTACH_INIT;
3262 
3263 	if (i40e_check_acc_handle(i40e->i40e_osdep_space.ios_cfg_handle) !=
3264 	    DDI_FM_OK) {
3265 		ddi_fm_service_impact(i40e->i40e_dip, DDI_SERVICE_LOST);
3266 		goto attach_fail;
3267 	}
3268 
3269 	if (!i40e_stats_init(i40e)) {
3270 		i40e_error(i40e, "Stats initialization failed.");
3271 		goto attach_fail;
3272 	}
3273 	i40e->i40e_attach_progress |= I40E_ATTACH_STATS;
3274 
3275 	if (!i40e_register_mac(i40e)) {
3276 		i40e_error(i40e, "Failed to register to MAC/GLDv3");
3277 		goto attach_fail;
3278 	}
3279 	i40e->i40e_attach_progress |= I40E_ATTACH_MAC;
3280 
3281 	i40e->i40e_periodic_id = ddi_periodic_add(i40e_timer, i40e,
3282 	    I40E_CYCLIC_PERIOD, DDI_IPL_0);
3283 	if (i40e->i40e_periodic_id == 0) {
3284 		i40e_error(i40e, "Failed to add the link-check timer");
3285 		goto attach_fail;
3286 	}
3287 	i40e->i40e_attach_progress |= I40E_ATTACH_LINK_TIMER;
3288 
3289 	if (!i40e_enable_interrupts(i40e)) {
3290 		i40e_error(i40e, "Failed to enable DDI interrupts");
3291 		goto attach_fail;
3292 	}
3293 	i40e->i40e_attach_progress |= I40E_ATTACH_ENABLE_INTR;
3294 
3295 	atomic_or_32(&i40e->i40e_state, I40E_INITIALIZED);
3296 
3297 	mutex_enter(&i40e_glock);
3298 	list_insert_tail(&i40e_glist, i40e);
3299 	mutex_exit(&i40e_glock);
3300 
3301 	return (DDI_SUCCESS);
3302 
3303 attach_fail:
3304 	i40e_unconfigure(devinfo, i40e);
3305 	return (DDI_FAILURE);
3306 }
3307 
3308 static int
3309 i40e_detach(dev_info_t *devinfo, ddi_detach_cmd_t cmd)
3310 {
3311 	i40e_t *i40e;
3312 
3313 	if (cmd != DDI_DETACH)
3314 		return (DDI_FAILURE);
3315 
3316 	i40e = (i40e_t *)ddi_get_driver_private(devinfo);
3317 	if (i40e == NULL) {
3318 		i40e_log(NULL, "i40e_detach() called with no i40e pointer!");
3319 		return (DDI_FAILURE);
3320 	}
3321 
3322 	if (i40e_drain_rx(i40e) == B_FALSE) {
3323 		i40e_log(i40e, "timed out draining DMA resources, %d buffers "
3324 		    "remain", i40e->i40e_rx_pending);
3325 		return (DDI_FAILURE);
3326 	}
3327 
3328 	mutex_enter(&i40e_glock);
3329 	list_remove(&i40e_glist, i40e);
3330 	mutex_exit(&i40e_glock);
3331 
3332 	i40e_unconfigure(devinfo, i40e);
3333 
3334 	return (DDI_SUCCESS);
3335 }
3336 
3337 static struct cb_ops i40e_cb_ops = {
3338 	nulldev,		/* cb_open */
3339 	nulldev,		/* cb_close */
3340 	nodev,			/* cb_strategy */
3341 	nodev,			/* cb_print */
3342 	nodev,			/* cb_dump */
3343 	nodev,			/* cb_read */
3344 	nodev,			/* cb_write */
3345 	nodev,			/* cb_ioctl */
3346 	nodev,			/* cb_devmap */
3347 	nodev,			/* cb_mmap */
3348 	nodev,			/* cb_segmap */
3349 	nochpoll,		/* cb_chpoll */
3350 	ddi_prop_op,		/* cb_prop_op */
3351 	NULL,			/* cb_stream */
3352 	D_MP | D_HOTPLUG,	/* cb_flag */
3353 	CB_REV,			/* cb_rev */
3354 	nodev,			/* cb_aread */
3355 	nodev			/* cb_awrite */
3356 };
3357 
3358 static struct dev_ops i40e_dev_ops = {
3359 	DEVO_REV,		/* devo_rev */
3360 	0,			/* devo_refcnt */
3361 	NULL,			/* devo_getinfo */
3362 	nulldev,		/* devo_identify */
3363 	nulldev,		/* devo_probe */
3364 	i40e_attach,		/* devo_attach */
3365 	i40e_detach,		/* devo_detach */
3366 	nodev,			/* devo_reset */
3367 	&i40e_cb_ops,		/* devo_cb_ops */
3368 	NULL,			/* devo_bus_ops */
3369 	ddi_power,		/* devo_power */
3370 	ddi_quiesce_not_supported /* devo_quiesce */
3371 };
3372 
3373 static struct modldrv i40e_modldrv = {
3374 	&mod_driverops,
3375 	i40e_ident,
3376 	&i40e_dev_ops
3377 };
3378 
3379 static struct modlinkage i40e_modlinkage = {
3380 	MODREV_1,
3381 	&i40e_modldrv,
3382 	NULL
3383 };
3384 
3385 /*
3386  * Module Initialization Functions.
3387  */
3388 int
3389 _init(void)
3390 {
3391 	int status;
3392 
3393 	list_create(&i40e_glist, sizeof (i40e_t), offsetof(i40e_t, i40e_glink));
3394 	list_create(&i40e_dlist, sizeof (i40e_device_t),
3395 	    offsetof(i40e_device_t, id_link));
3396 	mutex_init(&i40e_glock, NULL, MUTEX_DRIVER, NULL);
3397 	mac_init_ops(&i40e_dev_ops, I40E_MODULE_NAME);
3398 
3399 	status = mod_install(&i40e_modlinkage);
3400 	if (status != DDI_SUCCESS) {
3401 		mac_fini_ops(&i40e_dev_ops);
3402 		mutex_destroy(&i40e_glock);
3403 		list_destroy(&i40e_dlist);
3404 		list_destroy(&i40e_glist);
3405 	}
3406 
3407 	return (status);
3408 }
3409 
3410 int
3411 _info(struct modinfo *modinfop)
3412 {
3413 	return (mod_info(&i40e_modlinkage, modinfop));
3414 }
3415 
3416 int
3417 _fini(void)
3418 {
3419 	int status;
3420 
3421 	status = mod_remove(&i40e_modlinkage);
3422 	if (status == DDI_SUCCESS) {
3423 		mac_fini_ops(&i40e_dev_ops);
3424 		mutex_destroy(&i40e_glock);
3425 		list_destroy(&i40e_dlist);
3426 		list_destroy(&i40e_glist);
3427 	}
3428 
3429 	return (status);
3430 }
3431