]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/cxgbe/t4_main.c
Fix reference count overflow in mqueuefs.
[FreeBSD/FreeBSD.git] / sys / dev / cxgbe / t4_main.c
1 /*-
2  * Copyright (c) 2011 Chelsio Communications, Inc.
3  * All rights reserved.
4  * Written by: Navdeep Parhar <np@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_ddb.h"
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_rss.h"
35
36 #include <sys/param.h>
37 #include <sys/conf.h>
38 #include <sys/priv.h>
39 #include <sys/kernel.h>
40 #include <sys/bus.h>
41 #include <sys/module.h>
42 #include <sys/malloc.h>
43 #include <sys/queue.h>
44 #include <sys/taskqueue.h>
45 #include <sys/pciio.h>
46 #include <dev/pci/pcireg.h>
47 #include <dev/pci/pcivar.h>
48 #include <dev/pci/pci_private.h>
49 #include <sys/firmware.h>
50 #include <sys/sbuf.h>
51 #include <sys/smp.h>
52 #include <sys/socket.h>
53 #include <sys/sockio.h>
54 #include <sys/sysctl.h>
55 #include <net/ethernet.h>
56 #include <net/if.h>
57 #include <net/if_types.h>
58 #include <net/if_dl.h>
59 #include <net/if_vlan_var.h>
60 #ifdef RSS
61 #include <net/rss_config.h>
62 #endif
63 #include <netinet/in.h>
64 #include <netinet/ip.h>
65 #if defined(__i386__) || defined(__amd64__)
66 #include <machine/md_var.h>
67 #include <machine/cputypes.h>
68 #include <vm/vm.h>
69 #include <vm/pmap.h>
70 #endif
71 #include <crypto/rijndael/rijndael.h>
72 #ifdef DDB
73 #include <ddb/ddb.h>
74 #include <ddb/db_lex.h>
75 #endif
76
77 #include "common/common.h"
78 #include "common/t4_msg.h"
79 #include "common/t4_regs.h"
80 #include "common/t4_regs_values.h"
81 #include "cudbg/cudbg.h"
82 #include "t4_clip.h"
83 #include "t4_ioctl.h"
84 #include "t4_l2t.h"
85 #include "t4_mp_ring.h"
86 #include "t4_if.h"
87 #include "t4_smt.h"
88
89 /* T4 bus driver interface */
90 static int t4_probe(device_t);
91 static int t4_attach(device_t);
92 static int t4_detach(device_t);
93 static int t4_child_location_str(device_t, device_t, char *, size_t);
94 static int t4_ready(device_t);
95 static int t4_read_port_device(device_t, int, device_t *);
96 static device_method_t t4_methods[] = {
97         DEVMETHOD(device_probe,         t4_probe),
98         DEVMETHOD(device_attach,        t4_attach),
99         DEVMETHOD(device_detach,        t4_detach),
100
101         DEVMETHOD(bus_child_location_str, t4_child_location_str),
102
103         DEVMETHOD(t4_is_main_ready,     t4_ready),
104         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
105
106         DEVMETHOD_END
107 };
108 static driver_t t4_driver = {
109         "t4nex",
110         t4_methods,
111         sizeof(struct adapter)
112 };
113
114
115 /* T4 port (cxgbe) interface */
116 static int cxgbe_probe(device_t);
117 static int cxgbe_attach(device_t);
118 static int cxgbe_detach(device_t);
119 device_method_t cxgbe_methods[] = {
120         DEVMETHOD(device_probe,         cxgbe_probe),
121         DEVMETHOD(device_attach,        cxgbe_attach),
122         DEVMETHOD(device_detach,        cxgbe_detach),
123         { 0, 0 }
124 };
125 static driver_t cxgbe_driver = {
126         "cxgbe",
127         cxgbe_methods,
128         sizeof(struct port_info)
129 };
130
131 /* T4 VI (vcxgbe) interface */
132 static int vcxgbe_probe(device_t);
133 static int vcxgbe_attach(device_t);
134 static int vcxgbe_detach(device_t);
135 static device_method_t vcxgbe_methods[] = {
136         DEVMETHOD(device_probe,         vcxgbe_probe),
137         DEVMETHOD(device_attach,        vcxgbe_attach),
138         DEVMETHOD(device_detach,        vcxgbe_detach),
139         { 0, 0 }
140 };
141 static driver_t vcxgbe_driver = {
142         "vcxgbe",
143         vcxgbe_methods,
144         sizeof(struct vi_info)
145 };
146
147 static d_ioctl_t t4_ioctl;
148
149 static struct cdevsw t4_cdevsw = {
150        .d_version = D_VERSION,
151        .d_ioctl = t4_ioctl,
152        .d_name = "t4nex",
153 };
154
155 /* T5 bus driver interface */
156 static int t5_probe(device_t);
157 static device_method_t t5_methods[] = {
158         DEVMETHOD(device_probe,         t5_probe),
159         DEVMETHOD(device_attach,        t4_attach),
160         DEVMETHOD(device_detach,        t4_detach),
161
162         DEVMETHOD(bus_child_location_str, t4_child_location_str),
163
164         DEVMETHOD(t4_is_main_ready,     t4_ready),
165         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
166
167         DEVMETHOD_END
168 };
169 static driver_t t5_driver = {
170         "t5nex",
171         t5_methods,
172         sizeof(struct adapter)
173 };
174
175
176 /* T5 port (cxl) interface */
177 static driver_t cxl_driver = {
178         "cxl",
179         cxgbe_methods,
180         sizeof(struct port_info)
181 };
182
183 /* T5 VI (vcxl) interface */
184 static driver_t vcxl_driver = {
185         "vcxl",
186         vcxgbe_methods,
187         sizeof(struct vi_info)
188 };
189
190 /* T6 bus driver interface */
191 static int t6_probe(device_t);
192 static device_method_t t6_methods[] = {
193         DEVMETHOD(device_probe,         t6_probe),
194         DEVMETHOD(device_attach,        t4_attach),
195         DEVMETHOD(device_detach,        t4_detach),
196
197         DEVMETHOD(bus_child_location_str, t4_child_location_str),
198
199         DEVMETHOD(t4_is_main_ready,     t4_ready),
200         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
201
202         DEVMETHOD_END
203 };
204 static driver_t t6_driver = {
205         "t6nex",
206         t6_methods,
207         sizeof(struct adapter)
208 };
209
210
211 /* T6 port (cc) interface */
212 static driver_t cc_driver = {
213         "cc",
214         cxgbe_methods,
215         sizeof(struct port_info)
216 };
217
218 /* T6 VI (vcc) interface */
219 static driver_t vcc_driver = {
220         "vcc",
221         vcxgbe_methods,
222         sizeof(struct vi_info)
223 };
224
225 /* ifnet interface */
226 static void cxgbe_init(void *);
227 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
228 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
229 static void cxgbe_qflush(struct ifnet *);
230
231 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
232
233 /*
234  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
235  * then ADAPTER_LOCK, then t4_uld_list_lock.
236  */
237 static struct sx t4_list_lock;
238 SLIST_HEAD(, adapter) t4_list;
239 #ifdef TCP_OFFLOAD
240 static struct sx t4_uld_list_lock;
241 SLIST_HEAD(, uld_info) t4_uld_list;
242 #endif
243
244 /*
245  * Tunables.  See tweak_tunables() too.
246  *
247  * Each tunable is set to a default value here if it's known at compile-time.
248  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
249  * provide a reasonable default (upto n) when the driver is loaded.
250  *
251  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
252  * T5 are under hw.cxl.
253  */
254 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD, 0, "cxgbe(4) parameters");
255 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD, 0, "cxgbe(4) T5+ parameters");
256 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD, 0, "cxgbe(4) TOE parameters");
257
258 /*
259  * Number of queues for tx and rx, NIC and offload.
260  */
261 #define NTXQ 16
262 int t4_ntxq = -NTXQ;
263 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
264     "Number of TX queues per port");
265 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);      /* Old name, undocumented */
266
267 #define NRXQ 8
268 int t4_nrxq = -NRXQ;
269 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
270     "Number of RX queues per port");
271 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);      /* Old name, undocumented */
272
273 #define NTXQ_VI 1
274 static int t4_ntxq_vi = -NTXQ_VI;
275 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
276     "Number of TX queues per VI");
277
278 #define NRXQ_VI 1
279 static int t4_nrxq_vi = -NRXQ_VI;
280 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
281     "Number of RX queues per VI");
282
283 static int t4_rsrv_noflowq = 0;
284 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
285     0, "Reserve TX queue 0 of each VI for non-flowid packets");
286
287 #ifdef TCP_OFFLOAD
288 #define NOFLDTXQ 8
289 static int t4_nofldtxq = -NOFLDTXQ;
290 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
291     "Number of offload TX queues per port");
292
293 #define NOFLDRXQ 2
294 static int t4_nofldrxq = -NOFLDRXQ;
295 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
296     "Number of offload RX queues per port");
297
298 #define NOFLDTXQ_VI 1
299 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
300 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
301     "Number of offload TX queues per VI");
302
303 #define NOFLDRXQ_VI 1
304 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
305 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
306     "Number of offload RX queues per VI");
307
308 #define TMR_IDX_OFLD 1
309 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
310 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
311     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
312
313 #define PKTC_IDX_OFLD (-1)
314 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
315 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
316     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
317
318 /* 0 means chip/fw default, non-zero number is value in microseconds */
319 static u_long t4_toe_keepalive_idle = 0;
320 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
321     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
322
323 /* 0 means chip/fw default, non-zero number is value in microseconds */
324 static u_long t4_toe_keepalive_interval = 0;
325 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
326     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
327
328 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
329 static int t4_toe_keepalive_count = 0;
330 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
331     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
332
333 /* 0 means chip/fw default, non-zero number is value in microseconds */
334 static u_long t4_toe_rexmt_min = 0;
335 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
336     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
337
338 /* 0 means chip/fw default, non-zero number is value in microseconds */
339 static u_long t4_toe_rexmt_max = 0;
340 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
341     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
342
343 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
344 static int t4_toe_rexmt_count = 0;
345 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
346     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
347
348 /* -1 means chip/fw default, other values are raw backoff values to use */
349 static int t4_toe_rexmt_backoff[16] = {
350         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
351 };
352 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff, CTLFLAG_RD, 0,
353     "cxgbe(4) TOE retransmit backoff values");
354 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
355     &t4_toe_rexmt_backoff[0], 0, "");
356 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
357     &t4_toe_rexmt_backoff[1], 0, "");
358 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
359     &t4_toe_rexmt_backoff[2], 0, "");
360 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
361     &t4_toe_rexmt_backoff[3], 0, "");
362 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
363     &t4_toe_rexmt_backoff[4], 0, "");
364 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
365     &t4_toe_rexmt_backoff[5], 0, "");
366 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
367     &t4_toe_rexmt_backoff[6], 0, "");
368 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
369     &t4_toe_rexmt_backoff[7], 0, "");
370 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
371     &t4_toe_rexmt_backoff[8], 0, "");
372 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
373     &t4_toe_rexmt_backoff[9], 0, "");
374 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
375     &t4_toe_rexmt_backoff[10], 0, "");
376 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
377     &t4_toe_rexmt_backoff[11], 0, "");
378 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
379     &t4_toe_rexmt_backoff[12], 0, "");
380 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
381     &t4_toe_rexmt_backoff[13], 0, "");
382 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
383     &t4_toe_rexmt_backoff[14], 0, "");
384 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
385     &t4_toe_rexmt_backoff[15], 0, "");
386 #endif
387
388 #ifdef DEV_NETMAP
389 #define NNMTXQ_VI 2
390 static int t4_nnmtxq_vi = -NNMTXQ_VI;
391 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
392     "Number of netmap TX queues per VI");
393
394 #define NNMRXQ_VI 2
395 static int t4_nnmrxq_vi = -NNMRXQ_VI;
396 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
397     "Number of netmap RX queues per VI");
398 #endif
399
400 /*
401  * Holdoff parameters for ports.
402  */
403 #define TMR_IDX 1
404 int t4_tmr_idx = TMR_IDX;
405 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
406     0, "Holdoff timer index");
407 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);     /* Old name */
408
409 #define PKTC_IDX (-1)
410 int t4_pktc_idx = PKTC_IDX;
411 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
412     0, "Holdoff packet counter index");
413 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);     /* Old name */
414
415 /*
416  * Size (# of entries) of each tx and rx queue.
417  */
418 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
419 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
420     "Number of descriptors in each TX queue");
421
422 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
423 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
424     "Number of descriptors in each RX queue");
425
426 /*
427  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
428  */
429 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
430 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
431     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
432
433 /*
434  * Configuration file.  All the _CF names here are special.
435  */
436 #define DEFAULT_CF      "default"
437 #define BUILTIN_CF      "built-in"
438 #define FLASH_CF        "flash"
439 #define UWIRE_CF        "uwire"
440 #define FPGA_CF         "fpga"
441 static char t4_cfg_file[32] = DEFAULT_CF;
442 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
443     sizeof(t4_cfg_file), "Firmware configuration file");
444
445 /*
446  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
447  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
448  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
449  *            mark or when signalled to do so, 0 to never emit PAUSE.
450  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
451  *                 negotiated settings will override rx_pause/tx_pause.
452  *                 Otherwise rx_pause/tx_pause are applied forcibly.
453  */
454 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
455 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
456     &t4_pause_settings, 0,
457     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
458
459 /*
460  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
461  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
462  *  0 to disable FEC.
463  */
464 static int t4_fec = -1;
465 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
466     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
467
468 /*
469  * Link autonegotiation.
470  * -1 to run with the firmware default.
471  *  0 to disable.
472  *  1 to enable.
473  */
474 static int t4_autoneg = -1;
475 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
476     "Link autonegotiation");
477
478 /*
479  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
480  * encouraged respectively).  '-n' is the same as 'n' except the firmware
481  * version used in the checks is read from the firmware bundled with the driver.
482  */
483 static int t4_fw_install = 1;
484 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
485     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
486
487 /*
488  * ASIC features that will be used.  Disable the ones you don't want so that the
489  * chip resources aren't wasted on features that will not be used.
490  */
491 static int t4_nbmcaps_allowed = 0;
492 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
493     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
494
495 static int t4_linkcaps_allowed = 0;     /* No DCBX, PPP, etc. by default */
496 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
497     &t4_linkcaps_allowed, 0, "Default link capabilities");
498
499 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
500     FW_CAPS_CONFIG_SWITCH_EGRESS;
501 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
502     &t4_switchcaps_allowed, 0, "Default switch capabilities");
503
504 #ifdef RATELIMIT
505 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
506         FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
507 #else
508 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
509         FW_CAPS_CONFIG_NIC_HASHFILTER;
510 #endif
511 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
512     &t4_niccaps_allowed, 0, "Default NIC capabilities");
513
514 static int t4_toecaps_allowed = -1;
515 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
516     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
517
518 static int t4_rdmacaps_allowed = -1;
519 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
520     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
521
522 static int t4_cryptocaps_allowed = -1;
523 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
524     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
525
526 static int t4_iscsicaps_allowed = -1;
527 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
528     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
529
530 static int t4_fcoecaps_allowed = 0;
531 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
532     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
533
534 static int t5_write_combine = 0;
535 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
536     0, "Use WC instead of UC for BAR2");
537
538 static int t4_num_vis = 1;
539 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
540     "Number of VIs per port");
541
542 /*
543  * PCIe Relaxed Ordering.
544  * -1: driver should figure out a good value.
545  * 0: disable RO.
546  * 1: enable RO.
547  * 2: leave RO alone.
548  */
549 static int pcie_relaxed_ordering = -1;
550 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
551     &pcie_relaxed_ordering, 0,
552     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
553
554 static int t4_panic_on_fatal_err = 0;
555 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RDTUN,
556     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
557
558 #ifdef TCP_OFFLOAD
559 /*
560  * TOE tunables.
561  */
562 static int t4_cop_managed_offloading = 0;
563 TUNABLE_INT("hw.cxgbe.cop_managed_offloading", &t4_cop_managed_offloading);
564 #endif
565
566 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
567 static int vi_mac_funcs[] = {
568         FW_VI_FUNC_ETH,
569         FW_VI_FUNC_OFLD,
570         FW_VI_FUNC_IWARP,
571         FW_VI_FUNC_OPENISCSI,
572         FW_VI_FUNC_OPENFCOE,
573         FW_VI_FUNC_FOISCSI,
574         FW_VI_FUNC_FOFCOE,
575 };
576
577 struct intrs_and_queues {
578         uint16_t intr_type;     /* INTx, MSI, or MSI-X */
579         uint16_t num_vis;       /* number of VIs for each port */
580         uint16_t nirq;          /* Total # of vectors */
581         uint16_t ntxq;          /* # of NIC txq's for each port */
582         uint16_t nrxq;          /* # of NIC rxq's for each port */
583         uint16_t nofldtxq;      /* # of TOE txq's for each port */
584         uint16_t nofldrxq;      /* # of TOE rxq's for each port */
585
586         /* The vcxgbe/vcxl interfaces use these and not the ones above. */
587         uint16_t ntxq_vi;       /* # of NIC txq's */
588         uint16_t nrxq_vi;       /* # of NIC rxq's */
589         uint16_t nofldtxq_vi;   /* # of TOE txq's */
590         uint16_t nofldrxq_vi;   /* # of TOE rxq's */
591         uint16_t nnmtxq_vi;     /* # of netmap txq's */
592         uint16_t nnmrxq_vi;     /* # of netmap rxq's */
593 };
594
595 static void setup_memwin(struct adapter *);
596 static void position_memwin(struct adapter *, int, uint32_t);
597 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
598 static int fwmtype_to_hwmtype(int);
599 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
600     uint32_t *);
601 static int fixup_devlog_params(struct adapter *);
602 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
603 static int contact_firmware(struct adapter *);
604 static int partition_resources(struct adapter *);
605 static int get_params__pre_init(struct adapter *);
606 static int set_params__pre_init(struct adapter *);
607 static int get_params__post_init(struct adapter *);
608 static int set_params__post_init(struct adapter *);
609 static void t4_set_desc(struct adapter *);
610 static bool fixed_ifmedia(struct port_info *);
611 static void build_medialist(struct port_info *);
612 static void init_link_config(struct port_info *);
613 static int fixup_link_config(struct port_info *);
614 static int apply_link_config(struct port_info *);
615 static int cxgbe_init_synchronized(struct vi_info *);
616 static int cxgbe_uninit_synchronized(struct vi_info *);
617 static void quiesce_txq(struct adapter *, struct sge_txq *);
618 static void quiesce_wrq(struct adapter *, struct sge_wrq *);
619 static void quiesce_iq(struct adapter *, struct sge_iq *);
620 static void quiesce_fl(struct adapter *, struct sge_fl *);
621 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
622     driver_intr_t *, void *, char *);
623 static int t4_free_irq(struct adapter *, struct irq *);
624 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
625 static void vi_refresh_stats(struct adapter *, struct vi_info *);
626 static void cxgbe_refresh_stats(struct adapter *, struct port_info *);
627 static void cxgbe_tick(void *);
628 static void cxgbe_sysctls(struct port_info *);
629 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
630 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
631 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
632 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
633 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
634 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
635 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
636 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
637 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
638 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
639 static int sysctl_fec(SYSCTL_HANDLER_ARGS);
640 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
641 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
642 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
643 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
644 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
645 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
646 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
647 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
648 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
649 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
650 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
651 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
652 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
653 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
654 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
655 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
656 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
657 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
658 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
659 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
660 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
661 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
662 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
663 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
664 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
665 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
666 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
667 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
668 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
669 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
670 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
671 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
672 #ifdef TCP_OFFLOAD
673 static int sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS);
674 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
675 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
676 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
677 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
678 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
679 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
680 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
681 #endif
682 static int get_sge_context(struct adapter *, struct t4_sge_context *);
683 static int load_fw(struct adapter *, struct t4_data *);
684 static int load_cfg(struct adapter *, struct t4_data *);
685 static int load_boot(struct adapter *, struct t4_bootrom *);
686 static int load_bootcfg(struct adapter *, struct t4_data *);
687 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
688 static void free_offload_policy(struct t4_offload_policy *);
689 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
690 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
691 static int read_i2c(struct adapter *, struct t4_i2c_data *);
692 #ifdef TCP_OFFLOAD
693 static int toe_capability(struct vi_info *, int);
694 #endif
695 static int mod_event(module_t, int, void *);
696 static int notify_siblings(device_t, int);
697
698 struct {
699         uint16_t device;
700         char *desc;
701 } t4_pciids[] = {
702         {0xa000, "Chelsio Terminator 4 FPGA"},
703         {0x4400, "Chelsio T440-dbg"},
704         {0x4401, "Chelsio T420-CR"},
705         {0x4402, "Chelsio T422-CR"},
706         {0x4403, "Chelsio T440-CR"},
707         {0x4404, "Chelsio T420-BCH"},
708         {0x4405, "Chelsio T440-BCH"},
709         {0x4406, "Chelsio T440-CH"},
710         {0x4407, "Chelsio T420-SO"},
711         {0x4408, "Chelsio T420-CX"},
712         {0x4409, "Chelsio T420-BT"},
713         {0x440a, "Chelsio T404-BT"},
714         {0x440e, "Chelsio T440-LP-CR"},
715 }, t5_pciids[] = {
716         {0xb000, "Chelsio Terminator 5 FPGA"},
717         {0x5400, "Chelsio T580-dbg"},
718         {0x5401,  "Chelsio T520-CR"},           /* 2 x 10G */
719         {0x5402,  "Chelsio T522-CR"},           /* 2 x 10G, 2 X 1G */
720         {0x5403,  "Chelsio T540-CR"},           /* 4 x 10G */
721         {0x5407,  "Chelsio T520-SO"},           /* 2 x 10G, nomem */
722         {0x5409,  "Chelsio T520-BT"},           /* 2 x 10GBaseT */
723         {0x540a,  "Chelsio T504-BT"},           /* 4 x 1G */
724         {0x540d,  "Chelsio T580-CR"},           /* 2 x 40G */
725         {0x540e,  "Chelsio T540-LP-CR"},        /* 4 x 10G */
726         {0x5410,  "Chelsio T580-LP-CR"},        /* 2 x 40G */
727         {0x5411,  "Chelsio T520-LL-CR"},        /* 2 x 10G */
728         {0x5412,  "Chelsio T560-CR"},           /* 1 x 40G, 2 x 10G */
729         {0x5414,  "Chelsio T580-LP-SO-CR"},     /* 2 x 40G, nomem */
730         {0x5415,  "Chelsio T502-BT"},           /* 2 x 1G */
731         {0x5418,  "Chelsio T540-BT"},           /* 4 x 10GBaseT */
732         {0x5419,  "Chelsio T540-LP-BT"},        /* 4 x 10GBaseT */
733         {0x541a,  "Chelsio T540-SO-BT"},        /* 4 x 10GBaseT, nomem */
734         {0x541b,  "Chelsio T540-SO-CR"},        /* 4 x 10G, nomem */
735
736         /* Custom */
737         {0x5483, "Custom T540-CR"},
738         {0x5484, "Custom T540-BT"},
739 }, t6_pciids[] = {
740         {0xc006, "Chelsio Terminator 6 FPGA"},  /* T6 PE10K6 FPGA (PF0) */
741         {0x6400, "Chelsio T6-DBG-25"},          /* 2 x 10/25G, debug */
742         {0x6401, "Chelsio T6225-CR"},           /* 2 x 10/25G */
743         {0x6402, "Chelsio T6225-SO-CR"},        /* 2 x 10/25G, nomem */
744         {0x6403, "Chelsio T6425-CR"},           /* 4 x 10/25G */
745         {0x6404, "Chelsio T6425-SO-CR"},        /* 4 x 10/25G, nomem */
746         {0x6405, "Chelsio T6225-OCP-SO"},       /* 2 x 10/25G, nomem */
747         {0x6406, "Chelsio T62100-OCP-SO"},      /* 2 x 40/50/100G, nomem */
748         {0x6407, "Chelsio T62100-LP-CR"},       /* 2 x 40/50/100G */
749         {0x6408, "Chelsio T62100-SO-CR"},       /* 2 x 40/50/100G, nomem */
750         {0x6409, "Chelsio T6210-BT"},           /* 2 x 10GBASE-T */
751         {0x640d, "Chelsio T62100-CR"},          /* 2 x 40/50/100G */
752         {0x6410, "Chelsio T6-DBG-100"},         /* 2 x 40/50/100G, debug */
753         {0x6411, "Chelsio T6225-LL-CR"},        /* 2 x 10/25G */
754         {0x6414, "Chelsio T61100-OCP-SO"},      /* 1 x 40/50/100G, nomem */
755         {0x6415, "Chelsio T6201-BT"},           /* 2 x 1000BASE-T */
756
757         /* Custom */
758         {0x6480, "Custom T6225-CR"},
759         {0x6481, "Custom T62100-CR"},
760         {0x6482, "Custom T6225-CR"},
761         {0x6483, "Custom T62100-CR"},
762         {0x6484, "Custom T64100-CR"},
763         {0x6485, "Custom T6240-SO"},
764         {0x6486, "Custom T6225-SO-CR"},
765         {0x6487, "Custom T6225-CR"},
766 };
767
768 #ifdef TCP_OFFLOAD
769 /*
770  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
771  * be exactly the same for both rxq and ofld_rxq.
772  */
773 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
774 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
775 #endif
776 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
777
778 static int
779 t4_probe(device_t dev)
780 {
781         int i;
782         uint16_t v = pci_get_vendor(dev);
783         uint16_t d = pci_get_device(dev);
784         uint8_t f = pci_get_function(dev);
785
786         if (v != PCI_VENDOR_ID_CHELSIO)
787                 return (ENXIO);
788
789         /* Attach only to PF0 of the FPGA */
790         if (d == 0xa000 && f != 0)
791                 return (ENXIO);
792
793         for (i = 0; i < nitems(t4_pciids); i++) {
794                 if (d == t4_pciids[i].device) {
795                         device_set_desc(dev, t4_pciids[i].desc);
796                         return (BUS_PROBE_DEFAULT);
797                 }
798         }
799
800         return (ENXIO);
801 }
802
803 static int
804 t5_probe(device_t dev)
805 {
806         int i;
807         uint16_t v = pci_get_vendor(dev);
808         uint16_t d = pci_get_device(dev);
809         uint8_t f = pci_get_function(dev);
810
811         if (v != PCI_VENDOR_ID_CHELSIO)
812                 return (ENXIO);
813
814         /* Attach only to PF0 of the FPGA */
815         if (d == 0xb000 && f != 0)
816                 return (ENXIO);
817
818         for (i = 0; i < nitems(t5_pciids); i++) {
819                 if (d == t5_pciids[i].device) {
820                         device_set_desc(dev, t5_pciids[i].desc);
821                         return (BUS_PROBE_DEFAULT);
822                 }
823         }
824
825         return (ENXIO);
826 }
827
828 static int
829 t6_probe(device_t dev)
830 {
831         int i;
832         uint16_t v = pci_get_vendor(dev);
833         uint16_t d = pci_get_device(dev);
834
835         if (v != PCI_VENDOR_ID_CHELSIO)
836                 return (ENXIO);
837
838         for (i = 0; i < nitems(t6_pciids); i++) {
839                 if (d == t6_pciids[i].device) {
840                         device_set_desc(dev, t6_pciids[i].desc);
841                         return (BUS_PROBE_DEFAULT);
842                 }
843         }
844
845         return (ENXIO);
846 }
847
848 static void
849 t5_attribute_workaround(device_t dev)
850 {
851         device_t root_port;
852         uint32_t v;
853
854         /*
855          * The T5 chips do not properly echo the No Snoop and Relaxed
856          * Ordering attributes when replying to a TLP from a Root
857          * Port.  As a workaround, find the parent Root Port and
858          * disable No Snoop and Relaxed Ordering.  Note that this
859          * affects all devices under this root port.
860          */
861         root_port = pci_find_pcie_root_port(dev);
862         if (root_port == NULL) {
863                 device_printf(dev, "Unable to find parent root port\n");
864                 return;
865         }
866
867         v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
868             PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
869         if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
870             0)
871                 device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
872                     device_get_nameunit(root_port));
873 }
874
875 static const struct devnames devnames[] = {
876         {
877                 .nexus_name = "t4nex",
878                 .ifnet_name = "cxgbe",
879                 .vi_ifnet_name = "vcxgbe",
880                 .pf03_drv_name = "t4iov",
881                 .vf_nexus_name = "t4vf",
882                 .vf_ifnet_name = "cxgbev"
883         }, {
884                 .nexus_name = "t5nex",
885                 .ifnet_name = "cxl",
886                 .vi_ifnet_name = "vcxl",
887                 .pf03_drv_name = "t5iov",
888                 .vf_nexus_name = "t5vf",
889                 .vf_ifnet_name = "cxlv"
890         }, {
891                 .nexus_name = "t6nex",
892                 .ifnet_name = "cc",
893                 .vi_ifnet_name = "vcc",
894                 .pf03_drv_name = "t6iov",
895                 .vf_nexus_name = "t6vf",
896                 .vf_ifnet_name = "ccv"
897         }
898 };
899
900 void
901 t4_init_devnames(struct adapter *sc)
902 {
903         int id;
904
905         id = chip_id(sc);
906         if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
907                 sc->names = &devnames[id - CHELSIO_T4];
908         else {
909                 device_printf(sc->dev, "chip id %d is not supported.\n", id);
910                 sc->names = NULL;
911         }
912 }
913
914 static int
915 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
916 {
917         const char *parent, *name;
918         long value;
919         int line, unit;
920
921         line = 0;
922         parent = device_get_nameunit(sc->dev);
923         name = sc->names->ifnet_name;
924         while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
925                 if (resource_long_value(name, unit, "port", &value) == 0 &&
926                     value == pi->port_id)
927                         return (unit);
928         }
929         return (-1);
930 }
931
932 static int
933 t4_attach(device_t dev)
934 {
935         struct adapter *sc;
936         int rc = 0, i, j, rqidx, tqidx, nports;
937         struct make_dev_args mda;
938         struct intrs_and_queues iaq;
939         struct sge *s;
940         uint32_t *buf;
941 #ifdef TCP_OFFLOAD
942         int ofld_rqidx, ofld_tqidx;
943 #endif
944 #ifdef DEV_NETMAP
945         int nm_rqidx, nm_tqidx;
946 #endif
947         int num_vis;
948
949         sc = device_get_softc(dev);
950         sc->dev = dev;
951         TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
952
953         if ((pci_get_device(dev) & 0xff00) == 0x5400)
954                 t5_attribute_workaround(dev);
955         pci_enable_busmaster(dev);
956         if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
957                 uint32_t v;
958
959                 pci_set_max_read_req(dev, 4096);
960                 v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
961                 sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
962                 if (pcie_relaxed_ordering == 0 &&
963                     (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
964                         v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
965                         pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
966                 } else if (pcie_relaxed_ordering == 1 &&
967                     (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
968                         v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
969                         pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
970                 }
971         }
972
973         sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
974         sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
975         sc->traceq = -1;
976         mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
977         snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
978             device_get_nameunit(dev));
979
980         snprintf(sc->lockname, sizeof(sc->lockname), "%s",
981             device_get_nameunit(dev));
982         mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
983         t4_add_adapter(sc);
984
985         mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
986         TAILQ_INIT(&sc->sfl);
987         callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
988
989         mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
990
991         sc->policy = NULL;
992         rw_init(&sc->policy_lock, "connection offload policy");
993
994         rc = t4_map_bars_0_and_4(sc);
995         if (rc != 0)
996                 goto done; /* error message displayed already */
997
998         memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
999
1000         /* Prepare the adapter for operation. */
1001         buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1002         rc = -t4_prep_adapter(sc, buf);
1003         free(buf, M_CXGBE);
1004         if (rc != 0) {
1005                 device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1006                 goto done;
1007         }
1008
1009         /*
1010          * This is the real PF# to which we're attaching.  Works from within PCI
1011          * passthrough environments too, where pci_get_function() could return a
1012          * different PF# depending on the passthrough configuration.  We need to
1013          * use the real PF# in all our communication with the firmware.
1014          */
1015         j = t4_read_reg(sc, A_PL_WHOAMI);
1016         sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1017         sc->mbox = sc->pf;
1018
1019         t4_init_devnames(sc);
1020         if (sc->names == NULL) {
1021                 rc = ENOTSUP;
1022                 goto done; /* error message displayed already */
1023         }
1024
1025         /*
1026          * Do this really early, with the memory windows set up even before the
1027          * character device.  The userland tool's register i/o and mem read
1028          * will work even in "recovery mode".
1029          */
1030         setup_memwin(sc);
1031         if (t4_init_devlog_params(sc, 0) == 0)
1032                 fixup_devlog_params(sc);
1033         make_dev_args_init(&mda);
1034         mda.mda_devsw = &t4_cdevsw;
1035         mda.mda_uid = UID_ROOT;
1036         mda.mda_gid = GID_WHEEL;
1037         mda.mda_mode = 0600;
1038         mda.mda_si_drv1 = sc;
1039         rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1040         if (rc != 0)
1041                 device_printf(dev, "failed to create nexus char device: %d.\n",
1042                     rc);
1043
1044         /* Go no further if recovery mode has been requested. */
1045         if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1046                 device_printf(dev, "recovery mode.\n");
1047                 goto done;
1048         }
1049
1050 #if defined(__i386__)
1051         if ((cpu_feature & CPUID_CX8) == 0) {
1052                 device_printf(dev, "64 bit atomics not available.\n");
1053                 rc = ENOTSUP;
1054                 goto done;
1055         }
1056 #endif
1057
1058         /* Contact the firmware and try to become the master driver. */
1059         rc = contact_firmware(sc);
1060         if (rc != 0)
1061                 goto done; /* error message displayed already */
1062         MPASS(sc->flags & FW_OK);
1063
1064         rc = get_params__pre_init(sc);
1065         if (rc != 0)
1066                 goto done; /* error message displayed already */
1067
1068         if (sc->flags & MASTER_PF) {
1069                 rc = partition_resources(sc);
1070                 if (rc != 0)
1071                         goto done; /* error message displayed already */
1072                 t4_intr_clear(sc);
1073         }
1074
1075         rc = get_params__post_init(sc);
1076         if (rc != 0)
1077                 goto done; /* error message displayed already */
1078
1079         rc = set_params__post_init(sc);
1080         if (rc != 0)
1081                 goto done; /* error message displayed already */
1082
1083         rc = t4_map_bar_2(sc);
1084         if (rc != 0)
1085                 goto done; /* error message displayed already */
1086
1087         rc = t4_create_dma_tag(sc);
1088         if (rc != 0)
1089                 goto done; /* error message displayed already */
1090
1091         /*
1092          * First pass over all the ports - allocate VIs and initialize some
1093          * basic parameters like mac address, port type, etc.
1094          */
1095         for_each_port(sc, i) {
1096                 struct port_info *pi;
1097
1098                 pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1099                 sc->port[i] = pi;
1100
1101                 /* These must be set before t4_port_init */
1102                 pi->adapter = sc;
1103                 pi->port_id = i;
1104                 /*
1105                  * XXX: vi[0] is special so we can't delay this allocation until
1106                  * pi->nvi's final value is known.
1107                  */
1108                 pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1109                     M_ZERO | M_WAITOK);
1110
1111                 /*
1112                  * Allocate the "main" VI and initialize parameters
1113                  * like mac addr.
1114                  */
1115                 rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1116                 if (rc != 0) {
1117                         device_printf(dev, "unable to initialize port %d: %d\n",
1118                             i, rc);
1119                         free(pi->vi, M_CXGBE);
1120                         free(pi, M_CXGBE);
1121                         sc->port[i] = NULL;
1122                         goto done;
1123                 }
1124
1125                 snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1126                     device_get_nameunit(dev), i);
1127                 mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1128                 sc->chan_map[pi->tx_chan] = i;
1129
1130                 /* All VIs on this port share this media. */
1131                 ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1132                     cxgbe_media_status);
1133
1134                 PORT_LOCK(pi);
1135                 init_link_config(pi);
1136                 fixup_link_config(pi);
1137                 build_medialist(pi);
1138                 if (fixed_ifmedia(pi))
1139                         pi->flags |= FIXED_IFMEDIA;
1140                 PORT_UNLOCK(pi);
1141
1142                 pi->dev = device_add_child(dev, sc->names->ifnet_name,
1143                     t4_ifnet_unit(sc, pi));
1144                 if (pi->dev == NULL) {
1145                         device_printf(dev,
1146                             "failed to add device for port %d.\n", i);
1147                         rc = ENXIO;
1148                         goto done;
1149                 }
1150                 pi->vi[0].dev = pi->dev;
1151                 device_set_softc(pi->dev, pi);
1152         }
1153
1154         /*
1155          * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1156          */
1157         nports = sc->params.nports;
1158         rc = cfg_itype_and_nqueues(sc, &iaq);
1159         if (rc != 0)
1160                 goto done; /* error message displayed already */
1161
1162         num_vis = iaq.num_vis;
1163         sc->intr_type = iaq.intr_type;
1164         sc->intr_count = iaq.nirq;
1165
1166         s = &sc->sge;
1167         s->nrxq = nports * iaq.nrxq;
1168         s->ntxq = nports * iaq.ntxq;
1169         if (num_vis > 1) {
1170                 s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1171                 s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1172         }
1173         s->neq = s->ntxq + s->nrxq;     /* the free list in an rxq is an eq */
1174         s->neq += nports;               /* ctrl queues: 1 per port */
1175         s->niq = s->nrxq + 1;           /* 1 extra for firmware event queue */
1176 #ifdef TCP_OFFLOAD
1177         if (is_offload(sc)) {
1178                 s->nofldrxq = nports * iaq.nofldrxq;
1179                 s->nofldtxq = nports * iaq.nofldtxq;
1180                 if (num_vis > 1) {
1181                         s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1182                         s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1183                 }
1184                 s->neq += s->nofldtxq + s->nofldrxq;
1185                 s->niq += s->nofldrxq;
1186
1187                 s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1188                     M_CXGBE, M_ZERO | M_WAITOK);
1189                 s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_wrq),
1190                     M_CXGBE, M_ZERO | M_WAITOK);
1191         }
1192 #endif
1193 #ifdef DEV_NETMAP
1194         if (num_vis > 1) {
1195                 s->nnmrxq = nports * (num_vis - 1) * iaq.nnmrxq_vi;
1196                 s->nnmtxq = nports * (num_vis - 1) * iaq.nnmtxq_vi;
1197         }
1198         s->neq += s->nnmtxq + s->nnmrxq;
1199         s->niq += s->nnmrxq;
1200
1201         s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1202             M_CXGBE, M_ZERO | M_WAITOK);
1203         s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1204             M_CXGBE, M_ZERO | M_WAITOK);
1205 #endif
1206
1207         s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1208             M_ZERO | M_WAITOK);
1209         s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1210             M_ZERO | M_WAITOK);
1211         s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1212             M_ZERO | M_WAITOK);
1213         s->iqmap = malloc(s->niq * sizeof(struct sge_iq *), M_CXGBE,
1214             M_ZERO | M_WAITOK);
1215         s->eqmap = malloc(s->neq * sizeof(struct sge_eq *), M_CXGBE,
1216             M_ZERO | M_WAITOK);
1217
1218         sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1219             M_ZERO | M_WAITOK);
1220
1221         t4_init_l2t(sc, M_WAITOK);
1222         t4_init_smt(sc, M_WAITOK);
1223         t4_init_tx_sched(sc);
1224 #ifdef INET6
1225         t4_init_clip_table(sc);
1226 #endif
1227         if (sc->vres.key.size != 0)
1228                 sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1229                     sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1230
1231         /*
1232          * Second pass over the ports.  This time we know the number of rx and
1233          * tx queues that each port should get.
1234          */
1235         rqidx = tqidx = 0;
1236 #ifdef TCP_OFFLOAD
1237         ofld_rqidx = ofld_tqidx = 0;
1238 #endif
1239 #ifdef DEV_NETMAP
1240         nm_rqidx = nm_tqidx = 0;
1241 #endif
1242         for_each_port(sc, i) {
1243                 struct port_info *pi = sc->port[i];
1244                 struct vi_info *vi;
1245
1246                 if (pi == NULL)
1247                         continue;
1248
1249                 pi->nvi = num_vis;
1250                 for_each_vi(pi, j, vi) {
1251                         vi->pi = pi;
1252                         vi->qsize_rxq = t4_qsize_rxq;
1253                         vi->qsize_txq = t4_qsize_txq;
1254
1255                         vi->first_rxq = rqidx;
1256                         vi->first_txq = tqidx;
1257                         vi->tmr_idx = t4_tmr_idx;
1258                         vi->pktc_idx = t4_pktc_idx;
1259                         vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1260                         vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1261
1262                         rqidx += vi->nrxq;
1263                         tqidx += vi->ntxq;
1264
1265                         if (j == 0 && vi->ntxq > 1)
1266                                 vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1267                         else
1268                                 vi->rsrv_noflowq = 0;
1269
1270 #ifdef TCP_OFFLOAD
1271                         vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1272                         vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1273                         vi->first_ofld_rxq = ofld_rqidx;
1274                         vi->first_ofld_txq = ofld_tqidx;
1275                         vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1276                         vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1277
1278                         ofld_rqidx += vi->nofldrxq;
1279                         ofld_tqidx += vi->nofldtxq;
1280 #endif
1281 #ifdef DEV_NETMAP
1282                         if (j > 0) {
1283                                 vi->first_nm_rxq = nm_rqidx;
1284                                 vi->first_nm_txq = nm_tqidx;
1285                                 vi->nnmrxq = iaq.nnmrxq_vi;
1286                                 vi->nnmtxq = iaq.nnmtxq_vi;
1287                                 nm_rqidx += vi->nnmrxq;
1288                                 nm_tqidx += vi->nnmtxq;
1289                         }
1290 #endif
1291                 }
1292         }
1293
1294         rc = t4_setup_intr_handlers(sc);
1295         if (rc != 0) {
1296                 device_printf(dev,
1297                     "failed to setup interrupt handlers: %d\n", rc);
1298                 goto done;
1299         }
1300
1301         rc = bus_generic_probe(dev);
1302         if (rc != 0) {
1303                 device_printf(dev, "failed to probe child drivers: %d\n", rc);
1304                 goto done;
1305         }
1306
1307         /*
1308          * Ensure thread-safe mailbox access (in debug builds).
1309          *
1310          * So far this was the only thread accessing the mailbox but various
1311          * ifnets and sysctls are about to be created and their handlers/ioctls
1312          * will access the mailbox from different threads.
1313          */
1314         sc->flags |= CHK_MBOX_ACCESS;
1315
1316         rc = bus_generic_attach(dev);
1317         if (rc != 0) {
1318                 device_printf(dev,
1319                     "failed to attach all child ports: %d\n", rc);
1320                 goto done;
1321         }
1322
1323         device_printf(dev,
1324             "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1325             sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1326             sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1327             (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1328             sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1329
1330         t4_set_desc(sc);
1331
1332         notify_siblings(dev, 0);
1333
1334 done:
1335         if (rc != 0 && sc->cdev) {
1336                 /* cdev was created and so cxgbetool works; recover that way. */
1337                 device_printf(dev,
1338                     "error during attach, adapter is now in recovery mode.\n");
1339                 rc = 0;
1340         }
1341
1342         if (rc != 0)
1343                 t4_detach_common(dev);
1344         else
1345                 t4_sysctls(sc);
1346
1347         return (rc);
1348 }
1349
1350 static int
1351 t4_child_location_str(device_t bus, device_t dev, char *buf, size_t buflen)
1352 {
1353         struct adapter *sc;
1354         struct port_info *pi;
1355         int i;
1356
1357         sc = device_get_softc(bus);
1358         buf[0] = '\0';
1359         for_each_port(sc, i) {
1360                 pi = sc->port[i];
1361                 if (pi != NULL && pi->dev == dev) {
1362                         snprintf(buf, buflen, "port=%d", pi->port_id);
1363                         break;
1364                 }
1365         }
1366         return (0);
1367 }
1368
1369 static int
1370 t4_ready(device_t dev)
1371 {
1372         struct adapter *sc;
1373
1374         sc = device_get_softc(dev);
1375         if (sc->flags & FW_OK)
1376                 return (0);
1377         return (ENXIO);
1378 }
1379
1380 static int
1381 t4_read_port_device(device_t dev, int port, device_t *child)
1382 {
1383         struct adapter *sc;
1384         struct port_info *pi;
1385
1386         sc = device_get_softc(dev);
1387         if (port < 0 || port >= MAX_NPORTS)
1388                 return (EINVAL);
1389         pi = sc->port[port];
1390         if (pi == NULL || pi->dev == NULL)
1391                 return (ENXIO);
1392         *child = pi->dev;
1393         return (0);
1394 }
1395
1396 static int
1397 notify_siblings(device_t dev, int detaching)
1398 {
1399         device_t sibling;
1400         int error, i;
1401
1402         error = 0;
1403         for (i = 0; i < PCI_FUNCMAX; i++) {
1404                 if (i == pci_get_function(dev))
1405                         continue;
1406                 sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1407                     pci_get_slot(dev), i);
1408                 if (sibling == NULL || !device_is_attached(sibling))
1409                         continue;
1410                 if (detaching)
1411                         error = T4_DETACH_CHILD(sibling);
1412                 else
1413                         (void)T4_ATTACH_CHILD(sibling);
1414                 if (error)
1415                         break;
1416         }
1417         return (error);
1418 }
1419
1420 /*
1421  * Idempotent
1422  */
1423 static int
1424 t4_detach(device_t dev)
1425 {
1426         struct adapter *sc;
1427         int rc;
1428
1429         sc = device_get_softc(dev);
1430
1431         rc = notify_siblings(dev, 1);
1432         if (rc) {
1433                 device_printf(dev,
1434                     "failed to detach sibling devices: %d\n", rc);
1435                 return (rc);
1436         }
1437
1438         return (t4_detach_common(dev));
1439 }
1440
1441 int
1442 t4_detach_common(device_t dev)
1443 {
1444         struct adapter *sc;
1445         struct port_info *pi;
1446         int i, rc;
1447
1448         sc = device_get_softc(dev);
1449
1450         if (sc->cdev) {
1451                 destroy_dev(sc->cdev);
1452                 sc->cdev = NULL;
1453         }
1454
1455         sc->flags &= ~CHK_MBOX_ACCESS;
1456         if (sc->flags & FULL_INIT_DONE) {
1457                 if (!(sc->flags & IS_VF))
1458                         t4_intr_disable(sc);
1459         }
1460
1461         if (device_is_attached(dev)) {
1462                 rc = bus_generic_detach(dev);
1463                 if (rc) {
1464                         device_printf(dev,
1465                             "failed to detach child devices: %d\n", rc);
1466                         return (rc);
1467                 }
1468         }
1469
1470         for (i = 0; i < sc->intr_count; i++)
1471                 t4_free_irq(sc, &sc->irq[i]);
1472
1473         if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1474                 t4_free_tx_sched(sc);
1475
1476         for (i = 0; i < MAX_NPORTS; i++) {
1477                 pi = sc->port[i];
1478                 if (pi) {
1479                         t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1480                         if (pi->dev)
1481                                 device_delete_child(dev, pi->dev);
1482
1483                         mtx_destroy(&pi->pi_lock);
1484                         free(pi->vi, M_CXGBE);
1485                         free(pi, M_CXGBE);
1486                 }
1487         }
1488
1489         device_delete_children(dev);
1490
1491         if (sc->flags & FULL_INIT_DONE)
1492                 adapter_full_uninit(sc);
1493
1494         if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1495                 t4_fw_bye(sc, sc->mbox);
1496
1497         if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1498                 pci_release_msi(dev);
1499
1500         if (sc->regs_res)
1501                 bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1502                     sc->regs_res);
1503
1504         if (sc->udbs_res)
1505                 bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1506                     sc->udbs_res);
1507
1508         if (sc->msix_res)
1509                 bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1510                     sc->msix_res);
1511
1512         if (sc->l2t)
1513                 t4_free_l2t(sc->l2t);
1514         if (sc->key_map)
1515                 vmem_destroy(sc->key_map);
1516         if (sc->smt)
1517                 t4_free_smt(sc->smt);
1518 #ifdef INET6
1519         t4_destroy_clip_table(sc);
1520 #endif
1521
1522 #ifdef TCP_OFFLOAD
1523         free(sc->sge.ofld_rxq, M_CXGBE);
1524         free(sc->sge.ofld_txq, M_CXGBE);
1525 #endif
1526 #ifdef DEV_NETMAP
1527         free(sc->sge.nm_rxq, M_CXGBE);
1528         free(sc->sge.nm_txq, M_CXGBE);
1529 #endif
1530         free(sc->irq, M_CXGBE);
1531         free(sc->sge.rxq, M_CXGBE);
1532         free(sc->sge.txq, M_CXGBE);
1533         free(sc->sge.ctrlq, M_CXGBE);
1534         free(sc->sge.iqmap, M_CXGBE);
1535         free(sc->sge.eqmap, M_CXGBE);
1536         free(sc->tids.ftid_tab, M_CXGBE);
1537         free(sc->tids.hpftid_tab, M_CXGBE);
1538         free_hftid_hash(&sc->tids);
1539         free(sc->tids.atid_tab, M_CXGBE);
1540         free(sc->tids.tid_tab, M_CXGBE);
1541         free(sc->tt.tls_rx_ports, M_CXGBE);
1542         t4_destroy_dma_tag(sc);
1543         if (mtx_initialized(&sc->sc_lock)) {
1544                 sx_xlock(&t4_list_lock);
1545                 SLIST_REMOVE(&t4_list, sc, adapter, link);
1546                 sx_xunlock(&t4_list_lock);
1547                 mtx_destroy(&sc->sc_lock);
1548         }
1549
1550         callout_drain(&sc->sfl_callout);
1551         if (mtx_initialized(&sc->tids.ftid_lock)) {
1552                 mtx_destroy(&sc->tids.ftid_lock);
1553                 cv_destroy(&sc->tids.ftid_cv);
1554         }
1555         if (mtx_initialized(&sc->tids.atid_lock))
1556                 mtx_destroy(&sc->tids.atid_lock);
1557         if (mtx_initialized(&sc->sfl_lock))
1558                 mtx_destroy(&sc->sfl_lock);
1559         if (mtx_initialized(&sc->ifp_lock))
1560                 mtx_destroy(&sc->ifp_lock);
1561         if (mtx_initialized(&sc->reg_lock))
1562                 mtx_destroy(&sc->reg_lock);
1563
1564         if (rw_initialized(&sc->policy_lock)) {
1565                 rw_destroy(&sc->policy_lock);
1566 #ifdef TCP_OFFLOAD
1567                 if (sc->policy != NULL)
1568                         free_offload_policy(sc->policy);
1569 #endif
1570         }
1571
1572         for (i = 0; i < NUM_MEMWIN; i++) {
1573                 struct memwin *mw = &sc->memwin[i];
1574
1575                 if (rw_initialized(&mw->mw_lock))
1576                         rw_destroy(&mw->mw_lock);
1577         }
1578
1579         bzero(sc, sizeof(*sc));
1580
1581         return (0);
1582 }
1583
1584 static int
1585 cxgbe_probe(device_t dev)
1586 {
1587         char buf[128];
1588         struct port_info *pi = device_get_softc(dev);
1589
1590         snprintf(buf, sizeof(buf), "port %d", pi->port_id);
1591         device_set_desc_copy(dev, buf);
1592
1593         return (BUS_PROBE_DEFAULT);
1594 }
1595
1596 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
1597     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
1598     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS)
1599 #define T4_CAP_ENABLE (T4_CAP)
1600
1601 static int
1602 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
1603 {
1604         struct ifnet *ifp;
1605         struct sbuf *sb;
1606
1607         vi->xact_addr_filt = -1;
1608         callout_init(&vi->tick, 1);
1609
1610         /* Allocate an ifnet and set it up */
1611         ifp = if_alloc(IFT_ETHER);
1612         if (ifp == NULL) {
1613                 device_printf(dev, "Cannot allocate ifnet\n");
1614                 return (ENOMEM);
1615         }
1616         vi->ifp = ifp;
1617         ifp->if_softc = vi;
1618
1619         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1620         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1621
1622         ifp->if_init = cxgbe_init;
1623         ifp->if_ioctl = cxgbe_ioctl;
1624         ifp->if_transmit = cxgbe_transmit;
1625         ifp->if_qflush = cxgbe_qflush;
1626         ifp->if_get_counter = cxgbe_get_counter;
1627
1628         ifp->if_capabilities = T4_CAP;
1629 #ifdef TCP_OFFLOAD
1630         if (vi->nofldrxq != 0)
1631                 ifp->if_capabilities |= IFCAP_TOE;
1632 #endif
1633         ifp->if_capenable = T4_CAP_ENABLE;
1634         ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
1635             CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
1636
1637         ifp->if_hw_tsomax = IP_MAXPACKET;
1638         ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_TSO;
1639 #ifdef RATELIMIT
1640         if (is_ethoffload(vi->pi->adapter) && vi->nofldtxq != 0)
1641                 ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS_EO_TSO;
1642 #endif
1643         ifp->if_hw_tsomaxsegsize = 65536;
1644
1645         ether_ifattach(ifp, vi->hw_addr);
1646 #ifdef DEV_NETMAP
1647         if (vi->nnmrxq != 0)
1648                 cxgbe_nm_attach(vi);
1649 #endif
1650         sb = sbuf_new_auto();
1651         sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
1652 #ifdef TCP_OFFLOAD
1653         if (ifp->if_capabilities & IFCAP_TOE)
1654                 sbuf_printf(sb, "; %d txq, %d rxq (TOE)",
1655                     vi->nofldtxq, vi->nofldrxq);
1656 #endif
1657 #ifdef DEV_NETMAP
1658         if (ifp->if_capabilities & IFCAP_NETMAP)
1659                 sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
1660                     vi->nnmtxq, vi->nnmrxq);
1661 #endif
1662         sbuf_finish(sb);
1663         device_printf(dev, "%s\n", sbuf_data(sb));
1664         sbuf_delete(sb);
1665
1666         vi_sysctls(vi);
1667
1668         return (0);
1669 }
1670
1671 static int
1672 cxgbe_attach(device_t dev)
1673 {
1674         struct port_info *pi = device_get_softc(dev);
1675         struct adapter *sc = pi->adapter;
1676         struct vi_info *vi;
1677         int i, rc;
1678
1679         callout_init_mtx(&pi->tick, &pi->pi_lock, 0);
1680
1681         rc = cxgbe_vi_attach(dev, &pi->vi[0]);
1682         if (rc)
1683                 return (rc);
1684
1685         for_each_vi(pi, i, vi) {
1686                 if (i == 0)
1687                         continue;
1688                 vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
1689                 if (vi->dev == NULL) {
1690                         device_printf(dev, "failed to add VI %d\n", i);
1691                         continue;
1692                 }
1693                 device_set_softc(vi->dev, vi);
1694         }
1695
1696         cxgbe_sysctls(pi);
1697
1698         bus_generic_attach(dev);
1699
1700         return (0);
1701 }
1702
1703 static void
1704 cxgbe_vi_detach(struct vi_info *vi)
1705 {
1706         struct ifnet *ifp = vi->ifp;
1707
1708         ether_ifdetach(ifp);
1709
1710         /* Let detach proceed even if these fail. */
1711 #ifdef DEV_NETMAP
1712         if (ifp->if_capabilities & IFCAP_NETMAP)
1713                 cxgbe_nm_detach(vi);
1714 #endif
1715         cxgbe_uninit_synchronized(vi);
1716         callout_drain(&vi->tick);
1717         vi_full_uninit(vi);
1718
1719         if_free(vi->ifp);
1720         vi->ifp = NULL;
1721 }
1722
1723 static int
1724 cxgbe_detach(device_t dev)
1725 {
1726         struct port_info *pi = device_get_softc(dev);
1727         struct adapter *sc = pi->adapter;
1728         int rc;
1729
1730         /* Detach the extra VIs first. */
1731         rc = bus_generic_detach(dev);
1732         if (rc)
1733                 return (rc);
1734         device_delete_children(dev);
1735
1736         doom_vi(sc, &pi->vi[0]);
1737
1738         if (pi->flags & HAS_TRACEQ) {
1739                 sc->traceq = -1;        /* cloner should not create ifnet */
1740                 t4_tracer_port_detach(sc);
1741         }
1742
1743         cxgbe_vi_detach(&pi->vi[0]);
1744         callout_drain(&pi->tick);
1745         ifmedia_removeall(&pi->media);
1746
1747         end_synchronized_op(sc, 0);
1748
1749         return (0);
1750 }
1751
1752 static void
1753 cxgbe_init(void *arg)
1754 {
1755         struct vi_info *vi = arg;
1756         struct adapter *sc = vi->pi->adapter;
1757
1758         if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
1759                 return;
1760         cxgbe_init_synchronized(vi);
1761         end_synchronized_op(sc, 0);
1762 }
1763
1764 static int
1765 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
1766 {
1767         int rc = 0, mtu, can_sleep, if_flags, if_drv_flags, vi_if_flags;
1768         struct vi_info *vi = ifp->if_softc;
1769         struct port_info *pi = vi->pi;
1770         struct adapter *sc = pi->adapter;
1771         struct ifreq *ifr = (struct ifreq *)data;
1772         uint32_t mask;
1773
1774         switch (cmd) {
1775         case SIOCSIFMTU:
1776                 mtu = ifr->ifr_mtu;
1777                 if (mtu < ETHERMIN || mtu > MAX_MTU)
1778                         return (EINVAL);
1779
1780                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
1781                 if (rc)
1782                         return (rc);
1783                 ifp->if_mtu = mtu;
1784                 if (vi->flags & VI_INIT_DONE) {
1785                         t4_update_fl_bufsize(ifp);
1786                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1787                                 rc = update_mac_settings(ifp, XGMAC_MTU);
1788                 }
1789                 end_synchronized_op(sc, 0);
1790                 break;
1791
1792         case SIOCSIFFLAGS:
1793                 /*
1794                  * Decide what to do, with the port lock held.
1795                  */
1796                 PORT_LOCK(pi);
1797                 if_flags = ifp->if_flags;
1798                 if_drv_flags = ifp->if_drv_flags;
1799                 vi_if_flags = vi->if_flags;
1800                 if (if_flags & IFF_UP && if_drv_flags & IFF_DRV_RUNNING &&
1801                     (vi_if_flags ^ if_flags) & (IFF_PROMISC | IFF_ALLMULTI)) {
1802                         can_sleep = 0;
1803                 } else {
1804                         can_sleep = 1;
1805                 }
1806                 PORT_UNLOCK(pi);
1807
1808                 /*
1809                  * ifp/vi flags may change here but we'll just do what our local
1810                  * copy of the flags indicates and then update the driver owned
1811                  * ifp/vi flags (in a synch-op and with the port lock held) to
1812                  * reflect what we did.
1813                  */
1814
1815                 rc = begin_synchronized_op(sc, vi,
1816                     can_sleep ? (SLEEP_OK | INTR_OK) : HOLD_LOCK, "t4flg");
1817                 if (rc) {
1818                         if_printf(ifp, "%ssleepable synch operation failed: %d."
1819                             "  if_flags 0x%08x, if_drv_flags 0x%08x\n",
1820                             can_sleep ? "" : "non-", rc, if_flags,
1821                             if_drv_flags);
1822                         return (rc);
1823                 }
1824
1825                 if (if_flags & IFF_UP) {
1826                         if (if_drv_flags & IFF_DRV_RUNNING) {
1827                                 if ((if_flags ^ vi_if_flags) &
1828                                     (IFF_PROMISC | IFF_ALLMULTI)) {
1829                                         MPASS(can_sleep == 0);
1830                                         rc = update_mac_settings(ifp,
1831                                             XGMAC_PROMISC | XGMAC_ALLMULTI);
1832                                 }
1833                         } else {
1834                                 MPASS(can_sleep == 1);
1835                                 rc = cxgbe_init_synchronized(vi);
1836                         }
1837                 } else if (if_drv_flags & IFF_DRV_RUNNING) {
1838                         MPASS(can_sleep == 1);
1839                         rc = cxgbe_uninit_synchronized(vi);
1840                 }
1841                 PORT_LOCK(pi);
1842                 vi->if_flags = if_flags;
1843                 PORT_UNLOCK(pi);
1844                 end_synchronized_op(sc, can_sleep ? 0 : LOCK_HELD);
1845                 break;
1846
1847         case SIOCADDMULTI:
1848         case SIOCDELMULTI: /* these two are called with a mutex held :-( */
1849                 rc = begin_synchronized_op(sc, vi, HOLD_LOCK, "t4multi");
1850                 if (rc)
1851                         return (rc);
1852                 if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1853                         rc = update_mac_settings(ifp, XGMAC_MCADDRS);
1854                 end_synchronized_op(sc, LOCK_HELD);
1855                 break;
1856
1857         case SIOCSIFCAP:
1858                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
1859                 if (rc)
1860                         return (rc);
1861
1862                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1863                 if (mask & IFCAP_TXCSUM) {
1864                         ifp->if_capenable ^= IFCAP_TXCSUM;
1865                         ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
1866
1867                         if (IFCAP_TSO4 & ifp->if_capenable &&
1868                             !(IFCAP_TXCSUM & ifp->if_capenable)) {
1869                                 ifp->if_capenable &= ~IFCAP_TSO4;
1870                                 if_printf(ifp,
1871                                     "tso4 disabled due to -txcsum.\n");
1872                         }
1873                 }
1874                 if (mask & IFCAP_TXCSUM_IPV6) {
1875                         ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
1876                         ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
1877
1878                         if (IFCAP_TSO6 & ifp->if_capenable &&
1879                             !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1880                                 ifp->if_capenable &= ~IFCAP_TSO6;
1881                                 if_printf(ifp,
1882                                     "tso6 disabled due to -txcsum6.\n");
1883                         }
1884                 }
1885                 if (mask & IFCAP_RXCSUM)
1886                         ifp->if_capenable ^= IFCAP_RXCSUM;
1887                 if (mask & IFCAP_RXCSUM_IPV6)
1888                         ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
1889
1890                 /*
1891                  * Note that we leave CSUM_TSO alone (it is always set).  The
1892                  * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
1893                  * sending a TSO request our way, so it's sufficient to toggle
1894                  * IFCAP_TSOx only.
1895                  */
1896                 if (mask & IFCAP_TSO4) {
1897                         if (!(IFCAP_TSO4 & ifp->if_capenable) &&
1898                             !(IFCAP_TXCSUM & ifp->if_capenable)) {
1899                                 if_printf(ifp, "enable txcsum first.\n");
1900                                 rc = EAGAIN;
1901                                 goto fail;
1902                         }
1903                         ifp->if_capenable ^= IFCAP_TSO4;
1904                 }
1905                 if (mask & IFCAP_TSO6) {
1906                         if (!(IFCAP_TSO6 & ifp->if_capenable) &&
1907                             !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1908                                 if_printf(ifp, "enable txcsum6 first.\n");
1909                                 rc = EAGAIN;
1910                                 goto fail;
1911                         }
1912                         ifp->if_capenable ^= IFCAP_TSO6;
1913                 }
1914                 if (mask & IFCAP_LRO) {
1915 #if defined(INET) || defined(INET6)
1916                         int i;
1917                         struct sge_rxq *rxq;
1918
1919                         ifp->if_capenable ^= IFCAP_LRO;
1920                         for_each_rxq(vi, i, rxq) {
1921                                 if (ifp->if_capenable & IFCAP_LRO)
1922                                         rxq->iq.flags |= IQ_LRO_ENABLED;
1923                                 else
1924                                         rxq->iq.flags &= ~IQ_LRO_ENABLED;
1925                         }
1926 #endif
1927                 }
1928 #ifdef TCP_OFFLOAD
1929                 if (mask & IFCAP_TOE) {
1930                         int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
1931
1932                         rc = toe_capability(vi, enable);
1933                         if (rc != 0)
1934                                 goto fail;
1935
1936                         ifp->if_capenable ^= mask;
1937                 }
1938 #endif
1939                 if (mask & IFCAP_VLAN_HWTAGGING) {
1940                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1941                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1942                                 rc = update_mac_settings(ifp, XGMAC_VLANEX);
1943                 }
1944                 if (mask & IFCAP_VLAN_MTU) {
1945                         ifp->if_capenable ^= IFCAP_VLAN_MTU;
1946
1947                         /* Need to find out how to disable auto-mtu-inflation */
1948                 }
1949                 if (mask & IFCAP_VLAN_HWTSO)
1950                         ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
1951                 if (mask & IFCAP_VLAN_HWCSUM)
1952                         ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
1953
1954 #ifdef VLAN_CAPABILITIES
1955                 VLAN_CAPABILITIES(ifp);
1956 #endif
1957 fail:
1958                 end_synchronized_op(sc, 0);
1959                 break;
1960
1961         case SIOCSIFMEDIA:
1962         case SIOCGIFMEDIA:
1963         case SIOCGIFXMEDIA:
1964                 ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
1965                 break;
1966
1967         case SIOCGI2C: {
1968                 struct ifi2creq i2c;
1969
1970                 rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
1971                 if (rc != 0)
1972                         break;
1973                 if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
1974                         rc = EPERM;
1975                         break;
1976                 }
1977                 if (i2c.len > sizeof(i2c.data)) {
1978                         rc = EINVAL;
1979                         break;
1980                 }
1981                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
1982                 if (rc)
1983                         return (rc);
1984                 rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
1985                     i2c.offset, i2c.len, &i2c.data[0]);
1986                 end_synchronized_op(sc, 0);
1987                 if (rc == 0)
1988                         rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
1989                 break;
1990         }
1991
1992         default:
1993                 rc = ether_ioctl(ifp, cmd, data);
1994         }
1995
1996         return (rc);
1997 }
1998
1999 static int
2000 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
2001 {
2002         struct vi_info *vi = ifp->if_softc;
2003         struct port_info *pi = vi->pi;
2004         struct adapter *sc = pi->adapter;
2005         struct sge_txq *txq;
2006         void *items[1];
2007         int rc;
2008
2009         M_ASSERTPKTHDR(m);
2010         MPASS(m->m_nextpkt == NULL);    /* not quite ready for this yet */
2011
2012         if (__predict_false(pi->link_cfg.link_ok == false)) {
2013                 m_freem(m);
2014                 return (ENETDOWN);
2015         }
2016
2017         rc = parse_pkt(sc, &m);
2018         if (__predict_false(rc != 0)) {
2019                 MPASS(m == NULL);                       /* was freed already */
2020                 atomic_add_int(&pi->tx_parse_error, 1); /* rare, atomic is ok */
2021                 return (rc);
2022         }
2023
2024         /* Select a txq. */
2025         txq = &sc->sge.txq[vi->first_txq];
2026         if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2027                 txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
2028                     vi->rsrv_noflowq);
2029
2030         items[0] = m;
2031         rc = mp_ring_enqueue(txq->r, items, 1, 4096);
2032         if (__predict_false(rc != 0))
2033                 m_freem(m);
2034
2035         return (rc);
2036 }
2037
2038 static void
2039 cxgbe_qflush(struct ifnet *ifp)
2040 {
2041         struct vi_info *vi = ifp->if_softc;
2042         struct sge_txq *txq;
2043         int i;
2044
2045         /* queues do not exist if !VI_INIT_DONE. */
2046         if (vi->flags & VI_INIT_DONE) {
2047                 for_each_txq(vi, i, txq) {
2048                         TXQ_LOCK(txq);
2049                         txq->eq.flags |= EQ_QFLUSH;
2050                         TXQ_UNLOCK(txq);
2051                         while (!mp_ring_is_idle(txq->r)) {
2052                                 mp_ring_check_drainage(txq->r, 0);
2053                                 pause("qflush", 1);
2054                         }
2055                         TXQ_LOCK(txq);
2056                         txq->eq.flags &= ~EQ_QFLUSH;
2057                         TXQ_UNLOCK(txq);
2058                 }
2059         }
2060         if_qflush(ifp);
2061 }
2062
2063 static uint64_t
2064 vi_get_counter(struct ifnet *ifp, ift_counter c)
2065 {
2066         struct vi_info *vi = ifp->if_softc;
2067         struct fw_vi_stats_vf *s = &vi->stats;
2068
2069         vi_refresh_stats(vi->pi->adapter, vi);
2070
2071         switch (c) {
2072         case IFCOUNTER_IPACKETS:
2073                 return (s->rx_bcast_frames + s->rx_mcast_frames +
2074                     s->rx_ucast_frames);
2075         case IFCOUNTER_IERRORS:
2076                 return (s->rx_err_frames);
2077         case IFCOUNTER_OPACKETS:
2078                 return (s->tx_bcast_frames + s->tx_mcast_frames +
2079                     s->tx_ucast_frames + s->tx_offload_frames);
2080         case IFCOUNTER_OERRORS:
2081                 return (s->tx_drop_frames);
2082         case IFCOUNTER_IBYTES:
2083                 return (s->rx_bcast_bytes + s->rx_mcast_bytes +
2084                     s->rx_ucast_bytes);
2085         case IFCOUNTER_OBYTES:
2086                 return (s->tx_bcast_bytes + s->tx_mcast_bytes +
2087                     s->tx_ucast_bytes + s->tx_offload_bytes);
2088         case IFCOUNTER_IMCASTS:
2089                 return (s->rx_mcast_frames);
2090         case IFCOUNTER_OMCASTS:
2091                 return (s->tx_mcast_frames);
2092         case IFCOUNTER_OQDROPS: {
2093                 uint64_t drops;
2094
2095                 drops = 0;
2096                 if (vi->flags & VI_INIT_DONE) {
2097                         int i;
2098                         struct sge_txq *txq;
2099
2100                         for_each_txq(vi, i, txq)
2101                                 drops += counter_u64_fetch(txq->r->drops);
2102                 }
2103
2104                 return (drops);
2105
2106         }
2107
2108         default:
2109                 return (if_get_counter_default(ifp, c));
2110         }
2111 }
2112
2113 uint64_t
2114 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
2115 {
2116         struct vi_info *vi = ifp->if_softc;
2117         struct port_info *pi = vi->pi;
2118         struct adapter *sc = pi->adapter;
2119         struct port_stats *s = &pi->stats;
2120
2121         if (pi->nvi > 1 || sc->flags & IS_VF)
2122                 return (vi_get_counter(ifp, c));
2123
2124         cxgbe_refresh_stats(sc, pi);
2125
2126         switch (c) {
2127         case IFCOUNTER_IPACKETS:
2128                 return (s->rx_frames);
2129
2130         case IFCOUNTER_IERRORS:
2131                 return (s->rx_jabber + s->rx_runt + s->rx_too_long +
2132                     s->rx_fcs_err + s->rx_len_err);
2133
2134         case IFCOUNTER_OPACKETS:
2135                 return (s->tx_frames);
2136
2137         case IFCOUNTER_OERRORS:
2138                 return (s->tx_error_frames);
2139
2140         case IFCOUNTER_IBYTES:
2141                 return (s->rx_octets);
2142
2143         case IFCOUNTER_OBYTES:
2144                 return (s->tx_octets);
2145
2146         case IFCOUNTER_IMCASTS:
2147                 return (s->rx_mcast_frames);
2148
2149         case IFCOUNTER_OMCASTS:
2150                 return (s->tx_mcast_frames);
2151
2152         case IFCOUNTER_IQDROPS:
2153                 return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
2154                     s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
2155                     s->rx_trunc3 + pi->tnl_cong_drops);
2156
2157         case IFCOUNTER_OQDROPS: {
2158                 uint64_t drops;
2159
2160                 drops = s->tx_drop;
2161                 if (vi->flags & VI_INIT_DONE) {
2162                         int i;
2163                         struct sge_txq *txq;
2164
2165                         for_each_txq(vi, i, txq)
2166                                 drops += counter_u64_fetch(txq->r->drops);
2167                 }
2168
2169                 return (drops);
2170
2171         }
2172
2173         default:
2174                 return (if_get_counter_default(ifp, c));
2175         }
2176 }
2177
2178 /*
2179  * The kernel picks a media from the list we had provided but we still validate
2180  * the requeste.
2181  */
2182 int
2183 cxgbe_media_change(struct ifnet *ifp)
2184 {
2185         struct vi_info *vi = ifp->if_softc;
2186         struct port_info *pi = vi->pi;
2187         struct ifmedia *ifm = &pi->media;
2188         struct link_config *lc = &pi->link_cfg;
2189         struct adapter *sc = pi->adapter;
2190         int rc;
2191
2192         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
2193         if (rc != 0)
2194                 return (rc);
2195         PORT_LOCK(pi);
2196         if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
2197                 /* ifconfig .. media autoselect */
2198                 if (!(lc->supported & FW_PORT_CAP32_ANEG)) {
2199                         rc = ENOTSUP; /* AN not supported by transceiver */
2200                         goto done;
2201                 }
2202                 lc->requested_aneg = AUTONEG_ENABLE;
2203                 lc->requested_speed = 0;
2204                 lc->requested_fc |= PAUSE_AUTONEG;
2205         } else {
2206                 lc->requested_aneg = AUTONEG_DISABLE;
2207                 lc->requested_speed =
2208                     ifmedia_baudrate(ifm->ifm_media) / 1000000;
2209                 lc->requested_fc = 0;
2210                 if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
2211                         lc->requested_fc |= PAUSE_RX;
2212                 if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
2213                         lc->requested_fc |= PAUSE_TX;
2214         }
2215         if (pi->up_vis > 0) {
2216                 fixup_link_config(pi);
2217                 rc = apply_link_config(pi);
2218         }
2219 done:
2220         PORT_UNLOCK(pi);
2221         end_synchronized_op(sc, 0);
2222         return (rc);
2223 }
2224
2225 /*
2226  * Base media word (without ETHER, pause, link active, etc.) for the port at the
2227  * given speed.
2228  */
2229 static int
2230 port_mword(struct port_info *pi, uint32_t speed)
2231 {
2232
2233         MPASS(speed & M_FW_PORT_CAP32_SPEED);
2234         MPASS(powerof2(speed));
2235
2236         switch(pi->port_type) {
2237         case FW_PORT_TYPE_BT_SGMII:
2238         case FW_PORT_TYPE_BT_XFI:
2239         case FW_PORT_TYPE_BT_XAUI:
2240                 /* BaseT */
2241                 switch (speed) {
2242                 case FW_PORT_CAP32_SPEED_100M:
2243                         return (IFM_100_T);
2244                 case FW_PORT_CAP32_SPEED_1G:
2245                         return (IFM_1000_T);
2246                 case FW_PORT_CAP32_SPEED_10G:
2247                         return (IFM_10G_T);
2248                 }
2249                 break;
2250         case FW_PORT_TYPE_KX4:
2251                 if (speed == FW_PORT_CAP32_SPEED_10G)
2252                         return (IFM_10G_KX4);
2253                 break;
2254         case FW_PORT_TYPE_CX4:
2255                 if (speed == FW_PORT_CAP32_SPEED_10G)
2256                         return (IFM_10G_CX4);
2257                 break;
2258         case FW_PORT_TYPE_KX:
2259                 if (speed == FW_PORT_CAP32_SPEED_1G)
2260                         return (IFM_1000_KX);
2261                 break;
2262         case FW_PORT_TYPE_KR:
2263         case FW_PORT_TYPE_BP_AP:
2264         case FW_PORT_TYPE_BP4_AP:
2265         case FW_PORT_TYPE_BP40_BA:
2266         case FW_PORT_TYPE_KR4_100G:
2267         case FW_PORT_TYPE_KR_SFP28:
2268         case FW_PORT_TYPE_KR_XLAUI:
2269                 switch (speed) {
2270                 case FW_PORT_CAP32_SPEED_1G:
2271                         return (IFM_1000_KX);
2272                 case FW_PORT_CAP32_SPEED_10G:
2273                         return (IFM_10G_KR);
2274                 case FW_PORT_CAP32_SPEED_25G:
2275                         return (IFM_25G_KR);
2276                 case FW_PORT_CAP32_SPEED_40G:
2277                         return (IFM_40G_KR4);
2278                 case FW_PORT_CAP32_SPEED_50G:
2279                         return (IFM_50G_KR2);
2280                 case FW_PORT_CAP32_SPEED_100G:
2281                         return (IFM_100G_KR4);
2282                 }
2283                 break;
2284         case FW_PORT_TYPE_FIBER_XFI:
2285         case FW_PORT_TYPE_FIBER_XAUI:
2286         case FW_PORT_TYPE_SFP:
2287         case FW_PORT_TYPE_QSFP_10G:
2288         case FW_PORT_TYPE_QSA:
2289         case FW_PORT_TYPE_QSFP:
2290         case FW_PORT_TYPE_CR4_QSFP:
2291         case FW_PORT_TYPE_CR_QSFP:
2292         case FW_PORT_TYPE_CR2_QSFP:
2293         case FW_PORT_TYPE_SFP28:
2294                 /* Pluggable transceiver */
2295                 switch (pi->mod_type) {
2296                 case FW_PORT_MOD_TYPE_LR:
2297                         switch (speed) {
2298                         case FW_PORT_CAP32_SPEED_1G:
2299                                 return (IFM_1000_LX);
2300                         case FW_PORT_CAP32_SPEED_10G:
2301                                 return (IFM_10G_LR);
2302                         case FW_PORT_CAP32_SPEED_25G:
2303                                 return (IFM_25G_LR);
2304                         case FW_PORT_CAP32_SPEED_40G:
2305                                 return (IFM_40G_LR4);
2306                         case FW_PORT_CAP32_SPEED_50G:
2307                                 return (IFM_50G_LR2);
2308                         case FW_PORT_CAP32_SPEED_100G:
2309                                 return (IFM_100G_LR4);
2310                         }
2311                         break;
2312                 case FW_PORT_MOD_TYPE_SR:
2313                         switch (speed) {
2314                         case FW_PORT_CAP32_SPEED_1G:
2315                                 return (IFM_1000_SX);
2316                         case FW_PORT_CAP32_SPEED_10G:
2317                                 return (IFM_10G_SR);
2318                         case FW_PORT_CAP32_SPEED_25G:
2319                                 return (IFM_25G_SR);
2320                         case FW_PORT_CAP32_SPEED_40G:
2321                                 return (IFM_40G_SR4);
2322                         case FW_PORT_CAP32_SPEED_50G:
2323                                 return (IFM_50G_SR2);
2324                         case FW_PORT_CAP32_SPEED_100G:
2325                                 return (IFM_100G_SR4);
2326                         }
2327                         break;
2328                 case FW_PORT_MOD_TYPE_ER:
2329                         if (speed == FW_PORT_CAP32_SPEED_10G)
2330                                 return (IFM_10G_ER);
2331                         break;
2332                 case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
2333                 case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
2334                         switch (speed) {
2335                         case FW_PORT_CAP32_SPEED_1G:
2336                                 return (IFM_1000_CX);
2337                         case FW_PORT_CAP32_SPEED_10G:
2338                                 return (IFM_10G_TWINAX);
2339                         case FW_PORT_CAP32_SPEED_25G:
2340                                 return (IFM_25G_CR);
2341                         case FW_PORT_CAP32_SPEED_40G:
2342                                 return (IFM_40G_CR4);
2343                         case FW_PORT_CAP32_SPEED_50G:
2344                                 return (IFM_50G_CR2);
2345                         case FW_PORT_CAP32_SPEED_100G:
2346                                 return (IFM_100G_CR4);
2347                         }
2348                         break;
2349                 case FW_PORT_MOD_TYPE_LRM:
2350                         if (speed == FW_PORT_CAP32_SPEED_10G)
2351                                 return (IFM_10G_LRM);
2352                         break;
2353                 case FW_PORT_MOD_TYPE_NA:
2354                         MPASS(0);       /* Not pluggable? */
2355                         /* fall throough */
2356                 case FW_PORT_MOD_TYPE_ERROR:
2357                 case FW_PORT_MOD_TYPE_UNKNOWN:
2358                 case FW_PORT_MOD_TYPE_NOTSUPPORTED:
2359                         break;
2360                 case FW_PORT_MOD_TYPE_NONE:
2361                         return (IFM_NONE);
2362                 }
2363                 break;
2364         case FW_PORT_TYPE_NONE:
2365                 return (IFM_NONE);
2366         }
2367
2368         return (IFM_UNKNOWN);
2369 }
2370
2371 void
2372 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
2373 {
2374         struct vi_info *vi = ifp->if_softc;
2375         struct port_info *pi = vi->pi;
2376         struct adapter *sc = pi->adapter;
2377         struct link_config *lc = &pi->link_cfg;
2378
2379         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
2380                 return;
2381         PORT_LOCK(pi);
2382
2383         if (pi->up_vis == 0) {
2384                 /*
2385                  * If all the interfaces are administratively down the firmware
2386                  * does not report transceiver changes.  Refresh port info here
2387                  * so that ifconfig displays accurate ifmedia at all times.
2388                  * This is the only reason we have a synchronized op in this
2389                  * function.  Just PORT_LOCK would have been enough otherwise.
2390                  */
2391                 t4_update_port_info(pi);
2392                 build_medialist(pi);
2393         }
2394
2395         /* ifm_status */
2396         ifmr->ifm_status = IFM_AVALID;
2397         if (lc->link_ok == false)
2398                 goto done;
2399         ifmr->ifm_status |= IFM_ACTIVE;
2400
2401         /* ifm_active */
2402         ifmr->ifm_active = IFM_ETHER | IFM_FDX;
2403         ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
2404         if (lc->fc & PAUSE_RX)
2405                 ifmr->ifm_active |= IFM_ETH_RXPAUSE;
2406         if (lc->fc & PAUSE_TX)
2407                 ifmr->ifm_active |= IFM_ETH_TXPAUSE;
2408         ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
2409 done:
2410         PORT_UNLOCK(pi);
2411         end_synchronized_op(sc, 0);
2412 }
2413
2414 static int
2415 vcxgbe_probe(device_t dev)
2416 {
2417         char buf[128];
2418         struct vi_info *vi = device_get_softc(dev);
2419
2420         snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
2421             vi - vi->pi->vi);
2422         device_set_desc_copy(dev, buf);
2423
2424         return (BUS_PROBE_DEFAULT);
2425 }
2426
2427 static int
2428 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
2429 {
2430         int func, index, rc;
2431         uint32_t param, val;
2432
2433         ASSERT_SYNCHRONIZED_OP(sc);
2434
2435         index = vi - pi->vi;
2436         MPASS(index > 0);       /* This function deals with _extra_ VIs only */
2437         KASSERT(index < nitems(vi_mac_funcs),
2438             ("%s: VI %s doesn't have a MAC func", __func__,
2439             device_get_nameunit(vi->dev)));
2440         func = vi_mac_funcs[index];
2441         rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
2442             vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
2443         if (rc < 0) {
2444                 device_printf(vi->dev, "failed to allocate virtual interface %d"
2445                     "for port %d: %d\n", index, pi->port_id, -rc);
2446                 return (-rc);
2447         }
2448         vi->viid = rc;
2449
2450         if (vi->rss_size == 1) {
2451                 /*
2452                  * This VI didn't get a slice of the RSS table.  Reduce the
2453                  * number of VIs being created (hw.cxgbe.num_vis) or modify the
2454                  * configuration file (nvi, rssnvi for this PF) if this is a
2455                  * problem.
2456                  */
2457                 device_printf(vi->dev, "RSS table not available.\n");
2458                 vi->rss_base = 0xffff;
2459
2460                 return (0);
2461         }
2462
2463         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
2464             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
2465             V_FW_PARAMS_PARAM_YZ(vi->viid);
2466         rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
2467         if (rc)
2468                 vi->rss_base = 0xffff;
2469         else {
2470                 MPASS((val >> 16) == vi->rss_size);
2471                 vi->rss_base = val & 0xffff;
2472         }
2473
2474         return (0);
2475 }
2476
2477 static int
2478 vcxgbe_attach(device_t dev)
2479 {
2480         struct vi_info *vi;
2481         struct port_info *pi;
2482         struct adapter *sc;
2483         int rc;
2484
2485         vi = device_get_softc(dev);
2486         pi = vi->pi;
2487         sc = pi->adapter;
2488
2489         rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
2490         if (rc)
2491                 return (rc);
2492         rc = alloc_extra_vi(sc, pi, vi);
2493         end_synchronized_op(sc, 0);
2494         if (rc)
2495                 return (rc);
2496
2497         rc = cxgbe_vi_attach(dev, vi);
2498         if (rc) {
2499                 t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
2500                 return (rc);
2501         }
2502         return (0);
2503 }
2504
2505 static int
2506 vcxgbe_detach(device_t dev)
2507 {
2508         struct vi_info *vi;
2509         struct adapter *sc;
2510
2511         vi = device_get_softc(dev);
2512         sc = vi->pi->adapter;
2513
2514         doom_vi(sc, vi);
2515
2516         cxgbe_vi_detach(vi);
2517         t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
2518
2519         end_synchronized_op(sc, 0);
2520
2521         return (0);
2522 }
2523
2524 static struct callout fatal_callout;
2525
2526 static void
2527 delayed_panic(void *arg)
2528 {
2529         struct adapter *sc = arg;
2530
2531         panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
2532 }
2533
2534 void
2535 t4_fatal_err(struct adapter *sc, bool fw_error)
2536 {
2537
2538         t4_shutdown_adapter(sc);
2539         log(LOG_ALERT, "%s: encountered fatal error, adapter stopped.\n",
2540             device_get_nameunit(sc->dev));
2541         if (fw_error) {
2542                 ASSERT_SYNCHRONIZED_OP(sc);
2543                 sc->flags |= ADAP_ERR;
2544         } else {
2545                 ADAPTER_LOCK(sc);
2546                 sc->flags |= ADAP_ERR;
2547                 ADAPTER_UNLOCK(sc);
2548         }
2549
2550         if (t4_panic_on_fatal_err) {
2551                 log(LOG_ALERT, "%s: panic on fatal error after 30s",
2552                     device_get_nameunit(sc->dev));
2553                 callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
2554         }
2555 }
2556
2557 void
2558 t4_add_adapter(struct adapter *sc)
2559 {
2560         sx_xlock(&t4_list_lock);
2561         SLIST_INSERT_HEAD(&t4_list, sc, link);
2562         sx_xunlock(&t4_list_lock);
2563 }
2564
2565 int
2566 t4_map_bars_0_and_4(struct adapter *sc)
2567 {
2568         sc->regs_rid = PCIR_BAR(0);
2569         sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2570             &sc->regs_rid, RF_ACTIVE);
2571         if (sc->regs_res == NULL) {
2572                 device_printf(sc->dev, "cannot map registers.\n");
2573                 return (ENXIO);
2574         }
2575         sc->bt = rman_get_bustag(sc->regs_res);
2576         sc->bh = rman_get_bushandle(sc->regs_res);
2577         sc->mmio_len = rman_get_size(sc->regs_res);
2578         setbit(&sc->doorbells, DOORBELL_KDB);
2579
2580         sc->msix_rid = PCIR_BAR(4);
2581         sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2582             &sc->msix_rid, RF_ACTIVE);
2583         if (sc->msix_res == NULL) {
2584                 device_printf(sc->dev, "cannot map MSI-X BAR.\n");
2585                 return (ENXIO);
2586         }
2587
2588         return (0);
2589 }
2590
2591 int
2592 t4_map_bar_2(struct adapter *sc)
2593 {
2594
2595         /*
2596          * T4: only iWARP driver uses the userspace doorbells.  There is no need
2597          * to map it if RDMA is disabled.
2598          */
2599         if (is_t4(sc) && sc->rdmacaps == 0)
2600                 return (0);
2601
2602         sc->udbs_rid = PCIR_BAR(2);
2603         sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2604             &sc->udbs_rid, RF_ACTIVE);
2605         if (sc->udbs_res == NULL) {
2606                 device_printf(sc->dev, "cannot map doorbell BAR.\n");
2607                 return (ENXIO);
2608         }
2609         sc->udbs_base = rman_get_virtual(sc->udbs_res);
2610
2611         if (chip_id(sc) >= CHELSIO_T5) {
2612                 setbit(&sc->doorbells, DOORBELL_UDB);
2613 #if defined(__i386__) || defined(__amd64__)
2614                 if (t5_write_combine) {
2615                         int rc, mode;
2616
2617                         /*
2618                          * Enable write combining on BAR2.  This is the
2619                          * userspace doorbell BAR and is split into 128B
2620                          * (UDBS_SEG_SIZE) doorbell regions, each associated
2621                          * with an egress queue.  The first 64B has the doorbell
2622                          * and the second 64B can be used to submit a tx work
2623                          * request with an implicit doorbell.
2624                          */
2625
2626                         rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
2627                             rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
2628                         if (rc == 0) {
2629                                 clrbit(&sc->doorbells, DOORBELL_UDB);
2630                                 setbit(&sc->doorbells, DOORBELL_WCWR);
2631                                 setbit(&sc->doorbells, DOORBELL_UDBWC);
2632                         } else {
2633                                 device_printf(sc->dev,
2634                                     "couldn't enable write combining: %d\n",
2635                                     rc);
2636                         }
2637
2638                         mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
2639                         t4_write_reg(sc, A_SGE_STAT_CFG,
2640                             V_STATSOURCE_T5(7) | mode);
2641                 }
2642 #endif
2643         }
2644         sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
2645
2646         return (0);
2647 }
2648
2649 struct memwin_init {
2650         uint32_t base;
2651         uint32_t aperture;
2652 };
2653
2654 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
2655         { MEMWIN0_BASE, MEMWIN0_APERTURE },
2656         { MEMWIN1_BASE, MEMWIN1_APERTURE },
2657         { MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
2658 };
2659
2660 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
2661         { MEMWIN0_BASE, MEMWIN0_APERTURE },
2662         { MEMWIN1_BASE, MEMWIN1_APERTURE },
2663         { MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
2664 };
2665
2666 static void
2667 setup_memwin(struct adapter *sc)
2668 {
2669         const struct memwin_init *mw_init;
2670         struct memwin *mw;
2671         int i;
2672         uint32_t bar0;
2673
2674         if (is_t4(sc)) {
2675                 /*
2676                  * Read low 32b of bar0 indirectly via the hardware backdoor
2677                  * mechanism.  Works from within PCI passthrough environments
2678                  * too, where rman_get_start() can return a different value.  We
2679                  * need to program the T4 memory window decoders with the actual
2680                  * addresses that will be coming across the PCIe link.
2681                  */
2682                 bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
2683                 bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
2684
2685                 mw_init = &t4_memwin[0];
2686         } else {
2687                 /* T5+ use the relative offset inside the PCIe BAR */
2688                 bar0 = 0;
2689
2690                 mw_init = &t5_memwin[0];
2691         }
2692
2693         for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
2694                 rw_init(&mw->mw_lock, "memory window access");
2695                 mw->mw_base = mw_init->base;
2696                 mw->mw_aperture = mw_init->aperture;
2697                 mw->mw_curpos = 0;
2698                 t4_write_reg(sc,
2699                     PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
2700                     (mw->mw_base + bar0) | V_BIR(0) |
2701                     V_WINDOW(ilog2(mw->mw_aperture) - 10));
2702                 rw_wlock(&mw->mw_lock);
2703                 position_memwin(sc, i, 0);
2704                 rw_wunlock(&mw->mw_lock);
2705         }
2706
2707         /* flush */
2708         t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
2709 }
2710
2711 /*
2712  * Positions the memory window at the given address in the card's address space.
2713  * There are some alignment requirements and the actual position may be at an
2714  * address prior to the requested address.  mw->mw_curpos always has the actual
2715  * position of the window.
2716  */
2717 static void
2718 position_memwin(struct adapter *sc, int idx, uint32_t addr)
2719 {
2720         struct memwin *mw;
2721         uint32_t pf;
2722         uint32_t reg;
2723
2724         MPASS(idx >= 0 && idx < NUM_MEMWIN);
2725         mw = &sc->memwin[idx];
2726         rw_assert(&mw->mw_lock, RA_WLOCKED);
2727
2728         if (is_t4(sc)) {
2729                 pf = 0;
2730                 mw->mw_curpos = addr & ~0xf;    /* start must be 16B aligned */
2731         } else {
2732                 pf = V_PFNUM(sc->pf);
2733                 mw->mw_curpos = addr & ~0x7f;   /* start must be 128B aligned */
2734         }
2735         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
2736         t4_write_reg(sc, reg, mw->mw_curpos | pf);
2737         t4_read_reg(sc, reg);   /* flush */
2738 }
2739
2740 int
2741 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
2742     int len, int rw)
2743 {
2744         struct memwin *mw;
2745         uint32_t mw_end, v;
2746
2747         MPASS(idx >= 0 && idx < NUM_MEMWIN);
2748
2749         /* Memory can only be accessed in naturally aligned 4 byte units */
2750         if (addr & 3 || len & 3 || len <= 0)
2751                 return (EINVAL);
2752
2753         mw = &sc->memwin[idx];
2754         while (len > 0) {
2755                 rw_rlock(&mw->mw_lock);
2756                 mw_end = mw->mw_curpos + mw->mw_aperture;
2757                 if (addr >= mw_end || addr < mw->mw_curpos) {
2758                         /* Will need to reposition the window */
2759                         if (!rw_try_upgrade(&mw->mw_lock)) {
2760                                 rw_runlock(&mw->mw_lock);
2761                                 rw_wlock(&mw->mw_lock);
2762                         }
2763                         rw_assert(&mw->mw_lock, RA_WLOCKED);
2764                         position_memwin(sc, idx, addr);
2765                         rw_downgrade(&mw->mw_lock);
2766                         mw_end = mw->mw_curpos + mw->mw_aperture;
2767                 }
2768                 rw_assert(&mw->mw_lock, RA_RLOCKED);
2769                 while (addr < mw_end && len > 0) {
2770                         if (rw == 0) {
2771                                 v = t4_read_reg(sc, mw->mw_base + addr -
2772                                     mw->mw_curpos);
2773                                 *val++ = le32toh(v);
2774                         } else {
2775                                 v = *val++;
2776                                 t4_write_reg(sc, mw->mw_base + addr -
2777                                     mw->mw_curpos, htole32(v));
2778                         }
2779                         addr += 4;
2780                         len -= 4;
2781                 }
2782                 rw_runlock(&mw->mw_lock);
2783         }
2784
2785         return (0);
2786 }
2787
2788 int
2789 alloc_atid_tab(struct tid_info *t, int flags)
2790 {
2791         int i;
2792
2793         MPASS(t->natids > 0);
2794         MPASS(t->atid_tab == NULL);
2795
2796         t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
2797             M_ZERO | flags);
2798         if (t->atid_tab == NULL)
2799                 return (ENOMEM);
2800         mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
2801         t->afree = t->atid_tab;
2802         t->atids_in_use = 0;
2803         for (i = 1; i < t->natids; i++)
2804                 t->atid_tab[i - 1].next = &t->atid_tab[i];
2805         t->atid_tab[t->natids - 1].next = NULL;
2806
2807         return (0);
2808 }
2809
2810 void
2811 free_atid_tab(struct tid_info *t)
2812 {
2813
2814         KASSERT(t->atids_in_use == 0,
2815             ("%s: %d atids still in use.", __func__, t->atids_in_use));
2816
2817         if (mtx_initialized(&t->atid_lock))
2818                 mtx_destroy(&t->atid_lock);
2819         free(t->atid_tab, M_CXGBE);
2820         t->atid_tab = NULL;
2821 }
2822
2823 int
2824 alloc_atid(struct adapter *sc, void *ctx)
2825 {
2826         struct tid_info *t = &sc->tids;
2827         int atid = -1;
2828
2829         mtx_lock(&t->atid_lock);
2830         if (t->afree) {
2831                 union aopen_entry *p = t->afree;
2832
2833                 atid = p - t->atid_tab;
2834                 MPASS(atid <= M_TID_TID);
2835                 t->afree = p->next;
2836                 p->data = ctx;
2837                 t->atids_in_use++;
2838         }
2839         mtx_unlock(&t->atid_lock);
2840         return (atid);
2841 }
2842
2843 void *
2844 lookup_atid(struct adapter *sc, int atid)
2845 {
2846         struct tid_info *t = &sc->tids;
2847
2848         return (t->atid_tab[atid].data);
2849 }
2850
2851 void
2852 free_atid(struct adapter *sc, int atid)
2853 {
2854         struct tid_info *t = &sc->tids;
2855         union aopen_entry *p = &t->atid_tab[atid];
2856
2857         mtx_lock(&t->atid_lock);
2858         p->next = t->afree;
2859         t->afree = p;
2860         t->atids_in_use--;
2861         mtx_unlock(&t->atid_lock);
2862 }
2863
2864 static void
2865 queue_tid_release(struct adapter *sc, int tid)
2866 {
2867
2868         CXGBE_UNIMPLEMENTED("deferred tid release");
2869 }
2870
2871 void
2872 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
2873 {
2874         struct wrqe *wr;
2875         struct cpl_tid_release *req;
2876
2877         wr = alloc_wrqe(sizeof(*req), ctrlq);
2878         if (wr == NULL) {
2879                 queue_tid_release(sc, tid);     /* defer */
2880                 return;
2881         }
2882         req = wrtod(wr);
2883
2884         INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
2885
2886         t4_wrq_tx(sc, wr);
2887 }
2888
2889 static int
2890 t4_range_cmp(const void *a, const void *b)
2891 {
2892         return ((const struct t4_range *)a)->start -
2893                ((const struct t4_range *)b)->start;
2894 }
2895
2896 /*
2897  * Verify that the memory range specified by the addr/len pair is valid within
2898  * the card's address space.
2899  */
2900 static int
2901 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
2902 {
2903         struct t4_range mem_ranges[4], *r, *next;
2904         uint32_t em, addr_len;
2905         int i, n, remaining;
2906
2907         /* Memory can only be accessed in naturally aligned 4 byte units */
2908         if (addr & 3 || len & 3 || len == 0)
2909                 return (EINVAL);
2910
2911         /* Enabled memories */
2912         em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
2913
2914         r = &mem_ranges[0];
2915         n = 0;
2916         bzero(r, sizeof(mem_ranges));
2917         if (em & F_EDRAM0_ENABLE) {
2918                 addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
2919                 r->size = G_EDRAM0_SIZE(addr_len) << 20;
2920                 if (r->size > 0) {
2921                         r->start = G_EDRAM0_BASE(addr_len) << 20;
2922                         if (addr >= r->start &&
2923                             addr + len <= r->start + r->size)
2924                                 return (0);
2925                         r++;
2926                         n++;
2927                 }
2928         }
2929         if (em & F_EDRAM1_ENABLE) {
2930                 addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
2931                 r->size = G_EDRAM1_SIZE(addr_len) << 20;
2932                 if (r->size > 0) {
2933                         r->start = G_EDRAM1_BASE(addr_len) << 20;
2934                         if (addr >= r->start &&
2935                             addr + len <= r->start + r->size)
2936                                 return (0);
2937                         r++;
2938                         n++;
2939                 }
2940         }
2941         if (em & F_EXT_MEM_ENABLE) {
2942                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
2943                 r->size = G_EXT_MEM_SIZE(addr_len) << 20;
2944                 if (r->size > 0) {
2945                         r->start = G_EXT_MEM_BASE(addr_len) << 20;
2946                         if (addr >= r->start &&
2947                             addr + len <= r->start + r->size)
2948                                 return (0);
2949                         r++;
2950                         n++;
2951                 }
2952         }
2953         if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
2954                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
2955                 r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
2956                 if (r->size > 0) {
2957                         r->start = G_EXT_MEM1_BASE(addr_len) << 20;
2958                         if (addr >= r->start &&
2959                             addr + len <= r->start + r->size)
2960                                 return (0);
2961                         r++;
2962                         n++;
2963                 }
2964         }
2965         MPASS(n <= nitems(mem_ranges));
2966
2967         if (n > 1) {
2968                 /* Sort and merge the ranges. */
2969                 qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
2970
2971                 /* Start from index 0 and examine the next n - 1 entries. */
2972                 r = &mem_ranges[0];
2973                 for (remaining = n - 1; remaining > 0; remaining--, r++) {
2974
2975                         MPASS(r->size > 0);     /* r is a valid entry. */
2976                         next = r + 1;
2977                         MPASS(next->size > 0);  /* and so is the next one. */
2978
2979                         while (r->start + r->size >= next->start) {
2980                                 /* Merge the next one into the current entry. */
2981                                 r->size = max(r->start + r->size,
2982                                     next->start + next->size) - r->start;
2983                                 n--;    /* One fewer entry in total. */
2984                                 if (--remaining == 0)
2985                                         goto done;      /* short circuit */
2986                                 next++;
2987                         }
2988                         if (next != r + 1) {
2989                                 /*
2990                                  * Some entries were merged into r and next
2991                                  * points to the first valid entry that couldn't
2992                                  * be merged.
2993                                  */
2994                                 MPASS(next->size > 0);  /* must be valid */
2995                                 memcpy(r + 1, next, remaining * sizeof(*r));
2996 #ifdef INVARIANTS
2997                                 /*
2998                                  * This so that the foo->size assertion in the
2999                                  * next iteration of the loop do the right
3000                                  * thing for entries that were pulled up and are
3001                                  * no longer valid.
3002                                  */
3003                                 MPASS(n < nitems(mem_ranges));
3004                                 bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
3005                                     sizeof(struct t4_range));
3006 #endif
3007                         }
3008                 }
3009 done:
3010                 /* Done merging the ranges. */
3011                 MPASS(n > 0);
3012                 r = &mem_ranges[0];
3013                 for (i = 0; i < n; i++, r++) {
3014                         if (addr >= r->start &&
3015                             addr + len <= r->start + r->size)
3016                                 return (0);
3017                 }
3018         }
3019
3020         return (EFAULT);
3021 }
3022
3023 static int
3024 fwmtype_to_hwmtype(int mtype)
3025 {
3026
3027         switch (mtype) {
3028         case FW_MEMTYPE_EDC0:
3029                 return (MEM_EDC0);
3030         case FW_MEMTYPE_EDC1:
3031                 return (MEM_EDC1);
3032         case FW_MEMTYPE_EXTMEM:
3033                 return (MEM_MC0);
3034         case FW_MEMTYPE_EXTMEM1:
3035                 return (MEM_MC1);
3036         default:
3037                 panic("%s: cannot translate fw mtype %d.", __func__, mtype);
3038         }
3039 }
3040
3041 /*
3042  * Verify that the memory range specified by the memtype/offset/len pair is
3043  * valid and lies entirely within the memtype specified.  The global address of
3044  * the start of the range is returned in addr.
3045  */
3046 static int
3047 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
3048     uint32_t *addr)
3049 {
3050         uint32_t em, addr_len, maddr;
3051
3052         /* Memory can only be accessed in naturally aligned 4 byte units */
3053         if (off & 3 || len & 3 || len == 0)
3054                 return (EINVAL);
3055
3056         em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
3057         switch (fwmtype_to_hwmtype(mtype)) {
3058         case MEM_EDC0:
3059                 if (!(em & F_EDRAM0_ENABLE))
3060                         return (EINVAL);
3061                 addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
3062                 maddr = G_EDRAM0_BASE(addr_len) << 20;
3063                 break;
3064         case MEM_EDC1:
3065                 if (!(em & F_EDRAM1_ENABLE))
3066                         return (EINVAL);
3067                 addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
3068                 maddr = G_EDRAM1_BASE(addr_len) << 20;
3069                 break;
3070         case MEM_MC:
3071                 if (!(em & F_EXT_MEM_ENABLE))
3072                         return (EINVAL);
3073                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
3074                 maddr = G_EXT_MEM_BASE(addr_len) << 20;
3075                 break;
3076         case MEM_MC1:
3077                 if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
3078                         return (EINVAL);
3079                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
3080                 maddr = G_EXT_MEM1_BASE(addr_len) << 20;
3081                 break;
3082         default:
3083                 return (EINVAL);
3084         }
3085
3086         *addr = maddr + off;    /* global address */
3087         return (validate_mem_range(sc, *addr, len));
3088 }
3089
3090 static int
3091 fixup_devlog_params(struct adapter *sc)
3092 {
3093         struct devlog_params *dparams = &sc->params.devlog;
3094         int rc;
3095
3096         rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
3097             dparams->size, &dparams->addr);
3098
3099         return (rc);
3100 }
3101
3102 static void
3103 update_nirq(struct intrs_and_queues *iaq, int nports)
3104 {
3105         int extra = T4_EXTRA_INTR;
3106
3107         iaq->nirq = extra;
3108         iaq->nirq += nports * (iaq->nrxq + iaq->nofldrxq);
3109         iaq->nirq += nports * (iaq->num_vis - 1) *
3110             max(iaq->nrxq_vi, iaq->nnmrxq_vi);
3111         iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
3112 }
3113
3114 /*
3115  * Adjust requirements to fit the number of interrupts available.
3116  */
3117 static void
3118 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
3119     int navail)
3120 {
3121         int old_nirq;
3122         const int nports = sc->params.nports;
3123
3124         MPASS(nports > 0);
3125         MPASS(navail > 0);
3126
3127         bzero(iaq, sizeof(*iaq));
3128         iaq->intr_type = itype;
3129         iaq->num_vis = t4_num_vis;
3130         iaq->ntxq = t4_ntxq;
3131         iaq->ntxq_vi = t4_ntxq_vi;
3132         iaq->nrxq = t4_nrxq;
3133         iaq->nrxq_vi = t4_nrxq_vi;
3134 #ifdef TCP_OFFLOAD
3135         if (is_offload(sc)) {
3136                 iaq->nofldtxq = t4_nofldtxq;
3137                 iaq->nofldtxq_vi = t4_nofldtxq_vi;
3138                 iaq->nofldrxq = t4_nofldrxq;
3139                 iaq->nofldrxq_vi = t4_nofldrxq_vi;
3140         }
3141 #endif
3142 #ifdef DEV_NETMAP
3143         iaq->nnmtxq_vi = t4_nnmtxq_vi;
3144         iaq->nnmrxq_vi = t4_nnmrxq_vi;
3145 #endif
3146
3147         update_nirq(iaq, nports);
3148         if (iaq->nirq <= navail &&
3149             (itype != INTR_MSI || powerof2(iaq->nirq))) {
3150                 /*
3151                  * This is the normal case -- there are enough interrupts for
3152                  * everything.
3153                  */
3154                 goto done;
3155         }
3156
3157         /*
3158          * If extra VIs have been configured try reducing their count and see if
3159          * that works.
3160          */
3161         while (iaq->num_vis > 1) {
3162                 iaq->num_vis--;
3163                 update_nirq(iaq, nports);
3164                 if (iaq->nirq <= navail &&
3165                     (itype != INTR_MSI || powerof2(iaq->nirq))) {
3166                         device_printf(sc->dev, "virtual interfaces per port "
3167                             "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
3168                             "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
3169                             "itype %d, navail %u, nirq %d.\n",
3170                             iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
3171                             iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
3172                             itype, navail, iaq->nirq);
3173                         goto done;
3174                 }
3175         }
3176
3177         /*
3178          * Extra VIs will not be created.  Log a message if they were requested.
3179          */
3180         MPASS(iaq->num_vis == 1);
3181         iaq->ntxq_vi = iaq->nrxq_vi = 0;
3182         iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
3183         iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
3184         if (iaq->num_vis != t4_num_vis) {
3185                 device_printf(sc->dev, "extra virtual interfaces disabled.  "
3186                     "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
3187                     "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
3188                     iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
3189                     iaq->nnmrxq_vi, itype, navail, iaq->nirq);
3190         }
3191
3192         /*
3193          * Keep reducing the number of NIC rx queues to the next lower power of
3194          * 2 (for even RSS distribution) and halving the TOE rx queues and see
3195          * if that works.
3196          */
3197         do {
3198                 if (iaq->nrxq > 1) {
3199                         do {
3200                                 iaq->nrxq--;
3201                         } while (!powerof2(iaq->nrxq));
3202                 }
3203                 if (iaq->nofldrxq > 1)
3204                         iaq->nofldrxq >>= 1;
3205
3206                 old_nirq = iaq->nirq;
3207                 update_nirq(iaq, nports);
3208                 if (iaq->nirq <= navail &&
3209                     (itype != INTR_MSI || powerof2(iaq->nirq))) {
3210                         device_printf(sc->dev, "running with reduced number of "
3211                             "rx queues because of shortage of interrupts.  "
3212                             "nrxq=%u, nofldrxq=%u.  "
3213                             "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
3214                             iaq->nofldrxq, itype, navail, iaq->nirq);
3215                         goto done;
3216                 }
3217         } while (old_nirq != iaq->nirq);
3218
3219         /* One interrupt for everything.  Ugh. */
3220         device_printf(sc->dev, "running with minimal number of queues.  "
3221             "itype %d, navail %u.\n", itype, navail);
3222         iaq->nirq = 1;
3223         MPASS(iaq->nrxq == 1);
3224         iaq->ntxq = 1;
3225         if (iaq->nofldrxq > 1)
3226                 iaq->nofldtxq = 1;
3227 done:
3228         MPASS(iaq->num_vis > 0);
3229         if (iaq->num_vis > 1) {
3230                 MPASS(iaq->nrxq_vi > 0);
3231                 MPASS(iaq->ntxq_vi > 0);
3232         }
3233         MPASS(iaq->nirq > 0);
3234         MPASS(iaq->nrxq > 0);
3235         MPASS(iaq->ntxq > 0);
3236         if (itype == INTR_MSI) {
3237                 MPASS(powerof2(iaq->nirq));
3238         }
3239 }
3240
3241 static int
3242 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
3243 {
3244         int rc, itype, navail, nalloc;
3245
3246         for (itype = INTR_MSIX; itype; itype >>= 1) {
3247
3248                 if ((itype & t4_intr_types) == 0)
3249                         continue;       /* not allowed */
3250
3251                 if (itype == INTR_MSIX)
3252                         navail = pci_msix_count(sc->dev);
3253                 else if (itype == INTR_MSI)
3254                         navail = pci_msi_count(sc->dev);
3255                 else
3256                         navail = 1;
3257 restart:
3258                 if (navail == 0)
3259                         continue;
3260
3261                 calculate_iaq(sc, iaq, itype, navail);
3262                 nalloc = iaq->nirq;
3263                 rc = 0;
3264                 if (itype == INTR_MSIX)
3265                         rc = pci_alloc_msix(sc->dev, &nalloc);
3266                 else if (itype == INTR_MSI)
3267                         rc = pci_alloc_msi(sc->dev, &nalloc);
3268
3269                 if (rc == 0 && nalloc > 0) {
3270                         if (nalloc == iaq->nirq)
3271                                 return (0);
3272
3273                         /*
3274                          * Didn't get the number requested.  Use whatever number
3275                          * the kernel is willing to allocate.
3276                          */
3277                         device_printf(sc->dev, "fewer vectors than requested, "
3278                             "type=%d, req=%d, rcvd=%d; will downshift req.\n",
3279                             itype, iaq->nirq, nalloc);
3280                         pci_release_msi(sc->dev);
3281                         navail = nalloc;
3282                         goto restart;
3283                 }
3284
3285                 device_printf(sc->dev,
3286                     "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
3287                     itype, rc, iaq->nirq, nalloc);
3288         }
3289
3290         device_printf(sc->dev,
3291             "failed to find a usable interrupt type.  "
3292             "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
3293             pci_msix_count(sc->dev), pci_msi_count(sc->dev));
3294
3295         return (ENXIO);
3296 }
3297
3298 #define FW_VERSION(chip) ( \
3299     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
3300     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
3301     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
3302     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
3303 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
3304
3305 /* Just enough of fw_hdr to cover all version info. */
3306 struct fw_h {
3307         __u8    ver;
3308         __u8    chip;
3309         __be16  len512;
3310         __be32  fw_ver;
3311         __be32  tp_microcode_ver;
3312         __u8    intfver_nic;
3313         __u8    intfver_vnic;
3314         __u8    intfver_ofld;
3315         __u8    intfver_ri;
3316         __u8    intfver_iscsipdu;
3317         __u8    intfver_iscsi;
3318         __u8    intfver_fcoepdu;
3319         __u8    intfver_fcoe;
3320 };
3321 /* Spot check a couple of fields. */
3322 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
3323 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
3324 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
3325
3326 struct fw_info {
3327         uint8_t chip;
3328         char *kld_name;
3329         char *fw_mod_name;
3330         struct fw_h fw_h;
3331 } fw_info[] = {
3332         {
3333                 .chip = CHELSIO_T4,
3334                 .kld_name = "t4fw_cfg",
3335                 .fw_mod_name = "t4fw",
3336                 .fw_h = {
3337                         .chip = FW_HDR_CHIP_T4,
3338                         .fw_ver = htobe32(FW_VERSION(T4)),
3339                         .intfver_nic = FW_INTFVER(T4, NIC),
3340                         .intfver_vnic = FW_INTFVER(T4, VNIC),
3341                         .intfver_ofld = FW_INTFVER(T4, OFLD),
3342                         .intfver_ri = FW_INTFVER(T4, RI),
3343                         .intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
3344                         .intfver_iscsi = FW_INTFVER(T4, ISCSI),
3345                         .intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
3346                         .intfver_fcoe = FW_INTFVER(T4, FCOE),
3347                 },
3348         }, {
3349                 .chip = CHELSIO_T5,
3350                 .kld_name = "t5fw_cfg",
3351                 .fw_mod_name = "t5fw",
3352                 .fw_h = {
3353                         .chip = FW_HDR_CHIP_T5,
3354                         .fw_ver = htobe32(FW_VERSION(T5)),
3355                         .intfver_nic = FW_INTFVER(T5, NIC),
3356                         .intfver_vnic = FW_INTFVER(T5, VNIC),
3357                         .intfver_ofld = FW_INTFVER(T5, OFLD),
3358                         .intfver_ri = FW_INTFVER(T5, RI),
3359                         .intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
3360                         .intfver_iscsi = FW_INTFVER(T5, ISCSI),
3361                         .intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
3362                         .intfver_fcoe = FW_INTFVER(T5, FCOE),
3363                 },
3364         }, {
3365                 .chip = CHELSIO_T6,
3366                 .kld_name = "t6fw_cfg",
3367                 .fw_mod_name = "t6fw",
3368                 .fw_h = {
3369                         .chip = FW_HDR_CHIP_T6,
3370                         .fw_ver = htobe32(FW_VERSION(T6)),
3371                         .intfver_nic = FW_INTFVER(T6, NIC),
3372                         .intfver_vnic = FW_INTFVER(T6, VNIC),
3373                         .intfver_ofld = FW_INTFVER(T6, OFLD),
3374                         .intfver_ri = FW_INTFVER(T6, RI),
3375                         .intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
3376                         .intfver_iscsi = FW_INTFVER(T6, ISCSI),
3377                         .intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
3378                         .intfver_fcoe = FW_INTFVER(T6, FCOE),
3379                 },
3380         }
3381 };
3382
3383 static struct fw_info *
3384 find_fw_info(int chip)
3385 {
3386         int i;
3387
3388         for (i = 0; i < nitems(fw_info); i++) {
3389                 if (fw_info[i].chip == chip)
3390                         return (&fw_info[i]);
3391         }
3392         return (NULL);
3393 }
3394
3395 /*
3396  * Is the given firmware API compatible with the one the driver was compiled
3397  * with?
3398  */
3399 static int
3400 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
3401 {
3402
3403         /* short circuit if it's the exact same firmware version */
3404         if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
3405                 return (1);
3406
3407         /*
3408          * XXX: Is this too conservative?  Perhaps I should limit this to the
3409          * features that are supported in the driver.
3410          */
3411 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
3412         if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
3413             SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
3414             SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
3415                 return (1);
3416 #undef SAME_INTF
3417
3418         return (0);
3419 }
3420
3421 static int
3422 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
3423     const struct firmware **fw)
3424 {
3425         struct fw_info *fw_info;
3426
3427         *dcfg = NULL;
3428         if (fw != NULL)
3429                 *fw = NULL;
3430
3431         fw_info = find_fw_info(chip_id(sc));
3432         if (fw_info == NULL) {
3433                 device_printf(sc->dev,
3434                     "unable to look up firmware information for chip %d.\n",
3435                     chip_id(sc));
3436                 return (EINVAL);
3437         }
3438
3439         *dcfg = firmware_get(fw_info->kld_name);
3440         if (*dcfg != NULL) {
3441                 if (fw != NULL)
3442                         *fw = firmware_get(fw_info->fw_mod_name);
3443                 return (0);
3444         }
3445
3446         return (ENOENT);
3447 }
3448
3449 static void
3450 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
3451     const struct firmware *fw)
3452 {
3453
3454         if (fw != NULL)
3455                 firmware_put(fw, FIRMWARE_UNLOAD);
3456         if (dcfg != NULL)
3457                 firmware_put(dcfg, FIRMWARE_UNLOAD);
3458 }
3459
3460 /*
3461  * Return values:
3462  * 0 means no firmware install attempted.
3463  * ERESTART means a firmware install was attempted and was successful.
3464  * +ve errno means a firmware install was attempted but failed.
3465  */
3466 static int
3467 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
3468     const struct fw_h *drv_fw, const char *reason, int *already)
3469 {
3470         const struct firmware *cfg, *fw;
3471         const uint32_t c = be32toh(card_fw->fw_ver);
3472         uint32_t d, k;
3473         int rc, fw_install;
3474         struct fw_h bundled_fw;
3475         bool load_attempted;
3476
3477         cfg = fw = NULL;
3478         load_attempted = false;
3479         fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
3480
3481         memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
3482         if (t4_fw_install < 0) {
3483                 rc = load_fw_module(sc, &cfg, &fw);
3484                 if (rc != 0 || fw == NULL) {
3485                         device_printf(sc->dev,
3486                             "failed to load firmware module: %d. cfg %p, fw %p;"
3487                             " will use compiled-in firmware version for"
3488                             "hw.cxgbe.fw_install checks.\n",
3489                             rc, cfg, fw);
3490                 } else {
3491                         memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
3492                 }
3493                 load_attempted = true;
3494         }
3495         d = be32toh(bundled_fw.fw_ver);
3496
3497         if (reason != NULL)
3498                 goto install;
3499
3500         if ((sc->flags & FW_OK) == 0) {
3501
3502                 if (c == 0xffffffff) {
3503                         reason = "missing";
3504                         goto install;
3505                 }
3506
3507                 rc = 0;
3508                 goto done;
3509         }
3510
3511         if (!fw_compatible(card_fw, &bundled_fw)) {
3512                 reason = "incompatible or unusable";
3513                 goto install;
3514         }
3515
3516         if (d > c) {
3517                 reason = "older than the version bundled with this driver";
3518                 goto install;
3519         }
3520
3521         if (fw_install == 2 && d != c) {
3522                 reason = "different than the version bundled with this driver";
3523                 goto install;
3524         }
3525
3526         /* No reason to do anything to the firmware already on the card. */
3527         rc = 0;
3528         goto done;
3529
3530 install:
3531         rc = 0;
3532         if ((*already)++)
3533                 goto done;
3534
3535         if (fw_install == 0) {
3536                 device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3537                     "but the driver is prohibited from installing a firmware "
3538                     "on the card.\n",
3539                     G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3540                     G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
3541
3542                 goto done;
3543         }
3544
3545         /*
3546          * We'll attempt to install a firmware.  Load the module first (if it
3547          * hasn't been loaded already).
3548          */
3549         if (!load_attempted) {
3550                 rc = load_fw_module(sc, &cfg, &fw);
3551                 if (rc != 0 || fw == NULL) {
3552                         device_printf(sc->dev,
3553                             "failed to load firmware module: %d. cfg %p, fw %p\n",
3554                             rc, cfg, fw);
3555                         /* carry on */
3556                 }
3557         }
3558         if (fw == NULL) {
3559                 device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3560                     "but the driver cannot take corrective action because it "
3561                     "is unable to load the firmware module.\n",
3562                     G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3563                     G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
3564                 rc = sc->flags & FW_OK ? 0 : ENOENT;
3565                 goto done;
3566         }
3567         k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
3568         if (k != d) {
3569                 MPASS(t4_fw_install > 0);
3570                 device_printf(sc->dev,
3571                     "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
3572                     "expecting (%u.%u.%u.%u) and will not be used.\n",
3573                     G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
3574                     G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
3575                     G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
3576                     G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
3577                 rc = sc->flags & FW_OK ? 0 : EINVAL;
3578                 goto done;
3579         }
3580
3581         device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
3582             "installing firmware %u.%u.%u.%u on card.\n",
3583             G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3584             G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
3585             G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
3586             G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
3587
3588         rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
3589         if (rc != 0) {
3590                 device_printf(sc->dev, "failed to install firmware: %d\n", rc);
3591         } else {
3592                 /* Installed successfully, update the cached header too. */
3593                 rc = ERESTART;
3594                 memcpy(card_fw, fw->data, sizeof(*card_fw));
3595         }
3596 done:
3597         unload_fw_module(sc, cfg, fw);
3598
3599         return (rc);
3600 }
3601
3602 /*
3603  * Establish contact with the firmware and attempt to become the master driver.
3604  *
3605  * A firmware will be installed to the card if needed (if the driver is allowed
3606  * to do so).
3607  */
3608 static int
3609 contact_firmware(struct adapter *sc)
3610 {
3611         int rc, already = 0;
3612         enum dev_state state;
3613         struct fw_info *fw_info;
3614         struct fw_hdr *card_fw;         /* fw on the card */
3615         const struct fw_h *drv_fw;
3616
3617         fw_info = find_fw_info(chip_id(sc));
3618         if (fw_info == NULL) {
3619                 device_printf(sc->dev,
3620                     "unable to look up firmware information for chip %d.\n",
3621                     chip_id(sc));
3622                 return (EINVAL);
3623         }
3624         drv_fw = &fw_info->fw_h;
3625
3626         /* Read the header of the firmware on the card */
3627         card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
3628 restart:
3629         rc = -t4_get_fw_hdr(sc, card_fw);
3630         if (rc != 0) {
3631                 device_printf(sc->dev,
3632                     "unable to read firmware header from card's flash: %d\n",
3633                     rc);
3634                 goto done;
3635         }
3636
3637         rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
3638             &already);
3639         if (rc == ERESTART)
3640                 goto restart;
3641         if (rc != 0)
3642                 goto done;
3643
3644         rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
3645         if (rc < 0 || state == DEV_STATE_ERR) {
3646                 rc = -rc;
3647                 device_printf(sc->dev,
3648                     "failed to connect to the firmware: %d, %d.  "
3649                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
3650 #if 0
3651                 if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
3652                     "not responding properly to HELLO", &already) == ERESTART)
3653                         goto restart;
3654 #endif
3655                 goto done;
3656         }
3657         MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
3658         sc->flags |= FW_OK;     /* The firmware responded to the FW_HELLO. */
3659
3660         if (rc == sc->pf) {
3661                 sc->flags |= MASTER_PF;
3662                 rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
3663                     NULL, &already);
3664                 if (rc == ERESTART)
3665                         rc = 0;
3666                 else if (rc != 0)
3667                         goto done;
3668         } else if (state == DEV_STATE_UNINIT) {
3669                 /*
3670                  * We didn't get to be the master so we definitely won't be
3671                  * configuring the chip.  It's a bug if someone else hasn't
3672                  * configured it already.
3673                  */
3674                 device_printf(sc->dev, "couldn't be master(%d), "
3675                     "device not already initialized either(%d).  "
3676                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
3677                 rc = EPROTO;
3678                 goto done;
3679         } else {
3680                 /*
3681                  * Some other PF is the master and has configured the chip.
3682                  * This is allowed but untested.
3683                  */
3684                 device_printf(sc->dev, "PF%d is master, device state %d.  "
3685                     "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
3686                 snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
3687                 sc->cfcsum = 0;
3688                 rc = 0;
3689         }
3690 done:
3691         if (rc != 0 && sc->flags & FW_OK) {
3692                 t4_fw_bye(sc, sc->mbox);
3693                 sc->flags &= ~FW_OK;
3694         }
3695         free(card_fw, M_CXGBE);
3696         return (rc);
3697 }
3698
3699 static int
3700 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
3701     uint32_t mtype, uint32_t moff)
3702 {
3703         struct fw_info *fw_info;
3704         const struct firmware *dcfg, *rcfg = NULL;
3705         const uint32_t *cfdata;
3706         uint32_t cflen, addr;
3707         int rc;
3708
3709         load_fw_module(sc, &dcfg, NULL);
3710
3711         /* Card specific interpretation of "default". */
3712         if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
3713                 if (pci_get_device(sc->dev) == 0x440a)
3714                         snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
3715                 if (is_fpga(sc))
3716                         snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
3717         }
3718
3719         if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
3720                 if (dcfg == NULL) {
3721                         device_printf(sc->dev,
3722                             "KLD with default config is not available.\n");
3723                         rc = ENOENT;
3724                         goto done;
3725                 }
3726                 cfdata = dcfg->data;
3727                 cflen = dcfg->datasize & ~3;
3728         } else {
3729                 char s[32];
3730
3731                 fw_info = find_fw_info(chip_id(sc));
3732                 if (fw_info == NULL) {
3733                         device_printf(sc->dev,
3734                             "unable to look up firmware information for chip %d.\n",
3735                             chip_id(sc));
3736                         rc = EINVAL;
3737                         goto done;
3738                 }
3739                 snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
3740
3741                 rcfg = firmware_get(s);
3742                 if (rcfg == NULL) {
3743                         device_printf(sc->dev,
3744                             "unable to load module \"%s\" for configuration "
3745                             "profile \"%s\".\n", s, cfg_file);
3746                         rc = ENOENT;
3747                         goto done;
3748                 }
3749                 cfdata = rcfg->data;
3750                 cflen = rcfg->datasize & ~3;
3751         }
3752
3753         if (cflen > FLASH_CFG_MAX_SIZE) {
3754                 device_printf(sc->dev,
3755                     "config file too long (%d, max allowed is %d).\n",
3756                     cflen, FLASH_CFG_MAX_SIZE);
3757                 rc = EINVAL;
3758                 goto done;
3759         }
3760
3761         rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
3762         if (rc != 0) {
3763                 device_printf(sc->dev,
3764                     "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
3765                     __func__, mtype, moff, cflen, rc);
3766                 rc = EINVAL;
3767                 goto done;
3768         }
3769         write_via_memwin(sc, 2, addr, cfdata, cflen);
3770 done:
3771         if (rcfg != NULL)
3772                 firmware_put(rcfg, FIRMWARE_UNLOAD);
3773         unload_fw_module(sc, dcfg, NULL);
3774         return (rc);
3775 }
3776
3777 struct caps_allowed {
3778         uint16_t nbmcaps;
3779         uint16_t linkcaps;
3780         uint16_t switchcaps;
3781         uint16_t niccaps;
3782         uint16_t toecaps;
3783         uint16_t rdmacaps;
3784         uint16_t cryptocaps;
3785         uint16_t iscsicaps;
3786         uint16_t fcoecaps;
3787 };
3788
3789 #define FW_PARAM_DEV(param) \
3790         (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
3791          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
3792 #define FW_PARAM_PFVF(param) \
3793         (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
3794          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
3795
3796 /*
3797  * Provide a configuration profile to the firmware and have it initialize the
3798  * chip accordingly.  This may involve uploading a configuration file to the
3799  * card.
3800  */
3801 static int
3802 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
3803     const struct caps_allowed *caps_allowed)
3804 {
3805         int rc;
3806         struct fw_caps_config_cmd caps;
3807         uint32_t mtype, moff, finicsum, cfcsum, param, val;
3808
3809         rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
3810         if (rc != 0) {
3811                 device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
3812                 return (rc);
3813         }
3814
3815         bzero(&caps, sizeof(caps));
3816         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3817             F_FW_CMD_REQUEST | F_FW_CMD_READ);
3818         if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
3819                 mtype = 0;
3820                 moff = 0;
3821                 caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3822         } else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
3823                 mtype = FW_MEMTYPE_FLASH;
3824                 moff = t4_flash_cfg_addr(sc);
3825                 caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
3826                     V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
3827                     V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
3828                     FW_LEN16(caps));
3829         } else {
3830                 /*
3831                  * Ask the firmware where it wants us to upload the config file.
3832                  */
3833                 param = FW_PARAM_DEV(CF);
3834                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3835                 if (rc != 0) {
3836                         /* No support for config file?  Shouldn't happen. */
3837                         device_printf(sc->dev,
3838                             "failed to query config file location: %d.\n", rc);
3839                         goto done;
3840                 }
3841                 mtype = G_FW_PARAMS_PARAM_Y(val);
3842                 moff = G_FW_PARAMS_PARAM_Z(val) << 16;
3843                 caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
3844                     V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
3845                     V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
3846                     FW_LEN16(caps));
3847
3848                 rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
3849                 if (rc != 0) {
3850                         device_printf(sc->dev,
3851                             "failed to upload config file to card: %d.\n", rc);
3852                         goto done;
3853                 }
3854         }
3855         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3856         if (rc != 0) {
3857                 device_printf(sc->dev, "failed to pre-process config file: %d "
3858                     "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
3859                 goto done;
3860         }
3861
3862         finicsum = be32toh(caps.finicsum);
3863         cfcsum = be32toh(caps.cfcsum);  /* actual */
3864         if (finicsum != cfcsum) {
3865                 device_printf(sc->dev,
3866                     "WARNING: config file checksum mismatch: %08x %08x\n",
3867                     finicsum, cfcsum);
3868         }
3869         sc->cfcsum = cfcsum;
3870         snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
3871
3872         /*
3873          * Let the firmware know what features will (not) be used so it can tune
3874          * things accordingly.
3875          */
3876 #define LIMIT_CAPS(x) do { \
3877         caps.x##caps &= htobe16(caps_allowed->x##caps); \
3878 } while (0)
3879         LIMIT_CAPS(nbm);
3880         LIMIT_CAPS(link);
3881         LIMIT_CAPS(switch);
3882         LIMIT_CAPS(nic);
3883         LIMIT_CAPS(toe);
3884         LIMIT_CAPS(rdma);
3885         LIMIT_CAPS(crypto);
3886         LIMIT_CAPS(iscsi);
3887         LIMIT_CAPS(fcoe);
3888 #undef LIMIT_CAPS
3889         if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
3890                 /*
3891                  * TOE and hashfilters are mutually exclusive.  It is a config
3892                  * file or firmware bug if both are reported as available.  Try
3893                  * to cope with the situation in non-debug builds by disabling
3894                  * TOE.
3895                  */
3896                 MPASS(caps.toecaps == 0);
3897
3898                 caps.toecaps = 0;
3899                 caps.rdmacaps = 0;
3900                 caps.iscsicaps = 0;
3901         }
3902
3903         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3904             F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
3905         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3906         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
3907         if (rc != 0) {
3908                 device_printf(sc->dev,
3909                     "failed to process config file: %d.\n", rc);
3910                 goto done;
3911         }
3912
3913         t4_tweak_chip_settings(sc);
3914         set_params__pre_init(sc);
3915
3916         /* get basic stuff going */
3917         rc = -t4_fw_initialize(sc, sc->mbox);
3918         if (rc != 0) {
3919                 device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
3920                 goto done;
3921         }
3922 done:
3923         return (rc);
3924 }
3925
3926 /*
3927  * Partition chip resources for use between various PFs, VFs, etc.
3928  */
3929 static int
3930 partition_resources(struct adapter *sc)
3931 {
3932         char cfg_file[sizeof(t4_cfg_file)];
3933         struct caps_allowed caps_allowed;
3934         int rc;
3935         bool fallback;
3936
3937         /* Only the master driver gets to configure the chip resources. */
3938         MPASS(sc->flags & MASTER_PF);
3939
3940 #define COPY_CAPS(x) do { \
3941         caps_allowed.x##caps = t4_##x##caps_allowed; \
3942 } while (0)
3943         bzero(&caps_allowed, sizeof(caps_allowed));
3944         COPY_CAPS(nbm);
3945         COPY_CAPS(link);
3946         COPY_CAPS(switch);
3947         COPY_CAPS(nic);
3948         COPY_CAPS(toe);
3949         COPY_CAPS(rdma);
3950         COPY_CAPS(crypto);
3951         COPY_CAPS(iscsi);
3952         COPY_CAPS(fcoe);
3953         fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
3954         snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
3955 retry:
3956         rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
3957         if (rc != 0 && fallback) {
3958                 device_printf(sc->dev,
3959                     "failed (%d) to configure card with \"%s\" profile, "
3960                     "will fall back to a basic configuration and retry.\n",
3961                     rc, cfg_file);
3962                 snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
3963                 bzero(&caps_allowed, sizeof(caps_allowed));
3964                 COPY_CAPS(nbm);
3965                 COPY_CAPS(link);
3966                 COPY_CAPS(switch);
3967                 COPY_CAPS(nic);
3968                 fallback = false;
3969                 goto retry;
3970         }
3971 #undef COPY_CAPS
3972         return (rc);
3973 }
3974
3975 /*
3976  * Retrieve parameters that are needed (or nice to have) very early.
3977  */
3978 static int
3979 get_params__pre_init(struct adapter *sc)
3980 {
3981         int rc;
3982         uint32_t param[2], val[2];
3983
3984         t4_get_version_info(sc);
3985
3986         snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
3987             G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
3988             G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
3989             G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
3990             G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
3991
3992         snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
3993             G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
3994             G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
3995             G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
3996             G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
3997
3998         snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
3999             G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
4000             G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
4001             G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
4002             G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
4003
4004         snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
4005             G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
4006             G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
4007             G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
4008             G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
4009
4010         param[0] = FW_PARAM_DEV(PORTVEC);
4011         param[1] = FW_PARAM_DEV(CCLK);
4012         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4013         if (rc != 0) {
4014                 device_printf(sc->dev,
4015                     "failed to query parameters (pre_init): %d.\n", rc);
4016                 return (rc);
4017         }
4018
4019         sc->params.portvec = val[0];
4020         sc->params.nports = bitcount32(val[0]);
4021         sc->params.vpd.cclk = val[1];
4022
4023         /* Read device log parameters. */
4024         rc = -t4_init_devlog_params(sc, 1);
4025         if (rc == 0)
4026                 fixup_devlog_params(sc);
4027         else {
4028                 device_printf(sc->dev,
4029                     "failed to get devlog parameters: %d.\n", rc);
4030                 rc = 0; /* devlog isn't critical for device operation */
4031         }
4032
4033         return (rc);
4034 }
4035
4036 /*
4037  * Any params that need to be set before FW_INITIALIZE.
4038  */
4039 static int
4040 set_params__pre_init(struct adapter *sc)
4041 {
4042         int rc = 0;
4043         uint32_t param, val;
4044
4045         if (chip_id(sc) >= CHELSIO_T6) {
4046                 param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
4047                 val = 1;
4048                 rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4049                 /* firmwares < 1.20.1.0 do not have this param. */
4050                 if (rc == FW_EINVAL && sc->params.fw_vers <
4051                     (V_FW_HDR_FW_VER_MAJOR(1) | V_FW_HDR_FW_VER_MINOR(20) |
4052                     V_FW_HDR_FW_VER_MICRO(1) | V_FW_HDR_FW_VER_BUILD(0))) {
4053                         rc = 0;
4054                 }
4055                 if (rc != 0) {
4056                         device_printf(sc->dev,
4057                             "failed to enable high priority filters :%d.\n",
4058                             rc);
4059                 }
4060         }
4061
4062         /* Enable opaque VIIDs with firmwares that support it. */
4063         param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
4064         val = 1;
4065         rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4066         if (rc == 0 && val == 1)
4067                 sc->params.viid_smt_extn_support = true;
4068         else
4069                 sc->params.viid_smt_extn_support = false;
4070
4071         return (rc);
4072 }
4073
4074 /*
4075  * Retrieve various parameters that are of interest to the driver.  The device
4076  * has been initialized by the firmware at this point.
4077  */
4078 static int
4079 get_params__post_init(struct adapter *sc)
4080 {
4081         int rc;
4082         uint32_t param[7], val[7];
4083         struct fw_caps_config_cmd caps;
4084
4085         param[0] = FW_PARAM_PFVF(IQFLINT_START);
4086         param[1] = FW_PARAM_PFVF(EQ_START);
4087         param[2] = FW_PARAM_PFVF(FILTER_START);
4088         param[3] = FW_PARAM_PFVF(FILTER_END);
4089         param[4] = FW_PARAM_PFVF(L2T_START);
4090         param[5] = FW_PARAM_PFVF(L2T_END);
4091         param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
4092             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
4093             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
4094         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
4095         if (rc != 0) {
4096                 device_printf(sc->dev,
4097                     "failed to query parameters (post_init): %d.\n", rc);
4098                 return (rc);
4099         }
4100
4101         sc->sge.iq_start = val[0];
4102         sc->sge.eq_start = val[1];
4103         if ((int)val[3] > (int)val[2]) {
4104                 sc->tids.ftid_base = val[2];
4105                 sc->tids.ftid_end = val[3];
4106                 sc->tids.nftids = val[3] - val[2] + 1;
4107         }
4108         sc->vres.l2t.start = val[4];
4109         sc->vres.l2t.size = val[5] - val[4] + 1;
4110         KASSERT(sc->vres.l2t.size <= L2T_SIZE,
4111             ("%s: L2 table size (%u) larger than expected (%u)",
4112             __func__, sc->vres.l2t.size, L2T_SIZE));
4113         sc->params.core_vdd = val[6];
4114
4115         if (chip_id(sc) >= CHELSIO_T6) {
4116
4117                 sc->tids.tid_base = t4_read_reg(sc,
4118                     A_LE_DB_ACTIVE_TABLE_START_INDEX);
4119
4120                 param[0] = FW_PARAM_PFVF(HPFILTER_START);
4121                 param[1] = FW_PARAM_PFVF(HPFILTER_END);
4122                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4123                 if (rc != 0) {
4124                         device_printf(sc->dev,
4125                            "failed to query hpfilter parameters: %d.\n", rc);
4126                         return (rc);
4127                 }
4128                 if ((int)val[1] > (int)val[0]) {
4129                         sc->tids.hpftid_base = val[0];
4130                         sc->tids.hpftid_end = val[1];
4131                         sc->tids.nhpftids = val[1] - val[0] + 1;
4132
4133                         /*
4134                          * These should go off if the layout changes and the
4135                          * driver needs to catch up.
4136                          */
4137                         MPASS(sc->tids.hpftid_base == 0);
4138                         MPASS(sc->tids.tid_base == sc->tids.nhpftids);
4139                 }
4140         }
4141
4142         /*
4143          * MPSBGMAP is queried separately because only recent firmwares support
4144          * it as a parameter and we don't want the compound query above to fail
4145          * on older firmwares.
4146          */
4147         param[0] = FW_PARAM_DEV(MPSBGMAP);
4148         val[0] = 0;
4149         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4150         if (rc == 0)
4151                 sc->params.mps_bg_map = val[0];
4152         else
4153                 sc->params.mps_bg_map = 0;
4154
4155         /*
4156          * Determine whether the firmware supports the filter2 work request.
4157          * This is queried separately for the same reason as MPSBGMAP above.
4158          */
4159         param[0] = FW_PARAM_DEV(FILTER2_WR);
4160         val[0] = 0;
4161         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4162         if (rc == 0)
4163                 sc->params.filter2_wr_support = val[0] != 0;
4164         else
4165                 sc->params.filter2_wr_support = 0;
4166
4167         /*
4168          * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
4169          * This is queried separately for the same reason as other params above.
4170          */
4171         param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
4172         val[0] = 0;
4173         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4174         if (rc == 0)
4175                 sc->params.ulptx_memwrite_dsgl = val[0] != 0;
4176         else
4177                 sc->params.ulptx_memwrite_dsgl = false;
4178
4179         /* get capabilites */
4180         bzero(&caps, sizeof(caps));
4181         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4182             F_FW_CMD_REQUEST | F_FW_CMD_READ);
4183         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4184         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4185         if (rc != 0) {
4186                 device_printf(sc->dev,
4187                     "failed to get card capabilities: %d.\n", rc);
4188                 return (rc);
4189         }
4190
4191 #define READ_CAPS(x) do { \
4192         sc->x = htobe16(caps.x); \
4193 } while (0)
4194         READ_CAPS(nbmcaps);
4195         READ_CAPS(linkcaps);
4196         READ_CAPS(switchcaps);
4197         READ_CAPS(niccaps);
4198         READ_CAPS(toecaps);
4199         READ_CAPS(rdmacaps);
4200         READ_CAPS(cryptocaps);
4201         READ_CAPS(iscsicaps);
4202         READ_CAPS(fcoecaps);
4203
4204         if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
4205                 MPASS(chip_id(sc) > CHELSIO_T4);
4206                 MPASS(sc->toecaps == 0);
4207                 sc->toecaps = 0;
4208
4209                 param[0] = FW_PARAM_DEV(NTID);
4210                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
4211                 if (rc != 0) {
4212                         device_printf(sc->dev,
4213                             "failed to query HASHFILTER parameters: %d.\n", rc);
4214                         return (rc);
4215                 }
4216                 sc->tids.ntids = val[0];
4217                 if (sc->params.fw_vers <
4218                     (V_FW_HDR_FW_VER_MAJOR(1) | V_FW_HDR_FW_VER_MINOR(20) |
4219                     V_FW_HDR_FW_VER_MICRO(5) | V_FW_HDR_FW_VER_BUILD(0))) {
4220                         MPASS(sc->tids.ntids >= sc->tids.nhpftids);
4221                         sc->tids.ntids -= sc->tids.nhpftids;
4222                 }
4223                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
4224                 sc->params.hash_filter = 1;
4225         }
4226         if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
4227                 param[0] = FW_PARAM_PFVF(ETHOFLD_START);
4228                 param[1] = FW_PARAM_PFVF(ETHOFLD_END);
4229                 param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
4230                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
4231                 if (rc != 0) {
4232                         device_printf(sc->dev,
4233                             "failed to query NIC parameters: %d.\n", rc);
4234                         return (rc);
4235                 }
4236                 if ((int)val[1] > (int)val[0]) {
4237                         sc->tids.etid_base = val[0];
4238                         sc->tids.etid_end = val[1];
4239                         sc->tids.netids = val[1] - val[0] + 1;
4240                         sc->params.eo_wr_cred = val[2];
4241                         sc->params.ethoffload = 1;
4242                 }
4243         }
4244         if (sc->toecaps) {
4245                 /* query offload-related parameters */
4246                 param[0] = FW_PARAM_DEV(NTID);
4247                 param[1] = FW_PARAM_PFVF(SERVER_START);
4248                 param[2] = FW_PARAM_PFVF(SERVER_END);
4249                 param[3] = FW_PARAM_PFVF(TDDP_START);
4250                 param[4] = FW_PARAM_PFVF(TDDP_END);
4251                 param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
4252                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4253                 if (rc != 0) {
4254                         device_printf(sc->dev,
4255                             "failed to query TOE parameters: %d.\n", rc);
4256                         return (rc);
4257                 }
4258                 sc->tids.ntids = val[0];
4259                 if (sc->params.fw_vers <
4260                     (V_FW_HDR_FW_VER_MAJOR(1) | V_FW_HDR_FW_VER_MINOR(20) |
4261                     V_FW_HDR_FW_VER_MICRO(5) | V_FW_HDR_FW_VER_BUILD(0))) {
4262                         MPASS(sc->tids.ntids >= sc->tids.nhpftids);
4263                         sc->tids.ntids -= sc->tids.nhpftids;
4264                 }
4265                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
4266                 if ((int)val[2] > (int)val[1]) {
4267                         sc->tids.stid_base = val[1];
4268                         sc->tids.nstids = val[2] - val[1] + 1;
4269                 }
4270                 sc->vres.ddp.start = val[3];
4271                 sc->vres.ddp.size = val[4] - val[3] + 1;
4272                 sc->params.ofldq_wr_cred = val[5];
4273                 sc->params.offload = 1;
4274         } else {
4275                 /*
4276                  * The firmware attempts memfree TOE configuration for -SO cards
4277                  * and will report toecaps=0 if it runs out of resources (this
4278                  * depends on the config file).  It may not report 0 for other
4279                  * capabilities dependent on the TOE in this case.  Set them to
4280                  * 0 here so that the driver doesn't bother tracking resources
4281                  * that will never be used.
4282                  */
4283                 sc->iscsicaps = 0;
4284                 sc->rdmacaps = 0;
4285         }
4286         if (sc->rdmacaps) {
4287                 param[0] = FW_PARAM_PFVF(STAG_START);
4288                 param[1] = FW_PARAM_PFVF(STAG_END);
4289                 param[2] = FW_PARAM_PFVF(RQ_START);
4290                 param[3] = FW_PARAM_PFVF(RQ_END);
4291                 param[4] = FW_PARAM_PFVF(PBL_START);
4292                 param[5] = FW_PARAM_PFVF(PBL_END);
4293                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4294                 if (rc != 0) {
4295                         device_printf(sc->dev,
4296                             "failed to query RDMA parameters(1): %d.\n", rc);
4297                         return (rc);
4298                 }
4299                 sc->vres.stag.start = val[0];
4300                 sc->vres.stag.size = val[1] - val[0] + 1;
4301                 sc->vres.rq.start = val[2];
4302                 sc->vres.rq.size = val[3] - val[2] + 1;
4303                 sc->vres.pbl.start = val[4];
4304                 sc->vres.pbl.size = val[5] - val[4] + 1;
4305
4306                 param[0] = FW_PARAM_PFVF(SQRQ_START);
4307                 param[1] = FW_PARAM_PFVF(SQRQ_END);
4308                 param[2] = FW_PARAM_PFVF(CQ_START);
4309                 param[3] = FW_PARAM_PFVF(CQ_END);
4310                 param[4] = FW_PARAM_PFVF(OCQ_START);
4311                 param[5] = FW_PARAM_PFVF(OCQ_END);
4312                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
4313                 if (rc != 0) {
4314                         device_printf(sc->dev,
4315                             "failed to query RDMA parameters(2): %d.\n", rc);
4316                         return (rc);
4317                 }
4318                 sc->vres.qp.start = val[0];
4319                 sc->vres.qp.size = val[1] - val[0] + 1;
4320                 sc->vres.cq.start = val[2];
4321                 sc->vres.cq.size = val[3] - val[2] + 1;
4322                 sc->vres.ocq.start = val[4];
4323                 sc->vres.ocq.size = val[5] - val[4] + 1;
4324
4325                 param[0] = FW_PARAM_PFVF(SRQ_START);
4326                 param[1] = FW_PARAM_PFVF(SRQ_END);
4327                 param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
4328                 param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
4329                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
4330                 if (rc != 0) {
4331                         device_printf(sc->dev,
4332                             "failed to query RDMA parameters(3): %d.\n", rc);
4333                         return (rc);
4334                 }
4335                 sc->vres.srq.start = val[0];
4336                 sc->vres.srq.size = val[1] - val[0] + 1;
4337                 sc->params.max_ordird_qp = val[2];
4338                 sc->params.max_ird_adapter = val[3];
4339         }
4340         if (sc->iscsicaps) {
4341                 param[0] = FW_PARAM_PFVF(ISCSI_START);
4342                 param[1] = FW_PARAM_PFVF(ISCSI_END);
4343                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4344                 if (rc != 0) {
4345                         device_printf(sc->dev,
4346                             "failed to query iSCSI parameters: %d.\n", rc);
4347                         return (rc);
4348                 }
4349                 sc->vres.iscsi.start = val[0];
4350                 sc->vres.iscsi.size = val[1] - val[0] + 1;
4351         }
4352         if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
4353                 param[0] = FW_PARAM_PFVF(TLS_START);
4354                 param[1] = FW_PARAM_PFVF(TLS_END);
4355                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
4356                 if (rc != 0) {
4357                         device_printf(sc->dev,
4358                             "failed to query TLS parameters: %d.\n", rc);
4359                         return (rc);
4360                 }
4361                 sc->vres.key.start = val[0];
4362                 sc->vres.key.size = val[1] - val[0] + 1;
4363         }
4364
4365         t4_init_sge_params(sc);
4366
4367         /*
4368          * We've got the params we wanted to query via the firmware.  Now grab
4369          * some others directly from the chip.
4370          */
4371         rc = t4_read_chip_settings(sc);
4372
4373         return (rc);
4374 }
4375
4376 static int
4377 set_params__post_init(struct adapter *sc)
4378 {
4379         uint32_t param, val;
4380 #ifdef TCP_OFFLOAD
4381         int i, v, shift;
4382 #endif
4383
4384         /* ask for encapsulated CPLs */
4385         param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
4386         val = 1;
4387         (void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4388
4389         /* Enable 32b port caps if the firmware supports it. */
4390         param = FW_PARAM_PFVF(PORT_CAPS32);
4391         val = 1;
4392         if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
4393                 sc->params.port_caps32 = 1;
4394
4395 #ifdef TCP_OFFLOAD
4396         /*
4397          * Override the TOE timers with user provided tunables.  This is not the
4398          * recommended way to change the timers (the firmware config file is) so
4399          * these tunables are not documented.
4400          *
4401          * All the timer tunables are in microseconds.
4402          */
4403         if (t4_toe_keepalive_idle != 0) {
4404                 v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
4405                 v &= M_KEEPALIVEIDLE;
4406                 t4_set_reg_field(sc, A_TP_KEEP_IDLE,
4407                     V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
4408         }
4409         if (t4_toe_keepalive_interval != 0) {
4410                 v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
4411                 v &= M_KEEPALIVEINTVL;
4412                 t4_set_reg_field(sc, A_TP_KEEP_INTVL,
4413                     V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
4414         }
4415         if (t4_toe_keepalive_count != 0) {
4416                 v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
4417                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
4418                     V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
4419                     V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
4420                     V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
4421         }
4422         if (t4_toe_rexmt_min != 0) {
4423                 v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
4424                 v &= M_RXTMIN;
4425                 t4_set_reg_field(sc, A_TP_RXT_MIN,
4426                     V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
4427         }
4428         if (t4_toe_rexmt_max != 0) {
4429                 v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
4430                 v &= M_RXTMAX;
4431                 t4_set_reg_field(sc, A_TP_RXT_MAX,
4432                     V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
4433         }
4434         if (t4_toe_rexmt_count != 0) {
4435                 v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
4436                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
4437                     V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
4438                     V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
4439                     V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
4440         }
4441         for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
4442                 if (t4_toe_rexmt_backoff[i] != -1) {
4443                         v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
4444                         shift = (i & 3) << 3;
4445                         t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
4446                             M_TIMERBACKOFFINDEX0 << shift, v << shift);
4447                 }
4448         }
4449 #endif
4450         return (0);
4451 }
4452
4453 #undef FW_PARAM_PFVF
4454 #undef FW_PARAM_DEV
4455
4456 static void
4457 t4_set_desc(struct adapter *sc)
4458 {
4459         char buf[128];
4460         struct adapter_params *p = &sc->params;
4461
4462         snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
4463
4464         device_set_desc_copy(sc->dev, buf);
4465 }
4466
4467 static inline void
4468 ifmedia_add4(struct ifmedia *ifm, int m)
4469 {
4470
4471         ifmedia_add(ifm, m, 0, NULL);
4472         ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
4473         ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
4474         ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
4475 }
4476
4477 /*
4478  * This is the selected media, which is not quite the same as the active media.
4479  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
4480  * and active are not the same, and "media: Ethernet selected" otherwise.
4481  */
4482 static void
4483 set_current_media(struct port_info *pi)
4484 {
4485         struct link_config *lc;
4486         struct ifmedia *ifm;
4487         int mword;
4488         u_int speed;
4489
4490         PORT_LOCK_ASSERT_OWNED(pi);
4491
4492         /* Leave current media alone if it's already set to IFM_NONE. */
4493         ifm = &pi->media;
4494         if (ifm->ifm_cur != NULL &&
4495             IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
4496                 return;
4497
4498         lc = &pi->link_cfg;
4499         if (lc->requested_aneg != AUTONEG_DISABLE &&
4500             lc->supported & FW_PORT_CAP32_ANEG) {
4501                 ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
4502                 return;
4503         }
4504         mword = IFM_ETHER | IFM_FDX;
4505         if (lc->requested_fc & PAUSE_TX)
4506                 mword |= IFM_ETH_TXPAUSE;
4507         if (lc->requested_fc & PAUSE_RX)
4508                 mword |= IFM_ETH_RXPAUSE;
4509         if (lc->requested_speed == 0)
4510                 speed = port_top_speed(pi) * 1000;      /* Gbps -> Mbps */
4511         else
4512                 speed = lc->requested_speed;
4513         mword |= port_mword(pi, speed_to_fwcap(speed));
4514         ifmedia_set(ifm, mword);
4515 }
4516
4517 /*
4518  * Returns true if the ifmedia list for the port cannot change.
4519  */
4520 static bool
4521 fixed_ifmedia(struct port_info *pi)
4522 {
4523
4524         return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
4525             pi->port_type == FW_PORT_TYPE_BT_XFI ||
4526             pi->port_type == FW_PORT_TYPE_BT_XAUI ||
4527             pi->port_type == FW_PORT_TYPE_KX4 ||
4528             pi->port_type == FW_PORT_TYPE_KX ||
4529             pi->port_type == FW_PORT_TYPE_KR ||
4530             pi->port_type == FW_PORT_TYPE_BP_AP ||
4531             pi->port_type == FW_PORT_TYPE_BP4_AP ||
4532             pi->port_type == FW_PORT_TYPE_BP40_BA ||
4533             pi->port_type == FW_PORT_TYPE_KR4_100G ||
4534             pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
4535             pi->port_type == FW_PORT_TYPE_KR_XLAUI);
4536 }
4537
4538 static void
4539 build_medialist(struct port_info *pi)
4540 {
4541         uint32_t ss, speed;
4542         int unknown, mword, bit;
4543         struct link_config *lc;
4544         struct ifmedia *ifm;
4545
4546         PORT_LOCK_ASSERT_OWNED(pi);
4547
4548         if (pi->flags & FIXED_IFMEDIA)
4549                 return;
4550
4551         /*
4552          * Rebuild the ifmedia list.
4553          */
4554         ifm = &pi->media;
4555         ifmedia_removeall(ifm);
4556         lc = &pi->link_cfg;
4557         ss = G_FW_PORT_CAP32_SPEED(lc->supported); /* Supported Speeds */
4558         if (__predict_false(ss == 0)) { /* not supposed to happen. */
4559                 MPASS(ss != 0);
4560 no_media:
4561                 MPASS(LIST_EMPTY(&ifm->ifm_list));
4562                 ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
4563                 ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
4564                 return;
4565         }
4566
4567         unknown = 0;
4568         for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
4569                 speed = 1 << bit;
4570                 MPASS(speed & M_FW_PORT_CAP32_SPEED);
4571                 if (ss & speed) {
4572                         mword = port_mword(pi, speed);
4573                         if (mword == IFM_NONE) {
4574                                 goto no_media;
4575                         } else if (mword == IFM_UNKNOWN)
4576                                 unknown++;
4577                         else
4578                                 ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
4579                 }
4580         }
4581         if (unknown > 0) /* Add one unknown for all unknown media types. */
4582                 ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
4583         if (lc->supported & FW_PORT_CAP32_ANEG)
4584                 ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
4585
4586         set_current_media(pi);
4587 }
4588
4589 /*
4590  * Initialize the requested fields in the link config based on driver tunables.
4591  */
4592 static void
4593 init_link_config(struct port_info *pi)
4594 {
4595         struct link_config *lc = &pi->link_cfg;
4596
4597         PORT_LOCK_ASSERT_OWNED(pi);
4598
4599         lc->requested_speed = 0;
4600
4601         if (t4_autoneg == 0)
4602                 lc->requested_aneg = AUTONEG_DISABLE;
4603         else if (t4_autoneg == 1)
4604                 lc->requested_aneg = AUTONEG_ENABLE;
4605         else
4606                 lc->requested_aneg = AUTONEG_AUTO;
4607
4608         lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
4609             PAUSE_AUTONEG);
4610
4611         if (t4_fec == -1 || t4_fec & FEC_AUTO)
4612                 lc->requested_fec = FEC_AUTO;
4613         else {
4614                 lc->requested_fec = FEC_NONE;
4615                 if (t4_fec & FEC_RS)
4616                         lc->requested_fec |= FEC_RS;
4617                 if (t4_fec & FEC_BASER_RS)
4618                         lc->requested_fec |= FEC_BASER_RS;
4619         }
4620 }
4621
4622 /*
4623  * Makes sure that all requested settings comply with what's supported by the
4624  * port.  Returns the number of settings that were invalid and had to be fixed.
4625  */
4626 static int
4627 fixup_link_config(struct port_info *pi)
4628 {
4629         int n = 0;
4630         struct link_config *lc = &pi->link_cfg;
4631         uint32_t fwspeed;
4632
4633         PORT_LOCK_ASSERT_OWNED(pi);
4634
4635         /* Speed (when not autonegotiating) */
4636         if (lc->requested_speed != 0) {
4637                 fwspeed = speed_to_fwcap(lc->requested_speed);
4638                 if ((fwspeed & lc->supported) == 0) {
4639                         n++;
4640                         lc->requested_speed = 0;
4641                 }
4642         }
4643
4644         /* Link autonegotiation */
4645         MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
4646             lc->requested_aneg == AUTONEG_DISABLE ||
4647             lc->requested_aneg == AUTONEG_AUTO);
4648         if (lc->requested_aneg == AUTONEG_ENABLE &&
4649             !(lc->supported & FW_PORT_CAP32_ANEG)) {
4650                 n++;
4651                 lc->requested_aneg = AUTONEG_AUTO;
4652         }
4653
4654         /* Flow control */
4655         MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
4656         if (lc->requested_fc & PAUSE_TX &&
4657             !(lc->supported & FW_PORT_CAP32_FC_TX)) {
4658                 n++;
4659                 lc->requested_fc &= ~PAUSE_TX;
4660         }
4661         if (lc->requested_fc & PAUSE_RX &&
4662             !(lc->supported & FW_PORT_CAP32_FC_RX)) {
4663                 n++;
4664                 lc->requested_fc &= ~PAUSE_RX;
4665         }
4666         if (!(lc->requested_fc & PAUSE_AUTONEG) &&
4667             !(lc->supported & FW_PORT_CAP32_FORCE_PAUSE)) {
4668                 n++;
4669                 lc->requested_fc |= PAUSE_AUTONEG;
4670         }
4671
4672         /* FEC */
4673         if ((lc->requested_fec & FEC_RS &&
4674             !(lc->supported & FW_PORT_CAP32_FEC_RS)) ||
4675             (lc->requested_fec & FEC_BASER_RS &&
4676             !(lc->supported & FW_PORT_CAP32_FEC_BASER_RS))) {
4677                 n++;
4678                 lc->requested_fec = FEC_AUTO;
4679         }
4680
4681         return (n);
4682 }
4683
4684 /*
4685  * Apply the requested L1 settings, which are expected to be valid, to the
4686  * hardware.
4687  */
4688 static int
4689 apply_link_config(struct port_info *pi)
4690 {
4691         struct adapter *sc = pi->adapter;
4692         struct link_config *lc = &pi->link_cfg;
4693         int rc;
4694
4695 #ifdef INVARIANTS
4696         ASSERT_SYNCHRONIZED_OP(sc);
4697         PORT_LOCK_ASSERT_OWNED(pi);
4698
4699         if (lc->requested_aneg == AUTONEG_ENABLE)
4700                 MPASS(lc->supported & FW_PORT_CAP32_ANEG);
4701         if (!(lc->requested_fc & PAUSE_AUTONEG))
4702                 MPASS(lc->supported & FW_PORT_CAP32_FORCE_PAUSE);
4703         if (lc->requested_fc & PAUSE_TX)
4704                 MPASS(lc->supported & FW_PORT_CAP32_FC_TX);
4705         if (lc->requested_fc & PAUSE_RX)
4706                 MPASS(lc->supported & FW_PORT_CAP32_FC_RX);
4707         if (lc->requested_fec & FEC_RS)
4708                 MPASS(lc->supported & FW_PORT_CAP32_FEC_RS);
4709         if (lc->requested_fec & FEC_BASER_RS)
4710                 MPASS(lc->supported & FW_PORT_CAP32_FEC_BASER_RS);
4711 #endif
4712         rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
4713         if (rc != 0) {
4714                 /* Don't complain if the VF driver gets back an EPERM. */
4715                 if (!(sc->flags & IS_VF) || rc != FW_EPERM)
4716                         device_printf(pi->dev, "l1cfg failed: %d\n", rc);
4717         } else {
4718                 /*
4719                  * An L1_CFG will almost always result in a link-change event if
4720                  * the link is up, and the driver will refresh the actual
4721                  * fec/fc/etc. when the notification is processed.  If the link
4722                  * is down then the actual settings are meaningless.
4723                  *
4724                  * This takes care of the case where a change in the L1 settings
4725                  * may not result in a notification.
4726                  */
4727                 if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
4728                         lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
4729         }
4730         return (rc);
4731 }
4732
4733 #define FW_MAC_EXACT_CHUNK      7
4734
4735 /*
4736  * Program the port's XGMAC based on parameters in ifnet.  The caller also
4737  * indicates which parameters should be programmed (the rest are left alone).
4738  */
4739 int
4740 update_mac_settings(struct ifnet *ifp, int flags)
4741 {
4742         int rc = 0;
4743         struct vi_info *vi = ifp->if_softc;
4744         struct port_info *pi = vi->pi;
4745         struct adapter *sc = pi->adapter;
4746         int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
4747
4748         ASSERT_SYNCHRONIZED_OP(sc);
4749         KASSERT(flags, ("%s: not told what to update.", __func__));
4750
4751         if (flags & XGMAC_MTU)
4752                 mtu = ifp->if_mtu;
4753
4754         if (flags & XGMAC_PROMISC)
4755                 promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
4756
4757         if (flags & XGMAC_ALLMULTI)
4758                 allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
4759
4760         if (flags & XGMAC_VLANEX)
4761                 vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
4762
4763         if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
4764                 rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
4765                     allmulti, 1, vlanex, false);
4766                 if (rc) {
4767                         if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
4768                             rc);
4769                         return (rc);
4770                 }
4771         }
4772
4773         if (flags & XGMAC_UCADDR) {
4774                 uint8_t ucaddr[ETHER_ADDR_LEN];
4775
4776                 bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
4777                 rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
4778                     ucaddr, true, &vi->smt_idx);
4779                 if (rc < 0) {
4780                         rc = -rc;
4781                         if_printf(ifp, "change_mac failed: %d\n", rc);
4782                         return (rc);
4783                 } else {
4784                         vi->xact_addr_filt = rc;
4785                         rc = 0;
4786                 }
4787         }
4788
4789         if (flags & XGMAC_MCADDRS) {
4790                 const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
4791                 int del = 1;
4792                 uint64_t hash = 0;
4793                 struct ifmultiaddr *ifma;
4794                 int i = 0, j;
4795
4796                 if_maddr_rlock(ifp);
4797                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
4798                         if (ifma->ifma_addr->sa_family != AF_LINK)
4799                                 continue;
4800                         mcaddr[i] =
4801                             LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
4802                         MPASS(ETHER_IS_MULTICAST(mcaddr[i]));
4803                         i++;
4804
4805                         if (i == FW_MAC_EXACT_CHUNK) {
4806                                 rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
4807                                     del, i, mcaddr, NULL, &hash, 0);
4808                                 if (rc < 0) {
4809                                         rc = -rc;
4810                                         for (j = 0; j < i; j++) {
4811                                                 if_printf(ifp,
4812                                                     "failed to add mc address"
4813                                                     " %02x:%02x:%02x:"
4814                                                     "%02x:%02x:%02x rc=%d\n",
4815                                                     mcaddr[j][0], mcaddr[j][1],
4816                                                     mcaddr[j][2], mcaddr[j][3],
4817                                                     mcaddr[j][4], mcaddr[j][5],
4818                                                     rc);
4819                                         }
4820                                         goto mcfail;
4821                                 }
4822                                 del = 0;
4823                                 i = 0;
4824                         }
4825                 }
4826                 if (i > 0) {
4827                         rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, del, i,
4828                             mcaddr, NULL, &hash, 0);
4829                         if (rc < 0) {
4830                                 rc = -rc;
4831                                 for (j = 0; j < i; j++) {
4832                                         if_printf(ifp,
4833                                             "failed to add mc address"
4834                                             " %02x:%02x:%02x:"
4835                                             "%02x:%02x:%02x rc=%d\n",
4836                                             mcaddr[j][0], mcaddr[j][1],
4837                                             mcaddr[j][2], mcaddr[j][3],
4838                                             mcaddr[j][4], mcaddr[j][5],
4839                                             rc);
4840                                 }
4841                                 goto mcfail;
4842                         }
4843                 }
4844
4845                 rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, hash, 0);
4846                 if (rc != 0)
4847                         if_printf(ifp, "failed to set mc address hash: %d", rc);
4848 mcfail:
4849                 if_maddr_runlock(ifp);
4850         }
4851
4852         return (rc);
4853 }
4854
4855 /*
4856  * {begin|end}_synchronized_op must be called from the same thread.
4857  */
4858 int
4859 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
4860     char *wmesg)
4861 {
4862         int rc, pri;
4863
4864 #ifdef WITNESS
4865         /* the caller thinks it's ok to sleep, but is it really? */
4866         if (flags & SLEEP_OK)
4867                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
4868                     "begin_synchronized_op");
4869 #endif
4870
4871         if (INTR_OK)
4872                 pri = PCATCH;
4873         else
4874                 pri = 0;
4875
4876         ADAPTER_LOCK(sc);
4877         for (;;) {
4878
4879                 if (vi && IS_DOOMED(vi)) {
4880                         rc = ENXIO;
4881                         goto done;
4882                 }
4883
4884                 if (!IS_BUSY(sc)) {
4885                         rc = 0;
4886                         break;
4887                 }
4888
4889                 if (!(flags & SLEEP_OK)) {
4890                         rc = EBUSY;
4891                         goto done;
4892                 }
4893
4894                 if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
4895                         rc = EINTR;
4896                         goto done;
4897                 }
4898         }
4899
4900         KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
4901         SET_BUSY(sc);
4902 #ifdef INVARIANTS
4903         sc->last_op = wmesg;
4904         sc->last_op_thr = curthread;
4905         sc->last_op_flags = flags;
4906 #endif
4907
4908 done:
4909         if (!(flags & HOLD_LOCK) || rc)
4910                 ADAPTER_UNLOCK(sc);
4911
4912         return (rc);
4913 }
4914
4915 /*
4916  * Tell if_ioctl and if_init that the VI is going away.  This is
4917  * special variant of begin_synchronized_op and must be paired with a
4918  * call to end_synchronized_op.
4919  */
4920 void
4921 doom_vi(struct adapter *sc, struct vi_info *vi)
4922 {
4923
4924         ADAPTER_LOCK(sc);
4925         SET_DOOMED(vi);
4926         wakeup(&sc->flags);
4927         while (IS_BUSY(sc))
4928                 mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
4929         SET_BUSY(sc);
4930 #ifdef INVARIANTS
4931         sc->last_op = "t4detach";
4932         sc->last_op_thr = curthread;
4933         sc->last_op_flags = 0;
4934 #endif
4935         ADAPTER_UNLOCK(sc);
4936 }
4937
4938 /*
4939  * {begin|end}_synchronized_op must be called from the same thread.
4940  */
4941 void
4942 end_synchronized_op(struct adapter *sc, int flags)
4943 {
4944
4945         if (flags & LOCK_HELD)
4946                 ADAPTER_LOCK_ASSERT_OWNED(sc);
4947         else
4948                 ADAPTER_LOCK(sc);
4949
4950         KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
4951         CLR_BUSY(sc);
4952         wakeup(&sc->flags);
4953         ADAPTER_UNLOCK(sc);
4954 }
4955
4956 static int
4957 cxgbe_init_synchronized(struct vi_info *vi)
4958 {
4959         struct port_info *pi = vi->pi;
4960         struct adapter *sc = pi->adapter;
4961         struct ifnet *ifp = vi->ifp;
4962         int rc = 0, i;
4963         struct sge_txq *txq;
4964
4965         ASSERT_SYNCHRONIZED_OP(sc);
4966
4967         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4968                 return (0);     /* already running */
4969
4970         if (!(sc->flags & FULL_INIT_DONE) &&
4971             ((rc = adapter_full_init(sc)) != 0))
4972                 return (rc);    /* error message displayed already */
4973
4974         if (!(vi->flags & VI_INIT_DONE) &&
4975             ((rc = vi_full_init(vi)) != 0))
4976                 return (rc); /* error message displayed already */
4977
4978         rc = update_mac_settings(ifp, XGMAC_ALL);
4979         if (rc)
4980                 goto done;      /* error message displayed already */
4981
4982         PORT_LOCK(pi);
4983         if (pi->up_vis == 0) {
4984                 t4_update_port_info(pi);
4985                 fixup_link_config(pi);
4986                 build_medialist(pi);
4987                 apply_link_config(pi);
4988         }
4989
4990         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
4991         if (rc != 0) {
4992                 if_printf(ifp, "enable_vi failed: %d\n", rc);
4993                 PORT_UNLOCK(pi);
4994                 goto done;
4995         }
4996
4997         /*
4998          * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
4999          * if this changes.
5000          */
5001
5002         for_each_txq(vi, i, txq) {
5003                 TXQ_LOCK(txq);
5004                 txq->eq.flags |= EQ_ENABLED;
5005                 TXQ_UNLOCK(txq);
5006         }
5007
5008         /*
5009          * The first iq of the first port to come up is used for tracing.
5010          */
5011         if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
5012                 sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
5013                 t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
5014                     A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
5015                     V_QUEUENUMBER(sc->traceq));
5016                 pi->flags |= HAS_TRACEQ;
5017         }
5018
5019         /* all ok */
5020         pi->up_vis++;
5021         ifp->if_drv_flags |= IFF_DRV_RUNNING;
5022
5023         if (pi->nvi > 1 || sc->flags & IS_VF)
5024                 callout_reset(&vi->tick, hz, vi_tick, vi);
5025         else
5026                 callout_reset(&pi->tick, hz, cxgbe_tick, pi);
5027         if (pi->link_cfg.link_ok)
5028                 t4_os_link_changed(pi);
5029         PORT_UNLOCK(pi);
5030 done:
5031         if (rc != 0)
5032                 cxgbe_uninit_synchronized(vi);
5033
5034         return (rc);
5035 }
5036
5037 /*
5038  * Idempotent.
5039  */
5040 static int
5041 cxgbe_uninit_synchronized(struct vi_info *vi)
5042 {
5043         struct port_info *pi = vi->pi;
5044         struct adapter *sc = pi->adapter;
5045         struct ifnet *ifp = vi->ifp;
5046         int rc, i;
5047         struct sge_txq *txq;
5048
5049         ASSERT_SYNCHRONIZED_OP(sc);
5050
5051         if (!(vi->flags & VI_INIT_DONE)) {
5052                 if (__predict_false(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5053                         KASSERT(0, ("uninited VI is running"));
5054                         if_printf(ifp, "uninited VI with running ifnet.  "
5055                             "vi->flags 0x%016lx, if_flags 0x%08x, "
5056                             "if_drv_flags 0x%08x\n", vi->flags, ifp->if_flags,
5057                             ifp->if_drv_flags);
5058                 }
5059                 return (0);
5060         }
5061
5062         /*
5063          * Disable the VI so that all its data in either direction is discarded
5064          * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
5065          * tick) intact as the TP can deliver negative advice or data that it's
5066          * holding in its RAM (for an offloaded connection) even after the VI is
5067          * disabled.
5068          */
5069         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
5070         if (rc) {
5071                 if_printf(ifp, "disable_vi failed: %d\n", rc);
5072                 return (rc);
5073         }
5074
5075         for_each_txq(vi, i, txq) {
5076                 TXQ_LOCK(txq);
5077                 txq->eq.flags &= ~EQ_ENABLED;
5078                 TXQ_UNLOCK(txq);
5079         }
5080
5081         PORT_LOCK(pi);
5082         if (pi->nvi > 1 || sc->flags & IS_VF)
5083                 callout_stop(&vi->tick);
5084         else
5085                 callout_stop(&pi->tick);
5086         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5087                 PORT_UNLOCK(pi);
5088                 return (0);
5089         }
5090         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
5091         pi->up_vis--;
5092         if (pi->up_vis > 0) {
5093                 PORT_UNLOCK(pi);
5094                 return (0);
5095         }
5096
5097         pi->link_cfg.link_ok = false;
5098         pi->link_cfg.speed = 0;
5099         pi->link_cfg.link_down_rc = 255;
5100         t4_os_link_changed(pi);
5101         PORT_UNLOCK(pi);
5102
5103         return (0);
5104 }
5105
5106 /*
5107  * It is ok for this function to fail midway and return right away.  t4_detach
5108  * will walk the entire sc->irq list and clean up whatever is valid.
5109  */
5110 int
5111 t4_setup_intr_handlers(struct adapter *sc)
5112 {
5113         int rc, rid, p, q, v;
5114         char s[8];
5115         struct irq *irq;
5116         struct port_info *pi;
5117         struct vi_info *vi;
5118         struct sge *sge = &sc->sge;
5119         struct sge_rxq *rxq;
5120 #ifdef TCP_OFFLOAD
5121         struct sge_ofld_rxq *ofld_rxq;
5122 #endif
5123 #ifdef DEV_NETMAP
5124         struct sge_nm_rxq *nm_rxq;
5125 #endif
5126 #ifdef RSS
5127         int nbuckets = rss_getnumbuckets();
5128 #endif
5129
5130         /*
5131          * Setup interrupts.
5132          */
5133         irq = &sc->irq[0];
5134         rid = sc->intr_type == INTR_INTX ? 0 : 1;
5135         if (forwarding_intr_to_fwq(sc))
5136                 return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
5137
5138         /* Multiple interrupts. */
5139         if (sc->flags & IS_VF)
5140                 KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
5141                     ("%s: too few intr.", __func__));
5142         else
5143                 KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
5144                     ("%s: too few intr.", __func__));
5145
5146         /* The first one is always error intr on PFs */
5147         if (!(sc->flags & IS_VF)) {
5148                 rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
5149                 if (rc != 0)
5150                         return (rc);
5151                 irq++;
5152                 rid++;
5153         }
5154
5155         /* The second one is always the firmware event queue (first on VFs) */
5156         rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
5157         if (rc != 0)
5158                 return (rc);
5159         irq++;
5160         rid++;
5161
5162         for_each_port(sc, p) {
5163                 pi = sc->port[p];
5164                 for_each_vi(pi, v, vi) {
5165                         vi->first_intr = rid - 1;
5166
5167                         if (vi->nnmrxq > 0) {
5168                                 int n = max(vi->nrxq, vi->nnmrxq);
5169
5170                                 rxq = &sge->rxq[vi->first_rxq];
5171 #ifdef DEV_NETMAP
5172                                 nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
5173 #endif
5174                                 for (q = 0; q < n; q++) {
5175                                         snprintf(s, sizeof(s), "%x%c%x", p,
5176                                             'a' + v, q);
5177                                         if (q < vi->nrxq)
5178                                                 irq->rxq = rxq++;
5179 #ifdef DEV_NETMAP
5180                                         if (q < vi->nnmrxq)
5181                                                 irq->nm_rxq = nm_rxq++;
5182
5183                                         if (irq->nm_rxq != NULL &&
5184                                             irq->rxq == NULL) {
5185                                                 /* Netmap rx only */
5186                                                 rc = t4_alloc_irq(sc, irq, rid,
5187                                                     t4_nm_intr, irq->nm_rxq, s);
5188                                         }
5189                                         if (irq->nm_rxq != NULL &&
5190                                             irq->rxq != NULL) {
5191                                                 /* NIC and Netmap rx */
5192                                                 rc = t4_alloc_irq(sc, irq, rid,
5193                                                     t4_vi_intr, irq, s);
5194                                         }
5195 #endif
5196                                         if (irq->rxq != NULL &&
5197                                             irq->nm_rxq == NULL) {
5198                                                 /* NIC rx only */
5199                                                 rc = t4_alloc_irq(sc, irq, rid,
5200                                                     t4_intr, irq->rxq, s);
5201                                         }
5202                                         if (rc != 0)
5203                                                 return (rc);
5204 #ifdef RSS
5205                                         if (q < vi->nrxq) {
5206                                                 bus_bind_intr(sc->dev, irq->res,
5207                                                     rss_getcpu(q % nbuckets));
5208                                         }
5209 #endif
5210                                         irq++;
5211                                         rid++;
5212                                         vi->nintr++;
5213                                 }
5214                         } else {
5215                                 for_each_rxq(vi, q, rxq) {
5216                                         snprintf(s, sizeof(s), "%x%c%x", p,
5217                                             'a' + v, q);
5218                                         rc = t4_alloc_irq(sc, irq, rid,
5219                                             t4_intr, rxq, s);
5220                                         if (rc != 0)
5221                                                 return (rc);
5222 #ifdef RSS
5223                                         bus_bind_intr(sc->dev, irq->res,
5224                                             rss_getcpu(q % nbuckets));
5225 #endif
5226                                         irq++;
5227                                         rid++;
5228                                         vi->nintr++;
5229                                 }
5230                         }
5231 #ifdef TCP_OFFLOAD
5232                         for_each_ofld_rxq(vi, q, ofld_rxq) {
5233                                 snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
5234                                 rc = t4_alloc_irq(sc, irq, rid, t4_intr,
5235                                     ofld_rxq, s);
5236                                 if (rc != 0)
5237                                         return (rc);
5238                                 irq++;
5239                                 rid++;
5240                                 vi->nintr++;
5241                         }
5242 #endif
5243                 }
5244         }
5245         MPASS(irq == &sc->irq[sc->intr_count]);
5246
5247         return (0);
5248 }
5249
5250 int
5251 adapter_full_init(struct adapter *sc)
5252 {
5253         int rc, i;
5254 #ifdef RSS
5255         uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
5256         uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
5257 #endif
5258
5259         ASSERT_SYNCHRONIZED_OP(sc);
5260         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
5261         KASSERT((sc->flags & FULL_INIT_DONE) == 0,
5262             ("%s: FULL_INIT_DONE already", __func__));
5263
5264         /*
5265          * queues that belong to the adapter (not any particular port).
5266          */
5267         rc = t4_setup_adapter_queues(sc);
5268         if (rc != 0)
5269                 goto done;
5270
5271         for (i = 0; i < nitems(sc->tq); i++) {
5272                 sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
5273                     taskqueue_thread_enqueue, &sc->tq[i]);
5274                 if (sc->tq[i] == NULL) {
5275                         device_printf(sc->dev,
5276                             "failed to allocate task queue %d\n", i);
5277                         rc = ENOMEM;
5278                         goto done;
5279                 }
5280                 taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
5281                     device_get_nameunit(sc->dev), i);
5282         }
5283 #ifdef RSS
5284         MPASS(RSS_KEYSIZE == 40);
5285         rss_getkey((void *)&raw_rss_key[0]);
5286         for (i = 0; i < nitems(rss_key); i++) {
5287                 rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
5288         }
5289         t4_write_rss_key(sc, &rss_key[0], -1, 1);
5290 #endif
5291
5292         if (!(sc->flags & IS_VF))
5293                 t4_intr_enable(sc);
5294         sc->flags |= FULL_INIT_DONE;
5295 done:
5296         if (rc != 0)
5297                 adapter_full_uninit(sc);
5298
5299         return (rc);
5300 }
5301
5302 int
5303 adapter_full_uninit(struct adapter *sc)
5304 {
5305         int i;
5306
5307         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
5308
5309         t4_teardown_adapter_queues(sc);
5310
5311         for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
5312                 taskqueue_free(sc->tq[i]);
5313                 sc->tq[i] = NULL;
5314         }
5315
5316         sc->flags &= ~FULL_INIT_DONE;
5317
5318         return (0);
5319 }
5320
5321 #ifdef RSS
5322 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
5323     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
5324     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
5325     RSS_HASHTYPE_RSS_UDP_IPV6)
5326
5327 /* Translates kernel hash types to hardware. */
5328 static int
5329 hashconfig_to_hashen(int hashconfig)
5330 {
5331         int hashen = 0;
5332
5333         if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
5334                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
5335         if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
5336                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
5337         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
5338                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
5339                     F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
5340         }
5341         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
5342                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
5343                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
5344         }
5345         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
5346                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
5347         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
5348                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
5349
5350         return (hashen);
5351 }
5352
5353 /* Translates hardware hash types to kernel. */
5354 static int
5355 hashen_to_hashconfig(int hashen)
5356 {
5357         int hashconfig = 0;
5358
5359         if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
5360                 /*
5361                  * If UDP hashing was enabled it must have been enabled for
5362                  * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
5363                  * enabling any 4-tuple hash is nonsense configuration.
5364                  */
5365                 MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
5366                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
5367
5368                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
5369                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
5370                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
5371                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
5372         }
5373         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
5374                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
5375         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
5376                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
5377         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
5378                 hashconfig |= RSS_HASHTYPE_RSS_IPV4;
5379         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
5380                 hashconfig |= RSS_HASHTYPE_RSS_IPV6;
5381
5382         return (hashconfig);
5383 }
5384 #endif
5385
5386 int
5387 vi_full_init(struct vi_info *vi)
5388 {
5389         struct adapter *sc = vi->pi->adapter;
5390         struct ifnet *ifp = vi->ifp;
5391         uint16_t *rss;
5392         struct sge_rxq *rxq;
5393         int rc, i, j, hashen;
5394 #ifdef RSS
5395         int nbuckets = rss_getnumbuckets();
5396         int hashconfig = rss_gethashconfig();
5397         int extra;
5398 #endif
5399
5400         ASSERT_SYNCHRONIZED_OP(sc);
5401         KASSERT((vi->flags & VI_INIT_DONE) == 0,
5402             ("%s: VI_INIT_DONE already", __func__));
5403
5404         sysctl_ctx_init(&vi->ctx);
5405         vi->flags |= VI_SYSCTL_CTX;
5406
5407         /*
5408          * Allocate tx/rx/fl queues for this VI.
5409          */
5410         rc = t4_setup_vi_queues(vi);
5411         if (rc != 0)
5412                 goto done;      /* error message displayed already */
5413
5414         /*
5415          * Setup RSS for this VI.  Save a copy of the RSS table for later use.
5416          */
5417         if (vi->nrxq > vi->rss_size) {
5418                 if_printf(ifp, "nrxq (%d) > hw RSS table size (%d); "
5419                     "some queues will never receive traffic.\n", vi->nrxq,
5420                     vi->rss_size);
5421         } else if (vi->rss_size % vi->nrxq) {
5422                 if_printf(ifp, "nrxq (%d), hw RSS table size (%d); "
5423                     "expect uneven traffic distribution.\n", vi->nrxq,
5424                     vi->rss_size);
5425         }
5426 #ifdef RSS
5427         if (vi->nrxq != nbuckets) {
5428                 if_printf(ifp, "nrxq (%d) != kernel RSS buckets (%d);"
5429                     "performance will be impacted.\n", vi->nrxq, nbuckets);
5430         }
5431 #endif
5432         rss = malloc(vi->rss_size * sizeof (*rss), M_CXGBE, M_ZERO | M_WAITOK);
5433         for (i = 0; i < vi->rss_size;) {
5434 #ifdef RSS
5435                 j = rss_get_indirection_to_bucket(i);
5436                 j %= vi->nrxq;
5437                 rxq = &sc->sge.rxq[vi->first_rxq + j];
5438                 rss[i++] = rxq->iq.abs_id;
5439 #else
5440                 for_each_rxq(vi, j, rxq) {
5441                         rss[i++] = rxq->iq.abs_id;
5442                         if (i == vi->rss_size)
5443                                 break;
5444                 }
5445 #endif
5446         }
5447
5448         rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size, rss,
5449             vi->rss_size);
5450         if (rc != 0) {
5451                 free(rss, M_CXGBE);
5452                 if_printf(ifp, "rss_config failed: %d\n", rc);
5453                 goto done;
5454         }
5455
5456 #ifdef RSS
5457         hashen = hashconfig_to_hashen(hashconfig);
5458
5459         /*
5460          * We may have had to enable some hashes even though the global config
5461          * wants them disabled.  This is a potential problem that must be
5462          * reported to the user.
5463          */
5464         extra = hashen_to_hashconfig(hashen) ^ hashconfig;
5465
5466         /*
5467          * If we consider only the supported hash types, then the enabled hashes
5468          * are a superset of the requested hashes.  In other words, there cannot
5469          * be any supported hash that was requested but not enabled, but there
5470          * can be hashes that were not requested but had to be enabled.
5471          */
5472         extra &= SUPPORTED_RSS_HASHTYPES;
5473         MPASS((extra & hashconfig) == 0);
5474
5475         if (extra) {
5476                 if_printf(ifp,
5477                     "global RSS config (0x%x) cannot be accommodated.\n",
5478                     hashconfig);
5479         }
5480         if (extra & RSS_HASHTYPE_RSS_IPV4)
5481                 if_printf(ifp, "IPv4 2-tuple hashing forced on.\n");
5482         if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
5483                 if_printf(ifp, "TCP/IPv4 4-tuple hashing forced on.\n");
5484         if (extra & RSS_HASHTYPE_RSS_IPV6)
5485                 if_printf(ifp, "IPv6 2-tuple hashing forced on.\n");
5486         if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
5487                 if_printf(ifp, "TCP/IPv6 4-tuple hashing forced on.\n");
5488         if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
5489                 if_printf(ifp, "UDP/IPv4 4-tuple hashing forced on.\n");
5490         if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
5491                 if_printf(ifp, "UDP/IPv6 4-tuple hashing forced on.\n");
5492 #else
5493         hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
5494             F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
5495             F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
5496             F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
5497 #endif
5498         rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, hashen, rss[0], 0, 0);
5499         if (rc != 0) {
5500                 free(rss, M_CXGBE);
5501                 if_printf(ifp, "rss hash/defaultq config failed: %d\n", rc);
5502                 goto done;
5503         }
5504
5505         vi->rss = rss;
5506         vi->flags |= VI_INIT_DONE;
5507 done:
5508         if (rc != 0)
5509                 vi_full_uninit(vi);
5510
5511         return (rc);
5512 }
5513
5514 /*
5515  * Idempotent.
5516  */
5517 int
5518 vi_full_uninit(struct vi_info *vi)
5519 {
5520         struct port_info *pi = vi->pi;
5521         struct adapter *sc = pi->adapter;
5522         int i;
5523         struct sge_rxq *rxq;
5524         struct sge_txq *txq;
5525 #ifdef TCP_OFFLOAD
5526         struct sge_ofld_rxq *ofld_rxq;
5527         struct sge_wrq *ofld_txq;
5528 #endif
5529
5530         if (vi->flags & VI_INIT_DONE) {
5531
5532                 /* Need to quiesce queues.  */
5533
5534                 /* XXX: Only for the first VI? */
5535                 if (IS_MAIN_VI(vi) && !(sc->flags & IS_VF))
5536                         quiesce_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
5537
5538                 for_each_txq(vi, i, txq) {
5539                         quiesce_txq(sc, txq);
5540                 }
5541
5542 #ifdef TCP_OFFLOAD
5543                 for_each_ofld_txq(vi, i, ofld_txq) {
5544                         quiesce_wrq(sc, ofld_txq);
5545                 }
5546 #endif
5547
5548                 for_each_rxq(vi, i, rxq) {
5549                         quiesce_iq(sc, &rxq->iq);
5550                         quiesce_fl(sc, &rxq->fl);
5551                 }
5552
5553 #ifdef TCP_OFFLOAD
5554                 for_each_ofld_rxq(vi, i, ofld_rxq) {
5555                         quiesce_iq(sc, &ofld_rxq->iq);
5556                         quiesce_fl(sc, &ofld_rxq->fl);
5557                 }
5558 #endif
5559                 free(vi->rss, M_CXGBE);
5560                 free(vi->nm_rss, M_CXGBE);
5561         }
5562
5563         t4_teardown_vi_queues(vi);
5564         vi->flags &= ~VI_INIT_DONE;
5565
5566         return (0);
5567 }
5568
5569 static void
5570 quiesce_txq(struct adapter *sc, struct sge_txq *txq)
5571 {
5572         struct sge_eq *eq = &txq->eq;
5573         struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
5574
5575         (void) sc;      /* unused */
5576
5577 #ifdef INVARIANTS
5578         TXQ_LOCK(txq);
5579         MPASS((eq->flags & EQ_ENABLED) == 0);
5580         TXQ_UNLOCK(txq);
5581 #endif
5582
5583         /* Wait for the mp_ring to empty. */
5584         while (!mp_ring_is_idle(txq->r)) {
5585                 mp_ring_check_drainage(txq->r, 0);
5586                 pause("rquiesce", 1);
5587         }
5588
5589         /* Then wait for the hardware to finish. */
5590         while (spg->cidx != htobe16(eq->pidx))
5591                 pause("equiesce", 1);
5592
5593         /* Finally, wait for the driver to reclaim all descriptors. */
5594         while (eq->cidx != eq->pidx)
5595                 pause("dquiesce", 1);
5596 }
5597
5598 static void
5599 quiesce_wrq(struct adapter *sc, struct sge_wrq *wrq)
5600 {
5601
5602         /* XXXTX */
5603 }
5604
5605 static void
5606 quiesce_iq(struct adapter *sc, struct sge_iq *iq)
5607 {
5608         (void) sc;      /* unused */
5609
5610         /* Synchronize with the interrupt handler */
5611         while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
5612                 pause("iqfree", 1);
5613 }
5614
5615 static void
5616 quiesce_fl(struct adapter *sc, struct sge_fl *fl)
5617 {
5618         mtx_lock(&sc->sfl_lock);
5619         FL_LOCK(fl);
5620         fl->flags |= FL_DOOMED;
5621         FL_UNLOCK(fl);
5622         callout_stop(&sc->sfl_callout);
5623         mtx_unlock(&sc->sfl_lock);
5624
5625         KASSERT((fl->flags & FL_STARVING) == 0,
5626             ("%s: still starving", __func__));
5627 }
5628
5629 static int
5630 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
5631     driver_intr_t *handler, void *arg, char *name)
5632 {
5633         int rc;
5634
5635         irq->rid = rid;
5636         irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
5637             RF_SHAREABLE | RF_ACTIVE);
5638         if (irq->res == NULL) {
5639                 device_printf(sc->dev,
5640                     "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
5641                 return (ENOMEM);
5642         }
5643
5644         rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
5645             NULL, handler, arg, &irq->tag);
5646         if (rc != 0) {
5647                 device_printf(sc->dev,
5648                     "failed to setup interrupt for rid %d, name %s: %d\n",
5649                     rid, name, rc);
5650         } else if (name)
5651                 bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
5652
5653         return (rc);
5654 }
5655
5656 static int
5657 t4_free_irq(struct adapter *sc, struct irq *irq)
5658 {
5659         if (irq->tag)
5660                 bus_teardown_intr(sc->dev, irq->res, irq->tag);
5661         if (irq->res)
5662                 bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
5663
5664         bzero(irq, sizeof(*irq));
5665
5666         return (0);
5667 }
5668
5669 static void
5670 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
5671 {
5672
5673         regs->version = chip_id(sc) | chip_rev(sc) << 10;
5674         t4_get_regs(sc, buf, regs->len);
5675 }
5676
5677 #define A_PL_INDIR_CMD  0x1f8
5678
5679 #define S_PL_AUTOINC    31
5680 #define M_PL_AUTOINC    0x1U
5681 #define V_PL_AUTOINC(x) ((x) << S_PL_AUTOINC)
5682 #define G_PL_AUTOINC(x) (((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
5683
5684 #define S_PL_VFID       20
5685 #define M_PL_VFID       0xffU
5686 #define V_PL_VFID(x)    ((x) << S_PL_VFID)
5687 #define G_PL_VFID(x)    (((x) >> S_PL_VFID) & M_PL_VFID)
5688
5689 #define S_PL_ADDR       0
5690 #define M_PL_ADDR       0xfffffU
5691 #define V_PL_ADDR(x)    ((x) << S_PL_ADDR)
5692 #define G_PL_ADDR(x)    (((x) >> S_PL_ADDR) & M_PL_ADDR)
5693
5694 #define A_PL_INDIR_DATA 0x1fc
5695
5696 static uint64_t
5697 read_vf_stat(struct adapter *sc, u_int vin, int reg)
5698 {
5699         u32 stats[2];
5700
5701         mtx_assert(&sc->reg_lock, MA_OWNED);
5702         if (sc->flags & IS_VF) {
5703                 stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
5704                 stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
5705         } else {
5706                 t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
5707                     V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
5708                 stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
5709                 stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
5710         }
5711         return (((uint64_t)stats[1]) << 32 | stats[0]);
5712 }
5713
5714 static void
5715 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
5716 {
5717
5718 #define GET_STAT(name) \
5719         read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
5720
5721         stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
5722         stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
5723         stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
5724         stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
5725         stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
5726         stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
5727         stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
5728         stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
5729         stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
5730         stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
5731         stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
5732         stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
5733         stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
5734         stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
5735         stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
5736         stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
5737
5738 #undef GET_STAT
5739 }
5740
5741 static void
5742 t4_clr_vi_stats(struct adapter *sc, u_int vin)
5743 {
5744         int reg;
5745
5746         t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
5747             V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
5748         for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
5749              reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
5750                 t4_write_reg(sc, A_PL_INDIR_DATA, 0);
5751 }
5752
5753 static void
5754 vi_refresh_stats(struct adapter *sc, struct vi_info *vi)
5755 {
5756         struct timeval tv;
5757         const struct timeval interval = {0, 250000};    /* 250ms */
5758
5759         if (!(vi->flags & VI_INIT_DONE))
5760                 return;
5761
5762         getmicrotime(&tv);
5763         timevalsub(&tv, &interval);
5764         if (timevalcmp(&tv, &vi->last_refreshed, <))
5765                 return;
5766
5767         mtx_lock(&sc->reg_lock);
5768         t4_get_vi_stats(sc, vi->vin, &vi->stats);
5769         getmicrotime(&vi->last_refreshed);
5770         mtx_unlock(&sc->reg_lock);
5771 }
5772
5773 static void
5774 cxgbe_refresh_stats(struct adapter *sc, struct port_info *pi)
5775 {
5776         u_int i, v, tnl_cong_drops, bg_map;
5777         struct timeval tv;
5778         const struct timeval interval = {0, 250000};    /* 250ms */
5779
5780         getmicrotime(&tv);
5781         timevalsub(&tv, &interval);
5782         if (timevalcmp(&tv, &pi->last_refreshed, <))
5783                 return;
5784
5785         tnl_cong_drops = 0;
5786         t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
5787         bg_map = pi->mps_bg_map;
5788         while (bg_map) {
5789                 i = ffs(bg_map) - 1;
5790                 mtx_lock(&sc->reg_lock);
5791                 t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
5792                     A_TP_MIB_TNL_CNG_DROP_0 + i);
5793                 mtx_unlock(&sc->reg_lock);
5794                 tnl_cong_drops += v;
5795                 bg_map &= ~(1 << i);
5796         }
5797         pi->tnl_cong_drops = tnl_cong_drops;
5798         getmicrotime(&pi->last_refreshed);
5799 }
5800
5801 static void
5802 cxgbe_tick(void *arg)
5803 {
5804         struct port_info *pi = arg;
5805         struct adapter *sc = pi->adapter;
5806
5807         PORT_LOCK_ASSERT_OWNED(pi);
5808         cxgbe_refresh_stats(sc, pi);
5809
5810         callout_schedule(&pi->tick, hz);
5811 }
5812
5813 void
5814 vi_tick(void *arg)
5815 {
5816         struct vi_info *vi = arg;
5817         struct adapter *sc = vi->pi->adapter;
5818
5819         vi_refresh_stats(sc, vi);
5820
5821         callout_schedule(&vi->tick, hz);
5822 }
5823
5824 /*
5825  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
5826  */
5827 static char *caps_decoder[] = {
5828         "\20\001IPMI\002NCSI",                          /* 0: NBM */
5829         "\20\001PPP\002QFC\003DCBX",                    /* 1: link */
5830         "\20\001INGRESS\002EGRESS",                     /* 2: switch */
5831         "\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"      /* 3: NIC */
5832             "\006HASHFILTER\007ETHOFLD",
5833         "\20\001TOE",                                   /* 4: TOE */
5834         "\20\001RDDP\002RDMAC",                         /* 5: RDMA */
5835         "\20\001INITIATOR_PDU\002TARGET_PDU"            /* 6: iSCSI */
5836             "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
5837             "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
5838             "\007T10DIF"
5839             "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
5840         "\20\001LOOKASIDE\002TLSKEYS",                  /* 7: Crypto */
5841         "\20\001INITIATOR\002TARGET\003CTRL_OFLD"       /* 8: FCoE */
5842                     "\004PO_INITIATOR\005PO_TARGET",
5843 };
5844
5845 void
5846 t4_sysctls(struct adapter *sc)
5847 {
5848         struct sysctl_ctx_list *ctx;
5849         struct sysctl_oid *oid;
5850         struct sysctl_oid_list *children, *c0;
5851         static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
5852
5853         ctx = device_get_sysctl_ctx(sc->dev);
5854
5855         /*
5856          * dev.t4nex.X.
5857          */
5858         oid = device_get_sysctl_tree(sc->dev);
5859         c0 = children = SYSCTL_CHILDREN(oid);
5860
5861         sc->sc_do_rxcopy = 1;
5862         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
5863             &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
5864
5865         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
5866             sc->params.nports, "# of ports");
5867
5868         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
5869             CTLTYPE_STRING | CTLFLAG_RD, doorbells, (uintptr_t)&sc->doorbells,
5870             sysctl_bitfield_8b, "A", "available doorbells");
5871
5872         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
5873             sc->params.vpd.cclk, "core clock frequency (in KHz)");
5874
5875         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
5876             CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.timer_val,
5877             sizeof(sc->params.sge.timer_val), sysctl_int_array, "A",
5878             "interrupt holdoff timer values (us)");
5879
5880         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
5881             CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.counter_val,
5882             sizeof(sc->params.sge.counter_val), sysctl_int_array, "A",
5883             "interrupt holdoff packet counter values");
5884
5885         t4_sge_sysctls(sc, ctx, children);
5886
5887         sc->lro_timeout = 100;
5888         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
5889             &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
5890
5891         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
5892             &sc->debug_flags, 0, "flags to enable runtime debugging");
5893
5894         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
5895             CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
5896
5897         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
5898             CTLFLAG_RD, sc->fw_version, 0, "firmware version");
5899
5900         if (sc->flags & IS_VF)
5901                 return;
5902
5903         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
5904             NULL, chip_rev(sc), "chip hardware revision");
5905
5906         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
5907             CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
5908
5909         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
5910             CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
5911
5912         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
5913             CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
5914
5915         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
5916             CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
5917
5918         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
5919             CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
5920
5921         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
5922             sc->er_version, 0, "expansion ROM version");
5923
5924         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
5925             sc->bs_version, 0, "bootstrap firmware version");
5926
5927         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
5928             NULL, sc->params.scfg_vers, "serial config version");
5929
5930         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
5931             NULL, sc->params.vpd_vers, "VPD version");
5932
5933         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
5934             CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
5935
5936         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
5937             sc->cfcsum, "config file checksum");
5938
5939 #define SYSCTL_CAP(name, n, text) \
5940         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
5941             CTLTYPE_STRING | CTLFLAG_RD, caps_decoder[n], (uintptr_t)&sc->name, \
5942             sysctl_bitfield_16b, "A", "available " text " capabilities")
5943
5944         SYSCTL_CAP(nbmcaps, 0, "NBM");
5945         SYSCTL_CAP(linkcaps, 1, "link");
5946         SYSCTL_CAP(switchcaps, 2, "switch");
5947         SYSCTL_CAP(niccaps, 3, "NIC");
5948         SYSCTL_CAP(toecaps, 4, "TCP offload");
5949         SYSCTL_CAP(rdmacaps, 5, "RDMA");
5950         SYSCTL_CAP(iscsicaps, 6, "iSCSI");
5951         SYSCTL_CAP(cryptocaps, 7, "crypto");
5952         SYSCTL_CAP(fcoecaps, 8, "FCoE");
5953 #undef SYSCTL_CAP
5954
5955         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
5956             NULL, sc->tids.nftids, "number of filters");
5957
5958         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature", CTLTYPE_INT |
5959             CTLFLAG_RD, sc, 0, sysctl_temperature, "I",
5960             "chip temperature (in Celsius)");
5961
5962         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg", CTLTYPE_STRING |
5963             CTLFLAG_RD, sc, 0, sysctl_loadavg, "A",
5964             "microprocessor load averages (debug firmwares only)");
5965
5966         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_vdd", CTLFLAG_RD,
5967             &sc->params.core_vdd, 0, "core Vdd (in mV)");
5968
5969         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
5970             CTLTYPE_STRING | CTLFLAG_RD, sc, LOCAL_CPUS,
5971             sysctl_cpus, "A", "local CPUs");
5972
5973         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
5974             CTLTYPE_STRING | CTLFLAG_RD, sc, INTR_CPUS,
5975             sysctl_cpus, "A", "preferred CPUs for interrupts");
5976
5977         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
5978             &sc->swintr, 0, "software triggered interrupts");
5979
5980         /*
5981          * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
5982          */
5983         oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
5984             CTLFLAG_RD | CTLFLAG_SKIP, NULL,
5985             "logs and miscellaneous information");
5986         children = SYSCTL_CHILDREN(oid);
5987
5988         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
5989             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5990             sysctl_cctrl, "A", "congestion control");
5991
5992         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
5993             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5994             sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
5995
5996         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
5997             CTLTYPE_STRING | CTLFLAG_RD, sc, 1,
5998             sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
5999
6000         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
6001             CTLTYPE_STRING | CTLFLAG_RD, sc, 2,
6002             sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
6003
6004         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
6005             CTLTYPE_STRING | CTLFLAG_RD, sc, 3,
6006             sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
6007
6008         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
6009             CTLTYPE_STRING | CTLFLAG_RD, sc, 4,
6010             sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
6011
6012         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
6013             CTLTYPE_STRING | CTLFLAG_RD, sc, 5,
6014             sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
6015
6016         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
6017             CTLTYPE_STRING | CTLFLAG_RD, sc, 0, sysctl_cim_la,
6018             "A", "CIM logic analyzer");
6019
6020         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
6021             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6022             sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
6023
6024         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
6025             CTLTYPE_STRING | CTLFLAG_RD, sc, 0 + CIM_NUM_IBQ,
6026             sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
6027
6028         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
6029             CTLTYPE_STRING | CTLFLAG_RD, sc, 1 + CIM_NUM_IBQ,
6030             sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
6031
6032         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
6033             CTLTYPE_STRING | CTLFLAG_RD, sc, 2 + CIM_NUM_IBQ,
6034             sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
6035
6036         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
6037             CTLTYPE_STRING | CTLFLAG_RD, sc, 3 + CIM_NUM_IBQ,
6038             sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
6039
6040         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
6041             CTLTYPE_STRING | CTLFLAG_RD, sc, 4 + CIM_NUM_IBQ,
6042             sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
6043
6044         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
6045             CTLTYPE_STRING | CTLFLAG_RD, sc, 5 + CIM_NUM_IBQ,
6046             sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
6047
6048         if (chip_id(sc) > CHELSIO_T4) {
6049                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
6050                     CTLTYPE_STRING | CTLFLAG_RD, sc, 6 + CIM_NUM_IBQ,
6051                     sysctl_cim_ibq_obq, "A", "CIM OBQ 6 (SGE0-RX)");
6052
6053                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
6054                     CTLTYPE_STRING | CTLFLAG_RD, sc, 7 + CIM_NUM_IBQ,
6055                     sysctl_cim_ibq_obq, "A", "CIM OBQ 7 (SGE1-RX)");
6056         }
6057
6058         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
6059             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6060             sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
6061
6062         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
6063             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6064             sysctl_cim_qcfg, "A", "CIM queue configuration");
6065
6066         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
6067             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6068             sysctl_cpl_stats, "A", "CPL statistics");
6069
6070         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
6071             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6072             sysctl_ddp_stats, "A", "non-TCP DDP statistics");
6073
6074         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
6075             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6076             sysctl_devlog, "A", "firmware's device log");
6077
6078         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
6079             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6080             sysctl_fcoe_stats, "A", "FCoE statistics");
6081
6082         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
6083             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6084             sysctl_hw_sched, "A", "hardware scheduler ");
6085
6086         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
6087             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6088             sysctl_l2t, "A", "hardware L2 table");
6089
6090         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
6091             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6092             sysctl_smt, "A", "hardware source MAC table");
6093
6094 #ifdef INET6
6095         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
6096             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6097             sysctl_clip, "A", "active CLIP table entries");
6098 #endif
6099
6100         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
6101             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6102             sysctl_lb_stats, "A", "loopback statistics");
6103
6104         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
6105             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6106             sysctl_meminfo, "A", "memory regions");
6107
6108         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
6109             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6110             chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
6111             "A", "MPS TCAM entries");
6112
6113         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
6114             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6115             sysctl_path_mtus, "A", "path MTUs");
6116
6117         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
6118             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6119             sysctl_pm_stats, "A", "PM statistics");
6120
6121         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
6122             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6123             sysctl_rdma_stats, "A", "RDMA statistics");
6124
6125         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
6126             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6127             sysctl_tcp_stats, "A", "TCP statistics");
6128
6129         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
6130             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6131             sysctl_tids, "A", "TID information");
6132
6133         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
6134             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6135             sysctl_tp_err_stats, "A", "TP error statistics");
6136
6137         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
6138             CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tp_la_mask, "I",
6139             "TP logic analyzer event capture mask");
6140
6141         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
6142             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6143             sysctl_tp_la, "A", "TP logic analyzer");
6144
6145         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
6146             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6147             sysctl_tx_rate, "A", "Tx rate");
6148
6149         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
6150             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6151             sysctl_ulprx_la, "A", "ULPRX logic analyzer");
6152
6153         if (chip_id(sc) >= CHELSIO_T5) {
6154                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
6155                     CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
6156                     sysctl_wcwr_stats, "A", "write combined work requests");
6157         }
6158
6159 #ifdef TCP_OFFLOAD
6160         if (is_offload(sc)) {
6161                 int i;
6162                 char s[4];
6163
6164                 /*
6165                  * dev.t4nex.X.toe.
6166                  */
6167                 oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe", CTLFLAG_RD,
6168                     NULL, "TOE parameters");
6169                 children = SYSCTL_CHILDREN(oid);
6170
6171                 sc->tt.cong_algorithm = -1;
6172                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
6173                     CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
6174                     "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
6175                     "3 = highspeed)");
6176
6177                 sc->tt.sndbuf = 256 * 1024;
6178                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
6179                     &sc->tt.sndbuf, 0, "max hardware send buffer size");
6180
6181                 sc->tt.ddp = 0;
6182                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp", CTLFLAG_RW,
6183                     &sc->tt.ddp, 0, "DDP allowed");
6184
6185                 sc->tt.rx_coalesce = 1;
6186                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
6187                     CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
6188
6189                 sc->tt.tls = 0;
6190                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tls", CTLFLAG_RW,
6191                     &sc->tt.tls, 0, "Inline TLS allowed");
6192
6193                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls_rx_ports",
6194                     CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tls_rx_ports,
6195                     "I", "TCP ports that use inline TLS+TOE RX");
6196
6197                 sc->tt.tx_align = 1;
6198                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
6199                     CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
6200
6201                 sc->tt.tx_zcopy = 0;
6202                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
6203                     CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
6204                     "Enable zero-copy aio_write(2)");
6205
6206                 sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
6207                 SYSCTL_ADD_INT(ctx, children, OID_AUTO,
6208                     "cop_managed_offloading", CTLFLAG_RW,
6209                     &sc->tt.cop_managed_offloading, 0,
6210                     "COP (Connection Offload Policy) controls all TOE offload");
6211
6212                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
6213                     CTLTYPE_STRING | CTLFLAG_RD, sc, 0, sysctl_tp_tick, "A",
6214                     "TP timer tick (us)");
6215
6216                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
6217                     CTLTYPE_STRING | CTLFLAG_RD, sc, 1, sysctl_tp_tick, "A",
6218                     "TCP timestamp tick (us)");
6219
6220                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
6221                     CTLTYPE_STRING | CTLFLAG_RD, sc, 2, sysctl_tp_tick, "A",
6222                     "DACK tick (us)");
6223
6224                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
6225                     CTLTYPE_UINT | CTLFLAG_RD, sc, 0, sysctl_tp_dack_timer,
6226                     "IU", "DACK timer (us)");
6227
6228                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
6229                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MIN,
6230                     sysctl_tp_timer, "LU", "Minimum retransmit interval (us)");
6231
6232                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
6233                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MAX,
6234                     sysctl_tp_timer, "LU", "Maximum retransmit interval (us)");
6235
6236                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
6237                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MIN,
6238                     sysctl_tp_timer, "LU", "Persist timer min (us)");
6239
6240                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
6241                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MAX,
6242                     sysctl_tp_timer, "LU", "Persist timer max (us)");
6243
6244                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
6245                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_IDLE,
6246                     sysctl_tp_timer, "LU", "Keepalive idle timer (us)");
6247
6248                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
6249                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_INTVL,
6250                     sysctl_tp_timer, "LU", "Keepalive interval timer (us)");
6251
6252                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
6253                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_INIT_SRTT,
6254                     sysctl_tp_timer, "LU", "Initial SRTT (us)");
6255
6256                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
6257                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_FINWAIT2_TIMER,
6258                     sysctl_tp_timer, "LU", "FINWAIT2 timer (us)");
6259
6260                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
6261                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_SYNSHIFTMAX,
6262                     sysctl_tp_shift_cnt, "IU",
6263                     "Number of SYN retransmissions before abort");
6264
6265                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
6266                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_RXTSHIFTMAXR2,
6267                     sysctl_tp_shift_cnt, "IU",
6268                     "Number of retransmissions before abort");
6269
6270                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
6271                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_KEEPALIVEMAXR2,
6272                     sysctl_tp_shift_cnt, "IU",
6273                     "Number of keepalive probes before abort");
6274
6275                 oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
6276                     CTLFLAG_RD, NULL, "TOE retransmit backoffs");
6277                 children = SYSCTL_CHILDREN(oid);
6278                 for (i = 0; i < 16; i++) {
6279                         snprintf(s, sizeof(s), "%u", i);
6280                         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
6281                             CTLTYPE_UINT | CTLFLAG_RD, sc, i, sysctl_tp_backoff,
6282                             "IU", "TOE retransmit backoff");
6283                 }
6284         }
6285 #endif
6286 }
6287
6288 void
6289 vi_sysctls(struct vi_info *vi)
6290 {
6291         struct sysctl_ctx_list *ctx;
6292         struct sysctl_oid *oid;
6293         struct sysctl_oid_list *children;
6294
6295         ctx = device_get_sysctl_ctx(vi->dev);
6296
6297         /*
6298          * dev.v?(cxgbe|cxl).X.
6299          */
6300         oid = device_get_sysctl_tree(vi->dev);
6301         children = SYSCTL_CHILDREN(oid);
6302
6303         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
6304             vi->viid, "VI identifer");
6305         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
6306             &vi->nrxq, 0, "# of rx queues");
6307         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
6308             &vi->ntxq, 0, "# of tx queues");
6309         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
6310             &vi->first_rxq, 0, "index of first rx queue");
6311         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
6312             &vi->first_txq, 0, "index of first tx queue");
6313         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
6314             vi->rss_base, "start of RSS indirection table");
6315         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
6316             vi->rss_size, "size of RSS indirection table");
6317
6318         if (IS_MAIN_VI(vi)) {
6319                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
6320                     CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_noflowq, "IU",
6321                     "Reserve queue 0 for non-flowid packets");
6322         }
6323
6324 #ifdef TCP_OFFLOAD
6325         if (vi->nofldrxq != 0) {
6326                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
6327                     &vi->nofldrxq, 0,
6328                     "# of rx queues for offloaded TCP connections");
6329                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
6330                     &vi->nofldtxq, 0,
6331                     "# of tx queues for offloaded TCP connections");
6332                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
6333                     CTLFLAG_RD, &vi->first_ofld_rxq, 0,
6334                     "index of first TOE rx queue");
6335                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
6336                     CTLFLAG_RD, &vi->first_ofld_txq, 0,
6337                     "index of first TOE tx queue");
6338                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
6339                     CTLTYPE_INT | CTLFLAG_RW, vi, 0,
6340                     sysctl_holdoff_tmr_idx_ofld, "I",
6341                     "holdoff timer index for TOE queues");
6342                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
6343                     CTLTYPE_INT | CTLFLAG_RW, vi, 0,
6344                     sysctl_holdoff_pktc_idx_ofld, "I",
6345                     "holdoff packet counter index for TOE queues");
6346         }
6347 #endif
6348 #ifdef DEV_NETMAP
6349         if (vi->nnmrxq != 0) {
6350                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
6351                     &vi->nnmrxq, 0, "# of netmap rx queues");
6352                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
6353                     &vi->nnmtxq, 0, "# of netmap tx queues");
6354                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
6355                     CTLFLAG_RD, &vi->first_nm_rxq, 0,
6356                     "index of first netmap rx queue");
6357                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
6358                     CTLFLAG_RD, &vi->first_nm_txq, 0,
6359                     "index of first netmap tx queue");
6360         }
6361 #endif
6362
6363         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
6364             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_tmr_idx, "I",
6365             "holdoff timer index");
6366         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
6367             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_pktc_idx, "I",
6368             "holdoff packet counter index");
6369
6370         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
6371             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_rxq, "I",
6372             "rx queue size");
6373         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
6374             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_txq, "I",
6375             "tx queue size");
6376 }
6377
6378 static void
6379 cxgbe_sysctls(struct port_info *pi)
6380 {
6381         struct sysctl_ctx_list *ctx;
6382         struct sysctl_oid *oid;
6383         struct sysctl_oid_list *children, *children2;
6384         struct adapter *sc = pi->adapter;
6385         int i;
6386         char name[16];
6387         static char *tc_flags = {"\20\1USER\2SYNC\3ASYNC\4ERR"};
6388
6389         ctx = device_get_sysctl_ctx(pi->dev);
6390
6391         /*
6392          * dev.cxgbe.X.
6393          */
6394         oid = device_get_sysctl_tree(pi->dev);
6395         children = SYSCTL_CHILDREN(oid);
6396
6397         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc", CTLTYPE_STRING |
6398            CTLFLAG_RD, pi, 0, sysctl_linkdnrc, "A", "reason why link is down");
6399         if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
6400                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
6401                     CTLTYPE_INT | CTLFLAG_RD, pi, 0, sysctl_btphy, "I",
6402                     "PHY temperature (in Celsius)");
6403                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
6404                     CTLTYPE_INT | CTLFLAG_RD, pi, 1, sysctl_btphy, "I",
6405                     "PHY firmware version");
6406         }
6407
6408         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
6409             CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_pause_settings, "A",
6410     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
6411         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
6412             CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_fec, "A",
6413             "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
6414         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
6415             CTLTYPE_INT | CTLFLAG_RW, pi, 0, sysctl_autoneg, "I",
6416             "autonegotiation (-1 = not supported)");
6417
6418         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
6419             port_top_speed(pi), "max speed (in Gbps)");
6420         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
6421             pi->mps_bg_map, "MPS buffer group map");
6422         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
6423             NULL, pi->rx_e_chan_map, "TP rx e-channel map");
6424
6425         if (sc->flags & IS_VF)
6426                 return;
6427
6428         /*
6429          * dev.(cxgbe|cxl).X.tc.
6430          */
6431         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc", CTLFLAG_RD, NULL,
6432             "Tx scheduler traffic classes (cl_rl)");
6433         children2 = SYSCTL_CHILDREN(oid);
6434         SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
6435             CTLFLAG_RW, &pi->sched_params->pktsize, 0,
6436             "pktsize for per-flow cl-rl (0 means up to the driver )");
6437         SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
6438             CTLFLAG_RW, &pi->sched_params->burstsize, 0,
6439             "burstsize for per-flow cl-rl (0 means up to the driver)");
6440         for (i = 0; i < sc->chip_params->nsched_cls; i++) {
6441                 struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
6442
6443                 snprintf(name, sizeof(name), "%d", i);
6444                 children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
6445                     SYSCTL_CHILDREN(oid), OID_AUTO, name, CTLFLAG_RD, NULL,
6446                     "traffic class"));
6447                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
6448                     CTLTYPE_STRING | CTLFLAG_RD, tc_flags, (uintptr_t)&tc->flags,
6449                     sysctl_bitfield_8b, "A", "flags");
6450                 SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
6451                     CTLFLAG_RD, &tc->refcount, 0, "references to this class");
6452                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
6453                     CTLTYPE_STRING | CTLFLAG_RD, sc, (pi->port_id << 16) | i,
6454                     sysctl_tc_params, "A", "traffic class parameters");
6455         }
6456
6457         /*
6458          * dev.cxgbe.X.stats.
6459          */
6460         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats", CTLFLAG_RD,
6461             NULL, "port statistics");
6462         children = SYSCTL_CHILDREN(oid);
6463         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
6464             &pi->tx_parse_error, 0,
6465             "# of tx packets with invalid length or # of segments");
6466
6467 #define SYSCTL_ADD_T4_REG64(pi, name, desc, reg) \
6468         SYSCTL_ADD_OID(ctx, children, OID_AUTO, name, \
6469             CTLTYPE_U64 | CTLFLAG_RD, sc, reg, \
6470             sysctl_handle_t4_reg64, "QU", desc)
6471
6472         SYSCTL_ADD_T4_REG64(pi, "tx_octets", "# of octets in good frames",
6473             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BYTES_L));
6474         SYSCTL_ADD_T4_REG64(pi, "tx_frames", "total # of good frames",
6475             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_FRAMES_L));
6476         SYSCTL_ADD_T4_REG64(pi, "tx_bcast_frames", "# of broadcast frames",
6477             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BCAST_L));
6478         SYSCTL_ADD_T4_REG64(pi, "tx_mcast_frames", "# of multicast frames",
6479             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_MCAST_L));
6480         SYSCTL_ADD_T4_REG64(pi, "tx_ucast_frames", "# of unicast frames",
6481             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_UCAST_L));
6482         SYSCTL_ADD_T4_REG64(pi, "tx_error_frames", "# of error frames",
6483             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_ERROR_L));
6484         SYSCTL_ADD_T4_REG64(pi, "tx_frames_64",
6485             "# of tx frames in this range",
6486             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_64B_L));
6487         SYSCTL_ADD_T4_REG64(pi, "tx_frames_65_127",
6488             "# of tx frames in this range",
6489             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_65B_127B_L));
6490         SYSCTL_ADD_T4_REG64(pi, "tx_frames_128_255",
6491             "# of tx frames in this range",
6492             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_128B_255B_L));
6493         SYSCTL_ADD_T4_REG64(pi, "tx_frames_256_511",
6494             "# of tx frames in this range",
6495             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_256B_511B_L));
6496         SYSCTL_ADD_T4_REG64(pi, "tx_frames_512_1023",
6497             "# of tx frames in this range",
6498             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_512B_1023B_L));
6499         SYSCTL_ADD_T4_REG64(pi, "tx_frames_1024_1518",
6500             "# of tx frames in this range",
6501             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1024B_1518B_L));
6502         SYSCTL_ADD_T4_REG64(pi, "tx_frames_1519_max",
6503             "# of tx frames in this range",
6504             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1519B_MAX_L));
6505         SYSCTL_ADD_T4_REG64(pi, "tx_drop", "# of dropped tx frames",
6506             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_DROP_L));
6507         SYSCTL_ADD_T4_REG64(pi, "tx_pause", "# of pause frames transmitted",
6508             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PAUSE_L));
6509         SYSCTL_ADD_T4_REG64(pi, "tx_ppp0", "# of PPP prio 0 frames transmitted",
6510             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP0_L));
6511         SYSCTL_ADD_T4_REG64(pi, "tx_ppp1", "# of PPP prio 1 frames transmitted",
6512             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP1_L));
6513         SYSCTL_ADD_T4_REG64(pi, "tx_ppp2", "# of PPP prio 2 frames transmitted",
6514             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP2_L));
6515         SYSCTL_ADD_T4_REG64(pi, "tx_ppp3", "# of PPP prio 3 frames transmitted",
6516             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP3_L));
6517         SYSCTL_ADD_T4_REG64(pi, "tx_ppp4", "# of PPP prio 4 frames transmitted",
6518             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP4_L));
6519         SYSCTL_ADD_T4_REG64(pi, "tx_ppp5", "# of PPP prio 5 frames transmitted",
6520             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP5_L));
6521         SYSCTL_ADD_T4_REG64(pi, "tx_ppp6", "# of PPP prio 6 frames transmitted",
6522             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP6_L));
6523         SYSCTL_ADD_T4_REG64(pi, "tx_ppp7", "# of PPP prio 7 frames transmitted",
6524             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP7_L));
6525
6526         SYSCTL_ADD_T4_REG64(pi, "rx_octets", "# of octets in good frames",
6527             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BYTES_L));
6528         SYSCTL_ADD_T4_REG64(pi, "rx_frames", "total # of good frames",
6529             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_FRAMES_L));
6530         SYSCTL_ADD_T4_REG64(pi, "rx_bcast_frames", "# of broadcast frames",
6531             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BCAST_L));
6532         SYSCTL_ADD_T4_REG64(pi, "rx_mcast_frames", "# of multicast frames",
6533             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MCAST_L));
6534         SYSCTL_ADD_T4_REG64(pi, "rx_ucast_frames", "# of unicast frames",
6535             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_UCAST_L));
6536         SYSCTL_ADD_T4_REG64(pi, "rx_too_long", "# of frames exceeding MTU",
6537             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_ERROR_L));
6538         SYSCTL_ADD_T4_REG64(pi, "rx_jabber", "# of jabber frames",
6539             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_CRC_ERROR_L));
6540         SYSCTL_ADD_T4_REG64(pi, "rx_fcs_err",
6541             "# of frames received with bad FCS",
6542             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L));
6543         SYSCTL_ADD_T4_REG64(pi, "rx_len_err",
6544             "# of frames received with length error",
6545             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LEN_ERROR_L));
6546         SYSCTL_ADD_T4_REG64(pi, "rx_symbol_err", "symbol errors",
6547             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_SYM_ERROR_L));
6548         SYSCTL_ADD_T4_REG64(pi, "rx_runt", "# of short frames received",
6549             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LESS_64B_L));
6550         SYSCTL_ADD_T4_REG64(pi, "rx_frames_64",
6551             "# of rx frames in this range",
6552             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_64B_L));
6553         SYSCTL_ADD_T4_REG64(pi, "rx_frames_65_127",
6554             "# of rx frames in this range",
6555             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_65B_127B_L));
6556         SYSCTL_ADD_T4_REG64(pi, "rx_frames_128_255",
6557             "# of rx frames in this range",
6558             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_128B_255B_L));
6559         SYSCTL_ADD_T4_REG64(pi, "rx_frames_256_511",
6560             "# of rx frames in this range",
6561             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_256B_511B_L));
6562         SYSCTL_ADD_T4_REG64(pi, "rx_frames_512_1023",
6563             "# of rx frames in this range",
6564             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_512B_1023B_L));
6565         SYSCTL_ADD_T4_REG64(pi, "rx_frames_1024_1518",
6566             "# of rx frames in this range",
6567             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1024B_1518B_L));
6568         SYSCTL_ADD_T4_REG64(pi, "rx_frames_1519_max",
6569             "# of rx frames in this range",
6570             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1519B_MAX_L));
6571         SYSCTL_ADD_T4_REG64(pi, "rx_pause", "# of pause frames received",
6572             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PAUSE_L));
6573         SYSCTL_ADD_T4_REG64(pi, "rx_ppp0", "# of PPP prio 0 frames received",
6574             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP0_L));
6575         SYSCTL_ADD_T4_REG64(pi, "rx_ppp1", "# of PPP prio 1 frames received",
6576             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP1_L));
6577         SYSCTL_ADD_T4_REG64(pi, "rx_ppp2", "# of PPP prio 2 frames received",
6578             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP2_L));
6579         SYSCTL_ADD_T4_REG64(pi, "rx_ppp3", "# of PPP prio 3 frames received",
6580             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP3_L));
6581         SYSCTL_ADD_T4_REG64(pi, "rx_ppp4", "# of PPP prio 4 frames received",
6582             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP4_L));
6583         SYSCTL_ADD_T4_REG64(pi, "rx_ppp5", "# of PPP prio 5 frames received",
6584             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP5_L));
6585         SYSCTL_ADD_T4_REG64(pi, "rx_ppp6", "# of PPP prio 6 frames received",
6586             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP6_L));
6587         SYSCTL_ADD_T4_REG64(pi, "rx_ppp7", "# of PPP prio 7 frames received",
6588             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP7_L));
6589
6590 #undef SYSCTL_ADD_T4_REG64
6591
6592 #define SYSCTL_ADD_T4_PORTSTAT(name, desc) \
6593         SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
6594             &pi->stats.name, desc)
6595
6596         /* We get these from port_stats and they may be stale by up to 1s */
6597         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow0,
6598             "# drops due to buffer-group 0 overflows");
6599         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow1,
6600             "# drops due to buffer-group 1 overflows");
6601         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow2,
6602             "# drops due to buffer-group 2 overflows");
6603         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow3,
6604             "# drops due to buffer-group 3 overflows");
6605         SYSCTL_ADD_T4_PORTSTAT(rx_trunc0,
6606             "# of buffer-group 0 truncated packets");
6607         SYSCTL_ADD_T4_PORTSTAT(rx_trunc1,
6608             "# of buffer-group 1 truncated packets");
6609         SYSCTL_ADD_T4_PORTSTAT(rx_trunc2,
6610             "# of buffer-group 2 truncated packets");
6611         SYSCTL_ADD_T4_PORTSTAT(rx_trunc3,
6612             "# of buffer-group 3 truncated packets");
6613
6614 #undef SYSCTL_ADD_T4_PORTSTAT
6615
6616         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "tx_tls_records",
6617             CTLFLAG_RD, &pi->tx_tls_records,
6618             "# of TLS records transmitted");
6619         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "tx_tls_octets",
6620             CTLFLAG_RD, &pi->tx_tls_octets,
6621             "# of payload octets in transmitted TLS records");
6622         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "rx_tls_records",
6623             CTLFLAG_RD, &pi->rx_tls_records,
6624             "# of TLS records received");
6625         SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "rx_tls_octets",
6626             CTLFLAG_RD, &pi->rx_tls_octets,
6627             "# of payload octets in received TLS records");
6628 }
6629
6630 static int
6631 sysctl_int_array(SYSCTL_HANDLER_ARGS)
6632 {
6633         int rc, *i, space = 0;
6634         struct sbuf sb;
6635
6636         sbuf_new_for_sysctl(&sb, NULL, 64, req);
6637         for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
6638                 if (space)
6639                         sbuf_printf(&sb, " ");
6640                 sbuf_printf(&sb, "%d", *i);
6641                 space = 1;
6642         }
6643         rc = sbuf_finish(&sb);
6644         sbuf_delete(&sb);
6645         return (rc);
6646 }
6647
6648 static int
6649 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
6650 {
6651         int rc;
6652         struct sbuf *sb;
6653
6654         rc = sysctl_wire_old_buffer(req, 0);
6655         if (rc != 0)
6656                 return(rc);
6657
6658         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6659         if (sb == NULL)
6660                 return (ENOMEM);
6661
6662         sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
6663         rc = sbuf_finish(sb);
6664         sbuf_delete(sb);
6665
6666         return (rc);
6667 }
6668
6669 static int
6670 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
6671 {
6672         int rc;
6673         struct sbuf *sb;
6674
6675         rc = sysctl_wire_old_buffer(req, 0);
6676         if (rc != 0)
6677                 return(rc);
6678
6679         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6680         if (sb == NULL)
6681                 return (ENOMEM);
6682
6683         sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
6684         rc = sbuf_finish(sb);
6685         sbuf_delete(sb);
6686
6687         return (rc);
6688 }
6689
6690 static int
6691 sysctl_btphy(SYSCTL_HANDLER_ARGS)
6692 {
6693         struct port_info *pi = arg1;
6694         int op = arg2;
6695         struct adapter *sc = pi->adapter;
6696         u_int v;
6697         int rc;
6698
6699         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
6700         if (rc)
6701                 return (rc);
6702         /* XXX: magic numbers */
6703         rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e, op ? 0x20 : 0xc820,
6704             &v);
6705         end_synchronized_op(sc, 0);
6706         if (rc)
6707                 return (rc);
6708         if (op == 0)
6709                 v /= 256;
6710
6711         rc = sysctl_handle_int(oidp, &v, 0, req);
6712         return (rc);
6713 }
6714
6715 static int
6716 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
6717 {
6718         struct vi_info *vi = arg1;
6719         int rc, val;
6720
6721         val = vi->rsrv_noflowq;
6722         rc = sysctl_handle_int(oidp, &val, 0, req);
6723         if (rc != 0 || req->newptr == NULL)
6724                 return (rc);
6725
6726         if ((val >= 1) && (vi->ntxq > 1))
6727                 vi->rsrv_noflowq = 1;
6728         else
6729                 vi->rsrv_noflowq = 0;
6730
6731         return (rc);
6732 }
6733
6734 static int
6735 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
6736 {
6737         struct vi_info *vi = arg1;
6738         struct adapter *sc = vi->pi->adapter;
6739         int idx, rc, i;
6740         struct sge_rxq *rxq;
6741         uint8_t v;
6742
6743         idx = vi->tmr_idx;
6744
6745         rc = sysctl_handle_int(oidp, &idx, 0, req);
6746         if (rc != 0 || req->newptr == NULL)
6747                 return (rc);
6748
6749         if (idx < 0 || idx >= SGE_NTIMERS)
6750                 return (EINVAL);
6751
6752         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
6753             "t4tmr");
6754         if (rc)
6755                 return (rc);
6756
6757         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
6758         for_each_rxq(vi, i, rxq) {
6759 #ifdef atomic_store_rel_8
6760                 atomic_store_rel_8(&rxq->iq.intr_params, v);
6761 #else
6762                 rxq->iq.intr_params = v;
6763 #endif
6764         }
6765         vi->tmr_idx = idx;
6766
6767         end_synchronized_op(sc, LOCK_HELD);
6768         return (0);
6769 }
6770
6771 static int
6772 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
6773 {
6774         struct vi_info *vi = arg1;
6775         struct adapter *sc = vi->pi->adapter;
6776         int idx, rc;
6777
6778         idx = vi->pktc_idx;
6779
6780         rc = sysctl_handle_int(oidp, &idx, 0, req);
6781         if (rc != 0 || req->newptr == NULL)
6782                 return (rc);
6783
6784         if (idx < -1 || idx >= SGE_NCOUNTERS)
6785                 return (EINVAL);
6786
6787         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
6788             "t4pktc");
6789         if (rc)
6790                 return (rc);
6791
6792         if (vi->flags & VI_INIT_DONE)
6793                 rc = EBUSY; /* cannot be changed once the queues are created */
6794         else
6795                 vi->pktc_idx = idx;
6796
6797         end_synchronized_op(sc, LOCK_HELD);
6798         return (rc);
6799 }
6800
6801 static int
6802 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
6803 {
6804         struct vi_info *vi = arg1;
6805         struct adapter *sc = vi->pi->adapter;
6806         int qsize, rc;
6807
6808         qsize = vi->qsize_rxq;
6809
6810         rc = sysctl_handle_int(oidp, &qsize, 0, req);
6811         if (rc != 0 || req->newptr == NULL)
6812                 return (rc);
6813
6814         if (qsize < 128 || (qsize & 7))
6815                 return (EINVAL);
6816
6817         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
6818             "t4rxqs");
6819         if (rc)
6820                 return (rc);
6821
6822         if (vi->flags & VI_INIT_DONE)
6823                 rc = EBUSY; /* cannot be changed once the queues are created */
6824         else
6825                 vi->qsize_rxq = qsize;
6826
6827         end_synchronized_op(sc, LOCK_HELD);
6828         return (rc);
6829 }
6830
6831 static int
6832 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
6833 {
6834         struct vi_info *vi = arg1;
6835         struct adapter *sc = vi->pi->adapter;
6836         int qsize, rc;
6837
6838         qsize = vi->qsize_txq;
6839
6840         rc = sysctl_handle_int(oidp, &qsize, 0, req);
6841         if (rc != 0 || req->newptr == NULL)
6842                 return (rc);
6843
6844         if (qsize < 128 || qsize > 65536)
6845                 return (EINVAL);
6846
6847         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
6848             "t4txqs");
6849         if (rc)
6850                 return (rc);
6851
6852         if (vi->flags & VI_INIT_DONE)
6853                 rc = EBUSY; /* cannot be changed once the queues are created */
6854         else
6855                 vi->qsize_txq = qsize;
6856
6857         end_synchronized_op(sc, LOCK_HELD);
6858         return (rc);
6859 }
6860
6861 static int
6862 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
6863 {
6864         struct port_info *pi = arg1;
6865         struct adapter *sc = pi->adapter;
6866         struct link_config *lc = &pi->link_cfg;
6867         int rc;
6868
6869         if (req->newptr == NULL) {
6870                 struct sbuf *sb;
6871                 static char *bits = "\20\1RX\2TX\3AUTO";
6872
6873                 rc = sysctl_wire_old_buffer(req, 0);
6874                 if (rc != 0)
6875                         return(rc);
6876
6877                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6878                 if (sb == NULL)
6879                         return (ENOMEM);
6880
6881                 if (lc->link_ok) {
6882                         sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
6883                             (lc->requested_fc & PAUSE_AUTONEG), bits);
6884                 } else {
6885                         sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
6886                             PAUSE_RX | PAUSE_AUTONEG), bits);
6887                 }
6888                 rc = sbuf_finish(sb);
6889                 sbuf_delete(sb);
6890         } else {
6891                 char s[2];
6892                 int n;
6893
6894                 s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
6895                     PAUSE_AUTONEG));
6896                 s[1] = 0;
6897
6898                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
6899                 if (rc != 0)
6900                         return(rc);
6901
6902                 if (s[1] != 0)
6903                         return (EINVAL);
6904                 if (s[0] < '0' || s[0] > '9')
6905                         return (EINVAL);        /* not a number */
6906                 n = s[0] - '0';
6907                 if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
6908                         return (EINVAL);        /* some other bit is set too */
6909
6910                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6911                     "t4PAUSE");
6912                 if (rc)
6913                         return (rc);
6914                 PORT_LOCK(pi);
6915                 lc->requested_fc = n;
6916                 fixup_link_config(pi);
6917                 if (pi->up_vis > 0)
6918                         rc = apply_link_config(pi);
6919                 set_current_media(pi);
6920                 PORT_UNLOCK(pi);
6921                 end_synchronized_op(sc, 0);
6922         }
6923
6924         return (rc);
6925 }
6926
6927 static int
6928 sysctl_fec(SYSCTL_HANDLER_ARGS)
6929 {
6930         struct port_info *pi = arg1;
6931         struct adapter *sc = pi->adapter;
6932         struct link_config *lc = &pi->link_cfg;
6933         int rc;
6934         int8_t old;
6935
6936         if (req->newptr == NULL) {
6937                 struct sbuf *sb;
6938                 static char *bits = "\20\1RS\2BASE-R\3RSVD1\4RSVD2\5RSVD3\6AUTO";
6939
6940                 rc = sysctl_wire_old_buffer(req, 0);
6941                 if (rc != 0)
6942                         return(rc);
6943
6944                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6945                 if (sb == NULL)
6946                         return (ENOMEM);
6947
6948                 /*
6949                  * Display the requested_fec when the link is down -- the actual
6950                  * FEC makes sense only when the link is up.
6951                  */
6952                 if (lc->link_ok) {
6953                         sbuf_printf(sb, "%b", (lc->fec & M_FW_PORT_CAP32_FEC) |
6954                             (lc->requested_fec & FEC_AUTO), bits);
6955                 } else {
6956                         sbuf_printf(sb, "%b", lc->requested_fec, bits);
6957                 }
6958                 rc = sbuf_finish(sb);
6959                 sbuf_delete(sb);
6960         } else {
6961                 char s[3];
6962                 int n;
6963
6964                 snprintf(s, sizeof(s), "%d",
6965                     lc->requested_fec == FEC_AUTO ? -1 :
6966                     lc->requested_fec & M_FW_PORT_CAP32_FEC);
6967
6968                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
6969                 if (rc != 0)
6970                         return(rc);
6971
6972                 n = strtol(&s[0], NULL, 0);
6973                 if (n < 0 || n & FEC_AUTO)
6974                         n = FEC_AUTO;
6975                 else {
6976                         if (n & ~M_FW_PORT_CAP32_FEC)
6977                                 return (EINVAL);/* some other bit is set too */
6978                         if (!powerof2(n))
6979                                 return (EINVAL);/* one bit can be set at most */
6980                 }
6981
6982                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6983                     "t4fec");
6984                 if (rc)
6985                         return (rc);
6986                 PORT_LOCK(pi);
6987                 old = lc->requested_fec;
6988                 if (n == FEC_AUTO)
6989                         lc->requested_fec = FEC_AUTO;
6990                 else if (n == 0)
6991                         lc->requested_fec = FEC_NONE;
6992                 else {
6993                         if ((lc->supported | V_FW_PORT_CAP32_FEC(n)) !=
6994                             lc->supported) {
6995                                 rc = ENOTSUP;
6996                                 goto done;
6997                         }
6998                         lc->requested_fec = n;
6999                 }
7000                 fixup_link_config(pi);
7001                 if (pi->up_vis > 0) {
7002                         rc = apply_link_config(pi);
7003                         if (rc != 0) {
7004                                 lc->requested_fec = old;
7005                                 if (rc == FW_EPROTO)
7006                                         rc = ENOTSUP;
7007                         }
7008                 }
7009 done:
7010                 PORT_UNLOCK(pi);
7011                 end_synchronized_op(sc, 0);
7012         }
7013
7014         return (rc);
7015 }
7016
7017 static int
7018 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
7019 {
7020         struct port_info *pi = arg1;
7021         struct adapter *sc = pi->adapter;
7022         struct link_config *lc = &pi->link_cfg;
7023         int rc, val;
7024
7025         if (lc->supported & FW_PORT_CAP32_ANEG)
7026                 val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
7027         else
7028                 val = -1;
7029         rc = sysctl_handle_int(oidp, &val, 0, req);
7030         if (rc != 0 || req->newptr == NULL)
7031                 return (rc);
7032         if (val == 0)
7033                 val = AUTONEG_DISABLE;
7034         else if (val == 1)
7035                 val = AUTONEG_ENABLE;
7036         else
7037                 val = AUTONEG_AUTO;
7038
7039         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
7040             "t4aneg");
7041         if (rc)
7042                 return (rc);
7043         PORT_LOCK(pi);
7044         if (val == AUTONEG_ENABLE && !(lc->supported & FW_PORT_CAP32_ANEG)) {
7045                 rc = ENOTSUP;
7046                 goto done;
7047         }
7048         lc->requested_aneg = val;
7049         fixup_link_config(pi);
7050         if (pi->up_vis > 0)
7051                 rc = apply_link_config(pi);
7052         set_current_media(pi);
7053 done:
7054         PORT_UNLOCK(pi);
7055         end_synchronized_op(sc, 0);
7056         return (rc);
7057 }
7058
7059 static int
7060 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
7061 {
7062         struct adapter *sc = arg1;
7063         int reg = arg2;
7064         uint64_t val;
7065
7066         val = t4_read_reg64(sc, reg);
7067
7068         return (sysctl_handle_64(oidp, &val, 0, req));
7069 }
7070
7071 static int
7072 sysctl_temperature(SYSCTL_HANDLER_ARGS)
7073 {
7074         struct adapter *sc = arg1;
7075         int rc, t;
7076         uint32_t param, val;
7077
7078         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
7079         if (rc)
7080                 return (rc);
7081         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7082             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
7083             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
7084         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7085         end_synchronized_op(sc, 0);
7086         if (rc)
7087                 return (rc);
7088
7089         /* unknown is returned as 0 but we display -1 in that case */
7090         t = val == 0 ? -1 : val;
7091
7092         rc = sysctl_handle_int(oidp, &t, 0, req);
7093         return (rc);
7094 }
7095
7096 static int
7097 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
7098 {
7099         struct adapter *sc = arg1;
7100         struct sbuf *sb;
7101         int rc;
7102         uint32_t param, val;
7103
7104         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
7105         if (rc)
7106                 return (rc);
7107         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
7108             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
7109         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
7110         end_synchronized_op(sc, 0);
7111         if (rc)
7112                 return (rc);
7113
7114         rc = sysctl_wire_old_buffer(req, 0);
7115         if (rc != 0)
7116                 return (rc);
7117
7118         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7119         if (sb == NULL)
7120                 return (ENOMEM);
7121
7122         if (val == 0xffffffff) {
7123                 /* Only debug and custom firmwares report load averages. */
7124                 sbuf_printf(sb, "not available");
7125         } else {
7126                 sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
7127                     (val >> 16) & 0xff);
7128         }
7129         rc = sbuf_finish(sb);
7130         sbuf_delete(sb);
7131
7132         return (rc);
7133 }
7134
7135 static int
7136 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
7137 {
7138         struct adapter *sc = arg1;
7139         struct sbuf *sb;
7140         int rc, i;
7141         uint16_t incr[NMTUS][NCCTRL_WIN];
7142         static const char *dec_fac[] = {
7143                 "0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
7144                 "0.9375"
7145         };
7146
7147         rc = sysctl_wire_old_buffer(req, 0);
7148         if (rc != 0)
7149                 return (rc);
7150
7151         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7152         if (sb == NULL)
7153                 return (ENOMEM);
7154
7155         t4_read_cong_tbl(sc, incr);
7156
7157         for (i = 0; i < NCCTRL_WIN; ++i) {
7158                 sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
7159                     incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
7160                     incr[5][i], incr[6][i], incr[7][i]);
7161                 sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
7162                     incr[8][i], incr[9][i], incr[10][i], incr[11][i],
7163                     incr[12][i], incr[13][i], incr[14][i], incr[15][i],
7164                     sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
7165         }
7166
7167         rc = sbuf_finish(sb);
7168         sbuf_delete(sb);
7169
7170         return (rc);
7171 }
7172
7173 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
7174         "TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",   /* ibq's */
7175         "ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", /* obq's */
7176         "SGE0-RX", "SGE1-RX"    /* additional obq's (T5 onwards) */
7177 };
7178
7179 static int
7180 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
7181 {
7182         struct adapter *sc = arg1;
7183         struct sbuf *sb;
7184         int rc, i, n, qid = arg2;
7185         uint32_t *buf, *p;
7186         char *qtype;
7187         u_int cim_num_obq = sc->chip_params->cim_num_obq;
7188
7189         KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
7190             ("%s: bad qid %d\n", __func__, qid));
7191
7192         if (qid < CIM_NUM_IBQ) {
7193                 /* inbound queue */
7194                 qtype = "IBQ";
7195                 n = 4 * CIM_IBQ_SIZE;
7196                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
7197                 rc = t4_read_cim_ibq(sc, qid, buf, n);
7198         } else {
7199                 /* outbound queue */
7200                 qtype = "OBQ";
7201                 qid -= CIM_NUM_IBQ;
7202                 n = 4 * cim_num_obq * CIM_OBQ_SIZE;
7203                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
7204                 rc = t4_read_cim_obq(sc, qid, buf, n);
7205         }
7206
7207         if (rc < 0) {
7208                 rc = -rc;
7209                 goto done;
7210         }
7211         n = rc * sizeof(uint32_t);      /* rc has # of words actually read */
7212
7213         rc = sysctl_wire_old_buffer(req, 0);
7214         if (rc != 0)
7215                 goto done;
7216
7217         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
7218         if (sb == NULL) {
7219                 rc = ENOMEM;
7220                 goto done;
7221         }
7222
7223         sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
7224         for (i = 0, p = buf; i < n; i += 16, p += 4)
7225                 sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
7226                     p[2], p[3]);
7227
7228         rc = sbuf_finish(sb);
7229         sbuf_delete(sb);
7230 done:
7231         free(buf, M_CXGBE);
7232         return (rc);
7233 }
7234
7235 static void
7236 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
7237 {
7238         uint32_t *p;
7239
7240         sbuf_printf(sb, "Status   Data      PC%s",
7241             cfg & F_UPDBGLACAPTPCONLY ? "" :
7242             "     LS0Stat  LS0Addr             LS0Data");
7243
7244         for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
7245                 if (cfg & F_UPDBGLACAPTPCONLY) {
7246                         sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
7247                             p[6], p[7]);
7248                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
7249                             (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
7250                             p[4] & 0xff, p[5] >> 8);
7251                         sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
7252                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
7253                             p[1] & 0xf, p[2] >> 4);
7254                 } else {
7255                         sbuf_printf(sb,
7256                             "\n  %02x   %x%07x %x%07x %08x %08x "
7257                             "%08x%08x%08x%08x",
7258                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
7259                             p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
7260                             p[6], p[7]);
7261                 }
7262         }
7263 }
7264
7265 static void
7266 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
7267 {
7268         uint32_t *p;
7269
7270         sbuf_printf(sb, "Status   Inst    Data      PC%s",
7271             cfg & F_UPDBGLACAPTPCONLY ? "" :
7272             "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
7273
7274         for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
7275                 if (cfg & F_UPDBGLACAPTPCONLY) {
7276                         sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
7277                             p[3] & 0xff, p[2], p[1], p[0]);
7278                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
7279                             (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
7280                             p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
7281                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
7282                             (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
7283                             p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
7284                             p[6] >> 16);
7285                 } else {
7286                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
7287                             "%08x %08x %08x %08x %08x %08x",
7288                             (p[9] >> 16) & 0xff,
7289                             p[9] & 0xffff, p[8] >> 16,
7290                             p[8] & 0xffff, p[7] >> 16,
7291                             p[7] & 0xffff, p[6] >> 16,
7292                             p[2], p[1], p[0], p[5], p[4], p[3]);
7293                 }
7294         }
7295 }
7296
7297 static int
7298 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
7299 {
7300         uint32_t cfg, *buf;
7301         int rc;
7302
7303         rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
7304         if (rc != 0)
7305                 return (rc);
7306
7307         MPASS(flags == M_WAITOK || flags == M_NOWAIT);
7308         buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
7309             M_ZERO | flags);
7310         if (buf == NULL)
7311                 return (ENOMEM);
7312
7313         rc = -t4_cim_read_la(sc, buf, NULL);
7314         if (rc != 0)
7315                 goto done;
7316         if (chip_id(sc) < CHELSIO_T6)
7317                 sbuf_cim_la4(sc, sb, buf, cfg);
7318         else
7319                 sbuf_cim_la6(sc, sb, buf, cfg);
7320
7321 done:
7322         free(buf, M_CXGBE);
7323         return (rc);
7324 }
7325
7326 static int
7327 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
7328 {
7329         struct adapter *sc = arg1;
7330         struct sbuf *sb;
7331         int rc;
7332
7333         rc = sysctl_wire_old_buffer(req, 0);
7334         if (rc != 0)
7335                 return (rc);
7336         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7337         if (sb == NULL)
7338                 return (ENOMEM);
7339
7340         rc = sbuf_cim_la(sc, sb, M_WAITOK);
7341         if (rc == 0)
7342                 rc = sbuf_finish(sb);
7343         sbuf_delete(sb);
7344         return (rc);
7345 }
7346
7347 bool
7348 t4_os_dump_cimla(struct adapter *sc, int arg, bool verbose)
7349 {
7350         struct sbuf sb;
7351         int rc;
7352
7353         if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
7354                 return (false);
7355         rc = sbuf_cim_la(sc, &sb, M_NOWAIT);
7356         if (rc == 0) {
7357                 rc = sbuf_finish(&sb);
7358                 if (rc == 0) {
7359                         log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s",
7360                                 device_get_nameunit(sc->dev), sbuf_data(&sb));
7361                 }
7362         }
7363         sbuf_delete(&sb);
7364         return (false);
7365 }
7366
7367 static int
7368 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
7369 {
7370         struct adapter *sc = arg1;
7371         u_int i;
7372         struct sbuf *sb;
7373         uint32_t *buf, *p;
7374         int rc;
7375
7376         rc = sysctl_wire_old_buffer(req, 0);
7377         if (rc != 0)
7378                 return (rc);
7379
7380         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7381         if (sb == NULL)
7382                 return (ENOMEM);
7383
7384         buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
7385             M_ZERO | M_WAITOK);
7386
7387         t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
7388         p = buf;
7389
7390         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
7391                 sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
7392                     p[1], p[0]);
7393         }
7394
7395         sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
7396         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
7397                 sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
7398                     (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
7399                     (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
7400                     (p[1] >> 2) | ((p[2] & 3) << 30),
7401                     (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
7402                     p[0] & 1);
7403         }
7404
7405         rc = sbuf_finish(sb);
7406         sbuf_delete(sb);
7407         free(buf, M_CXGBE);
7408         return (rc);
7409 }
7410
7411 static int
7412 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
7413 {
7414         struct adapter *sc = arg1;
7415         u_int i;
7416         struct sbuf *sb;
7417         uint32_t *buf, *p;
7418         int rc;
7419
7420         rc = sysctl_wire_old_buffer(req, 0);
7421         if (rc != 0)
7422                 return (rc);
7423
7424         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7425         if (sb == NULL)
7426                 return (ENOMEM);
7427
7428         buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
7429             M_ZERO | M_WAITOK);
7430
7431         t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
7432         p = buf;
7433
7434         sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
7435         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
7436                 sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
7437                     (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
7438                     p[4], p[3], p[2], p[1], p[0]);
7439         }
7440
7441         sbuf_printf(sb, "\n\nCntl ID               Data");
7442         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
7443                 sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
7444                     (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
7445         }
7446
7447         rc = sbuf_finish(sb);
7448         sbuf_delete(sb);
7449         free(buf, M_CXGBE);
7450         return (rc);
7451 }
7452
7453 static int
7454 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
7455 {
7456         struct adapter *sc = arg1;
7457         struct sbuf *sb;
7458         int rc, i;
7459         uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
7460         uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
7461         uint16_t thres[CIM_NUM_IBQ];
7462         uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
7463         uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
7464         u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
7465
7466         cim_num_obq = sc->chip_params->cim_num_obq;
7467         if (is_t4(sc)) {
7468                 ibq_rdaddr = A_UP_IBQ_0_RDADDR;
7469                 obq_rdaddr = A_UP_OBQ_0_REALADDR;
7470         } else {
7471                 ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
7472                 obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
7473         }
7474         nq = CIM_NUM_IBQ + cim_num_obq;
7475
7476         rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
7477         if (rc == 0)
7478                 rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq, obq_wr);
7479         if (rc != 0)
7480                 return (rc);
7481
7482         t4_read_cimq_cfg(sc, base, size, thres);
7483
7484         rc = sysctl_wire_old_buffer(req, 0);
7485         if (rc != 0)
7486                 return (rc);
7487
7488         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
7489         if (sb == NULL)
7490                 return (ENOMEM);
7491
7492         sbuf_printf(sb,
7493             "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
7494
7495         for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
7496                 sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
7497                     qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
7498                     G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
7499                     G_QUEREMFLITS(p[2]) * 16);
7500         for ( ; i < nq; i++, p += 4, wr += 2)
7501                 sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
7502                     base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
7503                     wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
7504                     G_QUEREMFLITS(p[2]) * 16);
7505
7506         rc = sbuf_finish(sb);
7507         sbuf_delete(sb);
7508
7509         return (rc);
7510 }
7511
7512 static int
7513 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
7514 {
7515         struct adapter *sc = arg1;
7516         struct sbuf *sb;
7517         int rc;
7518         struct tp_cpl_stats stats;
7519
7520         rc = sysctl_wire_old_buffer(req, 0);
7521         if (rc != 0)
7522                 return (rc);
7523
7524         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7525         if (sb == NULL)
7526                 return (ENOMEM);
7527
7528         mtx_lock(&sc->reg_lock);
7529         t4_tp_get_cpl_stats(sc, &stats, 0);
7530         mtx_unlock(&sc->reg_lock);
7531
7532         if (sc->chip_params->nchan > 2) {
7533                 sbuf_printf(sb, "                 channel 0  channel 1"
7534                     "  channel 2  channel 3");
7535                 sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
7536                     stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
7537                 sbuf_printf(sb, "\nCPL responses:   %10u %10u %10u %10u",
7538                     stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
7539         } else {
7540                 sbuf_printf(sb, "                 channel 0  channel 1");
7541                 sbuf_printf(sb, "\nCPL requests:   %10u %10u",
7542                     stats.req[0], stats.req[1]);
7543                 sbuf_printf(sb, "\nCPL responses:   %10u %10u",
7544                     stats.rsp[0], stats.rsp[1]);
7545         }
7546
7547         rc = sbuf_finish(sb);
7548         sbuf_delete(sb);
7549
7550         return (rc);
7551 }
7552
7553 static int
7554 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
7555 {
7556         struct adapter *sc = arg1;
7557         struct sbuf *sb;
7558         int rc;
7559         struct tp_usm_stats stats;
7560
7561         rc = sysctl_wire_old_buffer(req, 0);
7562         if (rc != 0)
7563                 return(rc);
7564
7565         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7566         if (sb == NULL)
7567                 return (ENOMEM);
7568
7569         t4_get_usm_stats(sc, &stats, 1);
7570
7571         sbuf_printf(sb, "Frames: %u\n", stats.frames);
7572         sbuf_printf(sb, "Octets: %ju\n", stats.octets);
7573         sbuf_printf(sb, "Drops:  %u", stats.drops);
7574
7575         rc = sbuf_finish(sb);
7576         sbuf_delete(sb);
7577
7578         return (rc);
7579 }
7580
7581 static const char * const devlog_level_strings[] = {
7582         [FW_DEVLOG_LEVEL_EMERG]         = "EMERG",
7583         [FW_DEVLOG_LEVEL_CRIT]          = "CRIT",
7584         [FW_DEVLOG_LEVEL_ERR]           = "ERR",
7585         [FW_DEVLOG_LEVEL_NOTICE]        = "NOTICE",
7586         [FW_DEVLOG_LEVEL_INFO]          = "INFO",
7587         [FW_DEVLOG_LEVEL_DEBUG]         = "DEBUG"
7588 };
7589
7590 static const char * const devlog_facility_strings[] = {
7591         [FW_DEVLOG_FACILITY_CORE]       = "CORE",
7592         [FW_DEVLOG_FACILITY_CF]         = "CF",
7593         [FW_DEVLOG_FACILITY_SCHED]      = "SCHED",
7594         [FW_DEVLOG_FACILITY_TIMER]      = "TIMER",
7595         [FW_DEVLOG_FACILITY_RES]        = "RES",
7596         [FW_DEVLOG_FACILITY_HW]         = "HW",
7597         [FW_DEVLOG_FACILITY_FLR]        = "FLR",
7598         [FW_DEVLOG_FACILITY_DMAQ]       = "DMAQ",
7599         [FW_DEVLOG_FACILITY_PHY]        = "PHY",
7600         [FW_DEVLOG_FACILITY_MAC]        = "MAC",
7601         [FW_DEVLOG_FACILITY_PORT]       = "PORT",
7602         [FW_DEVLOG_FACILITY_VI]         = "VI",
7603         [FW_DEVLOG_FACILITY_FILTER]     = "FILTER",
7604         [FW_DEVLOG_FACILITY_ACL]        = "ACL",
7605         [FW_DEVLOG_FACILITY_TM]         = "TM",
7606         [FW_DEVLOG_FACILITY_QFC]        = "QFC",
7607         [FW_DEVLOG_FACILITY_DCB]        = "DCB",
7608         [FW_DEVLOG_FACILITY_ETH]        = "ETH",
7609         [FW_DEVLOG_FACILITY_OFLD]       = "OFLD",
7610         [FW_DEVLOG_FACILITY_RI]         = "RI",
7611         [FW_DEVLOG_FACILITY_ISCSI]      = "ISCSI",
7612         [FW_DEVLOG_FACILITY_FCOE]       = "FCOE",
7613         [FW_DEVLOG_FACILITY_FOISCSI]    = "FOISCSI",
7614         [FW_DEVLOG_FACILITY_FOFCOE]     = "FOFCOE",
7615         [FW_DEVLOG_FACILITY_CHNET]      = "CHNET",
7616 };
7617
7618 static int
7619 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
7620 {
7621         int i, j, rc, nentries, first = 0;
7622         struct devlog_params *dparams = &sc->params.devlog;
7623         struct fw_devlog_e *buf, *e;
7624         uint64_t ftstamp = UINT64_MAX;
7625
7626         if (dparams->addr == 0)
7627                 return (ENXIO);
7628
7629         MPASS(flags == M_WAITOK || flags == M_NOWAIT);
7630         buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
7631         if (buf == NULL)
7632                 return (ENOMEM);
7633
7634         rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf, dparams->size);
7635         if (rc != 0)
7636                 goto done;
7637
7638         nentries = dparams->size / sizeof(struct fw_devlog_e);
7639         for (i = 0; i < nentries; i++) {
7640                 e = &buf[i];
7641
7642                 if (e->timestamp == 0)
7643                         break;  /* end */
7644
7645                 e->timestamp = be64toh(e->timestamp);
7646                 e->seqno = be32toh(e->seqno);
7647                 for (j = 0; j < 8; j++)
7648                         e->params[j] = be32toh(e->params[j]);
7649
7650                 if (e->timestamp < ftstamp) {
7651                         ftstamp = e->timestamp;
7652                         first = i;
7653                 }
7654         }
7655
7656         if (buf[first].timestamp == 0)
7657                 goto done;      /* nothing in the log */
7658
7659         sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
7660             "Seq#", "Tstamp", "Level", "Facility", "Message");
7661
7662         i = first;
7663         do {
7664                 e = &buf[i];
7665                 if (e->timestamp == 0)
7666                         break;  /* end */
7667
7668                 sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
7669                     e->seqno, e->timestamp,
7670                     (e->level < nitems(devlog_level_strings) ?
7671                         devlog_level_strings[e->level] : "UNKNOWN"),
7672                     (e->facility < nitems(devlog_facility_strings) ?
7673                         devlog_facility_strings[e->facility] : "UNKNOWN"));
7674                 sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
7675                     e->params[2], e->params[3], e->params[4],
7676                     e->params[5], e->params[6], e->params[7]);
7677
7678                 if (++i == nentries)
7679                         i = 0;
7680         } while (i != first);
7681 done:
7682         free(buf, M_CXGBE);
7683         return (rc);
7684 }
7685
7686 static int
7687 sysctl_devlog(SYSCTL_HANDLER_ARGS)
7688 {
7689         struct adapter *sc = arg1;
7690         int rc;
7691         struct sbuf *sb;
7692
7693         rc = sysctl_wire_old_buffer(req, 0);
7694         if (rc != 0)
7695                 return (rc);
7696         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7697         if (sb == NULL)
7698                 return (ENOMEM);
7699
7700         rc = sbuf_devlog(sc, sb, M_WAITOK);
7701         if (rc == 0)
7702                 rc = sbuf_finish(sb);
7703         sbuf_delete(sb);
7704         return (rc);
7705 }
7706
7707 void
7708 t4_os_dump_devlog(struct adapter *sc)
7709 {
7710         int rc;
7711         struct sbuf sb;
7712
7713         if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb)
7714                 return;
7715         rc = sbuf_devlog(sc, &sb, M_NOWAIT);
7716         if (rc == 0) {
7717                 rc = sbuf_finish(&sb);
7718                 if (rc == 0) {
7719                         log(LOG_DEBUG, "%s: device log follows.\n%s",
7720                                 device_get_nameunit(sc->dev), sbuf_data(&sb));
7721                 }
7722         }
7723         sbuf_delete(&sb);
7724 }
7725
7726 static int
7727 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
7728 {
7729         struct adapter *sc = arg1;
7730         struct sbuf *sb;
7731         int rc;
7732         struct tp_fcoe_stats stats[MAX_NCHAN];
7733         int i, nchan = sc->chip_params->nchan;
7734
7735         rc = sysctl_wire_old_buffer(req, 0);
7736         if (rc != 0)
7737                 return (rc);
7738
7739         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7740         if (sb == NULL)
7741                 return (ENOMEM);
7742
7743         for (i = 0; i < nchan; i++)
7744                 t4_get_fcoe_stats(sc, i, &stats[i], 1);
7745
7746         if (nchan > 2) {
7747                 sbuf_printf(sb, "                   channel 0        channel 1"
7748                     "        channel 2        channel 3");
7749                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
7750                     stats[0].octets_ddp, stats[1].octets_ddp,
7751                     stats[2].octets_ddp, stats[3].octets_ddp);
7752                 sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
7753                     stats[0].frames_ddp, stats[1].frames_ddp,
7754                     stats[2].frames_ddp, stats[3].frames_ddp);
7755                 sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
7756                     stats[0].frames_drop, stats[1].frames_drop,
7757                     stats[2].frames_drop, stats[3].frames_drop);
7758         } else {
7759                 sbuf_printf(sb, "                   channel 0        channel 1");
7760                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
7761                     stats[0].octets_ddp, stats[1].octets_ddp);
7762                 sbuf_printf(sb, "\nframesDDP:  %16u %16u",
7763                     stats[0].frames_ddp, stats[1].frames_ddp);
7764                 sbuf_printf(sb, "\nframesDrop: %16u %16u",
7765                     stats[0].frames_drop, stats[1].frames_drop);
7766         }
7767
7768         rc = sbuf_finish(sb);
7769         sbuf_delete(sb);
7770
7771         return (rc);
7772 }
7773
7774 static int
7775 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
7776 {
7777         struct adapter *sc = arg1;
7778         struct sbuf *sb;
7779         int rc, i;
7780         unsigned int map, kbps, ipg, mode;
7781         unsigned int pace_tab[NTX_SCHED];
7782
7783         rc = sysctl_wire_old_buffer(req, 0);
7784         if (rc != 0)
7785                 return (rc);
7786
7787         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7788         if (sb == NULL)
7789                 return (ENOMEM);
7790
7791         map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
7792         mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
7793         t4_read_pace_tbl(sc, pace_tab);
7794
7795         sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
7796             "Class IPG (0.1 ns)   Flow IPG (us)");
7797
7798         for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
7799                 t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
7800                 sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
7801                     (mode & (1 << i)) ? "flow" : "class", map & 3);
7802                 if (kbps)
7803                         sbuf_printf(sb, "%9u     ", kbps);
7804                 else
7805                         sbuf_printf(sb, " disabled     ");
7806
7807                 if (ipg)
7808                         sbuf_printf(sb, "%13u        ", ipg);
7809                 else
7810                         sbuf_printf(sb, "     disabled        ");
7811
7812                 if (pace_tab[i])
7813                         sbuf_printf(sb, "%10u", pace_tab[i]);
7814                 else
7815                         sbuf_printf(sb, "  disabled");
7816         }
7817
7818         rc = sbuf_finish(sb);
7819         sbuf_delete(sb);
7820
7821         return (rc);
7822 }
7823
7824 static int
7825 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
7826 {
7827         struct adapter *sc = arg1;
7828         struct sbuf *sb;
7829         int rc, i, j;
7830         uint64_t *p0, *p1;
7831         struct lb_port_stats s[2];
7832         static const char *stat_name[] = {
7833                 "OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
7834                 "UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
7835                 "Frames128To255:", "Frames256To511:", "Frames512To1023:",
7836                 "Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
7837                 "BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
7838                 "BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
7839                 "BG2FramesTrunc:", "BG3FramesTrunc:"
7840         };
7841
7842         rc = sysctl_wire_old_buffer(req, 0);
7843         if (rc != 0)
7844                 return (rc);
7845
7846         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7847         if (sb == NULL)
7848                 return (ENOMEM);
7849
7850         memset(s, 0, sizeof(s));
7851
7852         for (i = 0; i < sc->chip_params->nchan; i += 2) {
7853                 t4_get_lb_stats(sc, i, &s[0]);
7854                 t4_get_lb_stats(sc, i + 1, &s[1]);
7855
7856                 p0 = &s[0].octets;
7857                 p1 = &s[1].octets;
7858                 sbuf_printf(sb, "%s                       Loopback %u"
7859                     "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
7860
7861                 for (j = 0; j < nitems(stat_name); j++)
7862                         sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
7863                                    *p0++, *p1++);
7864         }
7865
7866         rc = sbuf_finish(sb);
7867         sbuf_delete(sb);
7868
7869         return (rc);
7870 }
7871
7872 static int
7873 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
7874 {
7875         int rc = 0;
7876         struct port_info *pi = arg1;
7877         struct link_config *lc = &pi->link_cfg;
7878         struct sbuf *sb;
7879
7880         rc = sysctl_wire_old_buffer(req, 0);
7881         if (rc != 0)
7882                 return(rc);
7883         sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
7884         if (sb == NULL)
7885                 return (ENOMEM);
7886
7887         if (lc->link_ok || lc->link_down_rc == 255)
7888                 sbuf_printf(sb, "n/a");
7889         else
7890                 sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
7891
7892         rc = sbuf_finish(sb);
7893         sbuf_delete(sb);
7894
7895         return (rc);
7896 }
7897
7898 struct mem_desc {
7899         unsigned int base;
7900         unsigned int limit;
7901         unsigned int idx;
7902 };
7903
7904 static int
7905 mem_desc_cmp(const void *a, const void *b)
7906 {
7907         return ((const struct mem_desc *)a)->base -
7908                ((const struct mem_desc *)b)->base;
7909 }
7910
7911 static void
7912 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
7913     unsigned int to)
7914 {
7915         unsigned int size;
7916
7917         if (from == to)
7918                 return;
7919
7920         size = to - from + 1;
7921         if (size == 0)
7922                 return;
7923
7924         /* XXX: need humanize_number(3) in libkern for a more readable 'size' */
7925         sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
7926 }
7927
7928 static int
7929 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
7930 {
7931         struct adapter *sc = arg1;
7932         struct sbuf *sb;
7933         int rc, i, n;
7934         uint32_t lo, hi, used, alloc;
7935         static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
7936         static const char *region[] = {
7937                 "DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
7938                 "Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
7939                 "Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
7940                 "TDDP region:", "TPT region:", "STAG region:", "RQ region:",
7941                 "RQUDP region:", "PBL region:", "TXPBL region:",
7942                 "DBVFIFO region:", "ULPRX state:", "ULPTX state:",
7943                 "On-chip queues:", "TLS keys:",
7944         };
7945         struct mem_desc avail[4];
7946         struct mem_desc mem[nitems(region) + 3];        /* up to 3 holes */
7947         struct mem_desc *md = mem;
7948
7949         rc = sysctl_wire_old_buffer(req, 0);
7950         if (rc != 0)
7951                 return (rc);
7952
7953         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7954         if (sb == NULL)
7955                 return (ENOMEM);
7956
7957         for (i = 0; i < nitems(mem); i++) {
7958                 mem[i].limit = 0;
7959                 mem[i].idx = i;
7960         }
7961
7962         /* Find and sort the populated memory ranges */
7963         i = 0;
7964         lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
7965         if (lo & F_EDRAM0_ENABLE) {
7966                 hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
7967                 avail[i].base = G_EDRAM0_BASE(hi) << 20;
7968                 avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
7969                 avail[i].idx = 0;
7970                 i++;
7971         }
7972         if (lo & F_EDRAM1_ENABLE) {
7973                 hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
7974                 avail[i].base = G_EDRAM1_BASE(hi) << 20;
7975                 avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
7976                 avail[i].idx = 1;
7977                 i++;
7978         }
7979         if (lo & F_EXT_MEM_ENABLE) {
7980                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
7981                 avail[i].base = G_EXT_MEM_BASE(hi) << 20;
7982                 avail[i].limit = avail[i].base +
7983                     (G_EXT_MEM_SIZE(hi) << 20);
7984                 avail[i].idx = is_t5(sc) ? 3 : 2;       /* Call it MC0 for T5 */
7985                 i++;
7986         }
7987         if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
7988                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
7989                 avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
7990                 avail[i].limit = avail[i].base +
7991                     (G_EXT_MEM1_SIZE(hi) << 20);
7992                 avail[i].idx = 4;
7993                 i++;
7994         }
7995         if (!i)                                    /* no memory available */
7996                 return 0;
7997         qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
7998
7999         (md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
8000         (md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
8001         (md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
8002         (md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
8003         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
8004         (md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
8005         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
8006         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
8007         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
8008
8009         /* the next few have explicit upper bounds */
8010         md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
8011         md->limit = md->base - 1 +
8012                     t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
8013                     G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
8014         md++;
8015
8016         md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
8017         md->limit = md->base - 1 +
8018                     t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
8019                     G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
8020         md++;
8021
8022         if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
8023                 if (chip_id(sc) <= CHELSIO_T5)
8024                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
8025                 else
8026                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
8027                 md->limit = 0;
8028         } else {
8029                 md->base = 0;
8030                 md->idx = nitems(region);  /* hide it */
8031         }
8032         md++;
8033
8034 #define ulp_region(reg) \
8035         md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
8036         (md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
8037
8038         ulp_region(RX_ISCSI);
8039         ulp_region(RX_TDDP);
8040         ulp_region(TX_TPT);
8041         ulp_region(RX_STAG);
8042         ulp_region(RX_RQ);
8043         ulp_region(RX_RQUDP);
8044         ulp_region(RX_PBL);
8045         ulp_region(TX_PBL);
8046 #undef ulp_region
8047
8048         md->base = 0;
8049         md->idx = nitems(region);
8050         if (!is_t4(sc)) {
8051                 uint32_t size = 0;
8052                 uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
8053                 uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
8054
8055                 if (is_t5(sc)) {
8056                         if (sge_ctrl & F_VFIFO_ENABLE)
8057                                 size = G_DBVFIFO_SIZE(fifo_size);
8058                 } else
8059                         size = G_T6_DBVFIFO_SIZE(fifo_size);
8060
8061                 if (size) {
8062                         md->base = G_BASEADDR(t4_read_reg(sc,
8063                             A_SGE_DBVFIFO_BADDR));
8064                         md->limit = md->base + (size << 2) - 1;
8065                 }
8066         }
8067         md++;
8068
8069         md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
8070         md->limit = 0;
8071         md++;
8072         md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
8073         md->limit = 0;
8074         md++;
8075
8076         md->base = sc->vres.ocq.start;
8077         if (sc->vres.ocq.size)
8078                 md->limit = md->base + sc->vres.ocq.size - 1;
8079         else
8080                 md->idx = nitems(region);  /* hide it */
8081         md++;
8082
8083         md->base = sc->vres.key.start;
8084         if (sc->vres.key.size)
8085                 md->limit = md->base + sc->vres.key.size - 1;
8086         else
8087                 md->idx = nitems(region);  /* hide it */
8088         md++;
8089
8090         /* add any address-space holes, there can be up to 3 */
8091         for (n = 0; n < i - 1; n++)
8092                 if (avail[n].limit < avail[n + 1].base)
8093                         (md++)->base = avail[n].limit;
8094         if (avail[n].limit)
8095                 (md++)->base = avail[n].limit;
8096
8097         n = md - mem;
8098         qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
8099
8100         for (lo = 0; lo < i; lo++)
8101                 mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
8102                                 avail[lo].limit - 1);
8103
8104         sbuf_printf(sb, "\n");
8105         for (i = 0; i < n; i++) {
8106                 if (mem[i].idx >= nitems(region))
8107                         continue;                        /* skip holes */
8108                 if (!mem[i].limit)
8109                         mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
8110                 mem_region_show(sb, region[mem[i].idx], mem[i].base,
8111                                 mem[i].limit);
8112         }
8113
8114         sbuf_printf(sb, "\n");
8115         lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
8116         hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
8117         mem_region_show(sb, "uP RAM:", lo, hi);
8118
8119         lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
8120         hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
8121         mem_region_show(sb, "uP Extmem2:", lo, hi);
8122
8123         lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
8124         sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
8125                    G_PMRXMAXPAGE(lo),
8126                    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
8127                    (lo & F_PMRXNUMCHN) ? 2 : 1);
8128
8129         lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
8130         hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
8131         sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
8132                    G_PMTXMAXPAGE(lo),
8133                    hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
8134                    hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
8135         sbuf_printf(sb, "%u p-structs\n",
8136                    t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
8137
8138         for (i = 0; i < 4; i++) {
8139                 if (chip_id(sc) > CHELSIO_T5)
8140                         lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
8141                 else
8142                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
8143                 if (is_t5(sc)) {
8144                         used = G_T5_USED(lo);
8145                         alloc = G_T5_ALLOC(lo);
8146                 } else {
8147                         used = G_USED(lo);
8148                         alloc = G_ALLOC(lo);
8149                 }
8150                 /* For T6 these are MAC buffer groups */
8151                 sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
8152                     i, used, alloc);
8153         }
8154         for (i = 0; i < sc->chip_params->nchan; i++) {
8155                 if (chip_id(sc) > CHELSIO_T5)
8156                         lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
8157                 else
8158                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
8159                 if (is_t5(sc)) {
8160                         used = G_T5_USED(lo);
8161                         alloc = G_T5_ALLOC(lo);
8162                 } else {
8163                         used = G_USED(lo);
8164                         alloc = G_ALLOC(lo);
8165                 }
8166                 /* For T6 these are MAC buffer groups */
8167                 sbuf_printf(sb,
8168                     "\nLoopback %d using %u pages out of %u allocated",
8169                     i, used, alloc);
8170         }
8171
8172         rc = sbuf_finish(sb);
8173         sbuf_delete(sb);
8174
8175         return (rc);
8176 }
8177
8178 static inline void
8179 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
8180 {
8181         *mask = x | y;
8182         y = htobe64(y);
8183         memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
8184 }
8185
8186 static int
8187 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
8188 {
8189         struct adapter *sc = arg1;
8190         struct sbuf *sb;
8191         int rc, i;
8192
8193         MPASS(chip_id(sc) <= CHELSIO_T5);
8194
8195         rc = sysctl_wire_old_buffer(req, 0);
8196         if (rc != 0)
8197                 return (rc);
8198
8199         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8200         if (sb == NULL)
8201                 return (ENOMEM);
8202
8203         sbuf_printf(sb,
8204             "Idx  Ethernet address     Mask     Vld Ports PF"
8205             "  VF              Replication             P0 P1 P2 P3  ML");
8206         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
8207                 uint64_t tcamx, tcamy, mask;
8208                 uint32_t cls_lo, cls_hi;
8209                 uint8_t addr[ETHER_ADDR_LEN];
8210
8211                 tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
8212                 tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
8213                 if (tcamx & tcamy)
8214                         continue;
8215                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
8216                 cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
8217                 cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
8218                 sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
8219                            "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
8220                            addr[3], addr[4], addr[5], (uintmax_t)mask,
8221                            (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
8222                            G_PORTMAP(cls_hi), G_PF(cls_lo),
8223                            (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
8224
8225                 if (cls_lo & F_REPLICATE) {
8226                         struct fw_ldst_cmd ldst_cmd;
8227
8228                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
8229                         ldst_cmd.op_to_addrspace =
8230                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
8231                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
8232                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
8233                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
8234                         ldst_cmd.u.mps.rplc.fid_idx =
8235                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
8236                                 V_FW_LDST_CMD_IDX(i));
8237
8238                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8239                             "t4mps");
8240                         if (rc)
8241                                 break;
8242                         rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
8243                             sizeof(ldst_cmd), &ldst_cmd);
8244                         end_synchronized_op(sc, 0);
8245
8246                         if (rc != 0) {
8247                                 sbuf_printf(sb, "%36d", rc);
8248                                 rc = 0;
8249                         } else {
8250                                 sbuf_printf(sb, " %08x %08x %08x %08x",
8251                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
8252                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
8253                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
8254                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
8255                         }
8256                 } else
8257                         sbuf_printf(sb, "%36s", "");
8258
8259                 sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
8260                     G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
8261                     G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
8262         }
8263
8264         if (rc)
8265                 (void) sbuf_finish(sb);
8266         else
8267                 rc = sbuf_finish(sb);
8268         sbuf_delete(sb);
8269
8270         return (rc);
8271 }
8272
8273 static int
8274 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
8275 {
8276         struct adapter *sc = arg1;
8277         struct sbuf *sb;
8278         int rc, i;
8279
8280         MPASS(chip_id(sc) > CHELSIO_T5);
8281
8282         rc = sysctl_wire_old_buffer(req, 0);
8283         if (rc != 0)
8284                 return (rc);
8285
8286         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8287         if (sb == NULL)
8288                 return (ENOMEM);
8289
8290         sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
8291             "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
8292             "                           Replication"
8293             "                                    P0 P1 P2 P3  ML\n");
8294
8295         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
8296                 uint8_t dip_hit, vlan_vld, lookup_type, port_num;
8297                 uint16_t ivlan;
8298                 uint64_t tcamx, tcamy, val, mask;
8299                 uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
8300                 uint8_t addr[ETHER_ADDR_LEN];
8301
8302                 ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
8303                 if (i < 256)
8304                         ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
8305                 else
8306                         ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
8307                 t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
8308                 val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
8309                 tcamy = G_DMACH(val) << 32;
8310                 tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
8311                 data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
8312                 lookup_type = G_DATALKPTYPE(data2);
8313                 port_num = G_DATAPORTNUM(data2);
8314                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
8315                         /* Inner header VNI */
8316                         vniy = ((data2 & F_DATAVIDH2) << 23) |
8317                                        (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
8318                         dip_hit = data2 & F_DATADIPHIT;
8319                         vlan_vld = 0;
8320                 } else {
8321                         vniy = 0;
8322                         dip_hit = 0;
8323                         vlan_vld = data2 & F_DATAVIDH2;
8324                         ivlan = G_VIDL(val);
8325                 }
8326
8327                 ctl |= V_CTLXYBITSEL(1);
8328                 t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
8329                 val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
8330                 tcamx = G_DMACH(val) << 32;
8331                 tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
8332                 data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
8333                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
8334                         /* Inner header VNI mask */
8335                         vnix = ((data2 & F_DATAVIDH2) << 23) |
8336                                (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
8337                 } else
8338                         vnix = 0;
8339
8340                 if (tcamx & tcamy)
8341                         continue;
8342                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
8343
8344                 cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
8345                 cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
8346
8347                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
8348                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
8349                             "%012jx %06x %06x    -    -   %3c"
8350                             "      'I'  %4x   %3c   %#x%4u%4d", i, addr[0],
8351                             addr[1], addr[2], addr[3], addr[4], addr[5],
8352                             (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
8353                             port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
8354                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
8355                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
8356                 } else {
8357                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
8358                             "%012jx    -       -   ", i, addr[0], addr[1],
8359                             addr[2], addr[3], addr[4], addr[5],
8360                             (uintmax_t)mask);
8361
8362                         if (vlan_vld)
8363                                 sbuf_printf(sb, "%4u   Y     ", ivlan);
8364                         else
8365                                 sbuf_printf(sb, "  -    N     ");
8366
8367                         sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
8368                             lookup_type ? 'I' : 'O', port_num,
8369                             cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
8370                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
8371                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
8372                 }
8373
8374
8375                 if (cls_lo & F_T6_REPLICATE) {
8376                         struct fw_ldst_cmd ldst_cmd;
8377
8378                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
8379                         ldst_cmd.op_to_addrspace =
8380                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
8381                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
8382                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
8383                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
8384                         ldst_cmd.u.mps.rplc.fid_idx =
8385                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
8386                                 V_FW_LDST_CMD_IDX(i));
8387
8388                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8389                             "t6mps");
8390                         if (rc)
8391                                 break;
8392                         rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
8393                             sizeof(ldst_cmd), &ldst_cmd);
8394                         end_synchronized_op(sc, 0);
8395
8396                         if (rc != 0) {
8397                                 sbuf_printf(sb, "%72d", rc);
8398                                 rc = 0;
8399                         } else {
8400                                 sbuf_printf(sb, " %08x %08x %08x %08x"
8401                                     " %08x %08x %08x %08x",
8402                                     be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
8403                                     be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
8404                                     be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
8405                                     be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
8406                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
8407                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
8408                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
8409                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
8410                         }
8411                 } else
8412                         sbuf_printf(sb, "%72s", "");
8413
8414                 sbuf_printf(sb, "%4u%3u%3u%3u %#x",
8415                     G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
8416                     G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
8417                     (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
8418         }
8419
8420         if (rc)
8421                 (void) sbuf_finish(sb);
8422         else
8423                 rc = sbuf_finish(sb);
8424         sbuf_delete(sb);
8425
8426         return (rc);
8427 }
8428
8429 static int
8430 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
8431 {
8432         struct adapter *sc = arg1;
8433         struct sbuf *sb;
8434         int rc;
8435         uint16_t mtus[NMTUS];
8436
8437         rc = sysctl_wire_old_buffer(req, 0);
8438         if (rc != 0)
8439                 return (rc);
8440
8441         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8442         if (sb == NULL)
8443                 return (ENOMEM);
8444
8445         t4_read_mtu_tbl(sc, mtus, NULL);
8446
8447         sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
8448             mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
8449             mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
8450             mtus[14], mtus[15]);
8451
8452         rc = sbuf_finish(sb);
8453         sbuf_delete(sb);
8454
8455         return (rc);
8456 }
8457
8458 static int
8459 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
8460 {
8461         struct adapter *sc = arg1;
8462         struct sbuf *sb;
8463         int rc, i;
8464         uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
8465         uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
8466         static const char *tx_stats[MAX_PM_NSTATS] = {
8467                 "Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
8468                 "Tx FIFO wait", NULL, "Tx latency"
8469         };
8470         static const char *rx_stats[MAX_PM_NSTATS] = {
8471                 "Read:", "Write bypass:", "Write mem:", "Flush:",
8472                 "Rx FIFO wait", NULL, "Rx latency"
8473         };
8474
8475         rc = sysctl_wire_old_buffer(req, 0);
8476         if (rc != 0)
8477                 return (rc);
8478
8479         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8480         if (sb == NULL)
8481                 return (ENOMEM);
8482
8483         t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
8484         t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
8485
8486         sbuf_printf(sb, "                Tx pcmds             Tx bytes");
8487         for (i = 0; i < 4; i++) {
8488                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8489                     tx_cyc[i]);
8490         }
8491
8492         sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
8493         for (i = 0; i < 4; i++) {
8494                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8495                     rx_cyc[i]);
8496         }
8497
8498         if (chip_id(sc) > CHELSIO_T5) {
8499                 sbuf_printf(sb,
8500                     "\n              Total wait      Total occupancy");
8501                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8502                     tx_cyc[i]);
8503                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8504                     rx_cyc[i]);
8505
8506                 i += 2;
8507                 MPASS(i < nitems(tx_stats));
8508
8509                 sbuf_printf(sb,
8510                     "\n                   Reads           Total wait");
8511                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
8512                     tx_cyc[i]);
8513                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
8514                     rx_cyc[i]);
8515         }
8516
8517         rc = sbuf_finish(sb);
8518         sbuf_delete(sb);
8519
8520         return (rc);
8521 }
8522
8523 static int
8524 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
8525 {
8526         struct adapter *sc = arg1;
8527         struct sbuf *sb;
8528         int rc;
8529         struct tp_rdma_stats stats;
8530
8531         rc = sysctl_wire_old_buffer(req, 0);
8532         if (rc != 0)
8533                 return (rc);
8534
8535         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8536         if (sb == NULL)
8537                 return (ENOMEM);
8538
8539         mtx_lock(&sc->reg_lock);
8540         t4_tp_get_rdma_stats(sc, &stats, 0);
8541         mtx_unlock(&sc->reg_lock);
8542
8543         sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
8544         sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
8545
8546         rc = sbuf_finish(sb);
8547         sbuf_delete(sb);
8548
8549         return (rc);
8550 }
8551
8552 static int
8553 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
8554 {
8555         struct adapter *sc = arg1;
8556         struct sbuf *sb;
8557         int rc;
8558         struct tp_tcp_stats v4, v6;
8559
8560         rc = sysctl_wire_old_buffer(req, 0);
8561         if (rc != 0)
8562                 return (rc);
8563
8564         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8565         if (sb == NULL)
8566                 return (ENOMEM);
8567
8568         mtx_lock(&sc->reg_lock);
8569         t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
8570         mtx_unlock(&sc->reg_lock);
8571
8572         sbuf_printf(sb,
8573             "                                IP                 IPv6\n");
8574         sbuf_printf(sb, "OutRsts:      %20u %20u\n",
8575             v4.tcp_out_rsts, v6.tcp_out_rsts);
8576         sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
8577             v4.tcp_in_segs, v6.tcp_in_segs);
8578         sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
8579             v4.tcp_out_segs, v6.tcp_out_segs);
8580         sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
8581             v4.tcp_retrans_segs, v6.tcp_retrans_segs);
8582
8583         rc = sbuf_finish(sb);
8584         sbuf_delete(sb);
8585
8586         return (rc);
8587 }
8588
8589 static int
8590 sysctl_tids(SYSCTL_HANDLER_ARGS)
8591 {
8592         struct adapter *sc = arg1;
8593         struct sbuf *sb;
8594         int rc;
8595         struct tid_info *t = &sc->tids;
8596
8597         rc = sysctl_wire_old_buffer(req, 0);
8598         if (rc != 0)
8599                 return (rc);
8600
8601         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8602         if (sb == NULL)
8603                 return (ENOMEM);
8604
8605         if (t->natids) {
8606                 sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
8607                     t->atids_in_use);
8608         }
8609
8610         if (t->nhpftids) {
8611                 sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
8612                     t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
8613         }
8614
8615         if (t->ntids) {
8616                 sbuf_printf(sb, "TID range: ");
8617                 if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
8618                         uint32_t b, hb;
8619
8620                         if (chip_id(sc) <= CHELSIO_T5) {
8621                                 b = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
8622                                 hb = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
8623                         } else {
8624                                 b = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
8625                                 hb = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
8626                         }
8627
8628                         if (b)
8629                                 sbuf_printf(sb, "%u-%u, ", t->tid_base, b - 1);
8630                         sbuf_printf(sb, "%u-%u", hb, t->ntids - 1);
8631                 } else
8632                         sbuf_printf(sb, "%u-%u", t->tid_base, t->ntids - 1);
8633                 sbuf_printf(sb, ", in use: %u\n",
8634                     atomic_load_acq_int(&t->tids_in_use));
8635         }
8636
8637         if (t->nstids) {
8638                 sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
8639                     t->stid_base + t->nstids - 1, t->stids_in_use);
8640         }
8641
8642         if (t->nftids) {
8643                 sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
8644                     t->ftid_end, t->ftids_in_use);
8645         }
8646
8647         if (t->netids) {
8648                 sbuf_printf(sb, "ETID range: %u-%u\n", t->etid_base,
8649                     t->etid_base + t->netids - 1);
8650         }
8651
8652         sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users",
8653             t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4),
8654             t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6));
8655
8656         rc = sbuf_finish(sb);
8657         sbuf_delete(sb);
8658
8659         return (rc);
8660 }
8661
8662 static int
8663 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
8664 {
8665         struct adapter *sc = arg1;
8666         struct sbuf *sb;
8667         int rc;
8668         struct tp_err_stats stats;
8669
8670         rc = sysctl_wire_old_buffer(req, 0);
8671         if (rc != 0)
8672                 return (rc);
8673
8674         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8675         if (sb == NULL)
8676                 return (ENOMEM);
8677
8678         mtx_lock(&sc->reg_lock);
8679         t4_tp_get_err_stats(sc, &stats, 0);
8680         mtx_unlock(&sc->reg_lock);
8681
8682         if (sc->chip_params->nchan > 2) {
8683                 sbuf_printf(sb, "                 channel 0  channel 1"
8684                     "  channel 2  channel 3\n");
8685                 sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
8686                     stats.mac_in_errs[0], stats.mac_in_errs[1],
8687                     stats.mac_in_errs[2], stats.mac_in_errs[3]);
8688                 sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
8689                     stats.hdr_in_errs[0], stats.hdr_in_errs[1],
8690                     stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
8691                 sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
8692                     stats.tcp_in_errs[0], stats.tcp_in_errs[1],
8693                     stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
8694                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
8695                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
8696                     stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
8697                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
8698                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
8699                     stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
8700                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
8701                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
8702                     stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
8703                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
8704                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
8705                     stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
8706                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
8707                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
8708                     stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
8709         } else {
8710                 sbuf_printf(sb, "                 channel 0  channel 1\n");
8711                 sbuf_printf(sb, "macInErrs:      %10u %10u\n",
8712                     stats.mac_in_errs[0], stats.mac_in_errs[1]);
8713                 sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
8714                     stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
8715                 sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
8716                     stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
8717                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
8718                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
8719                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
8720                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
8721                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
8722                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
8723                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
8724                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
8725                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
8726                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
8727         }
8728
8729         sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
8730             stats.ofld_no_neigh, stats.ofld_cong_defer);
8731
8732         rc = sbuf_finish(sb);
8733         sbuf_delete(sb);
8734
8735         return (rc);
8736 }
8737
8738 static int
8739 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
8740 {
8741         struct adapter *sc = arg1;
8742         struct tp_params *tpp = &sc->params.tp;
8743         u_int mask;
8744         int rc;
8745
8746         mask = tpp->la_mask >> 16;
8747         rc = sysctl_handle_int(oidp, &mask, 0, req);
8748         if (rc != 0 || req->newptr == NULL)
8749                 return (rc);
8750         if (mask > 0xffff)
8751                 return (EINVAL);
8752         tpp->la_mask = mask << 16;
8753         t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U, tpp->la_mask);
8754
8755         return (0);
8756 }
8757
8758 struct field_desc {
8759         const char *name;
8760         u_int start;
8761         u_int width;
8762 };
8763
8764 static void
8765 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
8766 {
8767         char buf[32];
8768         int line_size = 0;
8769
8770         while (f->name) {
8771                 uint64_t mask = (1ULL << f->width) - 1;
8772                 int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
8773                     ((uintmax_t)v >> f->start) & mask);
8774
8775                 if (line_size + len >= 79) {
8776                         line_size = 8;
8777                         sbuf_printf(sb, "\n        ");
8778                 }
8779                 sbuf_printf(sb, "%s ", buf);
8780                 line_size += len + 1;
8781                 f++;
8782         }
8783         sbuf_printf(sb, "\n");
8784 }
8785
8786 static const struct field_desc tp_la0[] = {
8787         { "RcfOpCodeOut", 60, 4 },
8788         { "State", 56, 4 },
8789         { "WcfState", 52, 4 },
8790         { "RcfOpcSrcOut", 50, 2 },
8791         { "CRxError", 49, 1 },
8792         { "ERxError", 48, 1 },
8793         { "SanityFailed", 47, 1 },
8794         { "SpuriousMsg", 46, 1 },
8795         { "FlushInputMsg", 45, 1 },
8796         { "FlushInputCpl", 44, 1 },
8797         { "RssUpBit", 43, 1 },
8798         { "RssFilterHit", 42, 1 },
8799         { "Tid", 32, 10 },
8800         { "InitTcb", 31, 1 },
8801         { "LineNumber", 24, 7 },
8802         { "Emsg", 23, 1 },
8803         { "EdataOut", 22, 1 },
8804         { "Cmsg", 21, 1 },
8805         { "CdataOut", 20, 1 },
8806         { "EreadPdu", 19, 1 },
8807         { "CreadPdu", 18, 1 },
8808         { "TunnelPkt", 17, 1 },
8809         { "RcfPeerFin", 16, 1 },
8810         { "RcfReasonOut", 12, 4 },
8811         { "TxCchannel", 10, 2 },
8812         { "RcfTxChannel", 8, 2 },
8813         { "RxEchannel", 6, 2 },
8814         { "RcfRxChannel", 5, 1 },
8815         { "RcfDataOutSrdy", 4, 1 },
8816         { "RxDvld", 3, 1 },
8817         { "RxOoDvld", 2, 1 },
8818         { "RxCongestion", 1, 1 },
8819         { "TxCongestion", 0, 1 },
8820         { NULL }
8821 };
8822
8823 static const struct field_desc tp_la1[] = {
8824         { "CplCmdIn", 56, 8 },
8825         { "CplCmdOut", 48, 8 },
8826         { "ESynOut", 47, 1 },
8827         { "EAckOut", 46, 1 },
8828         { "EFinOut", 45, 1 },
8829         { "ERstOut", 44, 1 },
8830         { "SynIn", 43, 1 },
8831         { "AckIn", 42, 1 },
8832         { "FinIn", 41, 1 },
8833         { "RstIn", 40, 1 },
8834         { "DataIn", 39, 1 },
8835         { "DataInVld", 38, 1 },
8836         { "PadIn", 37, 1 },
8837         { "RxBufEmpty", 36, 1 },
8838         { "RxDdp", 35, 1 },
8839         { "RxFbCongestion", 34, 1 },
8840         { "TxFbCongestion", 33, 1 },
8841         { "TxPktSumSrdy", 32, 1 },
8842         { "RcfUlpType", 28, 4 },
8843         { "Eread", 27, 1 },
8844         { "Ebypass", 26, 1 },
8845         { "Esave", 25, 1 },
8846         { "Static0", 24, 1 },
8847         { "Cread", 23, 1 },
8848         { "Cbypass", 22, 1 },
8849         { "Csave", 21, 1 },
8850         { "CPktOut", 20, 1 },
8851         { "RxPagePoolFull", 18, 2 },
8852         { "RxLpbkPkt", 17, 1 },
8853         { "TxLpbkPkt", 16, 1 },
8854         { "RxVfValid", 15, 1 },
8855         { "SynLearned", 14, 1 },
8856         { "SetDelEntry", 13, 1 },
8857         { "SetInvEntry", 12, 1 },
8858         { "CpcmdDvld", 11, 1 },
8859         { "CpcmdSave", 10, 1 },
8860         { "RxPstructsFull", 8, 2 },
8861         { "EpcmdDvld", 7, 1 },
8862         { "EpcmdFlush", 6, 1 },
8863         { "EpcmdTrimPrefix", 5, 1 },
8864         { "EpcmdTrimPostfix", 4, 1 },
8865         { "ERssIp4Pkt", 3, 1 },
8866         { "ERssIp6Pkt", 2, 1 },
8867         { "ERssTcpUdpPkt", 1, 1 },
8868         { "ERssFceFipPkt", 0, 1 },
8869         { NULL }
8870 };
8871
8872 static const struct field_desc tp_la2[] = {
8873         { "CplCmdIn", 56, 8 },
8874         { "MpsVfVld", 55, 1 },
8875         { "MpsPf", 52, 3 },
8876         { "MpsVf", 44, 8 },
8877         { "SynIn", 43, 1 },
8878         { "AckIn", 42, 1 },
8879         { "FinIn", 41, 1 },
8880         { "RstIn", 40, 1 },
8881         { "DataIn", 39, 1 },
8882         { "DataInVld", 38, 1 },
8883         { "PadIn", 37, 1 },
8884         { "RxBufEmpty", 36, 1 },
8885         { "RxDdp", 35, 1 },
8886         { "RxFbCongestion", 34, 1 },
8887         { "TxFbCongestion", 33, 1 },
8888         { "TxPktSumSrdy", 32, 1 },
8889         { "RcfUlpType", 28, 4 },
8890         { "Eread", 27, 1 },
8891         { "Ebypass", 26, 1 },
8892         { "Esave", 25, 1 },
8893         { "Static0", 24, 1 },
8894         { "Cread", 23, 1 },
8895         { "Cbypass", 22, 1 },
8896         { "Csave", 21, 1 },
8897         { "CPktOut", 20, 1 },
8898         { "RxPagePoolFull", 18, 2 },
8899         { "RxLpbkPkt", 17, 1 },
8900         { "TxLpbkPkt", 16, 1 },
8901         { "RxVfValid", 15, 1 },
8902         { "SynLearned", 14, 1 },
8903         { "SetDelEntry", 13, 1 },
8904         { "SetInvEntry", 12, 1 },
8905         { "CpcmdDvld", 11, 1 },
8906         { "CpcmdSave", 10, 1 },
8907         { "RxPstructsFull", 8, 2 },
8908         { "EpcmdDvld", 7, 1 },
8909         { "EpcmdFlush", 6, 1 },
8910         { "EpcmdTrimPrefix", 5, 1 },
8911         { "EpcmdTrimPostfix", 4, 1 },
8912         { "ERssIp4Pkt", 3, 1 },
8913         { "ERssIp6Pkt", 2, 1 },
8914         { "ERssTcpUdpPkt", 1, 1 },
8915         { "ERssFceFipPkt", 0, 1 },
8916         { NULL }
8917 };
8918
8919 static void
8920 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
8921 {
8922
8923         field_desc_show(sb, *p, tp_la0);
8924 }
8925
8926 static void
8927 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
8928 {
8929
8930         if (idx)
8931                 sbuf_printf(sb, "\n");
8932         field_desc_show(sb, p[0], tp_la0);
8933         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
8934                 field_desc_show(sb, p[1], tp_la0);
8935 }
8936
8937 static void
8938 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
8939 {
8940
8941         if (idx)
8942                 sbuf_printf(sb, "\n");
8943         field_desc_show(sb, p[0], tp_la0);
8944         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
8945                 field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
8946 }
8947
8948 static int
8949 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
8950 {
8951         struct adapter *sc = arg1;
8952         struct sbuf *sb;
8953         uint64_t *buf, *p;
8954         int rc;
8955         u_int i, inc;
8956         void (*show_func)(struct sbuf *, uint64_t *, int);
8957
8958         rc = sysctl_wire_old_buffer(req, 0);
8959         if (rc != 0)
8960                 return (rc);
8961
8962         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8963         if (sb == NULL)
8964                 return (ENOMEM);
8965
8966         buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
8967
8968         t4_tp_read_la(sc, buf, NULL);
8969         p = buf;
8970
8971         switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
8972         case 2:
8973                 inc = 2;
8974                 show_func = tp_la_show2;
8975                 break;
8976         case 3:
8977                 inc = 2;
8978                 show_func = tp_la_show3;
8979                 break;
8980         default:
8981                 inc = 1;
8982                 show_func = tp_la_show;
8983         }
8984
8985         for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
8986                 (*show_func)(sb, p, i);
8987
8988         rc = sbuf_finish(sb);
8989         sbuf_delete(sb);
8990         free(buf, M_CXGBE);
8991         return (rc);
8992 }
8993
8994 static int
8995 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
8996 {
8997         struct adapter *sc = arg1;
8998         struct sbuf *sb;
8999         int rc;
9000         u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
9001
9002         rc = sysctl_wire_old_buffer(req, 0);
9003         if (rc != 0)
9004                 return (rc);
9005
9006         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9007         if (sb == NULL)
9008                 return (ENOMEM);
9009
9010         t4_get_chan_txrate(sc, nrate, orate);
9011
9012         if (sc->chip_params->nchan > 2) {
9013                 sbuf_printf(sb, "              channel 0   channel 1"
9014                     "   channel 2   channel 3\n");
9015                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
9016                     nrate[0], nrate[1], nrate[2], nrate[3]);
9017                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
9018                     orate[0], orate[1], orate[2], orate[3]);
9019         } else {
9020                 sbuf_printf(sb, "              channel 0   channel 1\n");
9021                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
9022                     nrate[0], nrate[1]);
9023                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
9024                     orate[0], orate[1]);
9025         }
9026
9027         rc = sbuf_finish(sb);
9028         sbuf_delete(sb);
9029
9030         return (rc);
9031 }
9032
9033 static int
9034 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
9035 {
9036         struct adapter *sc = arg1;
9037         struct sbuf *sb;
9038         uint32_t *buf, *p;
9039         int rc, i;
9040
9041         rc = sysctl_wire_old_buffer(req, 0);
9042         if (rc != 0)
9043                 return (rc);
9044
9045         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9046         if (sb == NULL)
9047                 return (ENOMEM);
9048
9049         buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
9050             M_ZERO | M_WAITOK);
9051
9052         t4_ulprx_read_la(sc, buf);
9053         p = buf;
9054
9055         sbuf_printf(sb, "      Pcmd        Type   Message"
9056             "                Data");
9057         for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
9058                 sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
9059                     p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
9060         }
9061
9062         rc = sbuf_finish(sb);
9063         sbuf_delete(sb);
9064         free(buf, M_CXGBE);
9065         return (rc);
9066 }
9067
9068 static int
9069 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
9070 {
9071         struct adapter *sc = arg1;
9072         struct sbuf *sb;
9073         int rc, v;
9074
9075         MPASS(chip_id(sc) >= CHELSIO_T5);
9076
9077         rc = sysctl_wire_old_buffer(req, 0);
9078         if (rc != 0)
9079                 return (rc);
9080
9081         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9082         if (sb == NULL)
9083                 return (ENOMEM);
9084
9085         v = t4_read_reg(sc, A_SGE_STAT_CFG);
9086         if (G_STATSOURCE_T5(v) == 7) {
9087                 int mode;
9088
9089                 mode = is_t5(sc) ? G_STATMODE(v) : G_T6_STATMODE(v);
9090                 if (mode == 0) {
9091                         sbuf_printf(sb, "total %d, incomplete %d",
9092                             t4_read_reg(sc, A_SGE_STAT_TOTAL),
9093                             t4_read_reg(sc, A_SGE_STAT_MATCH));
9094                 } else if (mode == 1) {
9095                         sbuf_printf(sb, "total %d, data overflow %d",
9096                             t4_read_reg(sc, A_SGE_STAT_TOTAL),
9097                             t4_read_reg(sc, A_SGE_STAT_MATCH));
9098                 } else {
9099                         sbuf_printf(sb, "unknown mode %d", mode);
9100                 }
9101         }
9102         rc = sbuf_finish(sb);
9103         sbuf_delete(sb);
9104
9105         return (rc);
9106 }
9107
9108 static int
9109 sysctl_cpus(SYSCTL_HANDLER_ARGS)
9110 {
9111         struct adapter *sc = arg1;
9112         enum cpu_sets op = arg2;
9113         cpuset_t cpuset;
9114         struct sbuf *sb;
9115         int i, rc;
9116
9117         MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
9118
9119         CPU_ZERO(&cpuset);
9120         rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
9121         if (rc != 0)
9122                 return (rc);
9123
9124         rc = sysctl_wire_old_buffer(req, 0);
9125         if (rc != 0)
9126                 return (rc);
9127
9128         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9129         if (sb == NULL)
9130                 return (ENOMEM);
9131
9132         CPU_FOREACH(i)
9133                 sbuf_printf(sb, "%d ", i);
9134         rc = sbuf_finish(sb);
9135         sbuf_delete(sb);
9136
9137         return (rc);
9138
9139 }
9140
9141 #ifdef TCP_OFFLOAD
9142 static int
9143 sysctl_tls_rx_ports(SYSCTL_HANDLER_ARGS)
9144 {
9145         struct adapter *sc = arg1;
9146         int *old_ports, *new_ports;
9147         int i, new_count, rc;
9148
9149         if (req->newptr == NULL && req->oldptr == NULL)
9150                 return (SYSCTL_OUT(req, NULL, imax(sc->tt.num_tls_rx_ports, 1) *
9151                     sizeof(sc->tt.tls_rx_ports[0])));
9152
9153         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tlsrx");
9154         if (rc)
9155                 return (rc);
9156
9157         if (sc->tt.num_tls_rx_ports == 0) {
9158                 i = -1;
9159                 rc = SYSCTL_OUT(req, &i, sizeof(i));
9160         } else
9161                 rc = SYSCTL_OUT(req, sc->tt.tls_rx_ports,
9162                     sc->tt.num_tls_rx_ports * sizeof(sc->tt.tls_rx_ports[0]));
9163         if (rc == 0 && req->newptr != NULL) {
9164                 new_count = req->newlen / sizeof(new_ports[0]);
9165                 new_ports = malloc(new_count * sizeof(new_ports[0]), M_CXGBE,
9166                     M_WAITOK);
9167                 rc = SYSCTL_IN(req, new_ports, new_count *
9168                     sizeof(new_ports[0]));
9169                 if (rc)
9170                         goto err;
9171
9172                 /* Allow setting to a single '-1' to clear the list. */
9173                 if (new_count == 1 && new_ports[0] == -1) {
9174                         ADAPTER_LOCK(sc);
9175                         old_ports = sc->tt.tls_rx_ports;
9176                         sc->tt.tls_rx_ports = NULL;
9177                         sc->tt.num_tls_rx_ports = 0;
9178                         ADAPTER_UNLOCK(sc);
9179                         free(old_ports, M_CXGBE);
9180                 } else {
9181                         for (i = 0; i < new_count; i++) {
9182                                 if (new_ports[i] < 1 ||
9183                                     new_ports[i] > IPPORT_MAX) {
9184                                         rc = EINVAL;
9185                                         goto err;
9186                                 }
9187                         }
9188
9189                         ADAPTER_LOCK(sc);
9190                         old_ports = sc->tt.tls_rx_ports;
9191                         sc->tt.tls_rx_ports = new_ports;
9192                         sc->tt.num_tls_rx_ports = new_count;
9193                         ADAPTER_UNLOCK(sc);
9194                         free(old_ports, M_CXGBE);
9195                         new_ports = NULL;
9196                 }
9197         err:
9198                 free(new_ports, M_CXGBE);
9199         }
9200         end_synchronized_op(sc, 0);
9201         return (rc);
9202 }
9203
9204 static void
9205 unit_conv(char *buf, size_t len, u_int val, u_int factor)
9206 {
9207         u_int rem = val % factor;
9208
9209         if (rem == 0)
9210                 snprintf(buf, len, "%u", val / factor);
9211         else {
9212                 while (rem % 10 == 0)
9213                         rem /= 10;
9214                 snprintf(buf, len, "%u.%u", val / factor, rem);
9215         }
9216 }
9217
9218 static int
9219 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
9220 {
9221         struct adapter *sc = arg1;
9222         char buf[16];
9223         u_int res, re;
9224         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9225
9226         res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
9227         switch (arg2) {
9228         case 0:
9229                 /* timer_tick */
9230                 re = G_TIMERRESOLUTION(res);
9231                 break;
9232         case 1:
9233                 /* TCP timestamp tick */
9234                 re = G_TIMESTAMPRESOLUTION(res);
9235                 break;
9236         case 2:
9237                 /* DACK tick */
9238                 re = G_DELAYEDACKRESOLUTION(res);
9239                 break;
9240         default:
9241                 return (EDOOFUS);
9242         }
9243
9244         unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
9245
9246         return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
9247 }
9248
9249 static int
9250 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
9251 {
9252         struct adapter *sc = arg1;
9253         u_int res, dack_re, v;
9254         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9255
9256         res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
9257         dack_re = G_DELAYEDACKRESOLUTION(res);
9258         v = ((cclk_ps << dack_re) / 1000000) * t4_read_reg(sc, A_TP_DACK_TIMER);
9259
9260         return (sysctl_handle_int(oidp, &v, 0, req));
9261 }
9262
9263 static int
9264 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
9265 {
9266         struct adapter *sc = arg1;
9267         int reg = arg2;
9268         u_int tre;
9269         u_long tp_tick_us, v;
9270         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
9271
9272         MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
9273             reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
9274             reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
9275             reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
9276
9277         tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
9278         tp_tick_us = (cclk_ps << tre) / 1000000;
9279
9280         if (reg == A_TP_INIT_SRTT)
9281                 v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
9282         else
9283                 v = tp_tick_us * t4_read_reg(sc, reg);
9284
9285         return (sysctl_handle_long(oidp, &v, 0, req));
9286 }
9287
9288 /*
9289  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
9290  * passed to this function.
9291  */
9292 static int
9293 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
9294 {
9295         struct adapter *sc = arg1;
9296         int idx = arg2;
9297         u_int v;
9298
9299         MPASS(idx >= 0 && idx <= 24);
9300
9301         v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
9302
9303         return (sysctl_handle_int(oidp, &v, 0, req));
9304 }
9305
9306 static int
9307 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
9308 {
9309         struct adapter *sc = arg1;
9310         int idx = arg2;
9311         u_int shift, v, r;
9312
9313         MPASS(idx >= 0 && idx < 16);
9314
9315         r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
9316         shift = (idx & 3) << 3;
9317         v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
9318
9319         return (sysctl_handle_int(oidp, &v, 0, req));
9320 }
9321
9322 static int
9323 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
9324 {
9325         struct vi_info *vi = arg1;
9326         struct adapter *sc = vi->pi->adapter;
9327         int idx, rc, i;
9328         struct sge_ofld_rxq *ofld_rxq;
9329         uint8_t v;
9330
9331         idx = vi->ofld_tmr_idx;
9332
9333         rc = sysctl_handle_int(oidp, &idx, 0, req);
9334         if (rc != 0 || req->newptr == NULL)
9335                 return (rc);
9336
9337         if (idx < 0 || idx >= SGE_NTIMERS)
9338                 return (EINVAL);
9339
9340         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9341             "t4otmr");
9342         if (rc)
9343                 return (rc);
9344
9345         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
9346         for_each_ofld_rxq(vi, i, ofld_rxq) {
9347 #ifdef atomic_store_rel_8
9348                 atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
9349 #else
9350                 ofld_rxq->iq.intr_params = v;
9351 #endif
9352         }
9353         vi->ofld_tmr_idx = idx;
9354
9355         end_synchronized_op(sc, LOCK_HELD);
9356         return (0);
9357 }
9358
9359 static int
9360 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
9361 {
9362         struct vi_info *vi = arg1;
9363         struct adapter *sc = vi->pi->adapter;
9364         int idx, rc;
9365
9366         idx = vi->ofld_pktc_idx;
9367
9368         rc = sysctl_handle_int(oidp, &idx, 0, req);
9369         if (rc != 0 || req->newptr == NULL)
9370                 return (rc);
9371
9372         if (idx < -1 || idx >= SGE_NCOUNTERS)
9373                 return (EINVAL);
9374
9375         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9376             "t4opktc");
9377         if (rc)
9378                 return (rc);
9379
9380         if (vi->flags & VI_INIT_DONE)
9381                 rc = EBUSY; /* cannot be changed once the queues are created */
9382         else
9383                 vi->ofld_pktc_idx = idx;
9384
9385         end_synchronized_op(sc, LOCK_HELD);
9386         return (rc);
9387 }
9388 #endif
9389
9390 static int
9391 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
9392 {
9393         int rc;
9394
9395         if (cntxt->cid > M_CTXTQID)
9396                 return (EINVAL);
9397
9398         if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
9399             cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
9400                 return (EINVAL);
9401
9402         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
9403         if (rc)
9404                 return (rc);
9405
9406         if (sc->flags & FW_OK) {
9407                 rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
9408                     &cntxt->data[0]);
9409                 if (rc == 0)
9410                         goto done;
9411         }
9412
9413         /*
9414          * Read via firmware failed or wasn't even attempted.  Read directly via
9415          * the backdoor.
9416          */
9417         rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
9418 done:
9419         end_synchronized_op(sc, 0);
9420         return (rc);
9421 }
9422
9423 static int
9424 load_fw(struct adapter *sc, struct t4_data *fw)
9425 {
9426         int rc;
9427         uint8_t *fw_data;
9428
9429         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
9430         if (rc)
9431                 return (rc);
9432
9433         /*
9434          * The firmware, with the sole exception of the memory parity error
9435          * handler, runs from memory and not flash.  It is almost always safe to
9436          * install a new firmware on a running system.  Just set bit 1 in
9437          * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
9438          */
9439         if (sc->flags & FULL_INIT_DONE &&
9440             (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
9441                 rc = EBUSY;
9442                 goto done;
9443         }
9444
9445         fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
9446         if (fw_data == NULL) {
9447                 rc = ENOMEM;
9448                 goto done;
9449         }
9450
9451         rc = copyin(fw->data, fw_data, fw->len);
9452         if (rc == 0)
9453                 rc = -t4_load_fw(sc, fw_data, fw->len);
9454
9455         free(fw_data, M_CXGBE);
9456 done:
9457         end_synchronized_op(sc, 0);
9458         return (rc);
9459 }
9460
9461 static int
9462 load_cfg(struct adapter *sc, struct t4_data *cfg)
9463 {
9464         int rc;
9465         uint8_t *cfg_data = NULL;
9466
9467         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
9468         if (rc)
9469                 return (rc);
9470
9471         if (cfg->len == 0) {
9472                 /* clear */
9473                 rc = -t4_load_cfg(sc, NULL, 0);
9474                 goto done;
9475         }
9476
9477         cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
9478         if (cfg_data == NULL) {
9479                 rc = ENOMEM;
9480                 goto done;
9481         }
9482
9483         rc = copyin(cfg->data, cfg_data, cfg->len);
9484         if (rc == 0)
9485                 rc = -t4_load_cfg(sc, cfg_data, cfg->len);
9486
9487         free(cfg_data, M_CXGBE);
9488 done:
9489         end_synchronized_op(sc, 0);
9490         return (rc);
9491 }
9492
9493 static int
9494 load_boot(struct adapter *sc, struct t4_bootrom *br)
9495 {
9496         int rc;
9497         uint8_t *br_data = NULL;
9498         u_int offset;
9499
9500         if (br->len > 1024 * 1024)
9501                 return (EFBIG);
9502
9503         if (br->pf_offset == 0) {
9504                 /* pfidx */
9505                 if (br->pfidx_addr > 7)
9506                         return (EINVAL);
9507                 offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
9508                     A_PCIE_PF_EXPROM_OFST)));
9509         } else if (br->pf_offset == 1) {
9510                 /* offset */
9511                 offset = G_OFFSET(br->pfidx_addr);
9512         } else {
9513                 return (EINVAL);
9514         }
9515
9516         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
9517         if (rc)
9518                 return (rc);
9519
9520         if (br->len == 0) {
9521                 /* clear */
9522                 rc = -t4_load_boot(sc, NULL, offset, 0);
9523                 goto done;
9524         }
9525
9526         br_data = malloc(br->len, M_CXGBE, M_WAITOK);
9527         if (br_data == NULL) {
9528                 rc = ENOMEM;
9529                 goto done;
9530         }
9531
9532         rc = copyin(br->data, br_data, br->len);
9533         if (rc == 0)
9534                 rc = -t4_load_boot(sc, br_data, offset, br->len);
9535
9536         free(br_data, M_CXGBE);
9537 done:
9538         end_synchronized_op(sc, 0);
9539         return (rc);
9540 }
9541
9542 static int
9543 load_bootcfg(struct adapter *sc, struct t4_data *bc)
9544 {
9545         int rc;
9546         uint8_t *bc_data = NULL;
9547
9548         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
9549         if (rc)
9550                 return (rc);
9551
9552         if (bc->len == 0) {
9553                 /* clear */
9554                 rc = -t4_load_bootcfg(sc, NULL, 0);
9555                 goto done;
9556         }
9557
9558         bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
9559         if (bc_data == NULL) {
9560                 rc = ENOMEM;
9561                 goto done;
9562         }
9563
9564         rc = copyin(bc->data, bc_data, bc->len);
9565         if (rc == 0)
9566                 rc = -t4_load_bootcfg(sc, bc_data, bc->len);
9567
9568         free(bc_data, M_CXGBE);
9569 done:
9570         end_synchronized_op(sc, 0);
9571         return (rc);
9572 }
9573
9574 static int
9575 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
9576 {
9577         int rc;
9578         struct cudbg_init *cudbg;
9579         void *handle, *buf;
9580
9581         /* buf is large, don't block if no memory is available */
9582         buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
9583         if (buf == NULL)
9584                 return (ENOMEM);
9585
9586         handle = cudbg_alloc_handle();
9587         if (handle == NULL) {
9588                 rc = ENOMEM;
9589                 goto done;
9590         }
9591
9592         cudbg = cudbg_get_init(handle);
9593         cudbg->adap = sc;
9594         cudbg->print = (cudbg_print_cb)printf;
9595
9596 #ifndef notyet
9597         device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
9598             __func__, dump->wr_flash, dump->len, dump->data);
9599 #endif
9600
9601         if (dump->wr_flash)
9602                 cudbg->use_flash = 1;
9603         MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
9604         memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
9605
9606         rc = cudbg_collect(handle, buf, &dump->len);
9607         if (rc != 0)
9608                 goto done;
9609
9610         rc = copyout(buf, dump->data, dump->len);
9611 done:
9612         cudbg_free_handle(handle);
9613         free(buf, M_CXGBE);
9614         return (rc);
9615 }
9616
9617 static void
9618 free_offload_policy(struct t4_offload_policy *op)
9619 {
9620         struct offload_rule *r;
9621         int i;
9622
9623         if (op == NULL)
9624                 return;
9625
9626         r = &op->rule[0];
9627         for (i = 0; i < op->nrules; i++, r++) {
9628                 free(r->bpf_prog.bf_insns, M_CXGBE);
9629         }
9630         free(op->rule, M_CXGBE);
9631         free(op, M_CXGBE);
9632 }
9633
9634 static int
9635 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
9636 {
9637         int i, rc, len;
9638         struct t4_offload_policy *op, *old;
9639         struct bpf_program *bf;
9640         const struct offload_settings *s;
9641         struct offload_rule *r;
9642         void *u;
9643
9644         if (!is_offload(sc))
9645                 return (ENODEV);
9646
9647         if (uop->nrules == 0) {
9648                 /* Delete installed policies. */
9649                 op = NULL;
9650                 goto set_policy;
9651         } if (uop->nrules > 256) { /* arbitrary */
9652                 return (E2BIG);
9653         }
9654
9655         /* Copy userspace offload policy to kernel */
9656         op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
9657         op->nrules = uop->nrules;
9658         len = op->nrules * sizeof(struct offload_rule);
9659         op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
9660         rc = copyin(uop->rule, op->rule, len);
9661         if (rc) {
9662                 free(op->rule, M_CXGBE);
9663                 free(op, M_CXGBE);
9664                 return (rc);
9665         }
9666
9667         r = &op->rule[0];
9668         for (i = 0; i < op->nrules; i++, r++) {
9669
9670                 /* Validate open_type */
9671                 if (r->open_type != OPEN_TYPE_LISTEN &&
9672                     r->open_type != OPEN_TYPE_ACTIVE &&
9673                     r->open_type != OPEN_TYPE_PASSIVE &&
9674                     r->open_type != OPEN_TYPE_DONTCARE) {
9675 error:
9676                         /*
9677                          * Rules 0 to i have malloc'd filters that need to be
9678                          * freed.  Rules i+1 to nrules have userspace pointers
9679                          * and should be left alone.
9680                          */
9681                         op->nrules = i;
9682                         free_offload_policy(op);
9683                         return (rc);
9684                 }
9685
9686                 /* Validate settings */
9687                 s = &r->settings;
9688                 if ((s->offload != 0 && s->offload != 1) ||
9689                     s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
9690                     s->sched_class < -1 ||
9691                     s->sched_class >= sc->chip_params->nsched_cls) {
9692                         rc = EINVAL;
9693                         goto error;
9694                 }
9695
9696                 bf = &r->bpf_prog;
9697                 u = bf->bf_insns;       /* userspace ptr */
9698                 bf->bf_insns = NULL;
9699                 if (bf->bf_len == 0) {
9700                         /* legal, matches everything */
9701                         continue;
9702                 }
9703                 len = bf->bf_len * sizeof(*bf->bf_insns);
9704                 bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
9705                 rc = copyin(u, bf->bf_insns, len);
9706                 if (rc != 0)
9707                         goto error;
9708
9709                 if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
9710                         rc = EINVAL;
9711                         goto error;
9712                 }
9713         }
9714 set_policy:
9715         rw_wlock(&sc->policy_lock);
9716         old = sc->policy;
9717         sc->policy = op;
9718         rw_wunlock(&sc->policy_lock);
9719         free_offload_policy(old);
9720
9721         return (0);
9722 }
9723
9724 #define MAX_READ_BUF_SIZE (128 * 1024)
9725 static int
9726 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
9727 {
9728         uint32_t addr, remaining, n;
9729         uint32_t *buf;
9730         int rc;
9731         uint8_t *dst;
9732
9733         rc = validate_mem_range(sc, mr->addr, mr->len);
9734         if (rc != 0)
9735                 return (rc);
9736
9737         buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
9738         addr = mr->addr;
9739         remaining = mr->len;
9740         dst = (void *)mr->data;
9741
9742         while (remaining) {
9743                 n = min(remaining, MAX_READ_BUF_SIZE);
9744                 read_via_memwin(sc, 2, addr, buf, n);
9745
9746                 rc = copyout(buf, dst, n);
9747                 if (rc != 0)
9748                         break;
9749
9750                 dst += n;
9751                 remaining -= n;
9752                 addr += n;
9753         }
9754
9755         free(buf, M_CXGBE);
9756         return (rc);
9757 }
9758 #undef MAX_READ_BUF_SIZE
9759
9760 static int
9761 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
9762 {
9763         int rc;
9764
9765         if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
9766                 return (EINVAL);
9767
9768         if (i2cd->len > sizeof(i2cd->data))
9769                 return (EFBIG);
9770
9771         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
9772         if (rc)
9773                 return (rc);
9774         rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
9775             i2cd->offset, i2cd->len, &i2cd->data[0]);
9776         end_synchronized_op(sc, 0);
9777
9778         return (rc);
9779 }
9780
9781 int
9782 t4_os_find_pci_capability(struct adapter *sc, int cap)
9783 {
9784         int i;
9785
9786         return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
9787 }
9788
9789 int
9790 t4_os_pci_save_state(struct adapter *sc)
9791 {
9792         device_t dev;
9793         struct pci_devinfo *dinfo;
9794
9795         dev = sc->dev;
9796         dinfo = device_get_ivars(dev);
9797
9798         pci_cfg_save(dev, dinfo, 0);
9799         return (0);
9800 }
9801
9802 int
9803 t4_os_pci_restore_state(struct adapter *sc)
9804 {
9805         device_t dev;
9806         struct pci_devinfo *dinfo;
9807
9808         dev = sc->dev;
9809         dinfo = device_get_ivars(dev);
9810
9811         pci_cfg_restore(dev, dinfo);
9812         return (0);
9813 }
9814
9815 void
9816 t4_os_portmod_changed(struct port_info *pi)
9817 {
9818         struct adapter *sc = pi->adapter;
9819         struct vi_info *vi;
9820         struct ifnet *ifp;
9821         static const char *mod_str[] = {
9822                 NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
9823         };
9824
9825         KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
9826             ("%s: port_type %u", __func__, pi->port_type));
9827
9828         vi = &pi->vi[0];
9829         if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
9830                 PORT_LOCK(pi);
9831                 build_medialist(pi);
9832                 if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
9833                         fixup_link_config(pi);
9834                         apply_link_config(pi);
9835                 }
9836                 PORT_UNLOCK(pi);
9837                 end_synchronized_op(sc, LOCK_HELD);
9838         }
9839
9840         ifp = vi->ifp;
9841         if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
9842                 if_printf(ifp, "transceiver unplugged.\n");
9843         else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
9844                 if_printf(ifp, "unknown transceiver inserted.\n");
9845         else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
9846                 if_printf(ifp, "unsupported transceiver inserted.\n");
9847         else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
9848                 if_printf(ifp, "%dGbps %s transceiver inserted.\n",
9849                     port_top_speed(pi), mod_str[pi->mod_type]);
9850         } else {
9851                 if_printf(ifp, "transceiver (type %d) inserted.\n",
9852                     pi->mod_type);
9853         }
9854 }
9855
9856 void
9857 t4_os_link_changed(struct port_info *pi)
9858 {
9859         struct vi_info *vi;
9860         struct ifnet *ifp;
9861         struct link_config *lc;
9862         int v;
9863
9864         PORT_LOCK_ASSERT_OWNED(pi);
9865
9866         for_each_vi(pi, v, vi) {
9867                 ifp = vi->ifp;
9868                 if (ifp == NULL)
9869                         continue;
9870
9871                 lc = &pi->link_cfg;
9872                 if (lc->link_ok) {
9873                         ifp->if_baudrate = IF_Mbps(lc->speed);
9874                         if_link_state_change(ifp, LINK_STATE_UP);
9875                 } else {
9876                         if_link_state_change(ifp, LINK_STATE_DOWN);
9877                 }
9878         }
9879 }
9880
9881 void
9882 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
9883 {
9884         struct adapter *sc;
9885
9886         sx_slock(&t4_list_lock);
9887         SLIST_FOREACH(sc, &t4_list, link) {
9888                 /*
9889                  * func should not make any assumptions about what state sc is
9890                  * in - the only guarantee is that sc->sc_lock is a valid lock.
9891                  */
9892                 func(sc, arg);
9893         }
9894         sx_sunlock(&t4_list_lock);
9895 }
9896
9897 static int
9898 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
9899     struct thread *td)
9900 {
9901         int rc;
9902         struct adapter *sc = dev->si_drv1;
9903
9904         rc = priv_check(td, PRIV_DRIVER);
9905         if (rc != 0)
9906                 return (rc);
9907
9908         switch (cmd) {
9909         case CHELSIO_T4_GETREG: {
9910                 struct t4_reg *edata = (struct t4_reg *)data;
9911
9912                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
9913                         return (EFAULT);
9914
9915                 if (edata->size == 4)
9916                         edata->val = t4_read_reg(sc, edata->addr);
9917                 else if (edata->size == 8)
9918                         edata->val = t4_read_reg64(sc, edata->addr);
9919                 else
9920                         return (EINVAL);
9921
9922                 break;
9923         }
9924         case CHELSIO_T4_SETREG: {
9925                 struct t4_reg *edata = (struct t4_reg *)data;
9926
9927                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
9928                         return (EFAULT);
9929
9930                 if (edata->size == 4) {
9931                         if (edata->val & 0xffffffff00000000)
9932                                 return (EINVAL);
9933                         t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
9934                 } else if (edata->size == 8)
9935                         t4_write_reg64(sc, edata->addr, edata->val);
9936                 else
9937                         return (EINVAL);
9938                 break;
9939         }
9940         case CHELSIO_T4_REGDUMP: {
9941                 struct t4_regdump *regs = (struct t4_regdump *)data;
9942                 int reglen = t4_get_regs_len(sc);
9943                 uint8_t *buf;
9944
9945                 if (regs->len < reglen) {
9946                         regs->len = reglen; /* hint to the caller */
9947                         return (ENOBUFS);
9948                 }
9949
9950                 regs->len = reglen;
9951                 buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
9952                 get_regs(sc, regs, buf);
9953                 rc = copyout(buf, regs->data, reglen);
9954                 free(buf, M_CXGBE);
9955                 break;
9956         }
9957         case CHELSIO_T4_GET_FILTER_MODE:
9958                 rc = get_filter_mode(sc, (uint32_t *)data);
9959                 break;
9960         case CHELSIO_T4_SET_FILTER_MODE:
9961                 rc = set_filter_mode(sc, *(uint32_t *)data);
9962                 break;
9963         case CHELSIO_T4_GET_FILTER:
9964                 rc = get_filter(sc, (struct t4_filter *)data);
9965                 break;
9966         case CHELSIO_T4_SET_FILTER:
9967                 rc = set_filter(sc, (struct t4_filter *)data);
9968                 break;
9969         case CHELSIO_T4_DEL_FILTER:
9970                 rc = del_filter(sc, (struct t4_filter *)data);
9971                 break;
9972         case CHELSIO_T4_GET_SGE_CONTEXT:
9973                 rc = get_sge_context(sc, (struct t4_sge_context *)data);
9974                 break;
9975         case CHELSIO_T4_LOAD_FW:
9976                 rc = load_fw(sc, (struct t4_data *)data);
9977                 break;
9978         case CHELSIO_T4_GET_MEM:
9979                 rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
9980                 break;
9981         case CHELSIO_T4_GET_I2C:
9982                 rc = read_i2c(sc, (struct t4_i2c_data *)data);
9983                 break;
9984         case CHELSIO_T4_CLEAR_STATS: {
9985                 int i, v, bg_map;
9986                 u_int port_id = *(uint32_t *)data;
9987                 struct port_info *pi;
9988                 struct vi_info *vi;
9989
9990                 if (port_id >= sc->params.nports)
9991                         return (EINVAL);
9992                 pi = sc->port[port_id];
9993                 if (pi == NULL)
9994                         return (EIO);
9995
9996                 /* MAC stats */
9997                 t4_clr_port_stats(sc, pi->tx_chan);
9998                 pi->tx_parse_error = 0;
9999                 pi->tnl_cong_drops = 0;
10000                 mtx_lock(&sc->reg_lock);
10001                 for_each_vi(pi, v, vi) {
10002                         if (vi->flags & VI_INIT_DONE)
10003                                 t4_clr_vi_stats(sc, vi->vin);
10004                 }
10005                 bg_map = pi->mps_bg_map;
10006                 v = 0;  /* reuse */
10007                 while (bg_map) {
10008                         i = ffs(bg_map) - 1;
10009                         t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
10010                             1, A_TP_MIB_TNL_CNG_DROP_0 + i);
10011                         bg_map &= ~(1 << i);
10012                 }
10013                 mtx_unlock(&sc->reg_lock);
10014
10015                 /*
10016                  * Since this command accepts a port, clear stats for
10017                  * all VIs on this port.
10018                  */
10019                 for_each_vi(pi, v, vi) {
10020                         if (vi->flags & VI_INIT_DONE) {
10021                                 struct sge_rxq *rxq;
10022                                 struct sge_txq *txq;
10023                                 struct sge_wrq *wrq;
10024
10025                                 for_each_rxq(vi, i, rxq) {
10026 #if defined(INET) || defined(INET6)
10027                                         rxq->lro.lro_queued = 0;
10028                                         rxq->lro.lro_flushed = 0;
10029 #endif
10030                                         rxq->rxcsum = 0;
10031                                         rxq->vlan_extraction = 0;
10032                                 }
10033
10034                                 for_each_txq(vi, i, txq) {
10035                                         txq->txcsum = 0;
10036                                         txq->tso_wrs = 0;
10037                                         txq->vlan_insertion = 0;
10038                                         txq->imm_wrs = 0;
10039                                         txq->sgl_wrs = 0;
10040                                         txq->txpkt_wrs = 0;
10041                                         txq->txpkts0_wrs = 0;
10042                                         txq->txpkts1_wrs = 0;
10043                                         txq->txpkts0_pkts = 0;
10044                                         txq->txpkts1_pkts = 0;
10045                                         mp_ring_reset_stats(txq->r);
10046                                 }
10047
10048 #ifdef TCP_OFFLOAD
10049                                 /* nothing to clear for each ofld_rxq */
10050
10051                                 for_each_ofld_txq(vi, i, wrq) {
10052                                         wrq->tx_wrs_direct = 0;
10053                                         wrq->tx_wrs_copied = 0;
10054                                 }
10055 #endif
10056
10057                                 if (IS_MAIN_VI(vi)) {
10058                                         wrq = &sc->sge.ctrlq[pi->port_id];
10059                                         wrq->tx_wrs_direct = 0;
10060                                         wrq->tx_wrs_copied = 0;
10061                                 }
10062                         }
10063                 }
10064                 break;
10065         }
10066         case CHELSIO_T4_SCHED_CLASS:
10067                 rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
10068                 break;
10069         case CHELSIO_T4_SCHED_QUEUE:
10070                 rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
10071                 break;
10072         case CHELSIO_T4_GET_TRACER:
10073                 rc = t4_get_tracer(sc, (struct t4_tracer *)data);
10074                 break;
10075         case CHELSIO_T4_SET_TRACER:
10076                 rc = t4_set_tracer(sc, (struct t4_tracer *)data);
10077                 break;
10078         case CHELSIO_T4_LOAD_CFG:
10079                 rc = load_cfg(sc, (struct t4_data *)data);
10080                 break;
10081         case CHELSIO_T4_LOAD_BOOT:
10082                 rc = load_boot(sc, (struct t4_bootrom *)data);
10083                 break;
10084         case CHELSIO_T4_LOAD_BOOTCFG:
10085                 rc = load_bootcfg(sc, (struct t4_data *)data);
10086                 break;
10087         case CHELSIO_T4_CUDBG_DUMP:
10088                 rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
10089                 break;
10090         case CHELSIO_T4_SET_OFLD_POLICY:
10091                 rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
10092                 break;
10093         default:
10094                 rc = ENOTTY;
10095         }
10096
10097         return (rc);
10098 }
10099
10100 #ifdef TCP_OFFLOAD
10101 void
10102 t4_iscsi_init(struct adapter *sc, u_int tag_mask, const u_int *pgsz_order)
10103 {
10104
10105         t4_write_reg(sc, A_ULP_RX_ISCSI_TAGMASK, tag_mask);
10106         t4_write_reg(sc, A_ULP_RX_ISCSI_PSZ, V_HPZ0(pgsz_order[0]) |
10107                 V_HPZ1(pgsz_order[1]) | V_HPZ2(pgsz_order[2]) |
10108                 V_HPZ3(pgsz_order[3]));
10109 }
10110
10111 static int
10112 toe_capability(struct vi_info *vi, int enable)
10113 {
10114         int rc;
10115         struct port_info *pi = vi->pi;
10116         struct adapter *sc = pi->adapter;
10117
10118         ASSERT_SYNCHRONIZED_OP(sc);
10119
10120         if (!is_offload(sc))
10121                 return (ENODEV);
10122
10123         if (enable) {
10124                 if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
10125                         /* TOE is already enabled. */
10126                         return (0);
10127                 }
10128
10129                 /*
10130                  * We need the port's queues around so that we're able to send
10131                  * and receive CPLs to/from the TOE even if the ifnet for this
10132                  * port has never been UP'd administratively.
10133                  */
10134                 if (!(vi->flags & VI_INIT_DONE)) {
10135                         rc = vi_full_init(vi);
10136                         if (rc)
10137                                 return (rc);
10138                 }
10139                 if (!(pi->vi[0].flags & VI_INIT_DONE)) {
10140                         rc = vi_full_init(&pi->vi[0]);
10141                         if (rc)
10142                                 return (rc);
10143                 }
10144
10145                 if (isset(&sc->offload_map, pi->port_id)) {
10146                         /* TOE is enabled on another VI of this port. */
10147                         pi->uld_vis++;
10148                         return (0);
10149                 }
10150
10151                 if (!uld_active(sc, ULD_TOM)) {
10152                         rc = t4_activate_uld(sc, ULD_TOM);
10153                         if (rc == EAGAIN) {
10154                                 log(LOG_WARNING,
10155                                     "You must kldload t4_tom.ko before trying "
10156                                     "to enable TOE on a cxgbe interface.\n");
10157                         }
10158                         if (rc != 0)
10159                                 return (rc);
10160                         KASSERT(sc->tom_softc != NULL,
10161                             ("%s: TOM activated but softc NULL", __func__));
10162                         KASSERT(uld_active(sc, ULD_TOM),
10163                             ("%s: TOM activated but flag not set", __func__));
10164                 }
10165
10166                 /* Activate iWARP and iSCSI too, if the modules are loaded. */
10167                 if (!uld_active(sc, ULD_IWARP))
10168                         (void) t4_activate_uld(sc, ULD_IWARP);
10169                 if (!uld_active(sc, ULD_ISCSI))
10170                         (void) t4_activate_uld(sc, ULD_ISCSI);
10171
10172                 pi->uld_vis++;
10173                 setbit(&sc->offload_map, pi->port_id);
10174         } else {
10175                 pi->uld_vis--;
10176
10177                 if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
10178                         return (0);
10179
10180                 KASSERT(uld_active(sc, ULD_TOM),
10181                     ("%s: TOM never initialized?", __func__));
10182                 clrbit(&sc->offload_map, pi->port_id);
10183         }
10184
10185         return (0);
10186 }
10187
10188 /*
10189  * Add an upper layer driver to the global list.
10190  */
10191 int
10192 t4_register_uld(struct uld_info *ui)
10193 {
10194         int rc = 0;
10195         struct uld_info *u;
10196
10197         sx_xlock(&t4_uld_list_lock);
10198         SLIST_FOREACH(u, &t4_uld_list, link) {
10199             if (u->uld_id == ui->uld_id) {
10200                     rc = EEXIST;
10201                     goto done;
10202             }
10203         }
10204
10205         SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
10206         ui->refcount = 0;
10207 done:
10208         sx_xunlock(&t4_uld_list_lock);
10209         return (rc);
10210 }
10211
10212 int
10213 t4_unregister_uld(struct uld_info *ui)
10214 {
10215         int rc = EINVAL;
10216         struct uld_info *u;
10217
10218         sx_xlock(&t4_uld_list_lock);
10219
10220         SLIST_FOREACH(u, &t4_uld_list, link) {
10221             if (u == ui) {
10222                     if (ui->refcount > 0) {
10223                             rc = EBUSY;
10224                             goto done;
10225                     }
10226
10227                     SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
10228                     rc = 0;
10229                     goto done;
10230             }
10231         }
10232 done:
10233         sx_xunlock(&t4_uld_list_lock);
10234         return (rc);
10235 }
10236
10237 int
10238 t4_activate_uld(struct adapter *sc, int id)
10239 {
10240         int rc;
10241         struct uld_info *ui;
10242
10243         ASSERT_SYNCHRONIZED_OP(sc);
10244
10245         if (id < 0 || id > ULD_MAX)
10246                 return (EINVAL);
10247         rc = EAGAIN;    /* kldoad the module with this ULD and try again. */
10248
10249         sx_slock(&t4_uld_list_lock);
10250
10251         SLIST_FOREACH(ui, &t4_uld_list, link) {
10252                 if (ui->uld_id == id) {
10253                         if (!(sc->flags & FULL_INIT_DONE)) {
10254                                 rc = adapter_full_init(sc);
10255                                 if (rc != 0)
10256                                         break;
10257                         }
10258
10259                         rc = ui->activate(sc);
10260                         if (rc == 0) {
10261                                 setbit(&sc->active_ulds, id);
10262                                 ui->refcount++;
10263                         }
10264                         break;
10265                 }
10266         }
10267
10268         sx_sunlock(&t4_uld_list_lock);
10269
10270         return (rc);
10271 }
10272
10273 int
10274 t4_deactivate_uld(struct adapter *sc, int id)
10275 {
10276         int rc;
10277         struct uld_info *ui;
10278
10279         ASSERT_SYNCHRONIZED_OP(sc);
10280
10281         if (id < 0 || id > ULD_MAX)
10282                 return (EINVAL);
10283         rc = ENXIO;
10284
10285         sx_slock(&t4_uld_list_lock);
10286
10287         SLIST_FOREACH(ui, &t4_uld_list, link) {
10288                 if (ui->uld_id == id) {
10289                         rc = ui->deactivate(sc);
10290                         if (rc == 0) {
10291                                 clrbit(&sc->active_ulds, id);
10292                                 ui->refcount--;
10293                         }
10294                         break;
10295                 }
10296         }
10297
10298         sx_sunlock(&t4_uld_list_lock);
10299
10300         return (rc);
10301 }
10302
10303 int
10304 uld_active(struct adapter *sc, int uld_id)
10305 {
10306
10307         MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
10308
10309         return (isset(&sc->active_ulds, uld_id));
10310 }
10311 #endif
10312
10313 /*
10314  * t  = ptr to tunable.
10315  * nc = number of CPUs.
10316  * c  = compiled in default for that tunable.
10317  */
10318 static void
10319 calculate_nqueues(int *t, int nc, const int c)
10320 {
10321         int nq;
10322
10323         if (*t > 0)
10324                 return;
10325         nq = *t < 0 ? -*t : c;
10326         *t = min(nc, nq);
10327 }
10328
10329 /*
10330  * Come up with reasonable defaults for some of the tunables, provided they're
10331  * not set by the user (in which case we'll use the values as is).
10332  */
10333 static void
10334 tweak_tunables(void)
10335 {
10336         int nc = mp_ncpus;      /* our snapshot of the number of CPUs */
10337
10338         if (t4_ntxq < 1) {
10339 #ifdef RSS
10340                 t4_ntxq = rss_getnumbuckets();
10341 #else
10342                 calculate_nqueues(&t4_ntxq, nc, NTXQ);
10343 #endif
10344         }
10345
10346         calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
10347
10348         if (t4_nrxq < 1) {
10349 #ifdef RSS
10350                 t4_nrxq = rss_getnumbuckets();
10351 #else
10352                 calculate_nqueues(&t4_nrxq, nc, NRXQ);
10353 #endif
10354         }
10355
10356         calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
10357
10358 #ifdef TCP_OFFLOAD
10359         calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
10360         calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
10361         calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
10362         calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
10363
10364         if (t4_toecaps_allowed == -1)
10365                 t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
10366
10367         if (t4_rdmacaps_allowed == -1) {
10368                 t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
10369                     FW_CAPS_CONFIG_RDMA_RDMAC;
10370         }
10371
10372         if (t4_iscsicaps_allowed == -1) {
10373                 t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
10374                     FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
10375                     FW_CAPS_CONFIG_ISCSI_T10DIF;
10376         }
10377
10378         if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
10379                 t4_tmr_idx_ofld = TMR_IDX_OFLD;
10380
10381         if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
10382                 t4_pktc_idx_ofld = PKTC_IDX_OFLD;
10383 #else
10384         if (t4_toecaps_allowed == -1)
10385                 t4_toecaps_allowed = 0;
10386
10387         if (t4_rdmacaps_allowed == -1)
10388                 t4_rdmacaps_allowed = 0;
10389
10390         if (t4_iscsicaps_allowed == -1)
10391                 t4_iscsicaps_allowed = 0;
10392 #endif
10393
10394 #ifdef DEV_NETMAP
10395         calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
10396         calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
10397 #endif
10398
10399         if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
10400                 t4_tmr_idx = TMR_IDX;
10401
10402         if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
10403                 t4_pktc_idx = PKTC_IDX;
10404
10405         if (t4_qsize_txq < 128)
10406                 t4_qsize_txq = 128;
10407
10408         if (t4_qsize_rxq < 128)
10409                 t4_qsize_rxq = 128;
10410         while (t4_qsize_rxq & 7)
10411                 t4_qsize_rxq++;
10412
10413         t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
10414
10415         /*
10416          * Number of VIs to create per-port.  The first VI is the "main" regular
10417          * VI for the port.  The rest are additional virtual interfaces on the
10418          * same physical port.  Note that the main VI does not have native
10419          * netmap support but the extra VIs do.
10420          *
10421          * Limit the number of VIs per port to the number of available
10422          * MAC addresses per port.
10423          */
10424         if (t4_num_vis < 1)
10425                 t4_num_vis = 1;
10426         if (t4_num_vis > nitems(vi_mac_funcs)) {
10427                 t4_num_vis = nitems(vi_mac_funcs);
10428                 printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
10429         }
10430
10431         if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
10432                 pcie_relaxed_ordering = 1;
10433 #if defined(__i386__) || defined(__amd64__)
10434                 if (cpu_vendor_id == CPU_VENDOR_INTEL)
10435                         pcie_relaxed_ordering = 0;
10436 #endif
10437         }
10438 }
10439
10440 #ifdef DDB
10441 static void
10442 t4_dump_tcb(struct adapter *sc, int tid)
10443 {
10444         uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
10445
10446         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
10447         save = t4_read_reg(sc, reg);
10448         base = sc->memwin[2].mw_base;
10449
10450         /* Dump TCB for the tid */
10451         tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
10452         tcb_addr += tid * TCB_SIZE;
10453
10454         if (is_t4(sc)) {
10455                 pf = 0;
10456                 win_pos = tcb_addr & ~0xf;      /* start must be 16B aligned */
10457         } else {
10458                 pf = V_PFNUM(sc->pf);
10459                 win_pos = tcb_addr & ~0x7f;     /* start must be 128B aligned */
10460         }
10461         t4_write_reg(sc, reg, win_pos | pf);
10462         t4_read_reg(sc, reg);
10463
10464         off = tcb_addr - win_pos;
10465         for (i = 0; i < 4; i++) {
10466                 uint32_t buf[8];
10467                 for (j = 0; j < 8; j++, off += 4)
10468                         buf[j] = htonl(t4_read_reg(sc, base + off));
10469
10470                 db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
10471                     buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
10472                     buf[7]);
10473         }
10474
10475         t4_write_reg(sc, reg, save);
10476         t4_read_reg(sc, reg);
10477 }
10478
10479 static void
10480 t4_dump_devlog(struct adapter *sc)
10481 {
10482         struct devlog_params *dparams = &sc->params.devlog;
10483         struct fw_devlog_e e;
10484         int i, first, j, m, nentries, rc;
10485         uint64_t ftstamp = UINT64_MAX;
10486
10487         if (dparams->start == 0) {
10488                 db_printf("devlog params not valid\n");
10489                 return;
10490         }
10491
10492         nentries = dparams->size / sizeof(struct fw_devlog_e);
10493         m = fwmtype_to_hwmtype(dparams->memtype);
10494
10495         /* Find the first entry. */
10496         first = -1;
10497         for (i = 0; i < nentries && !db_pager_quit; i++) {
10498                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
10499                     sizeof(e), (void *)&e);
10500                 if (rc != 0)
10501                         break;
10502
10503                 if (e.timestamp == 0)
10504                         break;
10505
10506                 e.timestamp = be64toh(e.timestamp);
10507                 if (e.timestamp < ftstamp) {
10508                         ftstamp = e.timestamp;
10509                         first = i;
10510                 }
10511         }
10512
10513         if (first == -1)
10514                 return;
10515
10516         i = first;
10517         do {
10518                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
10519                     sizeof(e), (void *)&e);
10520                 if (rc != 0)
10521                         return;
10522
10523                 if (e.timestamp == 0)
10524                         return;
10525
10526                 e.timestamp = be64toh(e.timestamp);
10527                 e.seqno = be32toh(e.seqno);
10528                 for (j = 0; j < 8; j++)
10529                         e.params[j] = be32toh(e.params[j]);
10530
10531                 db_printf("%10d  %15ju  %8s  %8s  ",
10532                     e.seqno, e.timestamp,
10533                     (e.level < nitems(devlog_level_strings) ?
10534                         devlog_level_strings[e.level] : "UNKNOWN"),
10535                     (e.facility < nitems(devlog_facility_strings) ?
10536                         devlog_facility_strings[e.facility] : "UNKNOWN"));
10537                 db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
10538                     e.params[3], e.params[4], e.params[5], e.params[6],
10539                     e.params[7]);
10540
10541                 if (++i == nentries)
10542                         i = 0;
10543         } while (i != first && !db_pager_quit);
10544 }
10545
10546 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
10547 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
10548
10549 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
10550 {
10551         device_t dev;
10552         int t;
10553         bool valid;
10554
10555         valid = false;
10556         t = db_read_token();
10557         if (t == tIDENT) {
10558                 dev = device_lookup_by_name(db_tok_string);
10559                 valid = true;
10560         }
10561         db_skip_to_eol();
10562         if (!valid) {
10563                 db_printf("usage: show t4 devlog <nexus>\n");
10564                 return;
10565         }
10566
10567         if (dev == NULL) {
10568                 db_printf("device not found\n");
10569                 return;
10570         }
10571
10572         t4_dump_devlog(device_get_softc(dev));
10573 }
10574
10575 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
10576 {
10577         device_t dev;
10578         int radix, tid, t;
10579         bool valid;
10580
10581         valid = false;
10582         radix = db_radix;
10583         db_radix = 10;
10584         t = db_read_token();
10585         if (t == tIDENT) {
10586                 dev = device_lookup_by_name(db_tok_string);
10587                 t = db_read_token();
10588                 if (t == tNUMBER) {
10589                         tid = db_tok_number;
10590                         valid = true;
10591                 }
10592         }       
10593         db_radix = radix;
10594         db_skip_to_eol();
10595         if (!valid) {
10596                 db_printf("usage: show t4 tcb <nexus> <tid>\n");
10597                 return;
10598         }
10599
10600         if (dev == NULL) {
10601                 db_printf("device not found\n");
10602                 return;
10603         }
10604         if (tid < 0) {
10605                 db_printf("invalid tid\n");
10606                 return;
10607         }
10608
10609         t4_dump_tcb(device_get_softc(dev), tid);
10610 }
10611 #endif
10612
10613 /*
10614  * Borrowed from cesa_prep_aes_key().
10615  *
10616  * NB: The crypto engine wants the words in the decryption key in reverse
10617  * order.
10618  */
10619 void
10620 t4_aes_getdeckey(void *dec_key, const void *enc_key, unsigned int kbits)
10621 {
10622         uint32_t ek[4 * (RIJNDAEL_MAXNR + 1)];
10623         uint32_t *dkey;
10624         int i;
10625
10626         rijndaelKeySetupEnc(ek, enc_key, kbits);
10627         dkey = dec_key;
10628         dkey += (kbits / 8) / 4;
10629
10630         switch (kbits) {
10631         case 128:
10632                 for (i = 0; i < 4; i++)
10633                         *--dkey = htobe32(ek[4 * 10 + i]);
10634                 break;
10635         case 192:
10636                 for (i = 0; i < 2; i++)
10637                         *--dkey = htobe32(ek[4 * 11 + 2 + i]);
10638                 for (i = 0; i < 4; i++)
10639                         *--dkey = htobe32(ek[4 * 12 + i]);
10640                 break;
10641         case 256:
10642                 for (i = 0; i < 4; i++)
10643                         *--dkey = htobe32(ek[4 * 13 + i]);
10644                 for (i = 0; i < 4; i++)
10645                         *--dkey = htobe32(ek[4 * 14 + i]);
10646                 break;
10647         }
10648         MPASS(dkey == dec_key);
10649 }
10650
10651 static struct sx mlu;   /* mod load unload */
10652 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
10653
10654 static int
10655 mod_event(module_t mod, int cmd, void *arg)
10656 {
10657         int rc = 0;
10658         static int loaded = 0;
10659
10660         switch (cmd) {
10661         case MOD_LOAD:
10662                 sx_xlock(&mlu);
10663                 if (loaded++ == 0) {
10664                         t4_sge_modload();
10665                         t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
10666                             t4_filter_rpl, CPL_COOKIE_FILTER);
10667                         t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
10668                             do_l2t_write_rpl, CPL_COOKIE_FILTER);
10669                         t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
10670                             t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
10671                         t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
10672                             t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
10673                         t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
10674                             t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
10675                         t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
10676                         t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
10677                         t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
10678                             do_smt_write_rpl);
10679                         sx_init(&t4_list_lock, "T4/T5 adapters");
10680                         SLIST_INIT(&t4_list);
10681                         callout_init(&fatal_callout, 1);
10682 #ifdef TCP_OFFLOAD
10683                         sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
10684                         SLIST_INIT(&t4_uld_list);
10685 #endif
10686 #ifdef INET6
10687                         t4_clip_modload();
10688 #endif
10689                         t4_tracer_modload();
10690                         tweak_tunables();
10691                 }
10692                 sx_xunlock(&mlu);
10693                 break;
10694
10695         case MOD_UNLOAD:
10696                 sx_xlock(&mlu);
10697                 if (--loaded == 0) {
10698                         int tries;
10699
10700                         sx_slock(&t4_list_lock);
10701                         if (!SLIST_EMPTY(&t4_list)) {
10702                                 rc = EBUSY;
10703                                 sx_sunlock(&t4_list_lock);
10704                                 goto done_unload;
10705                         }
10706 #ifdef TCP_OFFLOAD
10707                         sx_slock(&t4_uld_list_lock);
10708                         if (!SLIST_EMPTY(&t4_uld_list)) {
10709                                 rc = EBUSY;
10710                                 sx_sunlock(&t4_uld_list_lock);
10711                                 sx_sunlock(&t4_list_lock);
10712                                 goto done_unload;
10713                         }
10714 #endif
10715                         tries = 0;
10716                         while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
10717                                 uprintf("%ju clusters with custom free routine "
10718                                     "still is use.\n", t4_sge_extfree_refs());
10719                                 pause("t4unload", 2 * hz);
10720                         }
10721 #ifdef TCP_OFFLOAD
10722                         sx_sunlock(&t4_uld_list_lock);
10723 #endif
10724                         sx_sunlock(&t4_list_lock);
10725
10726                         if (t4_sge_extfree_refs() == 0) {
10727                                 t4_tracer_modunload();
10728 #ifdef INET6
10729                                 t4_clip_modunload();
10730 #endif
10731 #ifdef TCP_OFFLOAD
10732                                 sx_destroy(&t4_uld_list_lock);
10733 #endif
10734                                 sx_destroy(&t4_list_lock);
10735                                 t4_sge_modunload();
10736                                 loaded = 0;
10737                         } else {
10738                                 rc = EBUSY;
10739                                 loaded++;       /* undo earlier decrement */
10740                         }
10741                 }
10742 done_unload:
10743                 sx_xunlock(&mlu);
10744                 break;
10745         }
10746
10747         return (rc);
10748 }
10749
10750 static devclass_t t4_devclass, t5_devclass, t6_devclass;
10751 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
10752 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
10753
10754 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
10755 MODULE_VERSION(t4nex, 1);
10756 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
10757 #ifdef DEV_NETMAP
10758 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
10759 #endif /* DEV_NETMAP */
10760
10761 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
10762 MODULE_VERSION(t5nex, 1);
10763 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
10764 #ifdef DEV_NETMAP
10765 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
10766 #endif /* DEV_NETMAP */
10767
10768 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
10769 MODULE_VERSION(t6nex, 1);
10770 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
10771 #ifdef DEV_NETMAP
10772 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
10773 #endif /* DEV_NETMAP */
10774
10775 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
10776 MODULE_VERSION(cxgbe, 1);
10777
10778 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
10779 MODULE_VERSION(cxl, 1);
10780
10781 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
10782 MODULE_VERSION(cc, 1);
10783
10784 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
10785 MODULE_VERSION(vcxgbe, 1);
10786
10787 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
10788 MODULE_VERSION(vcxl, 1);
10789
10790 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
10791 MODULE_VERSION(vcc, 1);