xref: /illumos-gate/usr/src/uts/common/io/cxgbe/t4nex/t4_nexus.c (revision 31f89476218163eaf6cee254a52c8d4935354693)
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  * This file is part of the Chelsio T4 support code.
14  *
15  * Copyright (C) 2010-2013 Chelsio Communications.  All rights reserved.
16  *
17  * This program is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the LICENSE file included in this
20  * release for licensing terms and conditions.
21  */
22 
23 /*
24  * Copyright 2025 Oxide Computer Company
25  */
26 
27 #include <sys/ddi.h>
28 #include <sys/sunddi.h>
29 #include <sys/sunndi.h>
30 #include <sys/modctl.h>
31 #include <sys/conf.h>
32 #include <sys/devops.h>
33 #include <sys/pci.h>
34 #include <sys/atomic.h>
35 #include <sys/types.h>
36 #include <sys/file.h>
37 #include <sys/errno.h>
38 #include <sys/open.h>
39 #include <sys/cred.h>
40 #include <sys/stat.h>
41 #include <sys/mkdev.h>
42 #include <sys/containerof.h>
43 #include <sys/sensors.h>
44 #include <sys/firmload.h>
45 #include <sys/mac_provider.h>
46 #include <sys/mac_ether.h>
47 #include <sys/vlan.h>
48 #include <sys/cpuvar.h>
49 
50 #include "common/common.h"
51 #include "common/t4_msg.h"
52 #include "common/t4_regs.h"
53 #include "common/t4_extra_regs.h"
54 
55 /*
56  * Nexus driver for Chelsio Terminator Network Adapters (T4/T5/T6)
57  *
58  * This driver supports the Chelsio Terminator series of network adapters
59  * starting with the T4 generation and onward. These adapters present a "unified
60  * wire" for managing traditional L2 Ethernet traffic alongside a variety of
61  * stateful offloads including the usual TCP/UDP protocols along with storage
62  * technology like iSCSI, FCoE, NVMe over fabrics, and others. All of these
63  * features coexist on a single ASIC controlled by a single firmware image, thus
64  * the "unified wire". While these adapters provide many offload technologies,
65  * this driver remains focused on providing L2 Ethernet services as presented by
66  * the GLDv3/mac framework. In short, this consists of presenting the device as
67  * groups of rings with filtering and steering capabilities along with stateless
68  * offloads including checksums and LSO. This nexus driver does not preclude the
69  * support of the stateful offload features, but supporting them requires
70  * additional work both inside this driver along with general operating system
71  * enhancements.
72  *
73  * Naming & Terminology
74  * --------------------
75  *
76  * CPL:
77  *
78  *     Chelsio Protocol Language messages. We use these to wrap network data for
79  *     Tx and Rx, this wrapping of packets in CPL is referred to by Chelsio as
80  *     "tunneled" data. Not be to confused with the more general network
81  *     tunneling also known as encapsulation (e.g. IP tunnling, VXLAN, etc).
82  *
83  * Flit:
84  *
85  *     A 64-bit (8 byte) quantity. The Chelsio documentation and code divides
86  *     communication structures into units of flits. For example, a firmware
87  *     command may consist of up to 8 flits (8-bytes x 8 = 64 bytes) where the
88  *     command header is always made up of the first two flits and the remaining
89  *     6 may be used for variable payload data.
90  *
91  * Module/Block:
92  *
93  *     The T4 is comprised of various modules (also referred to as a "block" or
94  *     "engine" in some contexts) which work together to provide the services
95  *     offered by the chip. For example, the Scatter-Gather Engine (SGE) module
96  *     provides the DMA communications used to send and receive traffic.
97  *
98  * T4:
99  *
100  *     The short name to represent any Chelsio Terminator ASIC from the T4 and
101  *     onward. This includes the T4, T5, and T6 line of parts.
102  *
103  * Tunneled Traffic:
104  *
105  *     The Chelsio documentation often refers to sending or receiving "tunneled"
106  *     traffic, but it's not referring to the traditional networking terminology
107  *     of encapsulated data. Rather, it is referring to traffic that is
108  *     sent/received in a non-offload capacity. It's called "tunneled" because
109  *     the data is wrapped/"tunneled" in Work Requests and CPL messages. This
110  *     driver deals purely in tunneled traffic as it make no use of stateful
111  *     offloads.
112  *
113  * ULPTX
114  *
115  *    The Upper Layer Processing Transmit module handle DMA access related to
116  *    egress traffic.
117  *
118  * Work Request (WR)
119  *
120  *    Work Requests are commands and data descriptors use to send Tx packets.
121  *
122  * Communication
123  * -------------
124  *
125  * Before any requests can be made or any data can be transmitted we must first
126  * establish communication with the device. The Chelsio Terminator ASIC, or T4
127  * for short, presents four primary methods of communication between the driver
128  * and itself.
129  *
130  * 1. Registers: read/write simple values or bitwise data over PIO
131  *
132  * 2. Mailboxes: synchronized request/reply structured data over PIO
133  *
134  * 3. Queues: DMA memory of structured data for control and data plane
135  *
136  * 4. Interrupts: MSI/MSI-X interrupts for indicating queue status updates or
137  *    asynchronous events from the firmware
138  *
139  * The first access we have is to the registers via our BAR0 mapping. These
140  * registers provide control and configuration over many aspects of the
141  * different modules that make up the T4.
142  *
143  * Using the registers we then establish a mailbox which provides structured
144  * communication in the form of request/reply commands to the firmware. Both of
145  * these methods use Programmed I/O which is fine for administrative control,
146  * but inadequate for the latency and throughput demands of the datapath and its
147  * associated control plane.
148  *
149  * For the datapath we use the registers and mailbox to establish queues of DMA
150  * memory for transmitting and receiving data. Queues deal in Work Requests
151  * (WR), Chelsio Protocol Language messages (CPL), and Freelist buffer pointers
152  * (FL). These data structures may subsequently point to other DMA memory
153  * (buffers) that hold the data to be transmitted or received along with its
154  * associated software descriptors.
155  *
156  * Finally, the T4 provides various types of interrupt control to asynchronously
157  * signal the driver of conditions such as errors, firmware events, and datapath
158  * (queue) synchronization via status updates (cidx/pidx).
159  *
160  * While nothing precludes the driver from consuming directly these forms of
161  * communication, most of the interface with the T4 is currently provided by the
162  * "common code" interfaces. This common code is, nominally, code shared between
163  * the various operating systems for interacting with the T4.
164  *
165  * Queues (Rings)
166  * --------------
167  *
168  * Queues are circular buffers of DMA memory used to share structured data often
169  * referred to as a "descriptor". These circular buffers are also commonly
170  * called rings. Where each entry in the ring is a descriptor used for locating
171  * and describing data that is meant to be transmitted across or received from
172  * the network device.
173  *
174  * The T4 queues are used in this manner, to share descriptors between the
175  * driver and device, but their level of synchronization is not technically a
176  * descriptor. Rather, a queue is made up of a number of "host credits". The
177  * size of a host credit (sometimes also called an "entry" or "descriptor" in
178  * the code) depends on the type of queue and how it is configured. This
179  * difference in terminology between "host credit" vs. "descriptor" is mostly
180  * pertinent to Egress Queues, which always have 64-byte (8-flit) host credits.
181  * Those host credits are used to pass variable-sized Work Requests (WR), the
182  * structure which actually acts as the "descriptor", which may be smaller or
183  * larger than a single credit. Ingress Queues (IQ) also have variable-sized
184  * entries, but the size is determined at queue creation time and is uniform for
185  * each entry; therefore IQ entries can be called credits, entries, or
186  * descriptors without any real confusion. The official Chelsio documentation
187  * also uses mixed terminology, so it's important to keep that in mind. However,
188  * regardless of how many credits a descriptor requires, communication always
189  * occurs in units of whole credits. A good way to frame this is that queues
190  * provide logical rings of descriptors (WRs, CPLs, FLs) on top of physical
191  * units of host credits.
192  *
193  * There are different types of queues for different purposes, but they are all
194  * variations of either an Ingress Queue (IQ) or Egress Queue (EQ). As the names
195  * suggest, a queue is a unidirectional communication channel: one is the
196  * producer and the other side is a consumer. The Ingress Queue provides
197  * communication from T4 (producer) to driver (consumer), and the Egress Queue
198  * provides communication from the driver (producer) to the T4 (consumer).
199  *
200  * The producer/consumer synchronize communication in units of host credits. The
201  * producer tracks its next host credit to write under the producer index
202  * (pidx), and the consumer tracks its next host credit to read under the
203  * consumer index (cidx). These values are kept in sync through means such as
204  * doorbells (DB), Go-To-Sleep updates (GTS), and interrupts carrying CPL
205  * message (e.g. CPL_SGE_EGR_UPDATE).
206  *
207  * If you read the Terminator Programmer's Guide you will find dicussion about
208  * the queue's "context". This is described as an area of memory that dictates
209  * various features and behavior of the queue. While this queue context may at
210  * one point have been programmed directly, it no longer is. Rather, the various
211  * aspects of queue behavior are controlled by parameters passed during the
212  * queue creation firmware commands, along with other mechanisms such as
213  * registers.
214  *
215  * Each type of queue also has a "status page" which may optionally be updated
216  * with cidx or pidx updates. For EQs this page consumes 1 or 2 credits at the
217  * end of the queue. For IQs it consumes 1 entry at the end of the queue.
218  *
219  * We use EQs to create Tx rings and IQs (plus FLs) to create Rx rings. We
220  * create the same number of Tx and Rx queues. So if we have 32 Tx queues, we
221  * will also have 32 Rx queues. The number of queues created is based on the
222  * port speed. The association from speed to queue count can be found in the
223  * t4_queue_counts array.
224  *
225  * Egress Queues (EQ)
226  * ------------------
227  *
228  * Egress Queues (EQ) provide communication from driver to T4. The driver writes
229  * (produces) descriptors to the queue using one or more host credits. It
230  * notifies the T4 of these new outstanding host credits by updating its pidx
231  * via a doorbell. As new outstanding credits arrive via the doorbell the T4
232  * reads (consumes) them to determine what types of descriptors have been sent
233  * along with their content. As the T4 consumes host credits it notifies the
234  * driver with a programmable combination of status page updates, CPL messages,
235  * and interrupts.
236  *
237  * All EQs use a host credit size of 8 flits (64 bytes). The driver uses these
238  * host credits to send Work Requests (WR) to the T4.
239  *
240  * A WR is variable in size and may be smaller or larger than a single host
241  * credit, but communication is always in whole units of credits. It is legal
242  * for a WR to span across the end of the queue and warp around, but the
243  * contents of the WR may dictate that the wrap-around happens only at certain
244  * offsets within the descriptor. A WR may be 16 to 512 bytes long, but must
245  * always begin at the start of a host credit, thus all WRs must start at a
246  * 64-byte aligned address.
247  *
248  * At this time the only WRs we use are FW_ETH_TX_PKT_WR and FW_ETH_TX_PKTS_WR.
249  *
250  * Ingress Queues (IQ)
251  * -------------------
252  *
253  * Ingress Queues (IQ) provide communication from T4 to driver. The T4 produces
254  * queue entries for the dirver to consume. Unlike EQs, data passed in IQs is
255  * always done as fixed-size entries. That is, each entry in the IQ takes up
256  * exactly one credit, and that credit size is determined at creation time. So
257  * in that sense you could think of a IQ entry as a descriptor. However, these
258  * entries contain different types of data of variable lengths (within in the
259  * bounds of the entry/credit size). There are four possible entry sizes, and
260  * the entry size dictates the possible messages an IQ can hold. The possibles
261  * sizes are 2 flits (16 bytes), 4 flits (32 bytes), 8 flits (64 bytes), and 16
262  * flits (128 bytes). Depending on the size, each entry may a contain Freelist
263  * buffer completion, CPL message, or a forwarded interrupt destined for another
264  * IQ. Which size to use depends on the use case of the IQ.
265  *
266  * Currently we make use of the 64-byte entry size exclusively.
267  *
268  * Freelists (FL)
269  * --------------
270  *
271  * A freelist (FL) is a type of EQ used for providing (producing) buffers for
272  * the purpose of holding received network data for an associated IQ. The driver
273  * produces pointers to DMA data buffers and the associated IQ consumes them as
274  * data is received by the device. A freelist is always associated with an IQ; a
275  * freelist is never used on its own. An IQ, however, may have no FL associated
276  * with it; such is the case for event IQs and interrupt forwarding IQs. An Rx
277  * IQ must have one or two FLs associated with it used to store the incoming
278  * packet headers and payload. The use of two FLs is for when "header splitting"
279  * is enabled: where the headers are placed in one buffer and the payload is
280  * placed in the other. Only the first 1024 IQs may have FLs associated with
281  * them.
282  *
283  * A freelist is always made up of buffer "pointers". Each buffer pointer is 1
284  * flit (8 bytes) in size and points to DMA memory used to hold packet data. The
285  * lowest four bits of the pointer are used as an index into the freelist buffer
286  * size array, allowing up to 16 different buffer sizes. This implies that each
287  * FL buffer pointer must be at least 16-byte aligned. Each pointer may use a
288  * different size. Since EQ communication must happen in units of host credits,
289  * and an EQ host credit is 8 flits, it means that the driver must always
290  * produce 8 FL buffer pointers per credit. If the driver cannot produce 8
291  * buffer pointers, the rest of the credit may be filled with zero-sized
292  * pointers ("null" or "zero" buffer) which is to say their size index points to
293  * a zero-value entry in the array.
294  *
295  * The digram below depicts how the FL buffer pointer indexes into the
296  * SGE_FL_BUFFER_SZ[N] array.
297  *
298  * +-------------------+-------------------------+
299  * | Buffer Ptr [63:4] | SGE_FL_BUFFER_SIZE[3:0] |
300  * +-------------------+-------------------------+
301  *                                  |
302  *            +---------------------+
303  *            v
304  * +--------------------+--------------------+
305  * | SGE_FL_BUFFER_SZ0  |         0          |  "zero" buffer
306  * +--------------------+--------------------+
307  * | SGE_FL_BUFFER_SZ1  |        4096        |  4K buffer
308  * +--------------------+--------------------+
309  *                      .
310  *                      .
311  *                      .
312  * +--------------------+--------------------+
313  * | SGE_FL_BUFFER_SZ15 |       16384        |  16K buffer
314  * +--------------------+--------------------+
315  *
316  * FL buffers may have "packing" enabled where a single buffer may be used for
317  * multiple packets. This requires that the driver keep track of the current
318  * offset within the current FL buffer. When a new buffer is required by the
319  * device, because the next packet will not fit in the remaining space of the
320  * current buffer, it will consume a new buffer and set a bit in the IQ
321  * completion entry to notify the driver. At this point the driver updates its
322  * cidx and restarts the offset at zero.
323  *
324  * If packing is not enabled each new packet starts at a new buffer.
325  *
326  * This driver currently sets the FL buffer size to 8192 (rx_buf_size) and
327  * enables packing.
328  *
329  * Doorbells, GTS messages, and Interrupts
330  * ---------------------------------------
331  *
332  * The driver and T4 need some way to communicate udpates to the pidx/cidx
333  * values of their queues. To achieve this goal, the driver uses a combination
334  * of doorbells, GTS messages, status pages, and interrupts.
335  *
336  * Doorbells
337  * ---------
338  *
339  * The driver informs the T4 of new EQ credits by way of a "doorbell" (DB). A
340  * doorbell is a register write directed towards a single queue. The doorbell
341  * carries a priority and an incremental update to the pidx value. There are two
342  * types of doorbells:
343  *
344  * 1. Kernel Space doorbells (KDB) which use BAR0.
345  * 2. User Space doorbells (UDB) which use BAR2.
346  *
347  * The "user space" doorbells, while useful for kernel-bypass networking, are
348  * also used for regular in-kernel networking. They divide the queue doorbell
349  * space into multiple 128 byte segments versus KDB's single address for all
350  * queues. They also provide the ability to perform Write-Combining Work
351  * Requeusts (DOORBELL_WCWR) and Write-Combining Doorbells (DOORBELL_UDBWC). The
352  * WCWR allows you to send a single credit as one write and avoid the need for
353  * the T4 to DMA the credit's contents (a WR or FL buffer pointers) from host
354  * memory. We currently make use of WCWR for the Tx datapath, but not for
355  * writing freelist descriptors.
356  *
357  * There is some more discussion of doorbells at the t4_doorbells_t definition
358  * in adapter.h.
359  *
360  * EQ Status Updates
361  * -----------------
362  *
363  * This section covers how EQ status updates work. While an FL is technically an
364  * EQ it makes no use of these mechanisms because the use of FL buffers (cidx)
365  * is tracked implicitly as CPL Rx messages arrive on the associated IQ.
366  *
367  * The driver can track the EQ cidx either by reading the EQ status page or by
368  * asking for a notification via an IQ. This is delivered by way of a
369  * CPL_SGE_EGR_UPDATE message. Furthermore, if the IQ this message is destined
370  * for has interrupts enabled, an interrupt is generated upon delivery of the
371  * message. The EQ status page update and the delivery of this message is
372  * controlled by several factors.
373  *
374  * 1. The EQ context field 'CIDXFlushThresh' (FW_EQ_ETH_CMD.cidxfthresh)
375  *    indicates how many consumed credits must be outstanding before the T4
376  *    generates a cidx update (both status page update and CPL message).
377  *
378  * 2. The EQ context field 'FCThreshOverride' (FW_EQ_ETH_CMD.cidxfthresho) tells
379  *    the T4 to generate a cidx update anytime cidx==pidx; i.e., when the T4 has
380  *    consumed all outstanding credits. This happens regardless if the cidx
381  *    flush threshold has been reached or not (thus the "override"). This is
382  *    useful for dealing with cases of intermitten transmission where the
383  *    threshold may not be reached in a timely manner.
384  *
385  * 3. The DBQ Timer (see TAF_DBQ_TIMER) provides for sending a cidx notification
386  *    anytime the EQ has sat idle (no pidx updates) for a period of time. This
387  *    is preferred to method (2) as it allows batching cidx updates while also
388  *    recycling consumed credits in a timely manner. This is available starting
389  *    with the T6 chip.
390  *
391  * 4. The FW_EQ_FLUSH_WR (its own WR on the EQ) allows the driver to request
392  *    either a status page update, EGR update, or both.
393  *
394  * 5. The FW_ETH_TX_PKT_WR and FW_ETH_TX_PKTS_WR, used to send packets, allows
395  *    the driver to request either a status page update, EGR update, or both as
396  *    part of sending the packet.
397  *
398  * This driver utilizes both the status page and CPL udpates as well as all the
399  * methods listed above to generate these updates.
400  *
401  * GTS Messages
402  * ------------
403  *
404  * The driver sends a GTS (Go To Sleep) message to the T4 to update the SGE
405  * about a specific IQ. The message conveys four pieces of information.
406  *
407  * 1. The Ingress Queue the update is for.
408  *
409  * 2. The current cidx of the driver.
410  *
411  * 3. The new timer value for pidx update scheduling (see IQ context
412  *    'Update_Scheduling' field).
413  *
414  * 4. Either a) arming the "Solicited Event" Interrupt or b) setting the new
415  *    value for the IQ context 'Update_Scheduling' field. Which one depends on
416  *    the IQ context 'GTS_Mode' value.
417  *
418  * We currently always set 'GTS_Mode=1' which indicates that the GTS 'SEIntArm'
419  * value (number 4 above) is used to dictate the new value for the
420  * 'Update_Scheduling' field.
421  *
422  * As the driver processes outstanding IQ credits it uses GTS messages to notify
423  * the driver of how many credits it has consumed and optionally re-arm the
424  * timer and packet counter notifications.
425  *
426  * The GTS messages, like the EQ Doorbells, have both kernel and user space
427  * registers. We currently only make use of the kernel space register.
428  *
429  * Ingress Queue Generation Bit
430  * ----------------------------
431  *
432  * Ingress Queues have an alternative method for pidx updates beyond the status
433  * page update or an explicit CPL message like is done for Ethernet EQs. They
434  * also provide a generation bit as part of each queue entry (credit) which can
435  * be used by the driver, after it has received an interrupt indicating new data
436  * is available, to determine which entries are newly produced by the device.
437  * This method allows you to eschew IQ status page updates altogether, and that
438  * is how we use IQs both for our firmware queue as well as our Rx data queues.
439  *
440  * Freelist Updates
441  * ----------------
442  *
443  * While an FL is technically an EQ we do not make use of explicit EQ status
444  * updates to track the FL cidx. Rather, the current FL buffer is tracked
445  * implicitly by way of the Rx IQ CPL messages generated as part of incoming
446  * traffic. As new packets come in the SGE writes the data in the current FL
447  * buffer and writes a new CPL message onto the Rx IQ. These CPL messages allow
448  * the driver to track which FL buffer is currently in use by the device and
449  * when to move onto the next FL buffer.
450  *
451  * Interrupts
452  * ----------
453  *
454  * The T4 provides interrupt capability for support of asynchrnous
455  * notifications. The primary uses of interrupts consist of the following.
456  *
457  * 1. Notification of new IQ entries (credits) available for consumption by the
458  *    driver. That is, the T4 notifies the host that of its latest IQ pidx value
459  *    indicating that there are new credits for host consumption.
460  *
461  * 2. Notification of new EQ credits available for production by the driver.
462  *    That is, the T4 notifies the host of its latest EQ cidx value indicating
463  *    that there are new credits avilable for host production.
464  *
465  * 3. Notification of firmware events (also referred to as the "firmware queue"
466  *    or "asynchronous event queue").
467  *
468  * This driver employs three different strategies for assigning interrupts
469  * depending on the type and number of interrupts available. These strategies
470  * are listed in order of preference. The solution is chosen by
471  * t4_cfg_intrs_queues() and the setup is done by t4_setup_intrs().
472  *
473  * TIP_PER_PORT
474  *
475  *     The first strategy is used when we have enough MSI/MSI-X interrupts to
476  *     dedicate one to error conditions, one for asynchronous firmware events,
477  *     and at least one for Tx/Rx events on each network port on the adapter. A
478  *     port may have more than one interrupt, in which case its Tx/Rx queue
479  *     events are distributed across those interrupts as evenly as possible. For
480  *     example, given a two-port adapter with eight interrupts, one interrupt
481  *     would be consumed for error conditions, one for firmware events, and the
482  *     remaning six would be divided as three interrupts per port. If each port
483  *     has 32 Rx queues, then two interrupts would be responsbile for 11 queues,
484  *     and the third interrupt would be responsible for 10.
485  *
486  *     The error interrupt vector points to the t4_intr_err() function. Errors
487  *     are deliverd via registers and are handled by t4_slow_intr_handler().
488  *
489  *     The asynchronous firmware event interrupt points to the t4_intr_fwq()
490  *     function and the events arrive on the firmware queue (sc->sge.fwq).
491  *
492  *     The per port interrupts point to t4_intr_port_queue() and each port's
493  *     events land on one of the per port event queues (port->intr_iqs).
494  *
495  * TIP_ERR_QUEUES
496  *
497  *     The second strategy is used when we have only two interrupts. In this
498  *     case one of the interrupts is dedicated to errors and the other one is
499  *     shared between the firmware events and the port events (Rx/Tx
500  *     notifications).
501  *
502  *     In this case the firmware and port events all land on the firmware queue
503  *     which is processed by t4_intr_fwq().
504  *
505  * TIP_SINGLE
506  *
507  *     The last strategy is for when we have a single interrupt and everything
508  *     needs to share it. In this case the interrupt lands on t4_intr_all() and
509  *     all firmware and port events go to the firmware queue.
510  *
511  * The per-port events queues (port->intr_iq) do not receive any network data
512  * themselves. Rather, they are used for two purposes:
513  *
514  * 1. To handle CPL_SGE_EGR_UPDATE messages; used to notify the driver about the
515  *    device's current cidx in a particular EQ. This is how Tx queues know when
516  *    they reclaim credits used for sending packets.
517  *
518  * 2. To handle "forwarded interrupt" notifications; used to notify the driver
519  *    that a particular receive IQ has outstanding credits to read. This is how
520  *    Rx queues know when there are new packets available to read.
521  */
522 
523 static void *t4_soft_state;
524 
525 static kmutex_t t4_adapter_list_lock;
526 static list_t t4_adapter_list;
527 
528 typedef enum t4_port_speed {
529 	TPS_1G,
530 	TPS_10G,
531 	TPS_25G,
532 	TPS_40G,
533 	TPS_50G,
534 	TPS_100G,
535 	TPS_200G,
536 	TPS_400G,
537 } t4_port_speed_t;
538 
539 static uint_t t4_getpf(struct adapter *);
540 static int t4_prep_firmware(struct adapter *);
541 static int t4_upload_config_file(struct adapter *, uint32_t *, uint32_t *);
542 static int t4_partition_resources(struct adapter *);
543 static int t4_init_adap_tweaks(struct adapter *);
544 static int t4_init_get_params_pre(struct adapter *);
545 static int t4_init_get_params_post(struct adapter *);
546 static int t4_init_set_params(struct adapter *);
547 static void t4_setup_adapter_memwin(struct adapter *);
548 static uint32_t t4_position_memwin(struct adapter *, int, uint32_t);
549 static void t4_init_driver_props(struct adapter *);
550 static int t4_cfg_intrs_queues(struct adapter *);
551 static int t4_setup_intrs(struct adapter *);
552 static int t4_add_child_node(struct adapter *, uint_t);
553 static int t4_remove_child_node(struct adapter *, uint_t);
554 static kstat_t *t4_setup_kstats(struct adapter *);
555 static kstat_t *t4_setup_wc_kstats(struct adapter *);
556 static void t4_port_full_uninit(struct port_info *);
557 static t4_port_speed_t t4_port_speed(const struct port_info *);
558 
559 static int t4_temperature_read(void *, sensor_ioctl_scalar_t *);
560 static int t4_voltage_read(void *, sensor_ioctl_scalar_t *);
561 
562 static const ksensor_ops_t t4_temp_ops = {
563 	.kso_kind = ksensor_kind_temperature,
564 	.kso_scalar = t4_temperature_read
565 };
566 
567 static const ksensor_ops_t t4_volt_ops = {
568 	.kso_kind = ksensor_kind_voltage,
569 	.kso_scalar = t4_voltage_read
570 };
571 
572 static int t4_ufm_getcaps(ddi_ufm_handle_t *, void *, ddi_ufm_cap_t *);
573 static int t4_ufm_fill_image(ddi_ufm_handle_t *, void *, uint_t,
574     ddi_ufm_image_t *);
575 static int t4_ufm_fill_slot(ddi_ufm_handle_t *, void *, uint_t, uint_t,
576     ddi_ufm_slot_t *);
577 static ddi_ufm_ops_t t4_ufm_ops = {
578 	.ddi_ufm_op_fill_image = t4_ufm_fill_image,
579 	.ddi_ufm_op_fill_slot = t4_ufm_fill_slot,
580 	.ddi_ufm_op_getcaps = t4_ufm_getcaps
581 };
582 
583 
584 static int
t4_devo_getinfo(dev_info_t * dip,ddi_info_cmd_t cmd,void * arg,void ** rp)585 t4_devo_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg, void **rp)
586 {
587 	struct adapter *sc;
588 	minor_t minor;
589 
590 	minor = getminor((dev_t)arg);	/* same as instance# in our case */
591 
592 	if (cmd == DDI_INFO_DEVT2DEVINFO) {
593 		sc = ddi_get_soft_state(t4_soft_state, minor);
594 		if (sc == NULL)
595 			return (DDI_FAILURE);
596 
597 		ASSERT(sc->dev == (dev_t)arg);
598 		*rp = (void *)sc->dip;
599 	} else if (cmd == DDI_INFO_DEVT2INSTANCE)
600 		*rp = (void *) (unsigned long) minor;
601 	else
602 		ASSERT(0);
603 
604 	return (DDI_SUCCESS);
605 }
606 
607 static int
t4_devo_probe(dev_info_t * dip)608 t4_devo_probe(dev_info_t *dip)
609 {
610 	int rc, id, *reg;
611 	uint_t n, pf;
612 
613 	id = ddi_prop_get_int(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
614 	    "device-id", 0xffff);
615 	if (id == 0xffff)
616 		return (DDI_PROBE_DONTCARE);
617 
618 	rc = ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
619 	    "reg", &reg, &n);
620 	if (rc != DDI_SUCCESS)
621 		return (DDI_PROBE_DONTCARE);
622 
623 	pf = PCI_REG_FUNC_G(reg[0]);
624 	ddi_prop_free(reg);
625 
626 	/* Prevent driver attachment on any PF except 0 on the FPGA */
627 	if (id == 0xa000 && pf != 0)
628 		return (DDI_PROBE_FAILURE);
629 
630 	return (DDI_PROBE_DONTCARE);
631 }
632 
633 static int t4_devo_detach(dev_info_t *, ddi_detach_cmd_t);
634 
635 static int
t4_devo_attach(dev_info_t * dip,ddi_attach_cmd_t cmd)636 t4_devo_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
637 {
638 	int i = 0;
639 	int rc = DDI_SUCCESS;
640 	char name[16];
641 	ddi_device_acc_attr_t da = {
642 		.devacc_attr_version = DDI_DEVICE_ATTR_V0,
643 		.devacc_attr_endian_flags = DDI_STRUCTURE_LE_ACC,
644 		.devacc_attr_dataorder = DDI_STRICTORDER_ACC
645 	};
646 	ddi_device_acc_attr_t da_bar2 = {
647 		.devacc_attr_version = DDI_DEVICE_ATTR_V0,
648 		.devacc_attr_endian_flags = DDI_STRUCTURE_LE_ACC,
649 		.devacc_attr_dataorder = DDI_STRICTORDER_ACC
650 	};
651 
652 	if (cmd != DDI_ATTACH)
653 		return (DDI_FAILURE);
654 
655 	/*
656 	 * Allocate space for soft state.
657 	 */
658 	const int instance = ddi_get_instance(dip);
659 	rc = ddi_soft_state_zalloc(t4_soft_state, instance);
660 	if (rc != DDI_SUCCESS) {
661 		cxgb_printf(dip, CE_WARN,
662 		    "failed to allocate soft state: %d", rc);
663 		return (DDI_FAILURE);
664 	}
665 
666 	struct adapter *sc = ddi_get_soft_state(t4_soft_state, instance);
667 	sc->dip = dip;
668 	sc->dev = makedevice(ddi_driver_major(dip), instance);
669 	mutex_init(&sc->lock, NULL, MUTEX_DRIVER, NULL);
670 	cv_init(&sc->cv, NULL, CV_DRIVER, NULL);
671 	mutex_init(&sc->sfl_lock, NULL, MUTEX_DRIVER, NULL);
672 	list_create(&sc->sfl_list, sizeof (struct sge_fl),
673 	    offsetof(struct sge_fl, sfl_node));
674 	mutex_init(&sc->mbox_lock, NULL, MUTEX_DRIVER, NULL);
675 	list_create(&sc->mbox_list, sizeof (t4_mbox_waiter_t),
676 	    offsetof(t4_mbox_waiter_t, node));
677 
678 	mutex_enter(&t4_adapter_list_lock);
679 	list_insert_tail(&t4_adapter_list, sc);
680 	mutex_exit(&t4_adapter_list_lock);
681 
682 	sc->pf = t4_getpf(sc);
683 	if (sc->pf > 8) {
684 		rc = EINVAL;
685 		cxgb_printf(dip, CE_WARN,
686 		    "failed to determine PCI PF# of device");
687 		goto done;
688 	}
689 	sc->mbox = sc->pf;
690 
691 	/* Initialize the driver properties */
692 	t4_init_driver_props(sc);
693 	struct driver_properties *prp = &sc->props;
694 
695 	/*
696 	 * Enable access to the PCI config space.
697 	 */
698 	rc = pci_config_setup(dip, &sc->pci_regh);
699 	if (rc != DDI_SUCCESS) {
700 		cxgb_printf(dip, CE_WARN,
701 		    "failed to enable PCI config space access: %d", rc);
702 		goto done;
703 	}
704 
705 	/* TODO: Set max read request to 4K */
706 
707 	/*
708 	 * Enable BAR0 access.
709 	 */
710 	rc = ddi_regs_map_setup(dip, 1, &sc->regp, 0, 0, &da, &sc->regh);
711 	if (rc != DDI_SUCCESS) {
712 		cxgb_printf(dip, CE_WARN,
713 		    "failed to map device registers: %d", rc);
714 		goto done;
715 	}
716 
717 	(void) memset(sc->chan_map, 0xff, sizeof (sc->chan_map));
718 
719 	/*
720 	 * Prepare the adapter for operation.
721 	 */
722 	rc = -t4_prep_adapter(sc, false);
723 	if (rc != 0) {
724 		cxgb_printf(dip, CE_WARN, "failed to prepare adapter: %d", rc);
725 		goto done;
726 	}
727 
728 	/*
729 	 * Enable BAR2 access.
730 	 */
731 	sc->doorbells |= DOORBELL_KDB;
732 	rc = ddi_regs_map_setup(dip, 2, &sc->bar2_ptr, 0, 0, &da_bar2,
733 	    &sc->bar2_hdl);
734 	if (rc != DDI_SUCCESS) {
735 		cxgb_printf(dip, CE_WARN,
736 		    "failed to map BAR2 device registers: %d", rc);
737 		goto done;
738 	} else {
739 		if (t4_cver_ge(sc, CHELSIO_T5)) {
740 			sc->doorbells |= DOORBELL_UDB;
741 			if (prp->write_combine) {
742 				/*
743 				 * Enable write combining on BAR2.  This is the
744 				 * userspace doorbell BAR and is split into 128B
745 				 * (UDBS_SEG_SIZE) doorbell regions, each
746 				 * associated with an egress queue.  The first
747 				 * 64B has the doorbell and the second 64B can
748 				 * be used to submit a tx work request with an
749 				 * implicit doorbell.
750 				 */
751 				sc->doorbells &= ~DOORBELL_UDB;
752 				sc->doorbells |= (DOORBELL_WCWR |
753 				    DOORBELL_UDBWC);
754 
755 				const uint32_t stat_mode =
756 				    t4_cver_ge(sc, CHELSIO_T6) ?
757 				    V_T6_STATMODE(0) : V_STATMODE(0);
758 				t4_write_reg(sc, A_SGE_STAT_CFG,
759 				    V_STATSOURCE_T5(7) | stat_mode);
760 			}
761 		}
762 	}
763 
764 	/*
765 	 * Do this really early.  Note that minor number = instance.
766 	 */
767 	(void) snprintf(name, sizeof (name), "%s,%d", T4_NEXUS_NAME, instance);
768 	rc = ddi_create_minor_node(dip, name, S_IFCHR, instance,
769 	    DDI_NT_NEXUS, 0);
770 	if (rc != DDI_SUCCESS) {
771 		cxgb_printf(dip, CE_WARN,
772 		    "failed to create device node: %d", rc);
773 		rc = DDI_SUCCESS; /* carry on */
774 	}
775 
776 	/* Do this early. Memory window is required for loading config file. */
777 	t4_setup_adapter_memwin(sc);
778 
779 	/* Prepare the firmware for operation */
780 	rc = t4_prep_firmware(sc);
781 	if (rc != 0)
782 		goto done; /* error message displayed already */
783 
784 	rc = t4_init_adap_tweaks(sc);
785 	if (rc != 0)
786 		goto done;
787 
788 	rc = t4_init_get_params_pre(sc);
789 	if (rc != 0)
790 		goto done; /* error message displayed already */
791 
792 	t4_sge_init(sc);
793 
794 	if (sc->flags & TAF_MASTER_PF) {
795 		/* get basic stuff going */
796 		rc = -t4_fw_initialize(sc, sc->mbox);
797 		if (rc != 0) {
798 			cxgb_printf(sc->dip, CE_WARN,
799 			    "early init failed: %d.\n", rc);
800 			goto done;
801 		}
802 	}
803 
804 	rc = t4_init_get_params_post(sc);
805 	if (rc != 0)
806 		goto done; /* error message displayed already */
807 
808 	rc = t4_init_set_params(sc);
809 	if (rc != 0)
810 		goto done; /* error message displayed already */
811 
812 	/*
813 	 * TODO: This is the place to call t4_set_filter_mode()
814 	 */
815 
816 	t4_write_reg(sc, A_TP_SHIFT_CNT,
817 	    V_SYNSHIFTMAX(6) |
818 	    V_RXTSHIFTMAXR1(4) |
819 	    V_RXTSHIFTMAXR2(15) |
820 	    V_PERSHIFTBACKOFFMAX(8) |
821 	    V_PERSHIFTMAX(8) |
822 	    V_KEEPALIVEMAXR1(4) |
823 	    V_KEEPALIVEMAXR2(9));
824 	t4_write_reg(sc, A_ULP_RX_TDDP_PSZ, V_HPZ0(PAGE_SHIFT - 12));
825 
826 	/*
827 	 * Work-around for bug 2619
828 	 * Set DisableVlan field in TP_RSS_CONFIG_VRT register so that the
829 	 * VLAN tag extraction is disabled.
830 	 */
831 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_VRT, F_DISABLEVLAN, F_DISABLEVLAN);
832 
833 	/* Store filter mode */
834 	t4_read_indirect(sc, A_TP_PIO_ADDR, A_TP_PIO_DATA, &sc->filter_mode, 1,
835 	    A_TP_VLAN_PRI_MAP);
836 
837 	/*
838 	 * First pass over all the ports - allocate VIs and initialize some
839 	 * basic parameters like mac address, port type, etc.  We also figure
840 	 * out whether a port is 10G or 1G and use that information when
841 	 * calculating how many interrupts to attempt to allocate.
842 	 */
843 	for_each_port(sc, i) {
844 		struct port_info *pi;
845 
846 		pi = kmem_zalloc(sizeof (*pi), KM_SLEEP);
847 		sc->port[i] = pi;
848 
849 		/* These must be set before t4_port_init */
850 		pi->adapter = sc;
851 		pi->port_id = i;
852 	}
853 
854 	/* Allocate the vi and initialize parameters like mac addr */
855 	rc = -t4_port_init(sc, sc->mbox, sc->pf, 0);
856 	if (rc) {
857 		cxgb_printf(dip, CE_WARN, "unable to initialize port: %d", rc);
858 		goto done;
859 	}
860 
861 	for_each_port(sc, i) {
862 		struct port_info *pi = sc->port[i];
863 
864 		mutex_init(&pi->lock, NULL, MUTEX_DRIVER, NULL);
865 		pi->mtu = ETHERMTU;
866 
867 		pi->tmr_idx = prp->ethq_tmr_idx;
868 		pi->pktc_idx = prp->ethq_pktc_idx;
869 		pi->dbq_timer_idx = prp->dbq_timer_idx;
870 
871 		pi->xact_addr_filt = -1;
872 	}
873 
874 	if ((rc = t4_cfg_intrs_queues(sc)) != 0) {
875 		goto done; /* error message displayed already */
876 	}
877 
878 	const struct t4_intrs_queues *iaq = &sc->intr_queue_cfg;
879 	struct sge_info *sge = &sc->sge;
880 	sge->rxq =
881 	    kmem_zalloc(sge->rxq_count * sizeof (struct sge_rxq), KM_SLEEP);
882 	sge->txq =
883 	    kmem_zalloc(sge->txq_count * sizeof (struct sge_txq), KM_SLEEP);
884 	sge->iqmap =
885 	    kmem_zalloc(sge->iqmap_sz * sizeof (struct sge_iq *), KM_SLEEP);
886 	sge->eqmap =
887 	    kmem_zalloc(sge->eqmap_sz * sizeof (struct sge_eq *), KM_SLEEP);
888 
889 	sc->intr_handle =
890 	    kmem_zalloc(iaq->intr_count * sizeof (ddi_intr_handle_t),
891 	    KM_SLEEP);
892 
893 	/*
894 	 * Enable hw checksumming and LSO for all ports by default.
895 	 * They can be disabled using ndd (hw_csum and hw_lso).
896 	 */
897 	for_each_port(sc, i) {
898 		sc->port[i]->features |= (CXGBE_HW_CSUM | CXGBE_HW_LSO);
899 	}
900 
901 	/* Setup Interrupts. */
902 	if ((rc = t4_setup_intrs(sc)) != DDI_SUCCESS) {
903 		goto done;
904 	}
905 	sc->flags |= TAF_INTR_ALLOC;
906 
907 	if ((rc = ksensor_create_scalar_pcidev(dip, SENSOR_KIND_TEMPERATURE,
908 	    &t4_temp_ops, sc, "temp", &sc->temp_sensor)) != 0) {
909 		cxgb_printf(dip, CE_WARN, "failed to create temperature "
910 		    "sensor: %d", rc);
911 		rc = DDI_FAILURE;
912 		goto done;
913 	}
914 
915 	if ((rc = ksensor_create_scalar_pcidev(dip, SENSOR_KIND_VOLTAGE,
916 	    &t4_volt_ops, sc, "vdd", &sc->volt_sensor)) != 0) {
917 		cxgb_printf(dip, CE_WARN, "failed to create voltage "
918 		    "sensor: %d", rc);
919 		rc = DDI_FAILURE;
920 		goto done;
921 	}
922 
923 
924 	if ((rc = ddi_ufm_init(dip, DDI_UFM_CURRENT_VERSION, &t4_ufm_ops,
925 	    &sc->ufm_hdl, sc)) != 0) {
926 		cxgb_printf(dip, CE_WARN, "failed to enable UFM ops: %d", rc);
927 		rc = DDI_FAILURE;
928 		goto done;
929 	}
930 	ddi_ufm_update(sc->ufm_hdl);
931 
932 	if ((rc = t4_alloc_evt_iqs(sc)) != 0) {
933 		cxgb_printf(dip, CE_WARN, "failed to alloc FWQ: %d", rc);
934 		rc = DDI_FAILURE;
935 		goto done;
936 	}
937 
938 	if (sc->intr_cap & DDI_INTR_FLAG_BLOCK) {
939 		rc = ddi_intr_block_enable(sc->intr_handle, iaq->intr_count);
940 
941 		if (rc != DDI_SUCCESS) {
942 			cxgb_printf(dip, CE_WARN, "failed to enable intr "
943 			    "block: %d", rc);
944 			rc = DDI_FAILURE;
945 			goto done;
946 		}
947 	} else {
948 		for (i = 0; i < iaq->intr_count; i++) {
949 			rc = ddi_intr_enable(sc->intr_handle[i]);
950 			if (rc != DDI_SUCCESS) {
951 				cxgb_printf(dip, CE_WARN, "failed to enable "
952 				    "intr %d: %d", i, rc);
953 				rc = DDI_FAILURE;
954 				goto done;
955 			}
956 		}
957 	}
958 	t4_intr_enable(sc);
959 
960 	/*
961 	 * At this point, adapter-level initialization can be considered
962 	 * successful.  The ports themselves will be initialized later when mac
963 	 * attaches/starts them via cxgbe.
964 	 */
965 	sc->flags |= TAF_INIT_DONE;
966 	ddi_report_dev(dip);
967 
968 	/*
969 	 * Hardware/Firmware/etc. Version/Revision IDs.
970 	 */
971 	t4_dump_version_info(sc);
972 
973 	sc->ksp = t4_setup_kstats(sc);
974 	sc->ksp_stat = t4_setup_wc_kstats(sc);
975 	sc->params.drv_memwin = MEMWIN_NIC;
976 
977 done:
978 	if (rc != DDI_SUCCESS) {
979 		(void) t4_devo_detach(dip, DDI_DETACH);
980 
981 		/* rc may have errno style errors or DDI errors */
982 		rc = DDI_FAILURE;
983 	}
984 
985 	return (rc);
986 }
987 
988 static int
t4_devo_detach(dev_info_t * dip,ddi_detach_cmd_t cmd)989 t4_devo_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
990 {
991 	int i = 0;
992 	struct port_info *pi;
993 	struct sge_info *s;
994 
995 	if (cmd != DDI_DETACH)
996 		return (DDI_FAILURE);
997 
998 	const int instance = ddi_get_instance(dip);
999 	struct adapter *sc = ddi_get_soft_state(t4_soft_state, instance);
1000 	if (sc == NULL)
1001 		return (DDI_SUCCESS);
1002 
1003 	struct t4_intrs_queues *iaq = &sc->intr_queue_cfg;
1004 
1005 	if (sc->flags & TAF_INIT_DONE) {
1006 		t4_intr_disable(sc);
1007 		for_each_port(sc, i) {
1008 			pi = sc->port[i];
1009 			if (pi && pi->flags & TPF_INIT_DONE)
1010 				t4_port_full_uninit(pi);
1011 		}
1012 
1013 		if (sc->intr_cap & DDI_INTR_FLAG_BLOCK) {
1014 			(void) ddi_intr_block_disable(sc->intr_handle,
1015 			    iaq->intr_count);
1016 		} else {
1017 			for (i = 0; i < iaq->intr_count; i++)
1018 				(void) ddi_intr_disable(sc->intr_handle[i]);
1019 		}
1020 
1021 		t4_free_evt_iqs(sc);
1022 
1023 		sc->flags &= ~TAF_INIT_DONE;
1024 	}
1025 
1026 	/* Safe to call no matter what */
1027 	if (sc->ufm_hdl != NULL) {
1028 		ddi_ufm_fini(sc->ufm_hdl);
1029 		sc->ufm_hdl = NULL;
1030 	}
1031 	(void) ksensor_remove(dip, KSENSOR_ALL_IDS);
1032 	ddi_prop_remove_all(dip);
1033 	ddi_remove_minor_node(dip, NULL);
1034 
1035 	if (sc->ksp != NULL)
1036 		kstat_delete(sc->ksp);
1037 	if (sc->ksp_stat != NULL)
1038 		kstat_delete(sc->ksp_stat);
1039 
1040 	s = &sc->sge;
1041 	if (s->rxq != NULL)
1042 		kmem_free(s->rxq, s->rxq_count * sizeof (struct sge_rxq));
1043 	if (s->txq != NULL)
1044 		kmem_free(s->txq, s->txq_count * sizeof (struct sge_txq));
1045 	if (s->iqmap != NULL)
1046 		kmem_free(s->iqmap, s->iqmap_sz * sizeof (struct sge_iq *));
1047 	if (s->eqmap != NULL)
1048 		kmem_free(s->eqmap, s->eqmap_sz * sizeof (struct sge_eq *));
1049 
1050 	if (s->rxbuf_cache != NULL)
1051 		kmem_cache_destroy(s->rxbuf_cache);
1052 
1053 	if (sc->flags & TAF_INTR_ALLOC) {
1054 		for (int i = 0; i < iaq->intr_count; i++) {
1055 			int rc = ddi_intr_remove_handler(sc->intr_handle[i]);
1056 			if (rc != DDI_SUCCESS) {
1057 				cxgb_printf(sc->dip, CE_WARN, "failed to "
1058 				    "remove interrupt handler %d for type: %d "
1059 				    "plan: %d: %d", i, iaq->intr_type,
1060 				    iaq->intr_plan, rc);
1061 			}
1062 
1063 			rc = ddi_intr_free(sc->intr_handle[i]);
1064 			if (rc != DDI_SUCCESS) {
1065 				cxgb_printf(sc->dip, CE_WARN, "failed to free "
1066 				    "interrupt %d for type: %d plan: %d: %d", i,
1067 				    iaq->intr_type, iaq->intr_plan, rc);
1068 
1069 			}
1070 		}
1071 		sc->flags &= ~TAF_INTR_ALLOC;
1072 	}
1073 
1074 	if (sc->intr_handle != NULL) {
1075 		kmem_free(sc->intr_handle,
1076 		    iaq->intr_count * sizeof (*sc->intr_handle));
1077 	}
1078 
1079 	for_each_port(sc, i) {
1080 		pi = sc->port[i];
1081 		if (pi != NULL) {
1082 			if (pi->intr_iqs != NULL) {
1083 				kmem_free(pi->intr_iqs,
1084 				    sizeof (pi->intr_iqs[0]) *
1085 				    sc->intr_queue_cfg.intr_per_port);
1086 			}
1087 			mutex_destroy(&pi->lock);
1088 			kmem_free(pi, sizeof (*pi));
1089 		}
1090 	}
1091 
1092 	if (sc->flags & FW_OK)
1093 		(void) t4_fw_bye(sc, sc->mbox);
1094 
1095 	if (sc->bar2_hdl != NULL) {
1096 		ddi_regs_map_free(&sc->bar2_hdl);
1097 		sc->bar2_hdl = NULL;
1098 		sc->bar2_ptr = NULL;
1099 	}
1100 
1101 	if (sc->regh != NULL) {
1102 		ddi_regs_map_free(&sc->regh);
1103 		sc->regh = NULL;
1104 		sc->regp = NULL;
1105 	}
1106 
1107 	if (sc->pci_regh != NULL) {
1108 		pci_config_teardown(&sc->pci_regh);
1109 	}
1110 
1111 	mutex_enter(&t4_adapter_list_lock);
1112 	list_remove(&t4_adapter_list, sc);
1113 	mutex_exit(&t4_adapter_list_lock);
1114 
1115 	mutex_destroy(&sc->mbox_lock);
1116 	mutex_destroy(&sc->lock);
1117 	cv_destroy(&sc->cv);
1118 	mutex_destroy(&sc->sfl_lock);
1119 
1120 #ifdef DEBUG
1121 	bzero(sc, sizeof (*sc));
1122 #endif
1123 	ddi_soft_state_free(t4_soft_state, instance);
1124 
1125 	return (DDI_SUCCESS);
1126 }
1127 
1128 static int
t4_devo_quiesce(dev_info_t * dip)1129 t4_devo_quiesce(dev_info_t *dip)
1130 {
1131 	int instance;
1132 	struct adapter *sc;
1133 
1134 	instance = ddi_get_instance(dip);
1135 	sc = ddi_get_soft_state(t4_soft_state, instance);
1136 	if (sc == NULL)
1137 		return (DDI_SUCCESS);
1138 
1139 	t4_set_reg_field(sc, A_SGE_CONTROL, F_GLOBALENABLE, 0);
1140 	t4_intr_disable(sc);
1141 	t4_write_reg(sc, A_PL_RST, F_PIORSTMODE | F_PIORST);
1142 
1143 	return (DDI_SUCCESS);
1144 }
1145 
1146 static int
t4_bus_ctl(dev_info_t * dip,dev_info_t * rdip,ddi_ctl_enum_t op,void * arg,void * result)1147 t4_bus_ctl(dev_info_t *dip, dev_info_t *rdip, ddi_ctl_enum_t op, void *arg,
1148     void *result)
1149 {
1150 	char s[4];
1151 	struct port_info *pi;
1152 	dev_info_t *child = (dev_info_t *)arg;
1153 
1154 	switch (op) {
1155 	case DDI_CTLOPS_REPORTDEV:
1156 		if (rdip == NULL)
1157 			return (DDI_FAILURE);
1158 		cmn_err(CE_CONT, "?t4nexus: %s%d\n",
1159 		    ddi_driver_name(rdip), ddi_get_instance(rdip));
1160 		return (DDI_SUCCESS);
1161 
1162 	case DDI_CTLOPS_INITCHILD:
1163 		pi = ddi_get_parent_data(child);
1164 		if (pi == NULL)
1165 			return (DDI_NOT_WELL_FORMED);
1166 		(void) snprintf(s, sizeof (s), "%d", pi->port_id);
1167 		ddi_set_name_addr(child, s);
1168 		return (DDI_SUCCESS);
1169 
1170 	case DDI_CTLOPS_UNINITCHILD:
1171 		ddi_set_name_addr(child, NULL);
1172 		return (DDI_SUCCESS);
1173 
1174 	case DDI_CTLOPS_ATTACH:
1175 	case DDI_CTLOPS_DETACH:
1176 		return (DDI_SUCCESS);
1177 
1178 	default:
1179 		return (ddi_ctlops(dip, rdip, op, arg, result));
1180 	}
1181 }
1182 
1183 /* From a provided "cxgbe@0" string, parse the device number */
1184 static bool
t4_parse_devnum(const char * devname,uint_t * inst_nump)1185 t4_parse_devnum(const char *devname, uint_t *inst_nump)
1186 {
1187 	const size_t name_sz = strlen(devname) + 1;
1188 	char *name_copy = i_ddi_strdup(devname, KM_SLEEP);
1189 
1190 	bool res = false;
1191 	char *nodename, *addrname = NULL;
1192 	i_ddi_parse_name(name_copy, &nodename, &addrname, NULL);
1193 	if (addrname == NULL || strcmp(T4_PORT_NAME, nodename) != 0) {
1194 		goto done;
1195 	}
1196 
1197 	ulong_t num;
1198 	if (ddi_strtoul(addrname, NULL, 10, &num) != 0 || num > UINT_MAX) {
1199 		goto done;
1200 	}
1201 	*inst_nump = (uint_t)num;
1202 	res = true;
1203 
1204 done:
1205 	kmem_free(name_copy, name_sz);
1206 	return (res);
1207 }
1208 
1209 static int
t4_bus_config(dev_info_t * dip,uint_t flags,ddi_bus_config_op_t op,void * arg,dev_info_t ** cdipp)1210 t4_bus_config(dev_info_t *dip, uint_t flags, ddi_bus_config_op_t op, void *arg,
1211     dev_info_t **cdipp)
1212 {
1213 	struct adapter *sc =
1214 	    ddi_get_soft_state(t4_soft_state, ddi_get_instance(dip));
1215 
1216 	if (op == BUS_CONFIG_ONE) {
1217 		uint_t dev_num;
1218 
1219 		if (!t4_parse_devnum((const char *)arg, &dev_num)) {
1220 			return (NDI_FAILURE);
1221 		}
1222 		if (t4_add_child_node(sc, dev_num) != 0) {
1223 			return (NDI_FAILURE);
1224 		}
1225 
1226 		flags |= NDI_ONLINE_ATTACH;
1227 
1228 	} else if (op == BUS_CONFIG_ALL || op == BUS_CONFIG_DRIVER) {
1229 		int i;
1230 
1231 		/* Allocate and bind all child device nodes */
1232 		for_each_port(sc, i) {
1233 			(void) t4_add_child_node(sc, (uint_t)i);
1234 		}
1235 		flags |= NDI_ONLINE_ATTACH;
1236 	}
1237 
1238 	return (ndi_busop_bus_config(dip, flags, op, arg, cdipp, 0));
1239 }
1240 
1241 static int
t4_bus_unconfig(dev_info_t * dip,uint_t flags,ddi_bus_config_op_t op,void * arg)1242 t4_bus_unconfig(dev_info_t *dip, uint_t flags, ddi_bus_config_op_t op,
1243     void *arg)
1244 {
1245 	struct adapter *sc
1246 	    = ddi_get_soft_state(t4_soft_state, ddi_get_instance(dip));
1247 
1248 	if (op == BUS_UNCONFIG_ONE ||
1249 	    op == BUS_UNCONFIG_ALL ||
1250 	    op == BUS_UNCONFIG_DRIVER) {
1251 		flags |= NDI_UNCONFIG;
1252 	}
1253 
1254 	int rc = ndi_busop_bus_unconfig(dip, flags, op, arg);
1255 	if (rc != 0)
1256 		return (rc);
1257 
1258 	if (op == BUS_UNCONFIG_ONE) {
1259 		uint_t dev_num;
1260 
1261 		if (!t4_parse_devnum((const char *)arg, &dev_num)) {
1262 			return (NDI_FAILURE);
1263 		}
1264 
1265 		rc = t4_remove_child_node(sc, dev_num);
1266 	} else if (op == BUS_UNCONFIG_ALL || op == BUS_UNCONFIG_DRIVER) {
1267 		uint_t i;
1268 
1269 		for_each_port(sc, i) {
1270 			(void) t4_remove_child_node(sc, i);
1271 		}
1272 	}
1273 
1274 	return (rc);
1275 }
1276 
1277 static int
t4_cb_open(dev_t * devp,int flag,int otyp,cred_t * credp)1278 t4_cb_open(dev_t *devp, int flag, int otyp, cred_t *credp)
1279 {
1280 	struct adapter *sc;
1281 
1282 	if (otyp != OTYP_CHR) {
1283 		return (EINVAL);
1284 	}
1285 
1286 	sc = ddi_get_soft_state(t4_soft_state, getminor(*devp));
1287 	if (sc == NULL) {
1288 		return (ENXIO);
1289 	}
1290 
1291 	return (atomic_cas_uint(&sc->open, 0, EBUSY));
1292 }
1293 
1294 static int
t4_cb_close(dev_t dev,int flag,int otyp,cred_t * credp)1295 t4_cb_close(dev_t dev, int flag, int otyp, cred_t *credp)
1296 {
1297 	struct adapter *sc = ddi_get_soft_state(t4_soft_state, getminor(dev));
1298 
1299 	if (sc == NULL) {
1300 		return (EINVAL);
1301 	}
1302 
1303 	(void) atomic_swap_uint(&sc->open, 0);
1304 	return (0);
1305 }
1306 
1307 static int
t4_cb_ioctl(dev_t dev,int cmd,intptr_t d,int mode,cred_t * credp,int * rp)1308 t4_cb_ioctl(dev_t dev, int cmd, intptr_t d, int mode, cred_t *credp, int *rp)
1309 {
1310 	if (crgetuid(credp) != 0) {
1311 		return (EPERM);
1312 	}
1313 
1314 	struct adapter *sc = ddi_get_soft_state(t4_soft_state, getminor(dev));
1315 
1316 	if (sc == NULL) {
1317 		return (EINVAL);
1318 	}
1319 
1320 	return (t4_ioctl(sc, cmd, (void *)d, mode));
1321 }
1322 
1323 static uint_t
t4_getpf(struct adapter * sc)1324 t4_getpf(struct adapter *sc)
1325 {
1326 	int *data;
1327 	uint_t n;
1328 
1329 	const int rc = ddi_prop_lookup_int_array(DDI_DEV_T_ANY, sc->dip,
1330 	    DDI_PROP_DONTPASS, "reg", &data, &n);
1331 	if (rc != DDI_SUCCESS) {
1332 		return (UINT_MAX);
1333 	}
1334 
1335 	const uint_t pf = PCI_REG_FUNC_G(data[0]);
1336 	ddi_prop_free(data);
1337 
1338 	return (pf);
1339 }
1340 
1341 /*
1342  * Install a compatible firmware (if required), establish contact with it,
1343  * become the master, and reset the device.
1344  */
1345 static int
t4_prep_firmware(struct adapter * sc)1346 t4_prep_firmware(struct adapter *sc)
1347 {
1348 	int rc;
1349 
1350 	/* Contact firmware, request master */
1351 	enum dev_state state;
1352 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MUST, &state);
1353 	if (rc < 0) {
1354 		rc = -rc;
1355 		cxgb_printf(sc->dip, CE_WARN,
1356 		    "failed to connect to the firmware: %d.", rc);
1357 		return (rc);
1358 	}
1359 
1360 	if (rc == sc->mbox)
1361 		sc->flags |= TAF_MASTER_PF;
1362 
1363 	/* We may need FW version info for later reporting */
1364 	(void) t4_get_version_info(sc);
1365 
1366 	const char *fw_file = NULL;
1367 	switch (CHELSIO_CHIP_VERSION(sc->params.chip)) {
1368 	case CHELSIO_T4:
1369 		fw_file = "t4fw.bin";
1370 		break;
1371 	case CHELSIO_T5:
1372 		fw_file = "t5fw.bin";
1373 		break;
1374 	case CHELSIO_T6:
1375 		fw_file = "t6fw.bin";
1376 		break;
1377 	default:
1378 		cxgb_printf(sc->dip, CE_WARN, "Adapter type not supported\n");
1379 		return (EINVAL);
1380 	}
1381 
1382 	firmware_handle_t fw_hdl;
1383 	if (firmware_open(T4_PORT_NAME, fw_file, &fw_hdl) != 0) {
1384 		cxgb_printf(sc->dip, CE_WARN, "Could not open %s\n", fw_file);
1385 		return (EINVAL);
1386 	}
1387 
1388 	const size_t fw_size = firmware_get_size(fw_hdl);
1389 	if (fw_size < sizeof (struct fw_hdr)) {
1390 		cxgb_printf(sc->dip, CE_WARN, "%s is too small (%lu bytes)\n",
1391 		    fw_file, fw_size);
1392 		(void) firmware_close(fw_hdl);
1393 		return (EINVAL);
1394 	}
1395 	if (fw_size > FLASH_FW_MAX_SIZE) {
1396 		cxgb_printf(sc->dip, CE_WARN,
1397 		    "%s is too large (%lu bytes, max allowed is %lu)\n",
1398 		    fw_file, fw_size, FLASH_FW_MAX_SIZE);
1399 		(void) firmware_close(fw_hdl);
1400 		return (EFBIG);
1401 	}
1402 
1403 	unsigned char *fw_data = kmem_zalloc(fw_size, KM_SLEEP);
1404 	if (firmware_read(fw_hdl, 0, fw_data, fw_size) != 0) {
1405 		cxgb_printf(sc->dip, CE_WARN, "Failed to read from %s\n",
1406 		    fw_file);
1407 		(void) firmware_close(fw_hdl);
1408 		kmem_free(fw_data, fw_size);
1409 		return (EINVAL);
1410 	}
1411 	(void) firmware_close(fw_hdl);
1412 
1413 	const struct fw_hdr *hdr = (struct fw_hdr *)fw_data;
1414 	struct fw_info fi;
1415 	bzero(&fi, sizeof (fi));
1416 	fi.chip				= CHELSIO_CHIP_VERSION(sc->params.chip);
1417 	fi.fw_hdr.fw_ver		= hdr->fw_ver;
1418 	fi.fw_hdr.chip			= hdr->chip;
1419 	fi.fw_hdr.intfver_nic		= hdr->intfver_nic;
1420 	fi.fw_hdr.intfver_vnic		= hdr->intfver_vnic;
1421 	fi.fw_hdr.intfver_ofld		= hdr->intfver_ofld;
1422 	fi.fw_hdr.intfver_ri		= hdr->intfver_ri;
1423 	fi.fw_hdr.intfver_iscsipdu	= hdr->intfver_iscsipdu;
1424 	fi.fw_hdr.intfver_iscsi		= hdr->intfver_iscsi;
1425 	fi.fw_hdr.intfver_fcoepdu	= hdr->intfver_fcoepdu;
1426 	fi.fw_hdr.intfver_fcoe		= hdr->intfver_fcoe;
1427 
1428 	/* allocate memory to read the header of the firmware on the card */
1429 	struct fw_hdr *card_fw = kmem_zalloc(sizeof (struct fw_hdr), KM_SLEEP);
1430 
1431 	int reset = 1;
1432 	rc = -t4_prep_fw(sc, &fi, fw_data, fw_size, card_fw,
1433 	    sc->props.t4_fw_install, state, &reset);
1434 
1435 	kmem_free(card_fw, sizeof (*card_fw));
1436 	kmem_free(fw_data, fw_size);
1437 
1438 	if (rc != 0) {
1439 		cxgb_printf(sc->dip, CE_WARN,
1440 		    "failed to install firmware: %d", rc);
1441 		return (rc);
1442 	} else {
1443 		/* refresh */
1444 		(void) t4_check_fw_version(sc);
1445 	}
1446 
1447 	/* Reset device */
1448 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
1449 	if (rc != 0) {
1450 		cxgb_printf(sc->dip, CE_WARN,
1451 		    "firmware reset failed: %d.", rc);
1452 		if (rc != ETIMEDOUT && rc != EIO)
1453 			(void) t4_fw_bye(sc, sc->mbox);
1454 		return (rc);
1455 	}
1456 
1457 	/* Partition adapter resources as specified in the config file. */
1458 	if (sc->flags & TAF_MASTER_PF) {
1459 		/* Handle default vs special T4 config file */
1460 
1461 		rc = t4_partition_resources(sc);
1462 		if (rc != 0) {
1463 			return (rc);
1464 		}
1465 	}
1466 
1467 	sc->flags |= FW_OK;
1468 	return (0);
1469 }
1470 
1471 struct memwin {
1472 	uint32_t base;
1473 	uint32_t aperture;
1474 };
1475 
1476 static const struct memwin t4_memwin[] = {
1477 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
1478 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
1479 	{ MEMWIN2_BASE, MEMWIN2_APERTURE }
1480 };
1481 
1482 static const struct memwin t5_memwin[] = {
1483 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
1484 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
1485 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
1486 };
1487 
1488 #define	FW_PARAM_DEV(param) \
1489 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
1490 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
1491 #define	FW_PARAM_PFVF(param) \
1492 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
1493 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
1494 
1495 /*
1496  * Verify that the memory range specified by the memtype/offset/len pair is
1497  * valid and lies entirely within the memtype specified.  The global address of
1498  * the start of the range is returned in addr.
1499  */
1500 static int
t4_validate_mt_off_len(struct adapter * sc,int mtype,uint32_t off,int len,uint32_t * addr)1501 t4_validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, int len,
1502     uint32_t *addr)
1503 {
1504 	uint32_t em, addr_len, maddr, mlen;
1505 
1506 	/* Memory can only be accessed in naturally aligned 4 byte units */
1507 	if (off & 3 || len & 3 || len == 0)
1508 		return (EINVAL);
1509 
1510 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
1511 	switch (mtype) {
1512 		case MEM_EDC0:
1513 			if (!(em & F_EDRAM0_ENABLE))
1514 				return (EINVAL);
1515 			addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
1516 			maddr = G_EDRAM0_BASE(addr_len) << 20;
1517 			mlen = G_EDRAM0_SIZE(addr_len) << 20;
1518 			break;
1519 		case MEM_EDC1:
1520 			if (!(em & F_EDRAM1_ENABLE))
1521 				return (EINVAL);
1522 			addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
1523 			maddr = G_EDRAM1_BASE(addr_len) << 20;
1524 			mlen = G_EDRAM1_SIZE(addr_len) << 20;
1525 			break;
1526 		case MEM_MC:
1527 			if (!(em & F_EXT_MEM_ENABLE))
1528 				return (EINVAL);
1529 			addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
1530 			maddr = G_EXT_MEM_BASE(addr_len) << 20;
1531 			mlen = G_EXT_MEM_SIZE(addr_len) << 20;
1532 			break;
1533 		case MEM_MC1:
1534 			if (t4_cver_eq(sc, CHELSIO_T4) ||
1535 			    !(em & F_EXT_MEM1_ENABLE)) {
1536 				return (EINVAL);
1537 			}
1538 			addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
1539 			maddr = G_EXT_MEM1_BASE(addr_len) << 20;
1540 			mlen = G_EXT_MEM1_SIZE(addr_len) << 20;
1541 			break;
1542 		default:
1543 			return (EINVAL);
1544 	}
1545 
1546 	if (mlen > 0 && off < mlen && off + len <= mlen) {
1547 		*addr = maddr + off;    /* global address */
1548 		return (0);
1549 	}
1550 
1551 	return (EFAULT);
1552 }
1553 
1554 static void
t4_memwin_info(struct adapter * sc,int win,uint32_t * base,uint32_t * aperture)1555 t4_memwin_info(struct adapter *sc, int win, uint32_t *base, uint32_t *aperture)
1556 {
1557 	const struct memwin *mw;
1558 
1559 	if (t4_cver_eq(sc, CHELSIO_T4)) {
1560 		mw = &t4_memwin[win];
1561 	} else {
1562 		mw = &t5_memwin[win];
1563 	}
1564 
1565 	if (base != NULL)
1566 		*base = mw->base;
1567 	if (aperture != NULL)
1568 		*aperture = mw->aperture;
1569 }
1570 
1571 /*
1572  * Upload configuration file to card's memory.
1573  */
1574 static int
t4_upload_config_file(struct adapter * sc,uint32_t * mt,uint32_t * ma)1575 t4_upload_config_file(struct adapter *sc, uint32_t *mt, uint32_t *ma)
1576 {
1577 	int rc = 0;
1578 	size_t cflen, cfbaselen;
1579 	uint_t i, n;
1580 	uint32_t param, val, addr, mtype, maddr;
1581 	uint32_t off, mw_base, mw_aperture;
1582 	uint32_t *cfdata, *cfbase;
1583 	firmware_handle_t fw_hdl;
1584 	const char *cfg_file = NULL;
1585 
1586 	/* Figure out where the firmware wants us to upload it. */
1587 	param = FW_PARAM_DEV(CF);
1588 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
1589 	if (rc != 0) {
1590 		/* Firmwares without config file support will fail this way */
1591 		cxgb_printf(sc->dip, CE_WARN,
1592 		    "failed to query config file location: %d.\n", rc);
1593 		return (rc);
1594 	}
1595 	*mt = mtype = G_FW_PARAMS_PARAM_Y(val);
1596 	*ma = maddr = G_FW_PARAMS_PARAM_Z(val) << 16;
1597 
1598 	switch (CHELSIO_CHIP_VERSION(sc->params.chip)) {
1599 	case CHELSIO_T4:
1600 		cfg_file = "t4fw_cfg.txt";
1601 		break;
1602 	case CHELSIO_T5:
1603 		cfg_file = "t5fw_cfg.txt";
1604 		break;
1605 	case CHELSIO_T6:
1606 		cfg_file = "t6fw_cfg.txt";
1607 		break;
1608 	default:
1609 		cxgb_printf(sc->dip, CE_WARN, "Invalid Adapter detected\n");
1610 		return (EINVAL);
1611 	}
1612 
1613 	if (firmware_open(T4_PORT_NAME, cfg_file, &fw_hdl) != 0) {
1614 		cxgb_printf(sc->dip, CE_WARN, "Could not open %s\n", cfg_file);
1615 		return (EINVAL);
1616 	}
1617 
1618 	cflen = firmware_get_size(fw_hdl);
1619 	/*
1620 	 * Truncate the length to a multiple of uint32_ts. The configuration
1621 	 * text files have trailing comments (and hopefully always will) so
1622 	 * nothing important is lost.
1623 	 */
1624 	cflen &= ~3;
1625 
1626 	if (cflen > FLASH_CFG_MAX_SIZE) {
1627 		cxgb_printf(sc->dip, CE_WARN,
1628 		    "config file too long (%d, max allowed is %d).  ",
1629 		    cflen, FLASH_CFG_MAX_SIZE);
1630 		(void) firmware_close(fw_hdl);
1631 		return (EFBIG);
1632 	}
1633 
1634 	rc = t4_validate_mt_off_len(sc, mtype, maddr, cflen, &addr);
1635 	if (rc != 0) {
1636 		cxgb_printf(sc->dip, CE_WARN,
1637 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.  "
1638 		    "Will try to use the config on the card, if any.\n",
1639 		    __func__, mtype, maddr, cflen, rc);
1640 		(void) firmware_close(fw_hdl);
1641 		return (EFAULT);
1642 	}
1643 
1644 	cfbaselen = cflen;
1645 	cfbase = cfdata = kmem_zalloc(cflen, KM_SLEEP);
1646 	if (firmware_read(fw_hdl, 0, cfdata, cflen) != 0) {
1647 		cxgb_printf(sc->dip, CE_WARN, "Failed to read from %s\n",
1648 		    cfg_file);
1649 		(void) firmware_close(fw_hdl);
1650 		kmem_free(cfbase, cfbaselen);
1651 		return (EINVAL);
1652 	}
1653 	(void) firmware_close(fw_hdl);
1654 
1655 	t4_memwin_info(sc, 2, &mw_base, &mw_aperture);
1656 	while (cflen) {
1657 		off = t4_position_memwin(sc, 2, addr);
1658 		n = min(cflen, mw_aperture - off);
1659 		for (i = 0; i < n; i += 4)
1660 			t4_write_reg(sc, mw_base + off + i, *cfdata++);
1661 		cflen -= n;
1662 		addr += n;
1663 	}
1664 
1665 	kmem_free(cfbase, cfbaselen);
1666 
1667 	return (rc);
1668 }
1669 
1670 /*
1671  * Partition chip resources for use between various PFs, VFs, etc.  This is done
1672  * by uploading the firmware configuration file to the adapter and instructing
1673  * the firmware to process it.
1674  */
1675 static int
t4_partition_resources(struct adapter * sc)1676 t4_partition_resources(struct adapter *sc)
1677 {
1678 	int rc;
1679 	uint32_t mtype, maddr;
1680 
1681 	rc = t4_upload_config_file(sc, &mtype, &maddr);
1682 	if (rc != 0) {
1683 		mtype = FW_MEMTYPE_CF_FLASH;
1684 		maddr = t4_flash_cfg_addr(sc);
1685 	}
1686 
1687 	struct fw_caps_config_cmd caps;
1688 	bzero(&caps, sizeof (caps));
1689 	caps.op_to_write = BE_32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
1690 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
1691 	caps.cfvalid_to_len16 = BE_32(F_FW_CAPS_CONFIG_CMD_CFVALID |
1692 	    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
1693 	    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(maddr >> 16) |
1694 	    FW_LEN16(struct fw_caps_config_cmd));
1695 
1696 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof (caps), &caps);
1697 	if (rc != 0) {
1698 		cxgb_printf(sc->dip, CE_WARN,
1699 		    "failed to pre-process config file: %d.\n", rc);
1700 		return (rc);
1701 	}
1702 
1703 	if (caps.finicsum != caps.cfcsum) {
1704 		cxgb_printf(sc->dip, CE_WARN,
1705 		    "WARNING: config file checksum mismatch: %08x %08x\n",
1706 		    caps.finicsum, caps.cfcsum);
1707 	}
1708 	sc->cfcsum = caps.cfcsum;
1709 
1710 	/* Disable unused offloads and features */
1711 	caps.toecaps = 0;
1712 	caps.iscsicaps = 0;
1713 	caps.rdmacaps = 0;
1714 	caps.fcoecaps = 0;
1715 	caps.cryptocaps = 0;
1716 
1717 	/* TODO: Disable VNIC cap for now */
1718 	caps.niccaps &= BE_16(~FW_CAPS_CONFIG_NIC_VM);
1719 
1720 	caps.op_to_write = BE_32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
1721 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
1722 	caps.cfvalid_to_len16 = BE_32(FW_LEN16(caps));
1723 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof (caps), NULL);
1724 	if (rc != 0) {
1725 		cxgb_printf(sc->dip, CE_WARN,
1726 		    "failed to process config file: %d.\n", rc);
1727 		return (rc);
1728 	}
1729 
1730 	return (0);
1731 }
1732 
1733 /*
1734  * Tweak configuration based on module parameters, etc.  Most of these have
1735  * defaults assigned to them by Firmware Configuration Files (if we're using
1736  * them) but need to be explicitly set if we're using hard-coded
1737  * initialization.  But even in the case of using Firmware Configuration
1738  * Files, we'd like to expose the ability to change these via module
1739  * parameters so these are essentially common tweaks/settings for
1740  * Configuration Files and hard-coded initialization ...
1741  */
1742 static int
t4_init_adap_tweaks(struct adapter * sc)1743 t4_init_adap_tweaks(struct adapter *sc)
1744 {
1745 	int rx_dma_offset = 2; /* Offset of RX packets into DMA buffers */
1746 
1747 	/*
1748 	 * Fix up various Host-Dependent Parameters like Page Size, Cache
1749 	 * Line Size, etc.  The firmware default is for a 4KB Page Size and
1750 	 * 64B Cache Line Size ...
1751 	 */
1752 	(void) t4_fixup_host_params_compat(sc, PAGE_SIZE, _CACHE_LINE_SIZE,
1753 	    T5_LAST_REV);
1754 
1755 	t4_set_reg_field(sc, A_SGE_CONTROL, V_PKTSHIFT(M_PKTSHIFT),
1756 	    V_PKTSHIFT(rx_dma_offset));
1757 
1758 	return (0);
1759 }
1760 /*
1761  * Retrieve parameters that are needed (or nice to have) prior to calling
1762  * t4_sge_init and t4_fw_initialize.
1763  */
1764 static int
t4_init_get_params_pre(struct adapter * sc)1765 t4_init_get_params_pre(struct adapter *sc)
1766 {
1767 	int rc;
1768 	uint32_t param[2], val[2];
1769 
1770 	/*
1771 	 * Grab the raw VPD parameters.
1772 	 */
1773 	rc = -t4_get_raw_vpd_params(sc, &sc->params.vpd);
1774 	if (rc != 0) {
1775 		cxgb_printf(sc->dip, CE_WARN,
1776 		    "failed to query VPD parameters (pre_init): %d.\n", rc);
1777 		return (rc);
1778 	}
1779 
1780 	param[0] = FW_PARAM_DEV(PORTVEC);
1781 	param[1] = FW_PARAM_DEV(CCLK);
1782 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
1783 	if (rc != 0) {
1784 		cxgb_printf(sc->dip, CE_WARN,
1785 		    "failed to query parameters (pre_init): %d.\n", rc);
1786 		return (rc);
1787 	}
1788 
1789 	if (val[0] == 0) {
1790 		cxgb_printf(sc->dip, CE_WARN, "no usable ports");
1791 		return (ENODEV);
1792 	}
1793 
1794 	sc->params.portvec = val[0];
1795 	sc->params.nports = 0;
1796 	while (val[0]) {
1797 		sc->params.nports++;
1798 		val[0] &= val[0] - 1;
1799 	}
1800 	sc->params.vpd.cclk = val[1];
1801 
1802 	/* Read device log parameters. */
1803 	struct fw_devlog_cmd cmd;
1804 	bzero(&cmd, sizeof (cmd));
1805 	cmd.op_to_write = BE_32(V_FW_CMD_OP(FW_DEVLOG_CMD) |
1806 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
1807 	cmd.retval_len16 = BE_32(FW_LEN16(struct fw_devlog_cmd));
1808 
1809 	rc = -t4_wr_mbox(sc, sc->mbox, &cmd, sizeof (cmd), &cmd);
1810 	if (rc != 0) {
1811 		cxgb_printf(sc->dip, CE_WARN,
1812 		    "failed to get devlog parameters: %d.\n", rc);
1813 
1814 		/* devlog isn't critical for device operation */
1815 		bzero(&sc->params.devlog, sizeof (sc->params.devlog));
1816 		rc = 0;
1817 	} else {
1818 		const uint32_t info =
1819 		    BE_32(cmd.memtype_devlog_memaddr16_devlog);
1820 		struct devlog_params *dlog = &sc->params.devlog;
1821 
1822 		dlog->memtype = G_FW_DEVLOG_CMD_MEMTYPE_DEVLOG(info);
1823 		dlog->start = G_FW_DEVLOG_CMD_MEMADDR16_DEVLOG(info) << 4;
1824 		dlog->size = BE_32(cmd.memsize_devlog);
1825 	}
1826 
1827 	return (rc);
1828 }
1829 
1830 /*
1831  * Retrieve various parameters that are of interest to the driver.  The device
1832  * has been initialized by the firmware at this point.
1833  */
1834 static int
t4_init_get_params_post(struct adapter * sc)1835 t4_init_get_params_post(struct adapter *sc)
1836 {
1837 	int rc;
1838 	uint32_t param[4], val[4];
1839 
1840 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
1841 	param[1] = FW_PARAM_PFVF(EQ_START);
1842 	param[2] = FW_PARAM_PFVF(IQFLINT_END);
1843 	param[3] = FW_PARAM_PFVF(EQ_END);
1844 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
1845 	if (rc != 0) {
1846 		cxgb_printf(sc->dip, CE_WARN,
1847 		    "failed to query parameters (post_init): %d.\n", rc);
1848 		return (rc);
1849 	}
1850 
1851 	sc->sge.iqmap_start = val[0];
1852 	sc->sge.eqmap_start = val[1];
1853 	sc->sge.iqmap_sz = (val[2] - sc->sge.iqmap_start) + 1;
1854 	sc->sge.eqmap_sz = (val[3] - sc->sge.eqmap_start) + 1;
1855 
1856 	/* Check if DBQ timer is available for tracking egress completions */
1857 	param[0] = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
1858 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DBQ_TIMERTICK));
1859 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
1860 	if (rc == 0) {
1861 		sc->sge.dbq_timer_tick = val[0];
1862 		rc = t4_read_sge_dbqtimers(sc,
1863 		    ARRAY_SIZE(sc->sge.dbq_timers), sc->sge.dbq_timers);
1864 		if (rc == 0) {
1865 			sc->flags |= TAF_DBQ_TIMER;
1866 
1867 			/*
1868 			 * Expose DBQ timer values as property, converting them
1869 			 * to plain `int` as required.
1870 			 */
1871 			int tmp_encode[ARRAY_SIZE(sc->sge.dbq_timers)];
1872 			for (uint_t i = 0; i < ARRAY_SIZE(sc->sge.dbq_timers);
1873 			    i++) {
1874 				tmp_encode[i] = sc->sge.dbq_timers[i];
1875 			};
1876 			(void) ddi_prop_update_int_array(sc->dev, sc->dip,
1877 			    "tx-reclaim-timer-us-values",
1878 			    tmp_encode, SGE_NTIMERS);
1879 		} else {
1880 			sc->sge.dbq_timer_tick = 0;
1881 		}
1882 	}
1883 
1884 	/*
1885 	 * Now that we know if the DBQ timer is present, tune the properties for
1886 	 * hold-off parameter defaults.
1887 	 */
1888 	struct driver_properties *prp = &sc->props;
1889 	if ((sc->flags & TAF_DBQ_TIMER) != 0) {
1890 		/*
1891 		 * Choose default DBQ timer index to be closest to 100us.  With
1892 		 * that available, more aggressive coalescing on the FWQ is
1893 		 * unnecessary, so shorter hold-off parameters are fine there.
1894 		 */
1895 		prp->dbq_timer_idx = t4_choose_dbq_timer(sc, 100);
1896 		prp->fwq_tmr_idx = t4_choose_holdoff_timer(sc, 10);
1897 		prp->fwq_pktc_idx = t4_choose_holdoff_pktcnt(sc, -1);
1898 	} else {
1899 		/*
1900 		 * Without the DBQ timer, we fall back to the
1901 		 * CIDXFlushThresholdOverride mechanism for TX completions,
1902 		 * which can result in many more notifications, depending on the
1903 		 * traffic pattern.  More aggressive interrupt coalescing on the
1904 		 * firmware queue (where such notifications land) is recommended
1905 		 * to deal with it.
1906 		 *
1907 		 * Pick values closest to a hold-off of 100us and/or 32 entries.
1908 		 */
1909 		prp->fwq_tmr_idx = t4_choose_holdoff_timer(sc, 100);
1910 		prp->fwq_pktc_idx = t4_choose_holdoff_pktcnt(sc, 32);
1911 	}
1912 	sc->sge.fwq_tmr_idx = prp->fwq_tmr_idx;
1913 	sc->sge.fwq_pktc_idx = prp->fwq_pktc_idx;
1914 
1915 	rc = -t4_get_pfres(sc);
1916 	if (rc != 0) {
1917 		cxgb_printf(sc->dip, CE_WARN,
1918 		    "failed to query PF resource params: %d.\n", rc);
1919 		return (rc);
1920 	}
1921 
1922 	/* These are finalized by FW initialization, load their values now */
1923 	val[0] = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
1924 	sc->params.tp.tre = G_TIMERRESOLUTION(val[0]);
1925 	sc->params.tp.dack_re = G_DELAYEDACKRESOLUTION(val[0]);
1926 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
1927 	(void) t4_init_sge_params(sc);
1928 
1929 	return (0);
1930 }
1931 
1932 static int
t4_init_set_params(struct adapter * sc)1933 t4_init_set_params(struct adapter *sc)
1934 {
1935 	uint32_t param, val;
1936 
1937 	/* ask for encapsulated CPLs */
1938 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
1939 	val = 1;
1940 	(void) t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
1941 
1942 	return (0);
1943 }
1944 
1945 /* TODO: verify */
1946 static void
t4_setup_adapter_memwin(struct adapter * sc)1947 t4_setup_adapter_memwin(struct adapter *sc)
1948 {
1949 	pci_regspec_t *data;
1950 	int rc;
1951 	uint_t n;
1952 	uintptr_t bar0;
1953 	uintptr_t mem_win0_base, mem_win1_base, mem_win2_base;
1954 	uintptr_t mem_win2_aperture;
1955 
1956 	rc = ddi_prop_lookup_int_array(DDI_DEV_T_ANY, sc->dip,
1957 	    DDI_PROP_DONTPASS, "assigned-addresses", (int **)&data, &n);
1958 	if (rc != DDI_SUCCESS) {
1959 		cxgb_printf(sc->dip, CE_WARN,
1960 		    "failed to lookup \"assigned-addresses\" property: %d", rc);
1961 		return;
1962 	}
1963 	n /= sizeof (*data);
1964 
1965 	bar0 = ((uint64_t)data[0].pci_phys_mid << 32) | data[0].pci_phys_low;
1966 	ddi_prop_free(data);
1967 
1968 	if (t4_cver_eq(sc, CHELSIO_T4)) {
1969 		mem_win0_base = bar0 + MEMWIN0_BASE;
1970 		mem_win1_base = bar0 + MEMWIN1_BASE;
1971 		mem_win2_base = bar0 + MEMWIN2_BASE;
1972 		mem_win2_aperture = MEMWIN2_APERTURE;
1973 	} else {
1974 		/* For T5, only relative offset inside the PCIe BAR is passed */
1975 		mem_win0_base = MEMWIN0_BASE;
1976 		mem_win1_base = MEMWIN1_BASE;
1977 		mem_win2_base = MEMWIN2_BASE_T5;
1978 		mem_win2_aperture = MEMWIN2_APERTURE_T5;
1979 	}
1980 
1981 	t4_write_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 0),
1982 	    mem_win0_base | V_BIR(0) |
1983 	    V_WINDOW(ilog2(MEMWIN0_APERTURE) - 10));
1984 
1985 	t4_write_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 1),
1986 	    mem_win1_base | V_BIR(0) |
1987 	    V_WINDOW(ilog2(MEMWIN1_APERTURE) - 10));
1988 
1989 	t4_write_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2),
1990 	    mem_win2_base | V_BIR(0) |
1991 	    V_WINDOW(ilog2(mem_win2_aperture) - 10));
1992 
1993 	/* flush */
1994 	(void) t4_read_reg(sc,
1995 	    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
1996 }
1997 
1998 /*
1999  * Positions the memory window such that it can be used to access the specified
2000  * address in the chip's address space.  The return value is the offset of addr
2001  * from the start of the window.
2002  */
2003 static uint32_t
t4_position_memwin(struct adapter * sc,int n,uint32_t addr)2004 t4_position_memwin(struct adapter *sc, int n, uint32_t addr)
2005 {
2006 	uint32_t start, pf;
2007 	uint32_t reg;
2008 
2009 	if (addr & 3) {
2010 		cxgb_printf(sc->dip, CE_WARN,
2011 		    "addr (0x%x) is not at a 4B boundary.\n", addr);
2012 		return (EFAULT);
2013 	}
2014 
2015 	if (t4_cver_eq(sc, CHELSIO_T4)) {
2016 		pf = 0;
2017 		start = addr & ~0xf;    /* start must be 16B aligned */
2018 	} else {
2019 		pf = V_PFNUM(sc->pf);
2020 		start = addr & ~0x7f;   /* start must be 128B aligned */
2021 	}
2022 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, n);
2023 
2024 	t4_write_reg(sc, reg, start | pf);
2025 	(void) t4_read_reg(sc, reg);
2026 
2027 	return (addr - start);
2028 }
2029 
2030 static int
prop_lookup_int(struct adapter * sc,char * name,int defval)2031 prop_lookup_int(struct adapter *sc, char *name, int defval)
2032 {
2033 	int rc;
2034 
2035 	rc = ddi_prop_get_int(sc->dev, sc->dip, DDI_PROP_DONTPASS, name, -1);
2036 	if (rc != -1)
2037 		return (rc);
2038 
2039 	return (ddi_prop_get_int(DDI_DEV_T_ANY, sc->dip, DDI_PROP_DONTPASS,
2040 	    name, defval));
2041 }
2042 
2043 static bool
prop_lookup_bool(struct adapter * sc,char * name,bool defval)2044 prop_lookup_bool(struct adapter *sc, char *name, bool defval)
2045 {
2046 	int rc;
2047 
2048 	rc = ddi_prop_get_int(sc->dev, sc->dip, DDI_PROP_DONTPASS, name, -1);
2049 	if (rc == -1) {
2050 		rc = ddi_prop_get_int(DDI_DEV_T_ANY, sc->dip, DDI_PROP_DONTPASS,
2051 		    name, -1);
2052 	}
2053 
2054 	if (rc != -1) {
2055 		return (rc != 0);
2056 	} else {
2057 		return (defval);
2058 	}
2059 }
2060 
2061 const uint_t t4_holdoff_timer_default[SGE_NTIMERS] = {5, 10, 20, 50, 100, 200};
2062 const uint_t t4_holdoff_pktcnt_default[SGE_NCOUNTERS] = {1, 8, 16, 32};
2063 
2064 static void
t4_init_driver_props(struct adapter * sc)2065 t4_init_driver_props(struct adapter *sc)
2066 {
2067 	struct driver_properties *p = &sc->props;
2068 	dev_t dev = sc->dev;
2069 	dev_info_t *dip = sc->dip;
2070 	int val;
2071 
2072 	/*
2073 	 * For now, just use the defaults for the hold-off timers and counters.
2074 	 *
2075 	 * They can be turned back into writable properties if/when there is a
2076 	 * demonstrable need.
2077 	 */
2078 	for (uint_t i = 0; i < SGE_NTIMERS; i++) {
2079 		p->holdoff_timer_us[i] = t4_holdoff_timer_default[i];
2080 	}
2081 	for (uint_t i = 0; i < SGE_NCOUNTERS; i++) {
2082 		p->holdoff_pktcnt[i] = t4_holdoff_pktcnt_default[i];
2083 	}
2084 	(void) ddi_prop_update_int_array(dev, dip, "holdoff-timer-us-values",
2085 	    (int *)p->holdoff_timer_us, SGE_NTIMERS);
2086 	(void) ddi_prop_update_int_array(dev, dip, "holdoff-pkt-counter-values",
2087 	    (int *)p->holdoff_pktcnt, SGE_NCOUNTERS);
2088 
2089 	p->ethq_tmr_idx = prop_lookup_int(sc, "holdoff-timer-idx", 0);
2090 	p->ethq_pktc_idx = prop_lookup_int(sc, "holdoff-pktc-idx", 2);
2091 
2092 	(void) ddi_prop_update_int(dev, dip, "holdoff-timer-idx",
2093 	    p->ethq_tmr_idx);
2094 	(void) ddi_prop_update_int(dev, dip, "holdoff-pktc-idx",
2095 	    p->ethq_pktc_idx);
2096 
2097 	/* The size (number of host credits) of the tx queue. */
2098 	val = prop_lookup_int(sc, "qsize-txq", T4_TX_DEF_QSIZE);
2099 	p->qsize_txq = MAX(val, 128);
2100 	p->qsize_txq = MIN(p->qsize_txq, T4_MAX_EQ_SIZE);
2101 	if (p->qsize_txq != val) {
2102 		cxgb_printf(dip, CE_WARN,
2103 		    "using %d instead of %d as the tx queue size",
2104 		    p->qsize_txq, val);
2105 	}
2106 	(void) ddi_prop_update_int(dev, dip, "qsize-txq", p->qsize_txq);
2107 
2108 	/*
2109 	 * The size (number of entries/host credits) of the rx queue. The device
2110 	 * requires that all IQs be sized to a multiple of 16.
2111 	 */
2112 	val = prop_lookup_int(sc, "qsize-rxq", T4_RX_DEF_QSIZE);
2113 	p->qsize_rxq = MAX(val, 128) & ~15;
2114 	p->qsize_rxq = MIN(p->qsize_rxq, SGE_MAX_IQ_SIZE);
2115 	if (p->qsize_rxq != val) {
2116 		cxgb_printf(dip, CE_WARN,
2117 		    "using %u instead of %d as the rx queue size",
2118 		    p->qsize_rxq, val);
2119 	}
2120 	(void) ddi_prop_update_int(dev, dip, "qsize-rxq", p->qsize_rxq);
2121 
2122 	p->write_combine = prop_lookup_bool(sc, "write-combine", true);
2123 	(void) ddi_prop_update_int(dev, dip, "write-combine",
2124 	    p->write_combine ? 1 : 0);
2125 
2126 	p->t4_fw_install = prop_lookup_int(sc, "t4_fw_install", 1);
2127 	if (p->t4_fw_install != 0 && p->t4_fw_install != 2)
2128 		p->t4_fw_install = 1;
2129 	(void) ddi_prop_update_int(dev, dip, "t4_fw_install", p->t4_fw_install);
2130 }
2131 
2132 /*
2133  * Permit artificial clamping of interrupts for device.
2134  * Provided mainly for development and testing purposes.
2135  */
2136 static int t4_intr_count_clamp = 0;
2137 
2138 /*
2139  * Queue counts to allocate per-port based on device speed.
2140  *
2141  * These have been picked somewhat arbitrarily, and should be further
2142  * scrutinized with additional testing.
2143  */
2144 #define	T4_QCNT(speed, num)	[speed] = { speed, num, num }
2145 static const struct t4_queue_count {
2146 	t4_port_speed_t tqc_speed;
2147 	uint_t		tqc_rxq_count;
2148 	uint_t		tqc_txq_count;
2149 } t4_queue_counts[] = {
2150 	T4_QCNT(TPS_1G, 2),
2151 	T4_QCNT(TPS_10G, 8),
2152 	T4_QCNT(TPS_25G, 16),
2153 	T4_QCNT(TPS_40G, 24),
2154 	T4_QCNT(TPS_50G, 24),
2155 	T4_QCNT(TPS_100G, 32),
2156 	T4_QCNT(TPS_200G, 48),
2157 	T4_QCNT(TPS_400G, 64),
2158 };
2159 
2160 static int
t4_cfg_intrs_queues(struct adapter * sc)2161 t4_cfg_intrs_queues(struct adapter *sc)
2162 {
2163 	struct t4_intrs_queues *iaq = &sc->intr_queue_cfg;
2164 	int rc;
2165 
2166 	bzero(iaq, sizeof (*iaq));
2167 
2168 	int supported_itypes;
2169 	rc = ddi_intr_get_supported_types(sc->dip, &supported_itypes);
2170 	if (rc != DDI_SUCCESS) {
2171 		cxgb_printf(sc->dip, CE_WARN,
2172 		    "failed to determine supported interrupt types: %d", rc);
2173 		return (rc);
2174 	}
2175 
2176 	const int intr_types[] = {
2177 		DDI_INTR_TYPE_MSIX, DDI_INTR_TYPE_MSI, DDI_INTR_TYPE_FIXED,
2178 	};
2179 	const char *intr_str[] = { "MSI-X", "MSI", "Fixed" };
2180 	int itype = -1;
2181 
2182 	for (uint_t i = 0; i < ARRAY_SIZE(intr_types); i++) {
2183 		itype = intr_types[i];
2184 		if ((itype & supported_itypes) == 0) {
2185 			continue;
2186 		}
2187 
2188 		rc = ddi_intr_get_navail(sc->dip, itype, &iaq->intr_avail);
2189 		if (rc != DDI_SUCCESS || iaq->intr_avail < 0) {
2190 			cxgb_printf(sc->dip, CE_WARN, "failed to query "
2191 			    "available interrupts for type %s: %d", intr_str[i],
2192 			    rc);
2193 			continue;
2194 		}
2195 
2196 		/*
2197 		 * The device error and FWQ interrupts are hard-coded to indexes
2198 		 * 0 and 1, respectively.  We require at least two interrupts be
2199 		 * available for MSI(-X) in order to cover both of those cases.
2200 		 */
2201 		if (iaq->intr_avail >= 2 ||
2202 		    (iaq->intr_avail == 1 && itype == DDI_INTR_TYPE_FIXED)) {
2203 			break;
2204 		}
2205 	}
2206 
2207 	if (iaq->intr_avail == 0) {
2208 		cxgb_printf(sc->dip, CE_WARN, "failed to get any interrupts "
2209 		    "after querying all types");
2210 		return (rc);
2211 	}
2212 
2213 	ASSERT3S(iaq->intr_avail, >, 0);
2214 	iaq->intr_type = itype;
2215 	iaq->intr_count = iaq->intr_avail;
2216 
2217 	/* Permit artificial clamping of consumed interrupts. */
2218 	if (t4_intr_count_clamp > 1) {
2219 		iaq->intr_count = MIN(iaq->intr_avail, t4_intr_count_clamp);
2220 	}
2221 
2222 	const uint_t port_count = sc->params.nports;
2223 
2224 	iaq->intr_per_port = 0;
2225 	/* One IQ for the FWQ */
2226 	iaq->num_iqs = 1;
2227 
2228 	if (iaq->intr_count == 1) {
2229 		iaq->intr_plan = TIP_SINGLE;
2230 	} else if (iaq->intr_count == 2 || iaq->intr_count < (port_count + 2)) {
2231 		iaq->intr_plan = TIP_ERR_QUEUES;
2232 	} else {
2233 		/*
2234 		 * We know the interrupt count is at least equal to
2235 		 * port_count+2, and thus we should always have at least
2236 		 * one event interrupt per port.
2237 		 */
2238 		VERIFY(iaq->intr_count >= (port_count + 2));
2239 		iaq->intr_plan = TIP_PER_PORT;
2240 		iaq->intr_per_port = (iaq->intr_count - 2) / port_count;
2241 		VERIFY3U(iaq->intr_per_port, >, 0);
2242 		iaq->num_iqs += iaq->intr_per_port * port_count;
2243 	}
2244 
2245 	const struct pf_resources *pfres = &sc->params.pfres;
2246 	if (pfres->niqflint <= 1) {
2247 		/* We cannot achieve much with a single IQ */
2248 		cxgb_printf(sc->dip, CE_WARN,
2249 		    "inadequate IQ resources available");
2250 		return (DDI_FAILURE);
2251 	}
2252 
2253 	const uint_t port_iqs = pfres->niqflint - iaq->num_iqs;
2254 	/*
2255 	 * Every RX queue needs an IQ capable of interrupts (for the receive
2256 	 * notifications) as well as an EQ (for posting the freelist entries to
2257 	 * the device.  Half of the total EQs are left for TXQs.
2258 	 */
2259 	const uint_t max_rxq = MIN(port_iqs, pfres->neq / 2);
2260 
2261 	/* Every TX queue needs an ethernet-capable EQ. */
2262 	const uint_t max_txq = MIN(pfres->nethctrl, pfres->neq / 2);
2263 
2264 	if ((max_rxq / port_count) == 0) {
2265 		cxgb_printf(sc->dip, CE_WARN,
2266 		    "inadequate RX queue resources available");
2267 		return (DDI_FAILURE);
2268 	} else if ((max_txq / port_count) == 0) {
2269 		cxgb_printf(sc->dip, CE_WARN,
2270 		    "inadequate TX queue resources available");
2271 		return (DDI_FAILURE);
2272 	}
2273 
2274 	/* Clamp max queue counts to number of CPUs */
2275 	iaq->port_max_rxq = MIN(max_rxq, ncpus);
2276 	iaq->port_max_txq = MIN(max_txq, ncpus);
2277 
2278 	VERIFY(iaq->intr_count > 0);
2279 	VERIFY(iaq->port_max_rxq != 0);
2280 	VERIFY(iaq->port_max_txq != 0);
2281 	VERIFY(iaq->num_iqs != 0);
2282 
2283 	/*
2284 	 * Determine per-port queue counts based on maximum port speed.
2285 	 *
2286 	 * This is a bit unfortunate, since there does not seem to be a way to
2287 	 * query the maximum possible speed for a port independent of any
2288 	 * installed transceiver.  If a transceiver of lesser speed capability
2289 	 * is installed in a port, that port will clamp its own reported
2290 	 * capabilities to those of the transceiver.
2291 	 *
2292 	 * Our compromise is to size queue allocations based on the fastest port
2293 	 * we can find.  This will be less than ideal for adapters with
2294 	 * heterogeneous port configurations or systems where transceivers of
2295 	 * differing speed capabilities are swapped in after the driver
2296 	 * initializes the adapter(s).
2297 	 */
2298 	t4_port_speed_t max_speed = TPS_1G;
2299 	for (uint_t i = 0; i < port_count; i++) {
2300 		max_speed = MAX(max_speed, t4_port_speed(sc->port[i]));
2301 	}
2302 	ASSERT(max_speed < ARRAY_SIZE(t4_queue_counts));
2303 	const struct t4_queue_count *qc = &t4_queue_counts[max_speed];
2304 
2305 	uint_t rxq_idx = 0, txq_idx = 0;
2306 	for (uint_t i = 0; i < port_count; i++) {
2307 		struct port_info *pi = sc->port[i];
2308 
2309 		/* Clamp to per-port maximums */
2310 		pi->rxq_count = MIN(qc->tqc_rxq_count, iaq->port_max_rxq);
2311 		pi->txq_count = MIN(qc->tqc_txq_count, iaq->port_max_txq);
2312 
2313 		pi->rxq_start = rxq_idx;
2314 		pi->txq_start = txq_idx;
2315 		rxq_idx += pi->rxq_count;
2316 		txq_idx += pi->txq_count;
2317 	}
2318 
2319 	struct sge_info *sge = &sc->sge;
2320 	sge->rxq_count = rxq_idx;
2321 	sge->txq_count = txq_idx;
2322 
2323 	cxgb_printf(sc->dip, CE_NOTE, "(%u rxq, %u txq total) %d %s.",
2324 	    rxq_idx, txq_idx, iaq->intr_count,
2325 	    iaq->intr_type == DDI_INTR_TYPE_MSIX ? "MSI-X interrupts" :
2326 	    iaq->intr_type == DDI_INTR_TYPE_MSI ? "MSI interrupts" :
2327 	    "fixed interrupt");
2328 
2329 	return (DDI_SUCCESS);
2330 }
2331 
2332 static int
t4_setup_port_intrs(struct adapter * sc,int * handlers)2333 t4_setup_port_intrs(struct adapter *sc, int *handlers)
2334 {
2335 	int rc = 0;
2336 	const struct t4_intrs_queues *iaq = &sc->intr_queue_cfg;
2337 
2338 	for (uint_t i = 0; i < sc->params.nports; i++) {
2339 		struct port_info *port = sc->port[i];
2340 
2341 		port->intr_iqs = kmem_zalloc(iaq->intr_per_port *
2342 		    sizeof (t4_sge_iq_t), KM_SLEEP);
2343 
2344 		for (uint_t j = 0; j < iaq->intr_per_port; j++) {
2345 			uint_t intr_idx = 2 + (i * iaq->intr_per_port) + j;
2346 			VERIFY3S(intr_idx, <, iaq->intr_count);
2347 			ddi_intr_handle_t ihdl = sc->intr_handle[intr_idx];
2348 			rc = ddi_intr_add_handler(ihdl, t4_intr_port_queue,
2349 			    &port->intr_iqs[j], NULL);
2350 			if (rc != DDI_SUCCESS) {
2351 				/*
2352 				 * Previously installed handlers are cleaned up
2353 				 * by the parent function.
2354 				 */
2355 				cxgb_printf(sc->dip, CE_WARN, "failed to add "
2356 				    "interrupt handler %u for type: %d plan: "
2357 				    "%d: %d", intr_idx, iaq->intr_type,
2358 				    iaq->intr_plan, rc);
2359 				return (rc);
2360 			}
2361 			*handlers += 1;
2362 		}
2363 	}
2364 
2365 	return (DDI_SUCCESS);
2366 }
2367 
2368 static int
t4_setup_intrs(struct adapter * sc)2369 t4_setup_intrs(struct adapter *sc)
2370 {
2371 	const struct t4_intrs_queues *iaq = &sc->intr_queue_cfg;
2372 	const int intr_count = iaq->intr_count;
2373 	const int intr_type = iaq->intr_type;
2374 	int allocated = 0;
2375 	int handlers = 0;
2376 
2377 	int rc = ddi_intr_alloc(sc->dip, sc->intr_handle, intr_type, 0,
2378 	    intr_count, &allocated, DDI_INTR_ALLOC_STRICT);
2379 	if (rc != DDI_SUCCESS) {
2380 		cxgb_printf(sc->dip, CE_WARN,
2381 		    "failed to allocate %d interrupt(s) of type %d: %d, %d",
2382 		    intr_count, intr_type, rc, allocated);
2383 		goto fail;
2384 	}
2385 
2386 	VERIFY3U(intr_count, ==, allocated); /* allocation was STRICT */
2387 
2388 	rc = ddi_intr_get_cap(sc->intr_handle[0], &sc->intr_cap);
2389 	if (rc != DDI_SUCCESS) {
2390 		cxgb_printf(sc->dip, CE_WARN, "failed to get interrupt "
2391 		    "capabilities for type %d: %d", intr_type, rc);
2392 		goto fail;
2393 	}
2394 
2395 	rc = ddi_intr_get_pri(sc->intr_handle[0], &sc->intr_pri);
2396 	if (rc != DDI_SUCCESS) {
2397 		cxgb_printf(sc->dip, CE_WARN, "failed to get interrupt "
2398 		    "priority for type %d: %d", intr_type, rc);
2399 		goto fail;
2400 	}
2401 
2402 	switch (iaq->intr_plan) {
2403 	case TIP_SINGLE:
2404 		ASSERT3U(intr_count, ==, 1);
2405 		rc = ddi_intr_add_handler(sc->intr_handle[0], t4_intr_all, sc,
2406 		    NULL);
2407 		if (rc != DDI_SUCCESS) {
2408 			cxgb_printf(sc->dip, CE_WARN, "failed to add interrupt "
2409 			    "handler %u for type: %d plan: %d: %d", handlers,
2410 			    intr_type, iaq->intr_plan, rc);
2411 			goto fail;
2412 		}
2413 		handlers++;
2414 		break;
2415 
2416 	case TIP_ERR_QUEUES:
2417 		VERIFY3U(intr_count, ==, 2);
2418 		rc = ddi_intr_add_handler(sc->intr_handle[0], t4_intr_err, sc,
2419 		    NULL);
2420 		if (rc != DDI_SUCCESS) {
2421 			cxgb_printf(sc->dip, CE_WARN, "failed to add interrupt "
2422 			    "handler %u for type: %d plan: %d: %d", handlers,
2423 			    intr_type, iaq->intr_plan, rc);
2424 			goto fail;
2425 		}
2426 		handlers++;
2427 
2428 		rc = ddi_intr_add_handler(sc->intr_handle[1], t4_intr_fwq, sc,
2429 		    NULL);
2430 		if (rc != DDI_SUCCESS) {
2431 			cxgb_printf(sc->dip, CE_WARN, "failed to add interrupt "
2432 			    "handler %u for type: %d plan: %d: %d", handlers,
2433 			    intr_type, iaq->intr_plan, rc);
2434 			goto fail;
2435 		}
2436 		handlers++;
2437 		break;
2438 
2439 	case TIP_PER_PORT:
2440 		VERIFY3U(intr_count, >=, 2 + sc->params.nports);
2441 		rc = ddi_intr_add_handler(sc->intr_handle[0], t4_intr_err, sc,
2442 		    NULL);
2443 		if (rc != DDI_SUCCESS) {
2444 			cxgb_printf(sc->dip, CE_WARN, "failed to add interrupt "
2445 			    "handler %u for type: %d plan: %d: %d", handlers,
2446 			    intr_type, iaq->intr_plan, rc);
2447 			goto fail;
2448 		}
2449 		handlers++;
2450 
2451 		rc =  ddi_intr_add_handler(sc->intr_handle[1], t4_intr_fwq, sc,
2452 		    NULL);
2453 		if (rc != DDI_SUCCESS) {
2454 			cxgb_printf(sc->dip, CE_WARN, "failed to add interrupt "
2455 			    "handler %u for type: %d plan: %d: %d", handlers,
2456 			    intr_type, iaq->intr_plan, rc);
2457 			goto fail;
2458 		}
2459 		handlers++;
2460 
2461 		rc = t4_setup_port_intrs(sc, &handlers);
2462 
2463 		if (rc != DDI_SUCCESS) {
2464 			goto fail;
2465 		}
2466 
2467 		break;
2468 	}
2469 
2470 	return (DDI_SUCCESS);
2471 
2472 fail:
2473 	for (int i = 0; i < handlers; i++) {
2474 		rc = ddi_intr_remove_handler(sc->intr_handle[i]);
2475 		if (rc != DDI_SUCCESS) {
2476 			/*
2477 			 * We tried our best, the only thing left is to log the
2478 			 * failure and move on.
2479 			 */
2480 			cxgb_printf(sc->dip, CE_WARN, "failed to remove "
2481 			    "interrupt handler %d for type: %d plan: %d: %d", i,
2482 			    intr_type, iaq->intr_plan, rc);
2483 		}
2484 	}
2485 
2486 	for (int i = 0; i < allocated; i++) {
2487 		rc = ddi_intr_free(sc->intr_handle[i]);
2488 		if (rc != DDI_SUCCESS) {
2489 			cxgb_printf(sc->dip, CE_WARN, "failed to free "
2490 			    "interrupt %d for type: %d plan: %d: %d", i,
2491 			    intr_type, iaq->intr_plan, rc);
2492 		}
2493 	}
2494 
2495 	return (DDI_FAILURE);
2496 }
2497 
2498 static int
t4_add_child_node(struct adapter * sc,uint_t idx)2499 t4_add_child_node(struct adapter *sc, uint_t idx)
2500 {
2501 
2502 	if (idx >= sc->params.nports)
2503 		return (EINVAL);
2504 
2505 	struct port_info *pi = sc->port[idx];
2506 	if (pi == NULL) {
2507 		/* t4_port_init failed earlier */
2508 		return (ENODEV);
2509 	}
2510 
2511 	PORT_LOCK(pi);
2512 	if (pi->dip != NULL) {
2513 		PORT_UNLOCK(pi);
2514 		/* EEXIST really, but then bus_config fails */
2515 		return (0);
2516 	}
2517 
2518 	const int rc =
2519 	    ndi_devi_alloc(sc->dip, T4_PORT_NAME, DEVI_SID_NODEID, &pi->dip);
2520 	if (rc != DDI_SUCCESS || pi->dip == NULL) {
2521 		PORT_UNLOCK(pi);
2522 		return (ENOMEM);
2523 	}
2524 
2525 	(void) ddi_set_parent_data(pi->dip, pi);
2526 	(void) ndi_devi_bind_driver(pi->dip, 0);
2527 
2528 	PORT_UNLOCK(pi);
2529 	return (0);
2530 }
2531 
2532 static int
t4_remove_child_node(struct adapter * sc,uint_t idx)2533 t4_remove_child_node(struct adapter *sc, uint_t idx)
2534 {
2535 	if (idx >= sc->params.nports)
2536 		return (EINVAL);
2537 
2538 	struct port_info *pi = sc->port[idx];
2539 	if (pi == NULL)
2540 		return (ENODEV);
2541 
2542 	PORT_LOCK(pi);
2543 	if (pi->dip == NULL) {
2544 		PORT_UNLOCK(pi);
2545 		return (ENODEV);
2546 	}
2547 
2548 	const int rc = ndi_devi_free(pi->dip);
2549 	if (rc == 0)
2550 		pi->dip = NULL;
2551 
2552 	PORT_UNLOCK(pi);
2553 	return (rc);
2554 }
2555 
2556 struct t4_port_speed_def {
2557 	uint32_t	tpsd_cap;
2558 	t4_port_speed_t	tpsd_speed;
2559 	const char	*tpsd_name;
2560 };
2561 #define	T4_PORT_SPEED_DEF(speed)			\
2562 {							\
2563 	.tpsd_cap = FW_PORT_CAP32_SPEED_ ## speed,	\
2564 	.tpsd_speed = TPS_ ## speed,			\
2565 	.tpsd_name = #speed,				\
2566 }
2567 
2568 static const struct t4_port_speed_def t4_port_speeds[] = {
2569 	T4_PORT_SPEED_DEF(400G),
2570 	T4_PORT_SPEED_DEF(200G),
2571 	T4_PORT_SPEED_DEF(100G),
2572 	T4_PORT_SPEED_DEF(50G),
2573 	T4_PORT_SPEED_DEF(40G),
2574 	T4_PORT_SPEED_DEF(25G),
2575 	T4_PORT_SPEED_DEF(10G),
2576 	T4_PORT_SPEED_DEF(1G),
2577 };
2578 
2579 /*
2580  * Get maximum advertised speed of this port.
2581  *
2582  * This is, unfortunately, impacted by the installed transceiver at the time of
2583  * query.
2584  */
2585 static t4_port_speed_t
t4_port_speed(const struct port_info * pi)2586 t4_port_speed(const struct port_info *pi)
2587 {
2588 	ASSERT(pi != NULL);
2589 
2590 	const uint32_t pcap = pi->link_cfg.pcaps;
2591 	for (uint_t i = 0; i < ARRAY_SIZE(t4_port_speeds); i++) {
2592 		if (t4_port_speeds[i].tpsd_cap & pcap) {
2593 			return (t4_port_speeds[i].tpsd_speed);
2594 		}
2595 	}
2596 
2597 	/* Fall back to 1G for unknown speeds */
2598 	return (TPS_1G);
2599 }
2600 
2601 static const char *
t4_port_speed_name(const struct port_info * pi)2602 t4_port_speed_name(const struct port_info *pi)
2603 {
2604 	if (pi == NULL) {
2605 		return ("-");
2606 	}
2607 
2608 	const uint32_t pcap = pi->link_cfg.pcaps;
2609 	for (uint_t i = 0; i < ARRAY_SIZE(t4_port_speeds); i++) {
2610 		if (t4_port_speeds[i].tpsd_cap & pcap) {
2611 			return (t4_port_speeds[i].tpsd_name);
2612 		}
2613 	}
2614 
2615 	return ("-");
2616 }
2617 
2618 #define	KS_INIT_U64(kstatp,  n)	\
2619 	kstat_named_init(&kstatp->n, #n, KSTAT_DATA_UINT64)
2620 #define	KS_INIT_CHAR(kstatp, n)	\
2621 	kstat_named_init(&kstatp->n, #n, KSTAT_DATA_CHAR)
2622 #define	KS_INIT_STR(kstatp, n)	\
2623 	kstat_named_init(&kstatp->n, #n, KSTAT_DATA_STRING)
2624 #define	KS_SET_U64(kstatp, n, v)	kstatp->n.value.ul = (v)
2625 #define	KS_SET_CHAR(kstatp, n, ...)	\
2626 	(void) snprintf(kstatp->n.value.c, 16,  __VA_ARGS__)
2627 #define	KS_SET_STR(kstatp, n, v)	\
2628 	kstat_named_setstr(&kstatp->n, v)
2629 
2630 /*
2631  * t4nex:X:config
2632  */
2633 struct t4_kstats {
2634 	kstat_named_t chip_ver;
2635 	kstat_named_t fw_vers;
2636 	kstat_named_t tp_vers;
2637 	kstat_named_t driver_version;
2638 	kstat_named_t serial_number;
2639 	kstat_named_t ec_level;
2640 	kstat_named_t id;
2641 	kstat_named_t core_clock;
2642 	kstat_named_t port_cnt;
2643 	kstat_named_t port_type;
2644 };
2645 
2646 static kstat_t *
t4_setup_kstats(struct adapter * sc)2647 t4_setup_kstats(struct adapter *sc)
2648 {
2649 	const ulong_t ndata = sizeof (struct t4_kstats) /
2650 	    sizeof (kstat_named_t);
2651 	kstat_t *ksp = kstat_create(T4_NEXUS_NAME, ddi_get_instance(sc->dip),
2652 	    "config", "nexus", KSTAT_TYPE_NAMED, ndata, 0);
2653 	if (ksp == NULL) {
2654 		cxgb_printf(sc->dip, CE_WARN, "failed to initialize kstats.");
2655 		return (NULL);
2656 	}
2657 
2658 	struct t4_kstats *kstatp = (struct t4_kstats *)ksp->ks_data;
2659 
2660 	KS_INIT_U64(kstatp, chip_ver);
2661 	KS_INIT_CHAR(kstatp, fw_vers);
2662 	KS_INIT_CHAR(kstatp, tp_vers);
2663 	KS_INIT_CHAR(kstatp, driver_version);
2664 	KS_INIT_STR(kstatp, serial_number);
2665 	KS_INIT_STR(kstatp, ec_level);
2666 	KS_INIT_STR(kstatp, id);
2667 	KS_INIT_U64(kstatp, core_clock);
2668 	KS_INIT_U64(kstatp, port_cnt);
2669 	KS_INIT_CHAR(kstatp, port_type);
2670 
2671 	KS_SET_U64(kstatp, chip_ver, sc->params.chip);
2672 	KS_SET_CHAR(kstatp, fw_vers, "%d.%d.%d.%d",
2673 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
2674 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
2675 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
2676 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
2677 	KS_SET_CHAR(kstatp, tp_vers, "%d.%d.%d.%d",
2678 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
2679 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
2680 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
2681 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
2682 	KS_SET_CHAR(kstatp, driver_version, DRV_VERSION);
2683 
2684 	const struct vpd_params *vpd = &sc->params.vpd;
2685 	KS_SET_STR(kstatp, serial_number, (const char *)vpd->sn);
2686 	KS_SET_STR(kstatp, ec_level, (const char *)vpd->ec);
2687 	KS_SET_STR(kstatp, id, (const char *)vpd->id);
2688 	KS_SET_U64(kstatp, core_clock, vpd->cclk);
2689 	KS_SET_U64(kstatp, port_cnt, sc->params.nports);
2690 
2691 	KS_SET_CHAR(kstatp, port_type, "%s/%s/%s/%s",
2692 	    t4_port_speed_name(sc->port[0]),
2693 	    t4_port_speed_name(sc->port[1]),
2694 	    t4_port_speed_name(sc->port[2]),
2695 	    t4_port_speed_name(sc->port[3]));
2696 
2697 	/* Do NOT set ksp->ks_update.  These kstats do not change. */
2698 
2699 	/* Install the kstat */
2700 	ksp->ks_private = (void *)sc;
2701 	kstat_install(ksp);
2702 
2703 	return (ksp);
2704 }
2705 
2706 /*
2707  * t4nex:X:stat
2708  */
2709 struct t4_wc_kstats {
2710 	kstat_named_t write_coal_success;
2711 	kstat_named_t write_coal_failure;
2712 };
2713 
2714 static int
t4_update_wc_kstats(kstat_t * ksp,int rw)2715 t4_update_wc_kstats(kstat_t *ksp, int rw)
2716 {
2717 	struct t4_wc_kstats *kstatp = (struct t4_wc_kstats *)ksp->ks_data;
2718 	struct adapter *sc = ksp->ks_private;
2719 
2720 	if (rw == KSTAT_WRITE)
2721 		return (0);
2722 
2723 	if (t4_cver_ge(sc, CHELSIO_T5)) {
2724 		const uint32_t wc_total = t4_read_reg(sc, A_SGE_STAT_TOTAL);
2725 		const uint32_t wc_failure = t4_read_reg(sc, A_SGE_STAT_MATCH);
2726 		KS_SET_U64(kstatp, write_coal_success, wc_total - wc_failure);
2727 		KS_SET_U64(kstatp, write_coal_failure, wc_failure);
2728 	}
2729 
2730 	return (0);
2731 }
2732 
2733 static kstat_t *
t4_setup_wc_kstats(struct adapter * sc)2734 t4_setup_wc_kstats(struct adapter *sc)
2735 {
2736 	kstat_t *ksp;
2737 	struct t4_wc_kstats *kstatp;
2738 
2739 	const uint_t ndata =
2740 	    sizeof (struct t4_wc_kstats) / sizeof (kstat_named_t);
2741 	ksp = kstat_create(T4_NEXUS_NAME, ddi_get_instance(sc->dip), "stats",
2742 	    "nexus", KSTAT_TYPE_NAMED, ndata, 0);
2743 	if (ksp == NULL) {
2744 		cxgb_printf(sc->dip, CE_WARN, "failed to initialize kstats.");
2745 		return (NULL);
2746 	}
2747 
2748 	kstatp = (struct t4_wc_kstats *)ksp->ks_data;
2749 
2750 	KS_INIT_U64(kstatp, write_coal_success);
2751 	KS_INIT_U64(kstatp, write_coal_failure);
2752 
2753 	ksp->ks_update = t4_update_wc_kstats;
2754 	/* Install the kstat */
2755 	ksp->ks_private = (void *)sc;
2756 	kstat_install(ksp);
2757 
2758 	return (ksp);
2759 }
2760 
2761 /*
2762  * cxgbe:X:fec
2763  *
2764  * This provides visibility into the errors that have been found by the
2765  * different FEC subsystems. While it's tempting to combine the two different
2766  * FEC types logically, the data that the errors tell us are pretty different
2767  * between the two. Firecode is strictly per-lane, but RS has parts that are
2768  * related to symbol distribution to lanes and also to the overall channel.
2769  */
2770 struct cxgbe_port_fec_kstats {
2771 	kstat_named_t rs_corr;
2772 	kstat_named_t rs_uncorr;
2773 	kstat_named_t rs_sym0_corr;
2774 	kstat_named_t rs_sym1_corr;
2775 	kstat_named_t rs_sym2_corr;
2776 	kstat_named_t rs_sym3_corr;
2777 	kstat_named_t fc_lane0_corr;
2778 	kstat_named_t fc_lane0_uncorr;
2779 	kstat_named_t fc_lane1_corr;
2780 	kstat_named_t fc_lane1_uncorr;
2781 	kstat_named_t fc_lane2_corr;
2782 	kstat_named_t fc_lane2_uncorr;
2783 	kstat_named_t fc_lane3_corr;
2784 	kstat_named_t fc_lane3_uncorr;
2785 };
2786 
2787 static uint32_t
t4_read_fec_pair(struct port_info * pi,uint32_t lo_reg,uint32_t high_reg)2788 t4_read_fec_pair(struct port_info *pi, uint32_t lo_reg, uint32_t high_reg)
2789 {
2790 	struct adapter *sc = pi->adapter;
2791 	const uint8_t port = pi->tx_chan;
2792 
2793 	const uint32_t low = t4_read_reg(sc, T5_PORT_REG(port, lo_reg));
2794 	const uint32_t high = t4_read_reg(sc, T5_PORT_REG(port, high_reg));
2795 	return ((low & 0xffff) | ((high & 0xffff) << 16));
2796 }
2797 
2798 static int
t4_update_fec_kstats(kstat_t * ksp,int rw)2799 t4_update_fec_kstats(kstat_t *ksp, int rw)
2800 {
2801 	struct cxgbe_port_fec_kstats *fec = ksp->ks_data;
2802 	struct port_info *pi = ksp->ks_private;
2803 
2804 	if (rw == KSTAT_WRITE) {
2805 		return (EACCES);
2806 	}
2807 
2808 	/*
2809 	 * First go ahead and gather RS related stats.
2810 	 */
2811 	fec->rs_corr.value.ui64 +=
2812 	    t4_read_fec_pair(pi, T6_RS_FEC_CCW_LO, T6_RS_FEC_CCW_HI);
2813 	fec->rs_uncorr.value.ui64 +=
2814 	    t4_read_fec_pair(pi, T6_RS_FEC_NCCW_LO, T6_RS_FEC_NCCW_HI);
2815 	fec->rs_sym0_corr.value.ui64 +=
2816 	    t4_read_fec_pair(pi, T6_RS_FEC_SYMERR0_LO, T6_RS_FEC_SYMERR0_HI);
2817 	fec->rs_sym1_corr.value.ui64 +=
2818 	    t4_read_fec_pair(pi, T6_RS_FEC_SYMERR1_LO, T6_RS_FEC_SYMERR1_HI);
2819 	fec->rs_sym2_corr.value.ui64 +=
2820 	    t4_read_fec_pair(pi, T6_RS_FEC_SYMERR2_LO, T6_RS_FEC_SYMERR2_HI);
2821 	fec->rs_sym3_corr.value.ui64 +=
2822 	    t4_read_fec_pair(pi, T6_RS_FEC_SYMERR3_LO, T6_RS_FEC_SYMERR3_HI);
2823 
2824 	/*
2825 	 * Now go through and try to grab Firecode/BASE-R stats.
2826 	 */
2827 	fec->fc_lane0_corr.value.ui64 +=
2828 	    t4_read_fec_pair(pi, T6_FC_FEC_L0_CERR_LO, T6_FC_FEC_L0_CERR_HI);
2829 	fec->fc_lane0_uncorr.value.ui64 +=
2830 	    t4_read_fec_pair(pi, T6_FC_FEC_L0_NCERR_LO, T6_FC_FEC_L0_NCERR_HI);
2831 	fec->fc_lane1_corr.value.ui64 +=
2832 	    t4_read_fec_pair(pi, T6_FC_FEC_L1_CERR_LO, T6_FC_FEC_L1_CERR_HI);
2833 	fec->fc_lane1_uncorr.value.ui64 +=
2834 	    t4_read_fec_pair(pi, T6_FC_FEC_L1_NCERR_LO, T6_FC_FEC_L1_NCERR_HI);
2835 	fec->fc_lane2_corr.value.ui64 +=
2836 	    t4_read_fec_pair(pi, T6_FC_FEC_L2_CERR_LO, T6_FC_FEC_L2_CERR_HI);
2837 	fec->fc_lane2_uncorr.value.ui64 +=
2838 	    t4_read_fec_pair(pi, T6_FC_FEC_L2_NCERR_LO, T6_FC_FEC_L2_NCERR_HI);
2839 	fec->fc_lane3_corr.value.ui64 +=
2840 	    t4_read_fec_pair(pi, T6_FC_FEC_L3_CERR_LO, T6_FC_FEC_L3_CERR_HI);
2841 	fec->fc_lane3_uncorr.value.ui64 +=
2842 	    t4_read_fec_pair(pi, T6_FC_FEC_L3_NCERR_LO, T6_FC_FEC_L3_NCERR_HI);
2843 
2844 	return (0);
2845 }
2846 
2847 static kstat_t *
t4_init_fec_kstats(struct port_info * pi)2848 t4_init_fec_kstats(struct port_info *pi)
2849 {
2850 	kstat_t *ksp;
2851 	struct cxgbe_port_fec_kstats *kstatp;
2852 
2853 	if (!t4_cver_ge(pi->adapter, CHELSIO_T6)) {
2854 		return (NULL);
2855 	}
2856 
2857 	ksp = kstat_create(T4_PORT_NAME, ddi_get_instance(pi->dip), "fec",
2858 	    "net", KSTAT_TYPE_NAMED, sizeof (struct cxgbe_port_fec_kstats) /
2859 	    sizeof (kstat_named_t), 0);
2860 	if (ksp == NULL) {
2861 		cxgb_printf(pi->dip, CE_WARN, "failed to initialize fec "
2862 		    "kstats.");
2863 		return (NULL);
2864 	}
2865 
2866 	kstatp = ksp->ks_data;
2867 	KS_INIT_U64(kstatp, rs_corr);
2868 	KS_INIT_U64(kstatp, rs_uncorr);
2869 	KS_INIT_U64(kstatp, rs_sym0_corr);
2870 	KS_INIT_U64(kstatp, rs_sym1_corr);
2871 	KS_INIT_U64(kstatp, rs_sym2_corr);
2872 	KS_INIT_U64(kstatp, rs_sym3_corr);
2873 	KS_INIT_U64(kstatp, fc_lane0_corr);
2874 	KS_INIT_U64(kstatp, fc_lane0_uncorr);
2875 	KS_INIT_U64(kstatp, fc_lane1_corr);
2876 	KS_INIT_U64(kstatp, fc_lane1_uncorr);
2877 	KS_INIT_U64(kstatp, fc_lane2_corr);
2878 	KS_INIT_U64(kstatp, fc_lane2_uncorr);
2879 	KS_INIT_U64(kstatp, fc_lane3_corr);
2880 	KS_INIT_U64(kstatp, fc_lane3_uncorr);
2881 
2882 	ksp->ks_update = t4_update_fec_kstats;
2883 	ksp->ks_private = pi;
2884 	kstat_install(ksp);
2885 
2886 	return (ksp);
2887 }
2888 
2889 int
t4_port_full_init(struct port_info * pi)2890 t4_port_full_init(struct port_info *pi)
2891 {
2892 	struct adapter *sc = pi->adapter;
2893 	struct sge_rxq *rxq;
2894 	int rc, i;
2895 
2896 	ASSERT((pi->flags & TPF_INIT_DONE) == 0);
2897 
2898 	/* Allocate TX/RX/FL queues for this port. */
2899 	if ((rc = t4_port_queues_init(pi)) != 0) {
2900 		goto done;
2901 	}
2902 
2903 	/* Setup RSS for this port. */
2904 	uint16_t *rss = kmem_zalloc(pi->rxq_count * sizeof (*rss), KM_SLEEP);
2905 	for_each_rxq(pi, i, rxq) {
2906 		rss[i] = rxq->iq.tsi_abs_id;
2907 	}
2908 	rc = -t4_config_rss_range(sc, sc->mbox, pi->viid, 0,
2909 	    pi->rss_size, rss, pi->rxq_count);
2910 	kmem_free(rss, pi->rxq_count * sizeof (*rss));
2911 	if (rc != 0) {
2912 		cxgb_printf(pi->dip, CE_WARN, "rss_config failed: %d", rc);
2913 		goto done;
2914 	}
2915 
2916 	t4_port_kstats_init(pi);
2917 	pi->ksp_fec = t4_init_fec_kstats(pi);
2918 
2919 	pi->flags |= TPF_INIT_DONE;
2920 
2921 done:
2922 	if (rc != 0) {
2923 		/*
2924 		 * Clean up any state resulting which may be lingering due to
2925 		 * failure part way through initialization.
2926 		 */
2927 		t4_port_full_uninit(pi);
2928 	}
2929 
2930 	return (rc);
2931 }
2932 
2933 /*
2934  * Idempotent.
2935  */
2936 static void
t4_port_full_uninit(struct port_info * pi)2937 t4_port_full_uninit(struct port_info *pi)
2938 {
2939 	if (pi->ksp_fec != NULL) {
2940 		kstat_delete(pi->ksp_fec);
2941 		pi->ksp_fec = NULL;
2942 	}
2943 	t4_port_kstats_fini(pi);
2944 	t4_port_queues_fini(pi);
2945 	pi->flags &= ~TPF_INIT_DONE;
2946 }
2947 
2948 void
t4_fatal_err(struct adapter * sc)2949 t4_fatal_err(struct adapter *sc)
2950 {
2951 	t4_set_reg_field(sc, A_SGE_CONTROL, F_GLOBALENABLE, 0);
2952 	t4_intr_disable(sc);
2953 	cxgb_printf(sc->dip, CE_WARN,
2954 	    "encountered fatal error, adapter stopped.");
2955 }
2956 
2957 int
t4_os_find_pci_capability(struct adapter * sc,uint8_t cap)2958 t4_os_find_pci_capability(struct adapter *sc, uint8_t cap)
2959 {
2960 	const uint16_t stat = pci_config_get16(sc->pci_regh, PCI_CONF_STAT);
2961 	if ((stat & PCI_STAT_CAP) == 0) {
2962 		return (0);
2963 	}
2964 
2965 	uint8_t cap_ptr = pci_config_get8(sc->pci_regh, PCI_CONF_CAP_PTR);
2966 	while (cap_ptr) {
2967 		uint8_t cap_id =
2968 		    pci_config_get8(sc->pci_regh, cap_ptr + PCI_CAP_ID);
2969 		if (cap_id == cap) {
2970 			return (cap_ptr);
2971 		}
2972 		cap_ptr =
2973 		    pci_config_get8(sc->pci_regh, cap_ptr + PCI_CAP_NEXT_PTR);
2974 	}
2975 
2976 	return (0);
2977 }
2978 
2979 void
t4_os_portmod_changed(struct adapter * sc,int idx)2980 t4_os_portmod_changed(struct adapter *sc, int idx)
2981 {
2982 	static const char *mod_str[] = {
2983 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
2984 	};
2985 	struct port_info *pi = sc->port[idx];
2986 
2987 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
2988 		cxgb_printf(pi->dip, CE_NOTE, "transceiver unplugged.");
2989 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
2990 		cxgb_printf(pi->dip, CE_NOTE,
2991 		    "unknown transceiver inserted.\n");
2992 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
2993 		cxgb_printf(pi->dip, CE_NOTE,
2994 		    "unsupported transceiver inserted.\n");
2995 	else if (pi->mod_type > 0 && pi->mod_type < ARRAY_SIZE(mod_str))
2996 		cxgb_printf(pi->dip, CE_NOTE, "%s transceiver inserted.\n",
2997 		    mod_str[pi->mod_type]);
2998 	else
2999 		cxgb_printf(pi->dip, CE_NOTE, "transceiver (type %d) inserted.",
3000 		    pi->mod_type);
3001 
3002 	if ((pi->flags & TPF_OPEN) != 0 && pi->link_cfg.new_module) {
3003 		pi->link_cfg.redo_l1cfg = true;
3004 	}
3005 }
3006 
3007 void
t4_os_set_hw_addr(struct adapter * sc,int idx,const uint8_t * hw_addr)3008 t4_os_set_hw_addr(struct adapter *sc, int idx, const uint8_t *hw_addr)
3009 {
3010 	bcopy(hw_addr, sc->port[idx]->hw_addr, ETHERADDRL);
3011 }
3012 
3013 /* Add thread to list of consumers waiting to access adapter mailbox */
3014 void
t4_mbox_waiter_add(struct adapter * sc,t4_mbox_waiter_t * ent)3015 t4_mbox_waiter_add(struct adapter *sc, t4_mbox_waiter_t *ent)
3016 {
3017 	mutex_enter(&sc->mbox_lock);
3018 	ent->thread = curthread;
3019 	list_insert_tail(&sc->mbox_list, ent);
3020 	mutex_exit(&sc->mbox_lock);
3021 }
3022 
3023 /* Remove thread from list of consumers waiting to access adapter mailbox */
3024 void
t4_mbox_waiter_remove(struct adapter * sc,t4_mbox_waiter_t * ent)3025 t4_mbox_waiter_remove(struct adapter *sc, t4_mbox_waiter_t *ent)
3026 {
3027 	ASSERT(ent->thread == curthread);
3028 
3029 	mutex_enter(&sc->mbox_lock);
3030 	const bool was_owner = (list_head(&sc->mbox_list) == ent);
3031 	list_remove(&sc->mbox_list, ent);
3032 
3033 	if (was_owner && !list_is_empty(&sc->mbox_list)) {
3034 		/*
3035 		 * Wake the other threads waiting on the mbox as we are vacating
3036 		 * the "owner" slot.
3037 		 */
3038 		cv_broadcast(&sc->mbox_cv);
3039 	}
3040 	mutex_exit(&sc->mbox_lock);
3041 }
3042 
3043 /*
3044  * Wait for the current thread, which has called t4_mbox_waiter_add(), to become
3045  * the "owner" of the adapter mailbox (head of the waiter list).
3046  *
3047  * Returns true if current thread is the owner, else false if we slept/spun for
3048  * `wait_us` and are not yet owner (and thus should recheck adapter status).
3049  */
3050 bool
t4_mbox_wait_owner(struct adapter * sc,uint_t wait_us,bool sleep_ok)3051 t4_mbox_wait_owner(struct adapter *sc, uint_t wait_us, bool sleep_ok)
3052 {
3053 	mutex_enter(&sc->mbox_lock);
3054 	t4_mbox_waiter_t *head = list_head(&sc->mbox_list);
3055 	ASSERT(head != NULL);
3056 
3057 	if (head->thread == curthread) {
3058 		mutex_exit(&sc->mbox_lock);
3059 		return (true);
3060 	}
3061 
3062 	if (!sleep_ok) {
3063 		mutex_exit(&sc->mbox_lock);
3064 		drv_usecwait(wait_us);
3065 
3066 		mutex_enter(&sc->mbox_lock);
3067 		head = list_head(&sc->mbox_list);
3068 		ASSERT(head != NULL);
3069 		bool is_owner = head->thread == curthread;
3070 		mutex_exit(&sc->mbox_lock);
3071 		return (is_owner);
3072 	}
3073 
3074 	/*
3075 	 * Using a singal-aware wait would be more courteous here, but much of
3076 	 * the logic which ultimately accesses the device mbox is ill-equipped
3077 	 * to handle gracefully EINTR failures.
3078 	 */
3079 	const int res = cv_reltimedwait(&sc->mbox_cv, &sc->mbox_lock,
3080 	    USEC_TO_TICK(wait_us), TR_MICROSEC);
3081 	if (res > 0) {
3082 		head = list_head(&sc->mbox_list);
3083 		ASSERT(head != NULL);
3084 		if (head->thread == curthread) {
3085 			/*
3086 			 * CV was signaled and this thread now occupies the head
3087 			 * of the list (indicating mbox ownership).
3088 			 */
3089 			mutex_exit(&sc->mbox_lock);
3090 			return (true);
3091 		}
3092 	}
3093 	mutex_exit(&sc->mbox_lock);
3094 	return (false);
3095 }
3096 
3097 
3098 uint32_t
t4_read_reg(struct adapter * sc,uint32_t reg)3099 t4_read_reg(struct adapter *sc, uint32_t reg)
3100 {
3101 	const uint32_t val = ddi_get32(sc->regh, (uint32_t *)(sc->regp + reg));
3102 	DTRACE_PROBE3(t4__reg__read, struct adapter *, sc, uint32_t, reg,
3103 	    uint64_t, val);
3104 	return (val);
3105 }
3106 
3107 void
t4_write_reg(struct adapter * sc,uint32_t reg,uint32_t val)3108 t4_write_reg(struct adapter *sc, uint32_t reg, uint32_t val)
3109 {
3110 	DTRACE_PROBE3(t4__reg__write, struct adapter *, sc, uint32_t, reg,
3111 	    uint64_t, val);
3112 	ddi_put32(sc->regh, (uint32_t *)(sc->regp + reg), val);
3113 }
3114 
3115 uint64_t
t4_read_reg64(struct adapter * sc,uint32_t reg)3116 t4_read_reg64(struct adapter *sc, uint32_t reg)
3117 {
3118 	const uint64_t val = ddi_get64(sc->regh, (uint64_t *)(sc->regp + reg));
3119 	DTRACE_PROBE3(t4__reg__read, struct adapter *, sc, uint32_t, reg,
3120 	    uint64_t, val);
3121 	return (val);
3122 }
3123 
3124 void
t4_write_reg64(struct adapter * sc,uint32_t reg,uint64_t val)3125 t4_write_reg64(struct adapter *sc, uint32_t reg, uint64_t val)
3126 {
3127 	DTRACE_PROBE3(t4__reg__write, struct adapter *, sc, uint32_t, reg,
3128 	    uint64_t, val);
3129 	ddi_put64(sc->regh, (uint64_t *)(sc->regp + reg), val);
3130 }
3131 
3132 static int
t4_sensor_read(struct adapter * sc,uint32_t diag,uint32_t * valp)3133 t4_sensor_read(struct adapter *sc, uint32_t diag, uint32_t *valp)
3134 {
3135 	int rc;
3136 	uint32_t param, val;
3137 
3138 	ADAPTER_LOCK(sc);
3139 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3140 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
3141 	    V_FW_PARAMS_PARAM_Y(diag);
3142 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3143 	ADAPTER_UNLOCK(sc);
3144 
3145 	if (rc != 0) {
3146 		return (rc);
3147 	} else if (val == 0) {
3148 		return (EIO);
3149 	}
3150 
3151 	*valp = val;
3152 	return (0);
3153 }
3154 
3155 static int
t4_temperature_read(void * arg,sensor_ioctl_scalar_t * scalar)3156 t4_temperature_read(void *arg, sensor_ioctl_scalar_t *scalar)
3157 {
3158 	int ret;
3159 	struct adapter *sc = arg;
3160 	uint32_t val;
3161 
3162 	ret = t4_sensor_read(sc, FW_PARAM_DEV_DIAG_TMP, &val);
3163 	if (ret != 0) {
3164 		return (ret);
3165 	}
3166 
3167 	/*
3168 	 * The device measures temperature in units of 1 degree Celsius. We
3169 	 * don't know its precision.
3170 	 */
3171 	scalar->sis_unit = SENSOR_UNIT_CELSIUS;
3172 	scalar->sis_gran = 1;
3173 	scalar->sis_prec = 0;
3174 	scalar->sis_value = val;
3175 
3176 	return (0);
3177 }
3178 
3179 static int
t4_voltage_read(void * arg,sensor_ioctl_scalar_t * scalar)3180 t4_voltage_read(void *arg, sensor_ioctl_scalar_t *scalar)
3181 {
3182 	int ret;
3183 	struct adapter *sc = arg;
3184 	uint32_t val;
3185 
3186 	ret = t4_sensor_read(sc, FW_PARAM_DEV_DIAG_VDD, &val);
3187 	if (ret != 0) {
3188 		return (ret);
3189 	}
3190 
3191 	scalar->sis_unit = SENSOR_UNIT_VOLTS;
3192 	scalar->sis_gran = 1000;
3193 	scalar->sis_prec = 0;
3194 	scalar->sis_value = val;
3195 
3196 	return (0);
3197 }
3198 
3199 /*
3200  * While the hardware supports the ability to read and write the flash image,
3201  * this is not currently wired up.
3202  */
3203 static int
t4_ufm_getcaps(ddi_ufm_handle_t * ufmh,void * arg,ddi_ufm_cap_t * caps)3204 t4_ufm_getcaps(ddi_ufm_handle_t *ufmh, void *arg, ddi_ufm_cap_t *caps)
3205 {
3206 	*caps = DDI_UFM_CAP_REPORT;
3207 	return (0);
3208 }
3209 
3210 static int
t4_ufm_fill_image(ddi_ufm_handle_t * ufmh,void * arg,uint_t imgno,ddi_ufm_image_t * imgp)3211 t4_ufm_fill_image(ddi_ufm_handle_t *ufmh, void *arg, uint_t imgno,
3212     ddi_ufm_image_t *imgp)
3213 {
3214 	if (imgno != 0) {
3215 		return (EINVAL);
3216 	}
3217 
3218 	ddi_ufm_image_set_desc(imgp, "Firmware");
3219 	ddi_ufm_image_set_nslots(imgp, 1);
3220 
3221 	return (0);
3222 }
3223 
3224 static int
t4_ufm_fill_slot_version(nvlist_t * nvl,const char * key,uint32_t vers)3225 t4_ufm_fill_slot_version(nvlist_t *nvl, const char *key, uint32_t vers)
3226 {
3227 	char buf[128];
3228 
3229 	if (vers == 0) {
3230 		return (0);
3231 	}
3232 
3233 	if (snprintf(buf, sizeof (buf), "%u.%u.%u.%u",
3234 	    G_FW_HDR_FW_VER_MAJOR(vers), G_FW_HDR_FW_VER_MINOR(vers),
3235 	    G_FW_HDR_FW_VER_MICRO(vers), G_FW_HDR_FW_VER_BUILD(vers)) >=
3236 	    sizeof (buf)) {
3237 		return (EOVERFLOW);
3238 	}
3239 
3240 	return (nvlist_add_string(nvl, key, buf));
3241 }
3242 
3243 static int
t4_ufm_fill_slot(ddi_ufm_handle_t * ufmh,void * arg,uint_t imgno,uint_t slotno,ddi_ufm_slot_t * slotp)3244 t4_ufm_fill_slot(ddi_ufm_handle_t *ufmh, void *arg, uint_t imgno, uint_t slotno,
3245     ddi_ufm_slot_t *slotp)
3246 {
3247 	int ret;
3248 	struct adapter *sc = arg;
3249 	nvlist_t *misc = NULL;
3250 	char buf[128];
3251 
3252 	if (imgno != 0 || slotno != 0) {
3253 		return (EINVAL);
3254 	}
3255 
3256 	if (snprintf(buf, sizeof (buf), "%u.%u.%u.%u",
3257 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
3258 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
3259 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
3260 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers)) >= sizeof (buf)) {
3261 		return (EOVERFLOW);
3262 	}
3263 
3264 	ddi_ufm_slot_set_version(slotp, buf);
3265 
3266 	(void) nvlist_alloc(&misc, NV_UNIQUE_NAME, KM_SLEEP);
3267 	if ((ret = t4_ufm_fill_slot_version(misc, "TP Microcode",
3268 	    sc->params.tp_vers)) != 0) {
3269 		goto err;
3270 	}
3271 
3272 	if ((ret = t4_ufm_fill_slot_version(misc, "Bootstrap",
3273 	    sc->params.bs_vers)) != 0) {
3274 		goto err;
3275 	}
3276 
3277 	if ((ret = t4_ufm_fill_slot_version(misc, "Expansion ROM",
3278 	    sc->params.er_vers)) != 0) {
3279 		goto err;
3280 	}
3281 
3282 	if ((ret = nvlist_add_uint32(misc, "Serial Configuration",
3283 	    sc->params.scfg_vers)) != 0) {
3284 		goto err;
3285 	}
3286 
3287 	if ((ret = nvlist_add_uint32(misc, "VPD Version",
3288 	    sc->params.vpd_vers)) != 0) {
3289 		goto err;
3290 	}
3291 
3292 	ddi_ufm_slot_set_misc(slotp, misc);
3293 	ddi_ufm_slot_set_attrs(slotp, DDI_UFM_ATTR_ACTIVE |
3294 	    DDI_UFM_ATTR_WRITEABLE | DDI_UFM_ATTR_READABLE);
3295 	return (0);
3296 
3297 err:
3298 	nvlist_free(misc);
3299 	return (ret);
3300 
3301 }
3302 
3303 int
t4_cxgbe_attach(struct port_info * pi,dev_info_t * dip)3304 t4_cxgbe_attach(struct port_info *pi, dev_info_t *dip)
3305 {
3306 	ASSERT(pi != NULL);
3307 
3308 	mac_register_t *mac = mac_alloc(MAC_VERSION);
3309 	if (mac == NULL) {
3310 		return (DDI_FAILURE);
3311 	}
3312 
3313 	size_t prop_size;
3314 	const char **props = t4_get_priv_props(pi, &prop_size);
3315 
3316 	mac->m_type_ident = MAC_PLUGIN_IDENT_ETHER;
3317 	mac->m_driver = pi;
3318 	mac->m_dip = dip;
3319 	mac->m_src_addr = pi->hw_addr;
3320 	mac->m_callbacks = &t4_mac_callbacks;
3321 	mac->m_max_sdu = pi->mtu;
3322 	/* mac_register() treats this as const, so we can cast it away */
3323 	mac->m_priv_props = (char **)props;
3324 	mac->m_margin = VLAN_TAGSZ;
3325 	mac->m_v12n = MAC_VIRT_LEVEL1;
3326 
3327 	mac_handle_t mh = NULL;
3328 	const int rc = mac_register(mac, &mh);
3329 	mac_free(mac);
3330 	kmem_free(props, prop_size);
3331 	if (rc != 0) {
3332 		return (DDI_FAILURE);
3333 	}
3334 
3335 	pi->mh = mh;
3336 
3337 	/*
3338 	 * Link state from this point onwards to the time interface is plumbed,
3339 	 * should be set to LINK_STATE_UNKNOWN. The mac should be updated about
3340 	 * the link state as either LINK_STATE_UP or LINK_STATE_DOWN based on
3341 	 * the actual link state detection after interface plumb.
3342 	 */
3343 	mac_link_update(mh, LINK_STATE_UNKNOWN);
3344 
3345 	return (DDI_SUCCESS);
3346 }
3347 
3348 int
t4_cxgbe_detach(struct port_info * pi)3349 t4_cxgbe_detach(struct port_info *pi)
3350 {
3351 	ASSERT(pi != NULL);
3352 	ASSERT(pi->mh != NULL);
3353 
3354 	if (mac_unregister(pi->mh) == 0) {
3355 		pi->mh = NULL;
3356 		return (DDI_SUCCESS);
3357 	}
3358 
3359 	return (DDI_FAILURE);
3360 }
3361 
3362 struct cb_ops t4_cb_ops = {
3363 	.cb_open =		t4_cb_open,
3364 	.cb_close =		t4_cb_close,
3365 	.cb_strategy =		nodev,
3366 	.cb_print =		nodev,
3367 	.cb_dump =		nodev,
3368 	.cb_read =		nodev,
3369 	.cb_write =		nodev,
3370 	.cb_ioctl =		t4_cb_ioctl,
3371 	.cb_devmap =		nodev,
3372 	.cb_mmap =		nodev,
3373 	.cb_segmap =		nodev,
3374 	.cb_chpoll =		nochpoll,
3375 	.cb_prop_op =		ddi_prop_op,
3376 	.cb_flag =		D_MP,
3377 	.cb_rev =		CB_REV,
3378 	.cb_aread =		nodev,
3379 	.cb_awrite =		nodev
3380 };
3381 
3382 struct bus_ops t4_bus_ops = {
3383 	.busops_rev =		BUSO_REV,
3384 	.bus_ctl =		t4_bus_ctl,
3385 	.bus_prop_op =		ddi_bus_prop_op,
3386 	.bus_config =		t4_bus_config,
3387 	.bus_unconfig =		t4_bus_unconfig,
3388 };
3389 
3390 static struct dev_ops t4_dev_ops = {
3391 	.devo_rev =		DEVO_REV,
3392 	.devo_getinfo =		t4_devo_getinfo,
3393 	.devo_identify =	nulldev,
3394 	.devo_probe =		t4_devo_probe,
3395 	.devo_attach =		t4_devo_attach,
3396 	.devo_detach =		t4_devo_detach,
3397 	.devo_reset =		nodev,
3398 	.devo_cb_ops =		&t4_cb_ops,
3399 	.devo_bus_ops =		&t4_bus_ops,
3400 	.devo_quiesce =		&t4_devo_quiesce,
3401 };
3402 
3403 static struct modldrv t4nex_modldrv = {
3404 	.drv_modops =		&mod_driverops,
3405 	.drv_linkinfo =		"Chelsio T4-T6 nexus " DRV_VERSION,
3406 	.drv_dev_ops =		&t4_dev_ops
3407 };
3408 
3409 static struct modlinkage t4nex_modlinkage = {
3410 	.ml_rev =		MODREV_1,
3411 	.ml_linkage =		{&t4nex_modldrv, NULL},
3412 };
3413 
3414 int
_init(void)3415 _init(void)
3416 {
3417 	int rc;
3418 
3419 	rc = ddi_soft_state_init(&t4_soft_state, sizeof (struct adapter), 0);
3420 	if (rc != 0) {
3421 		return (rc);
3422 	}
3423 
3424 	mutex_init(&t4_adapter_list_lock, NULL, MUTEX_DRIVER, NULL);
3425 	list_create(&t4_adapter_list, sizeof (adapter_t),
3426 	    offsetof(adapter_t, node));
3427 	t4_debug_init();
3428 
3429 	rc = mod_install(&t4nex_modlinkage);
3430 	if (rc != 0) {
3431 		ddi_soft_state_fini(&t4_soft_state);
3432 		mutex_destroy(&t4_adapter_list_lock);
3433 		list_destroy(&t4_adapter_list);
3434 		t4_debug_fini();
3435 	}
3436 
3437 	return (rc);
3438 }
3439 
3440 int
_fini(void)3441 _fini(void)
3442 {
3443 	const int rc = mod_remove(&t4nex_modlinkage);
3444 	if (rc != 0) {
3445 		return (rc);
3446 	}
3447 
3448 	mutex_destroy(&t4_adapter_list_lock);
3449 	list_destroy(&t4_adapter_list);
3450 	ddi_soft_state_fini(&t4_soft_state);
3451 	t4_debug_fini();
3452 
3453 	return (0);
3454 }
3455 
3456 int
_info(struct modinfo * mi)3457 _info(struct modinfo *mi)
3458 {
3459 	return (mod_info(&t4nex_modlinkage, mi));
3460 }
3461