Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / drivers / net / phantom / phantom.c
1 /*
2  * Copyright (C) 2008 Michael Brown <mbrown@fensystems.co.uk>.
3  * Copyright (C) 2008 NetXen, Inc.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18  * 02110-1301, USA.
19  */
20
21 FILE_LICENCE ( GPL2_OR_LATER );
22
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <assert.h>
29 #include <byteswap.h>
30 #include <ipxe/pci.h>
31 #include <ipxe/io.h>
32 #include <ipxe/malloc.h>
33 #include <ipxe/iobuf.h>
34 #include <ipxe/netdevice.h>
35 #include <ipxe/if_ether.h>
36 #include <ipxe/ethernet.h>
37 #include <ipxe/spi.h>
38 #include <ipxe/settings.h>
39 #include "phantom.h"
40
41 /**
42  * @file
43  *
44  * NetXen Phantom NICs
45  *
46  */
47
48 /** Maximum number of ports */
49 #define PHN_MAX_NUM_PORTS 8
50
51 /** Maximum time to wait for command PEG to initialise
52  *
53  * BUGxxxx
54  *
55  * The command PEG will currently report initialisation complete only
56  * when at least one PHY has detected a link (so that the global PHY
57  * clock can be set to 10G/1G as appropriate).  This can take a very,
58  * very long time.
59  *
60  * A future firmware revision should decouple PHY initialisation from
61  * firmware initialisation, at which point the command PEG will report
62  * initialisation complete much earlier, and this timeout can be
63  * reduced.
64  */
65 #define PHN_CMDPEG_INIT_TIMEOUT_SEC 50
66
67 /** Maximum time to wait for receive PEG to initialise */
68 #define PHN_RCVPEG_INIT_TIMEOUT_SEC 2
69
70 /** Maximum time to wait for firmware to accept a command */
71 #define PHN_ISSUE_CMD_TIMEOUT_MS 2000
72
73 /** Maximum time to wait for test memory */
74 #define PHN_TEST_MEM_TIMEOUT_MS 100
75
76 /** Maximum time to wait for CLP command to be issued */
77 #define PHN_CLP_CMD_TIMEOUT_MS 500
78
79 /** Link state poll frequency
80  *
81  * The link state will be checked once in every N calls to poll().
82  */
83 #define PHN_LINK_POLL_FREQUENCY 4096
84
85 /** Number of RX descriptors */
86 #define PHN_NUM_RDS 32
87
88 /** RX maximum fill level.  Must be strictly less than PHN_NUM_RDS. */
89 #define PHN_RDS_MAX_FILL 16
90
91 /** RX buffer size */
92 #define PHN_RX_BUFSIZE ( 32 /* max LL padding added by card */ + \
93                          ETH_FRAME_LEN )
94
95 /** Number of RX status descriptors */
96 #define PHN_NUM_SDS 32
97
98 /** Number of TX descriptors */
99 #define PHN_NUM_CDS 8
100
101 /** A Phantom descriptor ring set */
102 struct phantom_descriptor_rings {
103         /** RX descriptors */
104         struct phantom_rds rds[PHN_NUM_RDS];
105         /** RX status descriptors */
106         struct phantom_sds sds[PHN_NUM_SDS];
107         /** TX descriptors */
108         union phantom_cds cds[PHN_NUM_CDS];
109         /** TX consumer index */
110         volatile uint32_t cmd_cons;
111 };
112
113 /** RX context creation request and response buffers */
114 struct phantom_create_rx_ctx_rqrsp {
115         struct {
116                 struct nx_hostrq_rx_ctx_s rx_ctx;
117                 struct nx_hostrq_rds_ring_s rds;
118                 struct nx_hostrq_sds_ring_s sds;
119         } __unm_dma_aligned hostrq;
120         struct {
121                 struct nx_cardrsp_rx_ctx_s rx_ctx;
122                 struct nx_cardrsp_rds_ring_s rds;
123                 struct nx_cardrsp_sds_ring_s sds;
124         } __unm_dma_aligned cardrsp;
125 };
126
127 /** TX context creation request and response buffers */
128 struct phantom_create_tx_ctx_rqrsp {
129         struct {
130                 struct nx_hostrq_tx_ctx_s tx_ctx;
131         } __unm_dma_aligned hostrq;
132         struct {
133                 struct nx_cardrsp_tx_ctx_s tx_ctx;
134         } __unm_dma_aligned cardrsp;
135 };
136
137 /** A Phantom NIC */
138 struct phantom_nic {
139         /** BAR 0 */
140         void *bar0;
141         /** Current CRB window */
142         unsigned long crb_window;
143         /** CRB window access method */
144         unsigned long ( *crb_access ) ( struct phantom_nic *phantom,
145                                         unsigned long reg );
146
147
148         /** Port number */
149         unsigned int port;
150
151
152         /** RX context ID */
153         uint16_t rx_context_id;
154         /** RX descriptor producer CRB offset */
155         unsigned long rds_producer_crb;
156         /** RX status descriptor consumer CRB offset */
157         unsigned long sds_consumer_crb;
158         /** RX interrupt mask CRB offset */
159         unsigned long sds_irq_mask_crb;
160         /** RX interrupts enabled */
161         unsigned int sds_irq_enabled;
162
163         /** RX producer index */
164         unsigned int rds_producer_idx;
165         /** RX consumer index */
166         unsigned int rds_consumer_idx;
167         /** RX status consumer index */
168         unsigned int sds_consumer_idx;
169         /** RX I/O buffers */
170         struct io_buffer *rds_iobuf[PHN_RDS_MAX_FILL];
171
172
173         /** TX context ID */
174         uint16_t tx_context_id;
175         /** TX descriptor producer CRB offset */
176         unsigned long cds_producer_crb;
177
178         /** TX producer index */
179         unsigned int cds_producer_idx;
180         /** TX consumer index */
181         unsigned int cds_consumer_idx;
182         /** TX I/O buffers */
183         struct io_buffer *cds_iobuf[PHN_NUM_CDS];
184
185
186         /** Descriptor rings */
187         struct phantom_descriptor_rings *desc;
188
189
190         /** Last known link state */
191         uint32_t link_state;
192         /** Link state poll timer */
193         unsigned long link_poll_timer;
194
195
196         /** Non-volatile settings */
197         struct settings settings;
198 };
199
200 /** Interrupt mask registers */
201 static const unsigned long phantom_irq_mask_reg[PHN_MAX_NUM_PORTS] = {
202         UNM_PCIE_IRQ_MASK_F0,
203         UNM_PCIE_IRQ_MASK_F1,
204         UNM_PCIE_IRQ_MASK_F2,
205         UNM_PCIE_IRQ_MASK_F3,
206         UNM_PCIE_IRQ_MASK_F4,
207         UNM_PCIE_IRQ_MASK_F5,
208         UNM_PCIE_IRQ_MASK_F6,
209         UNM_PCIE_IRQ_MASK_F7,
210 };
211
212 /** Interrupt status registers */
213 static const unsigned long phantom_irq_status_reg[PHN_MAX_NUM_PORTS] = {
214         UNM_PCIE_IRQ_STATUS_F0,
215         UNM_PCIE_IRQ_STATUS_F1,
216         UNM_PCIE_IRQ_STATUS_F2,
217         UNM_PCIE_IRQ_STATUS_F3,
218         UNM_PCIE_IRQ_STATUS_F4,
219         UNM_PCIE_IRQ_STATUS_F5,
220         UNM_PCIE_IRQ_STATUS_F6,
221         UNM_PCIE_IRQ_STATUS_F7,
222 };
223
224 /***************************************************************************
225  *
226  * CRB register access
227  *
228  */
229
230 /**
231  * Prepare for access to CRB register via 128MB BAR
232  *
233  * @v phantom           Phantom NIC
234  * @v reg               Register offset within abstract address space
235  * @ret offset          Register offset within PCI BAR0
236  */
237 static unsigned long phantom_crb_access_128m ( struct phantom_nic *phantom,
238                                                unsigned long reg ) {
239         unsigned long offset = ( 0x6000000 + ( reg & 0x1ffffff ) );
240         uint32_t window = ( reg & 0x2000000 );
241         uint32_t verify_window;
242
243         if ( phantom->crb_window != window ) {
244
245                 /* Write to the CRB window register */
246                 writel ( window, phantom->bar0 + UNM_128M_CRB_WINDOW );
247
248                 /* Ensure that the write has reached the card */
249                 verify_window = readl ( phantom->bar0 + UNM_128M_CRB_WINDOW );
250                 assert ( verify_window == window );
251
252                 /* Record new window */
253                 phantom->crb_window = window;
254         }
255
256         return offset;
257 }
258
259 /**
260  * Prepare for access to CRB register via 32MB BAR
261  *
262  * @v phantom           Phantom NIC
263  * @v reg               Register offset within abstract address space
264  * @ret offset          Register offset within PCI BAR0
265  */
266 static unsigned long phantom_crb_access_32m ( struct phantom_nic *phantom,
267                                               unsigned long reg ) {
268         unsigned long offset = ( reg & 0x1ffffff );
269         uint32_t window = ( reg & 0x2000000 );
270         uint32_t verify_window;
271
272         if ( phantom->crb_window != window ) {
273
274                 /* Write to the CRB window register */
275                 writel ( window, phantom->bar0 + UNM_32M_CRB_WINDOW );
276
277                 /* Ensure that the write has reached the card */
278                 verify_window = readl ( phantom->bar0 + UNM_32M_CRB_WINDOW );
279                 assert ( verify_window == window );
280
281                 /* Record new window */
282                 phantom->crb_window = window;
283         }
284
285         return offset;
286 }
287
288 /**
289  * Prepare for access to CRB register via 2MB BAR
290  *
291  * @v phantom           Phantom NIC
292  * @v reg               Register offset within abstract address space
293  * @ret offset          Register offset within PCI BAR0
294  */
295 static unsigned long phantom_crb_access_2m ( struct phantom_nic *phantom,
296                                              unsigned long reg ) {
297         static const struct {
298                 uint8_t block;
299                 uint16_t window_hi;
300         } reg_window_hi[] = {
301                 { UNM_CRB_BLK_PCIE,     0x773 },
302                 { UNM_CRB_BLK_CAM,      0x416 },
303                 { UNM_CRB_BLK_ROMUSB,   0x421 },
304                 { UNM_CRB_BLK_TEST,     0x295 },
305                 { UNM_CRB_BLK_PEG_0,    0x340 },
306                 { UNM_CRB_BLK_PEG_1,    0x341 },
307                 { UNM_CRB_BLK_PEG_2,    0x342 },
308                 { UNM_CRB_BLK_PEG_3,    0x343 },
309                 { UNM_CRB_BLK_PEG_4,    0x34b },
310         };
311         unsigned int block = UNM_CRB_BLK ( reg );
312         unsigned long offset = UNM_CRB_OFFSET ( reg );
313         uint32_t window;
314         uint32_t verify_window;
315         unsigned int i;
316
317         for ( i = 0 ; i < ( sizeof ( reg_window_hi ) /
318                             sizeof ( reg_window_hi[0] ) ) ; i++ ) {
319
320                 if ( reg_window_hi[i].block != block )
321                         continue;
322
323                 window = ( ( reg_window_hi[i].window_hi << 20 ) |
324                            ( offset & 0x000f0000 ) );
325
326                 if ( phantom->crb_window != window ) {
327
328                         /* Write to the CRB window register */
329                         writel ( window, phantom->bar0 + UNM_2M_CRB_WINDOW );
330
331                         /* Ensure that the write has reached the card */
332                         verify_window = readl ( phantom->bar0 +
333                                                 UNM_2M_CRB_WINDOW );
334                         assert ( verify_window == window );
335
336                         /* Record new window */
337                         phantom->crb_window = window;
338                 }
339
340                 return ( 0x1e0000 + ( offset & 0xffff ) );
341         }
342
343         assert ( 0 );
344         return 0;
345 }
346
347 /**
348  * Read from Phantom CRB register
349  *
350  * @v phantom           Phantom NIC
351  * @v reg               Register offset within abstract address space
352  * @ret value           Register value
353  */
354 static uint32_t phantom_readl ( struct phantom_nic *phantom,
355                                 unsigned long reg ) {
356         unsigned long offset;
357
358         offset = phantom->crb_access ( phantom, reg );
359         return readl ( phantom->bar0 + offset );
360 }
361
362 /**
363  * Write to Phantom CRB register
364  *
365  * @v phantom           Phantom NIC
366  * @v value             Register value
367  * @v reg               Register offset within abstract address space
368  */
369 static void phantom_writel ( struct phantom_nic *phantom, uint32_t value,
370                              unsigned long reg ) {
371         unsigned long offset;
372
373         offset = phantom->crb_access ( phantom, reg );
374         writel ( value, phantom->bar0 + offset );
375 }
376
377 /**
378  * Write to Phantom CRB HI/LO register pair
379  *
380  * @v phantom           Phantom NIC
381  * @v value             Register value
382  * @v lo_offset         LO register offset within CRB
383  * @v hi_offset         HI register offset within CRB
384  */
385 static inline void phantom_write_hilo ( struct phantom_nic *phantom,
386                                         uint64_t value,
387                                         unsigned long lo_offset,
388                                         unsigned long hi_offset ) {
389         uint32_t lo = ( value & 0xffffffffUL );
390         uint32_t hi = ( value >> 32 );
391
392         phantom_writel ( phantom, lo, lo_offset );
393         phantom_writel ( phantom, hi, hi_offset );
394 }
395
396 /***************************************************************************
397  *
398  * Firmware message buffer access (for debug)
399  *
400  */
401
402 /**
403  * Read from Phantom test memory
404  *
405  * @v phantom           Phantom NIC
406  * @v offset            Offset within test memory
407  * @v buf               8-byte buffer to fill
408  * @ret rc              Return status code
409  */
410 static int phantom_read_test_mem_block ( struct phantom_nic *phantom,
411                                          unsigned long offset,
412                                          uint32_t buf[2] ) {
413         unsigned int retries;
414         uint32_t test_control;
415
416         phantom_write_hilo ( phantom, offset, UNM_TEST_ADDR_LO,
417                              UNM_TEST_ADDR_HI );
418         phantom_writel ( phantom, UNM_TEST_CONTROL_ENABLE, UNM_TEST_CONTROL );
419         phantom_writel ( phantom,
420                          ( UNM_TEST_CONTROL_ENABLE | UNM_TEST_CONTROL_START ),
421                          UNM_TEST_CONTROL );
422         
423         for ( retries = 0 ; retries < PHN_TEST_MEM_TIMEOUT_MS ; retries++ ) {
424                 test_control = phantom_readl ( phantom, UNM_TEST_CONTROL );
425                 if ( ( test_control & UNM_TEST_CONTROL_BUSY ) == 0 ) {
426                         buf[0] = phantom_readl ( phantom, UNM_TEST_RDDATA_LO );
427                         buf[1] = phantom_readl ( phantom, UNM_TEST_RDDATA_HI );
428                         return 0;
429                 }
430                 mdelay ( 1 );
431         }
432
433         DBGC ( phantom, "Phantom %p timed out waiting for test memory\n",
434                phantom );
435         return -ETIMEDOUT;
436 }
437
438 /**
439  * Read single byte from Phantom test memory
440  *
441  * @v phantom           Phantom NIC
442  * @v offset            Offset within test memory
443  * @ret byte            Byte read, or negative error
444  */
445 static int phantom_read_test_mem ( struct phantom_nic *phantom,
446                                    unsigned long offset ) {
447         static union {
448                 uint8_t bytes[8];
449                 uint32_t dwords[2];
450         } cache;
451         static unsigned long cache_offset = -1UL;
452         unsigned long sub_offset;
453         int rc;
454
455         sub_offset = ( offset & ( sizeof ( cache ) - 1 ) );
456         offset = ( offset & ~( sizeof ( cache ) - 1 ) );
457
458         if ( cache_offset != offset ) {
459                 if ( ( rc = phantom_read_test_mem_block ( phantom, offset,
460                                                           cache.dwords )) !=0 )
461                         return rc;
462                 cache_offset = offset;
463         }
464
465         return cache.bytes[sub_offset];
466 }
467
468 /**
469  * Dump Phantom firmware dmesg log
470  *
471  * @v phantom           Phantom NIC
472  * @v log               Log number
473  * @v max_lines         Maximum number of lines to show, or -1 to show all
474  * @ret rc              Return status code
475  */
476 static int phantom_dmesg ( struct phantom_nic *phantom, unsigned int log,
477                             unsigned int max_lines ) {
478         uint32_t head;
479         uint32_t tail;
480         uint32_t sig;
481         uint32_t offset;
482         int byte;
483
484         /* Optimise out for non-debug builds */
485         if ( ! DBG_LOG )
486                 return 0;
487
488         /* Locate log */
489         head = phantom_readl ( phantom, UNM_CAM_RAM_DMESG_HEAD ( log ) );
490         tail = phantom_readl ( phantom, UNM_CAM_RAM_DMESG_TAIL ( log ) );
491         sig = phantom_readl ( phantom, UNM_CAM_RAM_DMESG_SIG ( log ) );
492         DBGC ( phantom, "Phantom %p firmware dmesg buffer %d (%08x-%08x)\n",
493                phantom, log, head, tail );
494         assert ( ( head & 0x07 ) == 0 );
495         if ( sig != UNM_CAM_RAM_DMESG_SIG_MAGIC ) {
496                 DBGC ( phantom, "Warning: bad signature %08x (want %08lx)\n",
497                        sig, UNM_CAM_RAM_DMESG_SIG_MAGIC );
498         }
499
500         /* Locate start of last (max_lines) lines */
501         for ( offset = tail ; offset > head ; offset-- ) {
502                 if ( ( byte = phantom_read_test_mem ( phantom,
503                                                       ( offset - 1 ) ) ) < 0 )
504                         return byte;
505                 if ( ( byte == '\n' ) && ( max_lines-- == 0 ) )
506                         break;
507         }
508
509         /* Print lines */
510         for ( ; offset < tail ; offset++ ) {
511                 if ( ( byte = phantom_read_test_mem ( phantom, offset ) ) < 0 )
512                         return byte;
513                 DBG ( "%c", byte );
514         }
515         DBG ( "\n" );
516         return 0;
517 }
518
519 /**
520  * Dump Phantom firmware dmesg logs
521  *
522  * @v phantom           Phantom NIC
523  * @v max_lines         Maximum number of lines to show, or -1 to show all
524  */
525 static void __attribute__ (( unused ))
526 phantom_dmesg_all ( struct phantom_nic *phantom, unsigned int max_lines ) {
527         unsigned int i;
528
529         for ( i = 0 ; i < UNM_CAM_RAM_NUM_DMESG_BUFFERS ; i++ )
530                 phantom_dmesg ( phantom, i, max_lines );
531 }
532
533 /***************************************************************************
534  *
535  * Firmware interface
536  *
537  */
538
539 /**
540  * Wait for firmware to accept command
541  *
542  * @v phantom           Phantom NIC
543  * @ret rc              Return status code
544  */
545 static int phantom_wait_for_cmd ( struct phantom_nic *phantom ) {
546         unsigned int retries;
547         uint32_t cdrp;
548
549         for ( retries = 0 ; retries < PHN_ISSUE_CMD_TIMEOUT_MS ; retries++ ) {
550                 mdelay ( 1 );
551                 cdrp = phantom_readl ( phantom, UNM_NIC_REG_NX_CDRP );
552                 if ( NX_CDRP_IS_RSP ( cdrp ) ) {
553                         switch ( NX_CDRP_FORM_RSP ( cdrp ) ) {
554                         case NX_CDRP_RSP_OK:
555                                 return 0;
556                         case NX_CDRP_RSP_FAIL:
557                                 return -EIO;
558                         case NX_CDRP_RSP_TIMEOUT:
559                                 return -ETIMEDOUT;
560                         default:
561                                 return -EPROTO;
562                         }
563                 }
564         }
565
566         DBGC ( phantom, "Phantom %p timed out waiting for firmware to accept "
567                "command\n", phantom );
568         return -ETIMEDOUT;
569 }
570
571 /**
572  * Issue command to firmware
573  *
574  * @v phantom           Phantom NIC
575  * @v command           Firmware command
576  * @v arg1              Argument 1
577  * @v arg2              Argument 2
578  * @v arg3              Argument 3
579  * @ret rc              Return status code
580  */
581 static int phantom_issue_cmd ( struct phantom_nic *phantom,
582                                uint32_t command, uint32_t arg1, uint32_t arg2,
583                                uint32_t arg3 ) {
584         uint32_t signature;
585         int rc;
586
587         /* Issue command */
588         signature = NX_CDRP_SIGNATURE_MAKE ( phantom->port,
589                                              NXHAL_VERSION );
590         DBGC2 ( phantom, "Phantom %p issuing command %08x (%08x, %08x, "
591                 "%08x)\n", phantom, command, arg1, arg2, arg3 );
592         phantom_writel ( phantom, signature, UNM_NIC_REG_NX_SIGN );
593         phantom_writel ( phantom, arg1, UNM_NIC_REG_NX_ARG1 );
594         phantom_writel ( phantom, arg2, UNM_NIC_REG_NX_ARG2 );
595         phantom_writel ( phantom, arg3, UNM_NIC_REG_NX_ARG3 );
596         phantom_writel ( phantom, NX_CDRP_FORM_CMD ( command ),
597                          UNM_NIC_REG_NX_CDRP );
598
599         /* Wait for command to be accepted */
600         if ( ( rc = phantom_wait_for_cmd ( phantom ) ) != 0 ) {
601                 DBGC ( phantom, "Phantom %p could not issue command: %s\n",
602                        phantom, strerror ( rc ) );
603                 return rc;
604         }
605
606         return 0;
607 }
608
609 /**
610  * Issue buffer-format command to firmware
611  *
612  * @v phantom           Phantom NIC
613  * @v command           Firmware command
614  * @v buffer            Buffer to pass to firmware
615  * @v len               Length of buffer
616  * @ret rc              Return status code
617  */
618 static int phantom_issue_buf_cmd ( struct phantom_nic *phantom,
619                                    uint32_t command, void *buffer,
620                                    size_t len ) {
621         uint64_t physaddr;
622
623         physaddr = virt_to_bus ( buffer );
624         return phantom_issue_cmd ( phantom, command, ( physaddr >> 32 ),
625                                    ( physaddr & 0xffffffffUL ), len );
626 }
627
628 /**
629  * Create Phantom RX context
630  *
631  * @v phantom           Phantom NIC
632  * @ret rc              Return status code
633  */
634 static int phantom_create_rx_ctx ( struct phantom_nic *phantom ) {
635         struct phantom_create_rx_ctx_rqrsp *buf;
636         int rc;
637
638         /* Allocate context creation buffer */
639         buf = malloc_dma ( sizeof ( *buf ), UNM_DMA_BUFFER_ALIGN );
640         if ( ! buf ) {
641                 rc = -ENOMEM;
642                 goto out;
643         }
644         memset ( buf, 0, sizeof ( *buf ) );
645         
646         /* Prepare request */
647         buf->hostrq.rx_ctx.host_rsp_dma_addr =
648                 cpu_to_le64 ( virt_to_bus ( &buf->cardrsp ) );
649         buf->hostrq.rx_ctx.capabilities[0] =
650                 cpu_to_le32 ( NX_CAP0_LEGACY_CONTEXT | NX_CAP0_LEGACY_MN );
651         buf->hostrq.rx_ctx.host_int_crb_mode =
652                 cpu_to_le32 ( NX_HOST_INT_CRB_MODE_SHARED );
653         buf->hostrq.rx_ctx.host_rds_crb_mode =
654                 cpu_to_le32 ( NX_HOST_RDS_CRB_MODE_UNIQUE );
655         buf->hostrq.rx_ctx.rds_ring_offset = cpu_to_le32 ( 0 );
656         buf->hostrq.rx_ctx.sds_ring_offset =
657                 cpu_to_le32 ( sizeof ( buf->hostrq.rds ) );
658         buf->hostrq.rx_ctx.num_rds_rings = cpu_to_le16 ( 1 );
659         buf->hostrq.rx_ctx.num_sds_rings = cpu_to_le16 ( 1 );
660         buf->hostrq.rds.host_phys_addr =
661                 cpu_to_le64 ( virt_to_bus ( phantom->desc->rds ) );
662         buf->hostrq.rds.buff_size = cpu_to_le64 ( PHN_RX_BUFSIZE );
663         buf->hostrq.rds.ring_size = cpu_to_le32 ( PHN_NUM_RDS );
664         buf->hostrq.rds.ring_kind = cpu_to_le32 ( NX_RDS_RING_TYPE_NORMAL );
665         buf->hostrq.sds.host_phys_addr =
666                 cpu_to_le64 ( virt_to_bus ( phantom->desc->sds ) );
667         buf->hostrq.sds.ring_size = cpu_to_le32 ( PHN_NUM_SDS );
668
669         DBGC ( phantom, "Phantom %p creating RX context\n", phantom );
670         DBGC2_HDA ( phantom, virt_to_bus ( &buf->hostrq ),
671                     &buf->hostrq, sizeof ( buf->hostrq ) );
672
673         /* Issue request */
674         if ( ( rc = phantom_issue_buf_cmd ( phantom,
675                                             NX_CDRP_CMD_CREATE_RX_CTX,
676                                             &buf->hostrq,
677                                             sizeof ( buf->hostrq ) ) ) != 0 ) {
678                 DBGC ( phantom, "Phantom %p could not create RX context: "
679                        "%s\n", phantom, strerror ( rc ) );
680                 DBGC ( phantom, "Request:\n" );
681                 DBGC_HDA ( phantom, virt_to_bus ( &buf->hostrq ),
682                            &buf->hostrq, sizeof ( buf->hostrq ) );
683                 DBGC ( phantom, "Response:\n" );
684                 DBGC_HDA ( phantom, virt_to_bus ( &buf->cardrsp ),
685                            &buf->cardrsp, sizeof ( buf->cardrsp ) );
686                 goto out;
687         }
688
689         /* Retrieve context parameters */
690         phantom->rx_context_id =
691                 le16_to_cpu ( buf->cardrsp.rx_ctx.context_id );
692         phantom->rds_producer_crb =
693                 ( UNM_CAM_RAM +
694                   le32_to_cpu ( buf->cardrsp.rds.host_producer_crb ) );
695         phantom->sds_consumer_crb =
696                 ( UNM_CAM_RAM +
697                   le32_to_cpu ( buf->cardrsp.sds.host_consumer_crb ) );
698         phantom->sds_irq_mask_crb =
699                 ( UNM_CAM_RAM +
700                   le32_to_cpu ( buf->cardrsp.sds.interrupt_crb ) );
701
702         DBGC ( phantom, "Phantom %p created RX context (id %04x, port phys "
703                "%02x virt %02x)\n", phantom, phantom->rx_context_id,
704                buf->cardrsp.rx_ctx.phys_port, buf->cardrsp.rx_ctx.virt_port );
705         DBGC2_HDA ( phantom, virt_to_bus ( &buf->cardrsp ),
706                     &buf->cardrsp, sizeof ( buf->cardrsp ) );
707         DBGC ( phantom, "Phantom %p RDS producer CRB is %08lx\n",
708                phantom, phantom->rds_producer_crb );
709         DBGC ( phantom, "Phantom %p SDS consumer CRB is %08lx\n",
710                phantom, phantom->sds_consumer_crb );
711         DBGC ( phantom, "Phantom %p SDS interrupt mask CRB is %08lx\n",
712                phantom, phantom->sds_irq_mask_crb );
713
714  out:
715         free_dma ( buf, sizeof ( *buf ) );
716         return rc;
717 }
718
719 /**
720  * Destroy Phantom RX context
721  *
722  * @v phantom           Phantom NIC
723  * @ret rc              Return status code
724  */
725 static void phantom_destroy_rx_ctx ( struct phantom_nic *phantom ) {
726         int rc;
727         
728         DBGC ( phantom, "Phantom %p destroying RX context (id %04x)\n",
729                phantom, phantom->rx_context_id );
730
731         /* Issue request */
732         if ( ( rc = phantom_issue_cmd ( phantom,
733                                         NX_CDRP_CMD_DESTROY_RX_CTX,
734                                         phantom->rx_context_id,
735                                         NX_DESTROY_CTX_RESET, 0 ) ) != 0 ) {
736                 DBGC ( phantom, "Phantom %p could not destroy RX context: "
737                        "%s\n", phantom, strerror ( rc ) );
738                 /* We're probably screwed */
739                 return;
740         }
741
742         /* Clear context parameters */
743         phantom->rx_context_id = 0;
744         phantom->rds_producer_crb = 0;
745         phantom->sds_consumer_crb = 0;
746
747         /* Reset software counters */
748         phantom->rds_producer_idx = 0;
749         phantom->rds_consumer_idx = 0;
750         phantom->sds_consumer_idx = 0;
751 }
752
753 /**
754  * Create Phantom TX context
755  *
756  * @v phantom           Phantom NIC
757  * @ret rc              Return status code
758  */
759 static int phantom_create_tx_ctx ( struct phantom_nic *phantom ) {
760         struct phantom_create_tx_ctx_rqrsp *buf;
761         int rc;
762
763         /* Allocate context creation buffer */
764         buf = malloc_dma ( sizeof ( *buf ), UNM_DMA_BUFFER_ALIGN );
765         if ( ! buf ) {
766                 rc = -ENOMEM;
767                 goto out;
768         }
769         memset ( buf, 0, sizeof ( *buf ) );
770
771         /* Prepare request */
772         buf->hostrq.tx_ctx.host_rsp_dma_addr =
773                 cpu_to_le64 ( virt_to_bus ( &buf->cardrsp ) );
774         buf->hostrq.tx_ctx.cmd_cons_dma_addr =
775                 cpu_to_le64 ( virt_to_bus ( &phantom->desc->cmd_cons ) );
776         buf->hostrq.tx_ctx.capabilities[0] =
777                 cpu_to_le32 ( NX_CAP0_LEGACY_CONTEXT | NX_CAP0_LEGACY_MN );
778         buf->hostrq.tx_ctx.host_int_crb_mode =
779                 cpu_to_le32 ( NX_HOST_INT_CRB_MODE_SHARED );
780         buf->hostrq.tx_ctx.cds_ring.host_phys_addr =
781                 cpu_to_le64 ( virt_to_bus ( phantom->desc->cds ) );
782         buf->hostrq.tx_ctx.cds_ring.ring_size = cpu_to_le32 ( PHN_NUM_CDS );
783
784         DBGC ( phantom, "Phantom %p creating TX context\n", phantom );
785         DBGC2_HDA ( phantom, virt_to_bus ( &buf->hostrq ),
786                     &buf->hostrq, sizeof ( buf->hostrq ) );
787
788         /* Issue request */
789         if ( ( rc = phantom_issue_buf_cmd ( phantom,
790                                             NX_CDRP_CMD_CREATE_TX_CTX,
791                                             &buf->hostrq,
792                                             sizeof ( buf->hostrq ) ) ) != 0 ) {
793                 DBGC ( phantom, "Phantom %p could not create TX context: "
794                        "%s\n", phantom, strerror ( rc ) );
795                 DBGC ( phantom, "Request:\n" );
796                 DBGC_HDA ( phantom, virt_to_bus ( &buf->hostrq ),
797                            &buf->hostrq, sizeof ( buf->hostrq ) );
798                 DBGC ( phantom, "Response:\n" );
799                 DBGC_HDA ( phantom, virt_to_bus ( &buf->cardrsp ),
800                            &buf->cardrsp, sizeof ( buf->cardrsp ) );
801                 goto out;
802         }
803
804         /* Retrieve context parameters */
805         phantom->tx_context_id =
806                 le16_to_cpu ( buf->cardrsp.tx_ctx.context_id );
807         phantom->cds_producer_crb =
808                 ( UNM_CAM_RAM +
809                   le32_to_cpu(buf->cardrsp.tx_ctx.cds_ring.host_producer_crb));
810
811         DBGC ( phantom, "Phantom %p created TX context (id %04x, port phys "
812                "%02x virt %02x)\n", phantom, phantom->tx_context_id,
813                buf->cardrsp.tx_ctx.phys_port, buf->cardrsp.tx_ctx.virt_port );
814         DBGC2_HDA ( phantom, virt_to_bus ( &buf->cardrsp ),
815                     &buf->cardrsp, sizeof ( buf->cardrsp ) );
816         DBGC ( phantom, "Phantom %p CDS producer CRB is %08lx\n",
817                phantom, phantom->cds_producer_crb );
818
819  out:
820         free_dma ( buf, sizeof ( *buf ) );
821         return rc;
822 }
823
824 /**
825  * Destroy Phantom TX context
826  *
827  * @v phantom           Phantom NIC
828  * @ret rc              Return status code
829  */
830 static void phantom_destroy_tx_ctx ( struct phantom_nic *phantom ) {
831         int rc;
832         
833         DBGC ( phantom, "Phantom %p destroying TX context (id %04x)\n",
834                phantom, phantom->tx_context_id );
835
836         /* Issue request */
837         if ( ( rc = phantom_issue_cmd ( phantom,
838                                         NX_CDRP_CMD_DESTROY_TX_CTX,
839                                         phantom->tx_context_id,
840                                         NX_DESTROY_CTX_RESET, 0 ) ) != 0 ) {
841                 DBGC ( phantom, "Phantom %p could not destroy TX context: "
842                        "%s\n", phantom, strerror ( rc ) );
843                 /* We're probably screwed */
844                 return;
845         }
846
847         /* Clear context parameters */
848         phantom->tx_context_id = 0;
849         phantom->cds_producer_crb = 0;
850
851         /* Reset software counters */
852         phantom->cds_producer_idx = 0;
853         phantom->cds_consumer_idx = 0;
854 }
855
856 /***************************************************************************
857  *
858  * Descriptor ring management
859  *
860  */
861
862 /**
863  * Allocate Phantom RX descriptor
864  *
865  * @v phantom           Phantom NIC
866  * @ret index           RX descriptor index, or negative error
867  */
868 static int phantom_alloc_rds ( struct phantom_nic *phantom ) {
869         unsigned int rds_producer_idx;
870         unsigned int next_rds_producer_idx;
871
872         /* Check for space in the ring.  RX descriptors are consumed
873          * out of order, but they are *read* by the hardware in strict
874          * order.  We maintain a pessimistic consumer index, which is
875          * guaranteed never to be an overestimate of the number of
876          * descriptors read by the hardware.
877          */
878         rds_producer_idx = phantom->rds_producer_idx;
879         next_rds_producer_idx = ( ( rds_producer_idx + 1 ) % PHN_NUM_RDS );
880         if ( next_rds_producer_idx == phantom->rds_consumer_idx ) {
881                 DBGC ( phantom, "Phantom %p RDS ring full (index %d not "
882                        "consumed)\n", phantom, next_rds_producer_idx );
883                 return -ENOBUFS;
884         }
885
886         return rds_producer_idx;
887 }
888
889 /**
890  * Post Phantom RX descriptor
891  *
892  * @v phantom           Phantom NIC
893  * @v rds               RX descriptor
894  */
895 static void phantom_post_rds ( struct phantom_nic *phantom,
896                                struct phantom_rds *rds ) {
897         unsigned int rds_producer_idx;
898         unsigned int next_rds_producer_idx;
899         struct phantom_rds *entry;
900
901         /* Copy descriptor to ring */
902         rds_producer_idx = phantom->rds_producer_idx;
903         entry = &phantom->desc->rds[rds_producer_idx];
904         memcpy ( entry, rds, sizeof ( *entry ) );
905         DBGC2 ( phantom, "Phantom %p posting RDS %ld (slot %d):\n",
906                 phantom, NX_GET ( rds, handle ), rds_producer_idx );
907         DBGC2_HDA ( phantom, virt_to_bus ( entry ), entry, sizeof ( *entry ) );
908
909         /* Update producer index */
910         next_rds_producer_idx = ( ( rds_producer_idx + 1 ) % PHN_NUM_RDS );
911         phantom->rds_producer_idx = next_rds_producer_idx;
912         wmb();
913         phantom_writel ( phantom, phantom->rds_producer_idx,
914                          phantom->rds_producer_crb );
915 }
916
917 /**
918  * Allocate Phantom TX descriptor
919  *
920  * @v phantom           Phantom NIC
921  * @ret index           TX descriptor index, or negative error
922  */
923 static int phantom_alloc_cds ( struct phantom_nic *phantom ) {
924         unsigned int cds_producer_idx;
925         unsigned int next_cds_producer_idx;
926
927         /* Check for space in the ring.  TX descriptors are consumed
928          * in strict order, so we just check for a collision against
929          * the consumer index.
930          */
931         cds_producer_idx = phantom->cds_producer_idx;
932         next_cds_producer_idx = ( ( cds_producer_idx + 1 ) % PHN_NUM_CDS );
933         if ( next_cds_producer_idx == phantom->cds_consumer_idx ) {
934                 DBGC ( phantom, "Phantom %p CDS ring full (index %d not "
935                        "consumed)\n", phantom, next_cds_producer_idx );
936                 return -ENOBUFS;
937         }
938
939         return cds_producer_idx;
940 }
941
942 /**
943  * Post Phantom TX descriptor
944  *
945  * @v phantom           Phantom NIC
946  * @v cds               TX descriptor
947  */
948 static void phantom_post_cds ( struct phantom_nic *phantom,
949                                union phantom_cds *cds ) {
950         unsigned int cds_producer_idx;
951         unsigned int next_cds_producer_idx;
952         union phantom_cds *entry;
953
954         /* Copy descriptor to ring */
955         cds_producer_idx = phantom->cds_producer_idx;
956         entry = &phantom->desc->cds[cds_producer_idx];
957         memcpy ( entry, cds, sizeof ( *entry ) );
958         DBGC2 ( phantom, "Phantom %p posting CDS %d:\n",
959                 phantom, cds_producer_idx );
960         DBGC2_HDA ( phantom, virt_to_bus ( entry ), entry, sizeof ( *entry ) );
961
962         /* Update producer index */
963         next_cds_producer_idx = ( ( cds_producer_idx + 1 ) % PHN_NUM_CDS );
964         phantom->cds_producer_idx = next_cds_producer_idx;
965         wmb();
966         phantom_writel ( phantom, phantom->cds_producer_idx,
967                          phantom->cds_producer_crb );
968 }
969
970 /***************************************************************************
971  *
972  * MAC address management
973  *
974  */
975
976 /**
977  * Add/remove MAC address
978  *
979  * @v phantom           Phantom NIC
980  * @v ll_addr           MAC address to add or remove
981  * @v opcode            MAC request opcode
982  * @ret rc              Return status code
983  */
984 static int phantom_update_macaddr ( struct phantom_nic *phantom,
985                                     const uint8_t *ll_addr,
986                                     unsigned int opcode ) {
987         union phantom_cds cds;
988         int index;
989
990         /* Get descriptor ring entry */
991         index = phantom_alloc_cds ( phantom );
992         if ( index < 0 )
993                 return index;
994
995         /* Fill descriptor ring entry */
996         memset ( &cds, 0, sizeof ( cds ) );
997         NX_FILL_1 ( &cds, 0,
998                     nic_request.common.opcode, UNM_NIC_REQUEST );
999         NX_FILL_2 ( &cds, 1,
1000                     nic_request.header.opcode, UNM_MAC_EVENT,
1001                     nic_request.header.context_id, phantom->port );
1002         NX_FILL_7 ( &cds, 2,
1003                     nic_request.body.mac_request.opcode, opcode,
1004                     nic_request.body.mac_request.mac_addr_0, ll_addr[0],
1005                     nic_request.body.mac_request.mac_addr_1, ll_addr[1],
1006                     nic_request.body.mac_request.mac_addr_2, ll_addr[2],
1007                     nic_request.body.mac_request.mac_addr_3, ll_addr[3],
1008                     nic_request.body.mac_request.mac_addr_4, ll_addr[4],
1009                     nic_request.body.mac_request.mac_addr_5, ll_addr[5] );
1010
1011         /* Post descriptor */
1012         phantom_post_cds ( phantom, &cds );
1013
1014         return 0;
1015 }
1016
1017 /**
1018  * Add MAC address
1019  *
1020  * @v phantom           Phantom NIC
1021  * @v ll_addr           MAC address to add or remove
1022  * @ret rc              Return status code
1023  */
1024 static inline int phantom_add_macaddr ( struct phantom_nic *phantom,
1025                                         const uint8_t *ll_addr ) {
1026
1027         DBGC ( phantom, "Phantom %p adding MAC address %s\n",
1028                phantom, eth_ntoa ( ll_addr ) );
1029
1030         return phantom_update_macaddr ( phantom, ll_addr, UNM_MAC_ADD );
1031 }
1032
1033 /**
1034  * Remove MAC address
1035  *
1036  * @v phantom           Phantom NIC
1037  * @v ll_addr           MAC address to add or remove
1038  * @ret rc              Return status code
1039  */
1040 static inline int phantom_del_macaddr ( struct phantom_nic *phantom,
1041                                         const uint8_t *ll_addr ) {
1042
1043         DBGC ( phantom, "Phantom %p removing MAC address %s\n",
1044                phantom, eth_ntoa ( ll_addr ) );
1045
1046         return phantom_update_macaddr ( phantom, ll_addr, UNM_MAC_DEL );
1047 }
1048
1049 /***************************************************************************
1050  *
1051  * Link state detection
1052  *
1053  */
1054
1055 /**
1056  * Poll link state
1057  *
1058  * @v netdev            Network device
1059  */
1060 static void phantom_poll_link_state ( struct net_device *netdev ) {
1061         struct phantom_nic *phantom = netdev_priv ( netdev );
1062         uint32_t xg_state_p3;
1063         unsigned int link;
1064
1065         /* Read link state */
1066         xg_state_p3 = phantom_readl ( phantom, UNM_NIC_REG_XG_STATE_P3 );
1067
1068         /* If there is no change, do nothing */
1069         if ( phantom->link_state == xg_state_p3 )
1070                 return;
1071
1072         /* Record new link state */
1073         DBGC ( phantom, "Phantom %p new link state %08x (was %08x)\n",
1074                phantom, xg_state_p3, phantom->link_state );
1075         phantom->link_state = xg_state_p3;
1076
1077         /* Indicate link state to iPXE */
1078         link = UNM_NIC_REG_XG_STATE_P3_LINK ( phantom->port,
1079                                               phantom->link_state );
1080         switch ( link ) {
1081         case UNM_NIC_REG_XG_STATE_P3_LINK_UP:
1082                 DBGC ( phantom, "Phantom %p link is up\n", phantom );
1083                 netdev_link_up ( netdev );
1084                 break;
1085         case UNM_NIC_REG_XG_STATE_P3_LINK_DOWN:
1086                 DBGC ( phantom, "Phantom %p link is down\n", phantom );
1087                 netdev_link_down ( netdev );
1088                 break;
1089         default:
1090                 DBGC ( phantom, "Phantom %p bad link state %d\n",
1091                        phantom, link );
1092                 break;
1093         }
1094 }
1095
1096 /***************************************************************************
1097  *
1098  * Main driver body
1099  *
1100  */
1101
1102 /**
1103  * Refill descriptor ring
1104  *
1105  * @v netdev            Net device
1106  */
1107 static void phantom_refill_rx_ring ( struct net_device *netdev ) {
1108         struct phantom_nic *phantom = netdev_priv ( netdev );
1109         struct io_buffer *iobuf;
1110         struct phantom_rds rds;
1111         unsigned int handle;
1112         int index;
1113
1114         for ( handle = 0 ; handle < PHN_RDS_MAX_FILL ; handle++ ) {
1115
1116                 /* Skip this index if the descriptor has not yet been
1117                  * consumed.
1118                  */
1119                 if ( phantom->rds_iobuf[handle] != NULL )
1120                         continue;
1121
1122                 /* Allocate descriptor ring entry */
1123                 index = phantom_alloc_rds ( phantom );
1124                 assert ( PHN_RDS_MAX_FILL < PHN_NUM_RDS );
1125                 assert ( index >= 0 ); /* Guaranteed by MAX_FILL < NUM_RDS ) */
1126
1127                 /* Try to allocate an I/O buffer */
1128                 iobuf = alloc_iob ( PHN_RX_BUFSIZE );
1129                 if ( ! iobuf ) {
1130                         /* Failure is non-fatal; we will retry later */
1131                         netdev_rx_err ( netdev, NULL, -ENOMEM );
1132                         break;
1133                 }
1134
1135                 /* Fill descriptor ring entry */
1136                 memset ( &rds, 0, sizeof ( rds ) );
1137                 NX_FILL_2 ( &rds, 0,
1138                             handle, handle,
1139                             length, iob_len ( iobuf ) );
1140                 NX_FILL_1 ( &rds, 1,
1141                             dma_addr, virt_to_bus ( iobuf->data ) );
1142
1143                 /* Record I/O buffer */
1144                 assert ( phantom->rds_iobuf[handle] == NULL );
1145                 phantom->rds_iobuf[handle] = iobuf;
1146
1147                 /* Post descriptor */
1148                 phantom_post_rds ( phantom, &rds );
1149         }
1150 }
1151
1152 /**
1153  * Open NIC
1154  *
1155  * @v netdev            Net device
1156  * @ret rc              Return status code
1157  */
1158 static int phantom_open ( struct net_device *netdev ) {
1159         struct phantom_nic *phantom = netdev_priv ( netdev );
1160         int rc;
1161
1162         /* Allocate and zero descriptor rings */
1163         phantom->desc = malloc_dma ( sizeof ( *(phantom->desc) ),
1164                                           UNM_DMA_BUFFER_ALIGN );
1165         if ( ! phantom->desc ) {
1166                 rc = -ENOMEM;
1167                 goto err_alloc_desc;
1168         }
1169         memset ( phantom->desc, 0, sizeof ( *(phantom->desc) ) );
1170
1171         /* Create RX context */
1172         if ( ( rc = phantom_create_rx_ctx ( phantom ) ) != 0 )
1173                 goto err_create_rx_ctx;
1174
1175         /* Create TX context */
1176         if ( ( rc = phantom_create_tx_ctx ( phantom ) ) != 0 )
1177                 goto err_create_tx_ctx;
1178
1179         /* Fill the RX descriptor ring */
1180         phantom_refill_rx_ring ( netdev );
1181
1182         /* Add MAC addresses
1183          *
1184          * BUG5583
1185          *
1186          * We would like to be able to enable receiving all multicast
1187          * packets (or, failing that, promiscuous mode), but the
1188          * firmware doesn't currently support this.
1189          */
1190         if ( ( rc = phantom_add_macaddr ( phantom,
1191                                           netdev->ll_broadcast ) ) != 0 )
1192                 goto err_add_macaddr_broadcast;
1193         if ( ( rc = phantom_add_macaddr ( phantom,
1194                                           netdev->ll_addr ) ) != 0 )
1195                 goto err_add_macaddr_unicast;
1196
1197         return 0;
1198
1199         phantom_del_macaddr ( phantom, netdev->ll_addr );
1200  err_add_macaddr_unicast:
1201         phantom_del_macaddr ( phantom, netdev->ll_broadcast );
1202  err_add_macaddr_broadcast:
1203         phantom_destroy_tx_ctx ( phantom );
1204  err_create_tx_ctx:
1205         phantom_destroy_rx_ctx ( phantom );
1206  err_create_rx_ctx:
1207         free_dma ( phantom->desc, sizeof ( *(phantom->desc) ) );
1208         phantom->desc = NULL;
1209  err_alloc_desc:
1210         return rc;
1211 }
1212
1213 /**
1214  * Close NIC
1215  *
1216  * @v netdev            Net device
1217  */
1218 static void phantom_close ( struct net_device *netdev ) {
1219         struct phantom_nic *phantom = netdev_priv ( netdev );
1220         struct io_buffer *iobuf;
1221         unsigned int i;
1222
1223         /* Shut down the port */
1224         phantom_del_macaddr ( phantom, netdev->ll_addr );
1225         phantom_del_macaddr ( phantom, netdev->ll_broadcast );
1226         phantom_destroy_tx_ctx ( phantom );
1227         phantom_destroy_rx_ctx ( phantom );
1228         free_dma ( phantom->desc, sizeof ( *(phantom->desc) ) );
1229         phantom->desc = NULL;
1230
1231         /* Flush any uncompleted descriptors */
1232         for ( i = 0 ; i < PHN_RDS_MAX_FILL ; i++ ) {
1233                 iobuf = phantom->rds_iobuf[i];
1234                 if ( iobuf ) {
1235                         free_iob ( iobuf );
1236                         phantom->rds_iobuf[i] = NULL;
1237                 }
1238         }
1239         for ( i = 0 ; i < PHN_NUM_CDS ; i++ ) {
1240                 iobuf = phantom->cds_iobuf[i];
1241                 if ( iobuf ) {
1242                         netdev_tx_complete_err ( netdev, iobuf, -ECANCELED );
1243                         phantom->cds_iobuf[i] = NULL;
1244                 }
1245         }
1246 }
1247
1248 /** 
1249  * Transmit packet
1250  *
1251  * @v netdev    Network device
1252  * @v iobuf     I/O buffer
1253  * @ret rc      Return status code
1254  */
1255 static int phantom_transmit ( struct net_device *netdev,
1256                               struct io_buffer *iobuf ) {
1257         struct phantom_nic *phantom = netdev_priv ( netdev );
1258         union phantom_cds cds;
1259         int index;
1260
1261         /* Get descriptor ring entry */
1262         index = phantom_alloc_cds ( phantom );
1263         if ( index < 0 )
1264                 return index;
1265
1266         /* Fill descriptor ring entry */
1267         memset ( &cds, 0, sizeof ( cds ) );
1268         NX_FILL_3 ( &cds, 0,
1269                     tx.opcode, UNM_TX_ETHER_PKT,
1270                     tx.num_buffers, 1,
1271                     tx.length, iob_len ( iobuf ) );
1272         NX_FILL_2 ( &cds, 2,
1273                     tx.port, phantom->port,
1274                     tx.context_id, phantom->port );
1275         NX_FILL_1 ( &cds, 4,
1276                     tx.buffer1_dma_addr, virt_to_bus ( iobuf->data ) );
1277         NX_FILL_1 ( &cds, 5,
1278                     tx.buffer1_length, iob_len ( iobuf ) );
1279
1280         /* Record I/O buffer */
1281         assert ( phantom->cds_iobuf[index] == NULL );
1282         phantom->cds_iobuf[index] = iobuf;
1283
1284         /* Post descriptor */
1285         phantom_post_cds ( phantom, &cds );
1286
1287         return 0;
1288 }
1289
1290 /**
1291  * Poll for received packets
1292  *
1293  * @v netdev    Network device
1294  */
1295 static void phantom_poll ( struct net_device *netdev ) {
1296         struct phantom_nic *phantom = netdev_priv ( netdev );
1297         struct io_buffer *iobuf;
1298         unsigned int irq_vector;
1299         unsigned int irq_state;
1300         unsigned int cds_consumer_idx;
1301         unsigned int raw_new_cds_consumer_idx;
1302         unsigned int new_cds_consumer_idx;
1303         unsigned int rds_consumer_idx;
1304         unsigned int sds_consumer_idx;
1305         struct phantom_sds *sds;
1306         unsigned int sds_handle;
1307         unsigned int sds_opcode;
1308
1309         /* Occasionally poll the link state */
1310         if ( phantom->link_poll_timer-- == 0 ) {
1311                 phantom_poll_link_state ( netdev );
1312                 /* Reset the link poll timer */
1313                 phantom->link_poll_timer = PHN_LINK_POLL_FREQUENCY;
1314         }
1315
1316         /* Check for interrupts */
1317         if ( phantom->sds_irq_enabled ) {
1318
1319                 /* Do nothing unless an interrupt is asserted */
1320                 irq_vector = phantom_readl ( phantom, UNM_PCIE_IRQ_VECTOR );
1321                 if ( ! ( irq_vector & UNM_PCIE_IRQ_VECTOR_BIT( phantom->port )))
1322                         return;
1323
1324                 /* Do nothing unless interrupt state machine has stabilised */
1325                 irq_state = phantom_readl ( phantom, UNM_PCIE_IRQ_STATE );
1326                 if ( ! UNM_PCIE_IRQ_STATE_TRIGGERED ( irq_state ) )
1327                         return;
1328
1329                 /* Acknowledge interrupt */
1330                 phantom_writel ( phantom, UNM_PCIE_IRQ_STATUS_MAGIC,
1331                                  phantom_irq_status_reg[phantom->port] );
1332                 phantom_readl ( phantom, UNM_PCIE_IRQ_VECTOR );
1333         }
1334
1335         /* Check for TX completions */
1336         cds_consumer_idx = phantom->cds_consumer_idx;
1337         raw_new_cds_consumer_idx = phantom->desc->cmd_cons;
1338         new_cds_consumer_idx = le32_to_cpu ( raw_new_cds_consumer_idx );
1339         while ( cds_consumer_idx != new_cds_consumer_idx ) {
1340                 DBGC2 ( phantom, "Phantom %p CDS %d complete\n",
1341                         phantom, cds_consumer_idx );
1342                 /* Completions may be for commands other than TX, so
1343                  * there may not always be an associated I/O buffer.
1344                  */
1345                 if ( ( iobuf = phantom->cds_iobuf[cds_consumer_idx] ) ) {
1346                         netdev_tx_complete ( netdev, iobuf );
1347                         phantom->cds_iobuf[cds_consumer_idx] = NULL;
1348                 }
1349                 cds_consumer_idx = ( ( cds_consumer_idx + 1 ) % PHN_NUM_CDS );
1350                 phantom->cds_consumer_idx = cds_consumer_idx;
1351         }
1352
1353         /* Check for received packets */
1354         rds_consumer_idx = phantom->rds_consumer_idx;
1355         sds_consumer_idx = phantom->sds_consumer_idx;
1356         while ( 1 ) {
1357                 sds = &phantom->desc->sds[sds_consumer_idx];
1358                 if ( NX_GET ( sds, owner ) == 0 )
1359                         break;
1360
1361                 DBGC2 ( phantom, "Phantom %p SDS %d status:\n",
1362                         phantom, sds_consumer_idx );
1363                 DBGC2_HDA ( phantom, virt_to_bus ( sds ), sds, sizeof (*sds) );
1364
1365                 /* Check received opcode */
1366                 sds_opcode = NX_GET ( sds, opcode );
1367                 if ( ( sds_opcode == UNM_RXPKT_DESC ) ||
1368                      ( sds_opcode == UNM_SYN_OFFLOAD ) ) {
1369
1370                         /* Sanity check: ensure that all of the SDS
1371                          * descriptor has been written.
1372                          */
1373                         if ( NX_GET ( sds, total_length ) == 0 ) {
1374                                 DBGC ( phantom, "Phantom %p SDS %d "
1375                                        "incomplete; deferring\n",
1376                                        phantom, sds_consumer_idx );
1377                                 /* Leave for next poll() */
1378                                 break;
1379                         }
1380
1381                         /* Process received packet */
1382                         sds_handle = NX_GET ( sds, handle );
1383                         iobuf = phantom->rds_iobuf[sds_handle];
1384                         assert ( iobuf != NULL );
1385                         iob_put ( iobuf, NX_GET ( sds, total_length ) );
1386                         iob_pull ( iobuf, NX_GET ( sds, pkt_offset ) );
1387                         DBGC2 ( phantom, "Phantom %p RDS %d complete\n",
1388                                 phantom, sds_handle );
1389                         netdev_rx ( netdev, iobuf );
1390                         phantom->rds_iobuf[sds_handle] = NULL;
1391
1392                         /* Update RDS consumer counter.  This is a
1393                          * lower bound for the number of descriptors
1394                          * that have been read by the hardware, since
1395                          * the hardware must have read at least one
1396                          * descriptor for each completion that we
1397                          * receive.
1398                          */
1399                         rds_consumer_idx =
1400                                 ( ( rds_consumer_idx + 1 ) % PHN_NUM_RDS );
1401                         phantom->rds_consumer_idx = rds_consumer_idx;
1402
1403                 } else {
1404
1405                         DBGC ( phantom, "Phantom %p unexpected SDS opcode "
1406                                "%02x\n", phantom, sds_opcode );
1407                         DBGC_HDA ( phantom, virt_to_bus ( sds ),
1408                                    sds, sizeof ( *sds ) );
1409                 }
1410                         
1411                 /* Clear status descriptor */
1412                 memset ( sds, 0, sizeof ( *sds ) );
1413
1414                 /* Update SDS consumer index */
1415                 sds_consumer_idx = ( ( sds_consumer_idx + 1 ) % PHN_NUM_SDS );
1416                 phantom->sds_consumer_idx = sds_consumer_idx;
1417                 wmb();
1418                 phantom_writel ( phantom, phantom->sds_consumer_idx,
1419                                  phantom->sds_consumer_crb );
1420         }
1421
1422         /* Refill the RX descriptor ring */
1423         phantom_refill_rx_ring ( netdev );
1424 }
1425
1426 /**
1427  * Enable/disable interrupts
1428  *
1429  * @v netdev    Network device
1430  * @v enable    Interrupts should be enabled
1431  */
1432 static void phantom_irq ( struct net_device *netdev, int enable ) {
1433         struct phantom_nic *phantom = netdev_priv ( netdev );
1434
1435         phantom_writel ( phantom, ( enable ? 1 : 0 ),
1436                          phantom->sds_irq_mask_crb );
1437         phantom_writel ( phantom, UNM_PCIE_IRQ_MASK_MAGIC,
1438                          phantom_irq_mask_reg[phantom->port] );
1439         phantom->sds_irq_enabled = enable;
1440 }
1441
1442 /** Phantom net device operations */
1443 static struct net_device_operations phantom_operations = {
1444         .open           = phantom_open,
1445         .close          = phantom_close,
1446         .transmit       = phantom_transmit,
1447         .poll           = phantom_poll,
1448         .irq            = phantom_irq,
1449 };
1450
1451 /***************************************************************************
1452  *
1453  * CLP settings
1454  *
1455  */
1456
1457 /** Phantom CLP settings scope */
1458 static const struct settings_scope phantom_settings_scope;
1459
1460 /** Phantom CLP data
1461  *
1462  */
1463 union phantom_clp_data {
1464         /** Data bytes
1465          *
1466          * This field is right-aligned; if only N bytes are present
1467          * then bytes[0]..bytes[7-N] should be zero, and the data
1468          * should be in bytes[7-N+1] to bytes[7];
1469          */
1470         uint8_t bytes[8];
1471         /** Dwords for the CLP interface */
1472         struct {
1473                 /** High dword, in network byte order */
1474                 uint32_t hi;
1475                 /** Low dword, in network byte order */
1476                 uint32_t lo;
1477         } dwords;
1478 };
1479 #define PHN_CLP_BLKSIZE ( sizeof ( union phantom_clp_data ) )
1480
1481 /**
1482  * Wait for Phantom CLP command to complete
1483  *
1484  * @v phantom           Phantom NIC
1485  * @ret rc              Return status code
1486  */
1487 static int phantom_clp_wait ( struct phantom_nic *phantom ) {
1488         unsigned int retries;
1489         uint32_t status;
1490
1491         for ( retries = 0 ; retries < PHN_CLP_CMD_TIMEOUT_MS ; retries++ ) {
1492                 status = phantom_readl ( phantom, UNM_CAM_RAM_CLP_STATUS );
1493                 if ( status & UNM_CAM_RAM_CLP_STATUS_DONE )
1494                         return 0;
1495                 mdelay ( 1 );
1496         }
1497
1498         DBGC ( phantom, "Phantom %p timed out waiting for CLP command\n",
1499                phantom );
1500         return -ETIMEDOUT;
1501 }
1502
1503 /**
1504  * Issue Phantom CLP command
1505  *
1506  * @v phantom           Phantom NIC
1507  * @v port              Virtual port number
1508  * @v opcode            Opcode
1509  * @v data_in           Data in, or NULL
1510  * @v data_out          Data out, or NULL
1511  * @v offset            Offset within data
1512  * @v len               Data buffer length
1513  * @ret len             Total transfer length (for reads), or negative error
1514  */
1515 static int phantom_clp_cmd ( struct phantom_nic *phantom, unsigned int port,
1516                              unsigned int opcode, const void *data_in,
1517                              void *data_out, size_t offset, size_t len ) {
1518         union phantom_clp_data data;
1519         unsigned int index = ( offset / sizeof ( data ) );
1520         unsigned int last = 0;
1521         size_t in_frag_len;
1522         uint8_t *in_frag;
1523         uint32_t command;
1524         uint32_t status;
1525         size_t read_len;
1526         unsigned int error;
1527         size_t out_frag_len;
1528         uint8_t *out_frag;
1529         int rc;
1530
1531         /* Sanity checks */
1532         assert ( ( offset % sizeof ( data ) ) == 0 );
1533         if ( len > 255 ) {
1534                 DBGC ( phantom, "Phantom %p invalid CLP length %zd\n",
1535                        phantom, len );
1536                 return -EINVAL;
1537         }
1538
1539         /* Check that CLP interface is ready */
1540         if ( ( rc = phantom_clp_wait ( phantom ) ) != 0 )
1541                 return rc;
1542
1543         /* Copy data in */
1544         memset ( &data, 0, sizeof ( data ) );
1545         if ( data_in ) {
1546                 assert ( offset < len );
1547                 in_frag_len = ( len - offset );
1548                 if ( in_frag_len > sizeof ( data ) ) {
1549                         in_frag_len = sizeof ( data );
1550                 } else {
1551                         last = 1;
1552                 }
1553                 in_frag = &data.bytes[ sizeof ( data ) - in_frag_len ];
1554                 memcpy ( in_frag, ( data_in + offset ), in_frag_len );
1555                 phantom_writel ( phantom, be32_to_cpu ( data.dwords.lo ),
1556                                  UNM_CAM_RAM_CLP_DATA_LO );
1557                 phantom_writel ( phantom, be32_to_cpu ( data.dwords.hi ),
1558                                  UNM_CAM_RAM_CLP_DATA_HI );
1559         }
1560
1561         /* Issue CLP command */
1562         command = ( ( index << 24 ) | ( ( data_in ? len : 0 ) << 16 ) |
1563                     ( port << 8 ) | ( last << 7 ) | ( opcode << 0 ) );
1564         phantom_writel ( phantom, command, UNM_CAM_RAM_CLP_COMMAND );
1565         mb();
1566         phantom_writel ( phantom, UNM_CAM_RAM_CLP_STATUS_START,
1567                          UNM_CAM_RAM_CLP_STATUS );
1568
1569         /* Wait for command to complete */
1570         if ( ( rc = phantom_clp_wait ( phantom ) ) != 0 )
1571                 return rc;
1572
1573         /* Get command status */
1574         status = phantom_readl ( phantom, UNM_CAM_RAM_CLP_STATUS );
1575         read_len = ( ( status >> 16 ) & 0xff );
1576         error = ( ( status >> 8 ) & 0xff );
1577         if ( error ) {
1578                 DBGC ( phantom, "Phantom %p CLP command error %02x\n",
1579                        phantom, error );
1580                 return -EIO;
1581         }
1582
1583         /* Copy data out */
1584         if ( data_out ) {
1585                 data.dwords.lo = cpu_to_be32 ( phantom_readl ( phantom,
1586                                                   UNM_CAM_RAM_CLP_DATA_LO ) );
1587                 data.dwords.hi = cpu_to_be32 ( phantom_readl ( phantom,
1588                                                   UNM_CAM_RAM_CLP_DATA_HI ) );
1589                 out_frag_len = ( read_len - offset );
1590                 if ( out_frag_len > sizeof ( data ) )
1591                         out_frag_len = sizeof ( data );
1592                 out_frag = &data.bytes[ sizeof ( data ) - out_frag_len ];
1593                 if ( out_frag_len > ( len - offset ) )
1594                         out_frag_len = ( len - offset );
1595                 memcpy ( ( data_out + offset ), out_frag, out_frag_len );
1596         }
1597
1598         return read_len;
1599 }
1600
1601 /**
1602  * Store Phantom CLP setting
1603  *
1604  * @v phantom           Phantom NIC
1605  * @v port              Virtual port number
1606  * @v setting           Setting number
1607  * @v data              Data buffer
1608  * @v len               Length of data buffer
1609  * @ret rc              Return status code
1610  */
1611 static int phantom_clp_store ( struct phantom_nic *phantom, unsigned int port,
1612                                unsigned int setting, const void *data,
1613                                size_t len ) {
1614         unsigned int opcode = setting;
1615         size_t offset;
1616         int rc;
1617
1618         for ( offset = 0 ; offset < len ; offset += PHN_CLP_BLKSIZE ) {
1619                 if ( ( rc = phantom_clp_cmd ( phantom, port, opcode, data,
1620                                               NULL, offset, len ) ) < 0 )
1621                         return rc;
1622         }
1623         return 0;
1624 }
1625
1626 /**
1627  * Fetch Phantom CLP setting
1628  *
1629  * @v phantom           Phantom NIC
1630  * @v port              Virtual port number
1631  * @v setting           Setting number
1632  * @v data              Data buffer
1633  * @v len               Length of data buffer
1634  * @ret len             Length of setting, or negative error
1635  */
1636 static int phantom_clp_fetch ( struct phantom_nic *phantom, unsigned int port,
1637                                unsigned int setting, void *data, size_t len ) {
1638         unsigned int opcode = ( setting + 1 );
1639         size_t offset = 0;
1640         int read_len;
1641
1642         while ( 1 ) {
1643                 read_len = phantom_clp_cmd ( phantom, port, opcode, NULL,
1644                                              data, offset, len );
1645                 if ( read_len < 0 )
1646                         return read_len;
1647                 offset += PHN_CLP_BLKSIZE;
1648                 if ( offset >= ( unsigned ) read_len )
1649                         break;
1650                 if ( offset >= len )
1651                         break;
1652         }
1653         return read_len;
1654 }
1655
1656 /** A Phantom CLP setting */
1657 struct phantom_clp_setting {
1658         /** iPXE setting */
1659         const struct setting *setting;
1660         /** Setting number */
1661         unsigned int clp_setting;
1662 };
1663
1664 /** Phantom CLP settings */
1665 static struct phantom_clp_setting clp_settings[] = {
1666         { &mac_setting, 0x01 },
1667 };
1668
1669 /**
1670  * Find Phantom CLP setting
1671  *
1672  * @v setting           iPXE setting
1673  * @v clp_setting       Setting number, or 0 if not found
1674  */
1675 static unsigned int
1676 phantom_clp_setting ( struct phantom_nic *phantom,
1677                       const struct setting *setting ) {
1678         struct phantom_clp_setting *clp_setting;
1679         unsigned int i;
1680
1681         /* Search the list of explicitly-defined settings */
1682         for ( i = 0 ; i < ( sizeof ( clp_settings ) /
1683                             sizeof ( clp_settings[0] ) ) ; i++ ) {
1684                 clp_setting = &clp_settings[i];
1685                 if ( setting_cmp ( setting, clp_setting->setting ) == 0 )
1686                         return clp_setting->clp_setting;
1687         }
1688
1689         /* Allow for use of numbered settings */
1690         if ( setting->scope == &phantom_settings_scope )
1691                 return setting->tag;
1692
1693         DBGC2 ( phantom, "Phantom %p has no \"%s\" setting\n",
1694                 phantom, setting->name );
1695
1696         return 0;
1697 }
1698
1699 /**
1700  * Check applicability of Phantom CLP setting
1701  *
1702  * @v settings          Settings block
1703  * @v setting           Setting
1704  * @ret applies         Setting applies within this settings block
1705  */
1706 static int phantom_setting_applies ( struct settings *settings,
1707                                      const struct setting *setting ) {
1708         struct phantom_nic *phantom =
1709                 container_of ( settings, struct phantom_nic, settings );
1710         unsigned int clp_setting;
1711
1712         /* Find Phantom setting equivalent to iPXE setting */
1713         clp_setting = phantom_clp_setting ( phantom, setting );
1714         return ( clp_setting != 0 );
1715 }
1716
1717 /**
1718  * Store Phantom CLP setting
1719  *
1720  * @v settings          Settings block
1721  * @v setting           Setting to store
1722  * @v data              Setting data, or NULL to clear setting
1723  * @v len               Length of setting data
1724  * @ret rc              Return status code
1725  */
1726 static int phantom_store_setting ( struct settings *settings,
1727                                    const struct setting *setting,
1728                                    const void *data, size_t len ) {
1729         struct phantom_nic *phantom =
1730                 container_of ( settings, struct phantom_nic, settings );
1731         unsigned int clp_setting;
1732         int rc;
1733
1734         /* Find Phantom setting equivalent to iPXE setting */
1735         clp_setting = phantom_clp_setting ( phantom, setting );
1736         assert ( clp_setting != 0 );
1737
1738         /* Store setting */
1739         if ( ( rc = phantom_clp_store ( phantom, phantom->port,
1740                                         clp_setting, data, len ) ) != 0 ) {
1741                 DBGC ( phantom, "Phantom %p could not store setting \"%s\": "
1742                        "%s\n", phantom, setting->name, strerror ( rc ) );
1743                 return rc;
1744         }
1745
1746         return 0;
1747 }
1748
1749 /**
1750  * Fetch Phantom CLP setting
1751  *
1752  * @v settings          Settings block
1753  * @v setting           Setting to fetch
1754  * @v data              Buffer to fill with setting data
1755  * @v len               Length of buffer
1756  * @ret len             Length of setting data, or negative error
1757  */
1758 static int phantom_fetch_setting ( struct settings *settings,
1759                                    struct setting *setting,
1760                                    void *data, size_t len ) {
1761         struct phantom_nic *phantom =
1762                 container_of ( settings, struct phantom_nic, settings );
1763         unsigned int clp_setting;
1764         int read_len;
1765         int rc;
1766
1767         /* Find Phantom setting equivalent to iPXE setting */
1768         clp_setting = phantom_clp_setting ( phantom, setting );
1769         assert ( clp_setting != 0 );
1770
1771         /* Fetch setting */
1772         if ( ( read_len = phantom_clp_fetch ( phantom, phantom->port,
1773                                               clp_setting, data, len ) ) < 0 ){
1774                 rc = read_len;
1775                 DBGC ( phantom, "Phantom %p could not fetch setting \"%s\": "
1776                        "%s\n", phantom, setting->name, strerror ( rc ) );
1777                 return rc;
1778         }
1779
1780         return read_len;
1781 }
1782
1783 /** Phantom CLP settings operations */
1784 static struct settings_operations phantom_settings_operations = {
1785         .applies        = phantom_setting_applies,
1786         .store          = phantom_store_setting,
1787         .fetch          = phantom_fetch_setting,
1788 };
1789
1790 /***************************************************************************
1791  *
1792  * Initialisation
1793  *
1794  */
1795
1796 /**
1797  * Map Phantom CRB window
1798  *
1799  * @v phantom           Phantom NIC
1800  * @ret rc              Return status code
1801  */
1802 static int phantom_map_crb ( struct phantom_nic *phantom,
1803                              struct pci_device *pci ) {
1804         unsigned long bar0_start;
1805         unsigned long bar0_size;
1806
1807         bar0_start = pci_bar_start ( pci, PCI_BASE_ADDRESS_0 );
1808         bar0_size = pci_bar_size ( pci, PCI_BASE_ADDRESS_0 );
1809         DBGC ( phantom, "Phantom %p is " PCI_FMT " with BAR0 at %08lx+%lx\n",
1810                phantom, PCI_ARGS ( pci ), bar0_start, bar0_size );
1811
1812         if ( ! bar0_start ) {
1813                 DBGC ( phantom, "Phantom %p BAR not assigned; ignoring\n",
1814                        phantom );
1815                 return -EINVAL;
1816         }
1817
1818         switch ( bar0_size ) {
1819         case ( 128 * 1024 * 1024 ) :
1820                 DBGC ( phantom, "Phantom %p has 128MB BAR\n", phantom );
1821                 phantom->crb_access = phantom_crb_access_128m;
1822                 break;
1823         case ( 32 * 1024 * 1024 ) :
1824                 DBGC ( phantom, "Phantom %p has 32MB BAR\n", phantom );
1825                 phantom->crb_access = phantom_crb_access_32m;
1826                 break;
1827         case ( 2 * 1024 * 1024 ) :
1828                 DBGC ( phantom, "Phantom %p has 2MB BAR\n", phantom );
1829                 phantom->crb_access = phantom_crb_access_2m;
1830                 break;
1831         default:
1832                 DBGC ( phantom, "Phantom %p has bad BAR size\n", phantom );
1833                 return -EINVAL;
1834         }
1835
1836         phantom->bar0 = ioremap ( bar0_start, bar0_size );
1837         if ( ! phantom->bar0 ) {
1838                 DBGC ( phantom, "Phantom %p could not map BAR0\n", phantom );
1839                 return -EIO;
1840         }
1841
1842         /* Mark current CRB window as invalid, so that the first
1843          * read/write will set the current window.
1844          */
1845         phantom->crb_window = -1UL;
1846
1847         return 0;
1848 }
1849
1850 /**
1851  * Unhalt all PEGs
1852  *
1853  * @v phantom           Phantom NIC
1854  */
1855 static void phantom_unhalt_pegs ( struct phantom_nic *phantom ) {
1856         uint32_t halt_status;
1857
1858         halt_status = phantom_readl ( phantom, UNM_PEG_0_HALT_STATUS );
1859         phantom_writel ( phantom, halt_status, UNM_PEG_0_HALT_STATUS );
1860         halt_status = phantom_readl ( phantom, UNM_PEG_1_HALT_STATUS );
1861         phantom_writel ( phantom, halt_status, UNM_PEG_1_HALT_STATUS );
1862         halt_status = phantom_readl ( phantom, UNM_PEG_2_HALT_STATUS );
1863         phantom_writel ( phantom, halt_status, UNM_PEG_2_HALT_STATUS );
1864         halt_status = phantom_readl ( phantom, UNM_PEG_3_HALT_STATUS );
1865         phantom_writel ( phantom, halt_status, UNM_PEG_3_HALT_STATUS );
1866         halt_status = phantom_readl ( phantom, UNM_PEG_4_HALT_STATUS );
1867         phantom_writel ( phantom, halt_status, UNM_PEG_4_HALT_STATUS );
1868 }
1869
1870 /**
1871  * Initialise the Phantom command PEG
1872  *
1873  * @v phantom           Phantom NIC
1874  * @ret rc              Return status code
1875  */
1876 static int phantom_init_cmdpeg ( struct phantom_nic *phantom ) {
1877         uint32_t cold_boot;
1878         uint32_t sw_reset;
1879         unsigned int retries;
1880         uint32_t cmdpeg_state;
1881         uint32_t last_cmdpeg_state = 0;
1882
1883         /* Check for a previous initialisation.  This could have
1884          * happened if, for example, the BIOS used the UNDI API to
1885          * drive the NIC prior to a full PXE boot.
1886          */
1887         cmdpeg_state = phantom_readl ( phantom, UNM_NIC_REG_CMDPEG_STATE );
1888         if ( cmdpeg_state == UNM_NIC_REG_CMDPEG_STATE_INITIALIZE_ACK ) {
1889                 DBGC ( phantom, "Phantom %p command PEG already initialized\n",
1890                        phantom );
1891                 /* Unhalt the PEGs.  Previous firmware (e.g. BOFM) may
1892                  * have halted the PEGs to prevent internal bus
1893                  * collisions when the BIOS re-reads the expansion ROM.
1894                  */
1895                 phantom_unhalt_pegs ( phantom );
1896                 return 0;
1897         }
1898
1899         /* If this was a cold boot, check that the hardware came up ok */
1900         cold_boot = phantom_readl ( phantom, UNM_CAM_RAM_COLD_BOOT );
1901         if ( cold_boot == UNM_CAM_RAM_COLD_BOOT_MAGIC ) {
1902                 DBGC ( phantom, "Phantom %p coming up from cold boot\n",
1903                        phantom );
1904                 sw_reset = phantom_readl ( phantom, UNM_ROMUSB_GLB_SW_RESET );
1905                 if ( sw_reset != UNM_ROMUSB_GLB_SW_RESET_MAGIC ) {
1906                         DBGC ( phantom, "Phantom %p reset failed: %08x\n",
1907                                phantom, sw_reset );
1908                         return -EIO;
1909                 }
1910         } else {
1911                 DBGC ( phantom, "Phantom %p coming up from warm boot "
1912                        "(%08x)\n", phantom, cold_boot );
1913         }
1914         /* Clear cold-boot flag */
1915         phantom_writel ( phantom, 0, UNM_CAM_RAM_COLD_BOOT );
1916
1917         /* Set port modes */
1918         phantom_writel ( phantom, UNM_CAM_RAM_PORT_MODE_AUTO_NEG_1G,
1919                          UNM_CAM_RAM_WOL_PORT_MODE );
1920
1921         /* Pass dummy DMA area to card */
1922         phantom_write_hilo ( phantom, 0,
1923                              UNM_NIC_REG_DUMMY_BUF_ADDR_LO,
1924                              UNM_NIC_REG_DUMMY_BUF_ADDR_HI );
1925         phantom_writel ( phantom, UNM_NIC_REG_DUMMY_BUF_INIT,
1926                          UNM_NIC_REG_DUMMY_BUF );
1927
1928         /* Tell the hardware that tuning is complete */
1929         phantom_writel ( phantom, UNM_ROMUSB_GLB_PEGTUNE_DONE_MAGIC,
1930                          UNM_ROMUSB_GLB_PEGTUNE_DONE );
1931
1932         /* Wait for command PEG to finish initialising */
1933         DBGC ( phantom, "Phantom %p initialising command PEG (will take up to "
1934                "%d seconds)...\n", phantom, PHN_CMDPEG_INIT_TIMEOUT_SEC );
1935         for ( retries = 0; retries < PHN_CMDPEG_INIT_TIMEOUT_SEC; retries++ ) {
1936                 cmdpeg_state = phantom_readl ( phantom,
1937                                                UNM_NIC_REG_CMDPEG_STATE );
1938                 if ( cmdpeg_state != last_cmdpeg_state ) {
1939                         DBGC ( phantom, "Phantom %p command PEG state is "
1940                                "%08x after %d seconds...\n",
1941                                phantom, cmdpeg_state, retries );
1942                         last_cmdpeg_state = cmdpeg_state;
1943                 }
1944                 if ( cmdpeg_state == UNM_NIC_REG_CMDPEG_STATE_INITIALIZED ) {
1945                         /* Acknowledge the PEG initialisation */
1946                         phantom_writel ( phantom,
1947                                        UNM_NIC_REG_CMDPEG_STATE_INITIALIZE_ACK,
1948                                        UNM_NIC_REG_CMDPEG_STATE );
1949                         return 0;
1950                 }
1951                 mdelay ( 1000 );
1952         }
1953
1954         DBGC ( phantom, "Phantom %p timed out waiting for command PEG to "
1955                "initialise (status %08x)\n", phantom, cmdpeg_state );
1956         return -ETIMEDOUT;
1957 }
1958
1959 /**
1960  * Read Phantom MAC address
1961  *
1962  * @v phanton_port      Phantom NIC
1963  * @v hw_addr           Buffer to fill with MAC address
1964  */
1965 static void phantom_get_macaddr ( struct phantom_nic *phantom,
1966                                   uint8_t *hw_addr ) {
1967         union {
1968                 uint8_t mac_addr[2][ETH_ALEN];
1969                 uint32_t dwords[3];
1970         } u;
1971         unsigned long offset;
1972         int i;
1973
1974         /* Read the three dwords that include this MAC address and one other */
1975         offset = ( UNM_CAM_RAM_MAC_ADDRS +
1976                    ( 12 * ( phantom->port / 2 ) ) );
1977         for ( i = 0 ; i < 3 ; i++, offset += 4 ) {
1978                 u.dwords[i] = phantom_readl ( phantom, offset );
1979         }
1980
1981         /* Copy out the relevant MAC address */
1982         for ( i = 0 ; i < ETH_ALEN ; i++ ) {
1983                 hw_addr[ ETH_ALEN - i - 1 ] =
1984                         u.mac_addr[ phantom->port & 1 ][i];
1985         }
1986         DBGC ( phantom, "Phantom %p MAC address is %s\n",
1987                phantom, eth_ntoa ( hw_addr ) );
1988 }
1989
1990 /**
1991  * Check Phantom is enabled for boot
1992  *
1993  * @v phanton_port      Phantom NIC
1994  * @ret rc              Return status code
1995  *
1996  * This is something of an ugly hack to accommodate an OEM
1997  * requirement.  The NIC has only one expansion ROM BAR, rather than
1998  * one per port.  To allow individual ports to be selectively
1999  * enabled/disabled for PXE boot (as required), we must therefore
2000  * leave the expansion ROM always enabled, and place the per-port
2001  * enable/disable logic within the iPXE driver.
2002  */
2003 static int phantom_check_boot_enable ( struct phantom_nic *phantom ) {
2004         unsigned long boot_enable;
2005
2006         boot_enable = phantom_readl ( phantom, UNM_CAM_RAM_BOOT_ENABLE );
2007         if ( ! ( boot_enable & ( 1 << phantom->port ) ) ) {
2008                 DBGC ( phantom, "Phantom %p PXE boot is disabled\n",
2009                        phantom );
2010                 return -ENOTSUP;
2011         }
2012
2013         return 0;
2014 }
2015
2016 /**
2017  * Initialise Phantom receive PEG
2018  *
2019  * @v phantom           Phantom NIC
2020  * @ret rc              Return status code
2021  */
2022 static int phantom_init_rcvpeg ( struct phantom_nic *phantom ) {
2023         unsigned int retries;
2024         uint32_t rcvpeg_state;
2025         uint32_t last_rcvpeg_state = 0;
2026
2027         DBGC ( phantom, "Phantom %p initialising receive PEG (will take up to "
2028                "%d seconds)...\n", phantom, PHN_RCVPEG_INIT_TIMEOUT_SEC );
2029         for ( retries = 0; retries < PHN_RCVPEG_INIT_TIMEOUT_SEC; retries++ ) {
2030                 rcvpeg_state = phantom_readl ( phantom,
2031                                                UNM_NIC_REG_RCVPEG_STATE );
2032                 if ( rcvpeg_state != last_rcvpeg_state ) {
2033                         DBGC ( phantom, "Phantom %p receive PEG state is "
2034                                "%08x after %d seconds...\n",
2035                                phantom, rcvpeg_state, retries );
2036                         last_rcvpeg_state = rcvpeg_state;
2037                 }
2038                 if ( rcvpeg_state == UNM_NIC_REG_RCVPEG_STATE_INITIALIZED )
2039                         return 0;
2040                 mdelay ( 1000 );
2041         }
2042
2043         DBGC ( phantom, "Phantom %p timed out waiting for receive PEG to "
2044                "initialise (status %08x)\n", phantom, rcvpeg_state );
2045         return -ETIMEDOUT;
2046 }
2047
2048 /**
2049  * Probe PCI device
2050  *
2051  * @v pci               PCI device
2052  * @v id                PCI ID
2053  * @ret rc              Return status code
2054  */
2055 static int phantom_probe ( struct pci_device *pci ) {
2056         struct net_device *netdev;
2057         struct phantom_nic *phantom;
2058         struct settings *parent_settings;
2059         int rc;
2060
2061         /* Allocate Phantom device */
2062         netdev = alloc_etherdev ( sizeof ( *phantom ) );
2063         if ( ! netdev ) {
2064                 rc = -ENOMEM;
2065                 goto err_alloc_etherdev;
2066         }
2067         netdev_init ( netdev, &phantom_operations );
2068         phantom = netdev_priv ( netdev );
2069         pci_set_drvdata ( pci, netdev );
2070         netdev->dev = &pci->dev;
2071         memset ( phantom, 0, sizeof ( *phantom ) );
2072         phantom->port = PCI_FUNC ( pci->busdevfn );
2073         assert ( phantom->port < PHN_MAX_NUM_PORTS );
2074         settings_init ( &phantom->settings,
2075                         &phantom_settings_operations,
2076                         &netdev->refcnt, &phantom_settings_scope );
2077
2078         /* Fix up PCI device */
2079         adjust_pci_device ( pci );
2080
2081         /* Map CRB */
2082         if ( ( rc = phantom_map_crb ( phantom, pci ) ) != 0 )
2083                 goto err_map_crb;
2084
2085         /* BUG5945 - need to hack PCI config space on P3 B1 silicon.
2086          * B2 will have this fixed; remove this hack when B1 is no
2087          * longer in use.
2088          */
2089         if ( PCI_FUNC ( pci->busdevfn ) == 0 ) {
2090                 unsigned int i;
2091                 for ( i = 0 ; i < 8 ; i++ ) {
2092                         uint32_t temp;
2093                         pci->busdevfn =
2094                                 PCI_BUSDEVFN ( PCI_BUS ( pci->busdevfn ),
2095                                                PCI_SLOT ( pci->busdevfn ), i );
2096                         pci_read_config_dword ( pci, 0xc8, &temp );
2097                         pci_read_config_dword ( pci, 0xc8, &temp );
2098                         pci_write_config_dword ( pci, 0xc8, 0xf1000 );
2099                 }
2100                 pci->busdevfn = PCI_BUSDEVFN ( PCI_BUS ( pci->busdevfn ),
2101                                                PCI_SLOT ( pci->busdevfn ), 0 );
2102         }
2103
2104         /* Initialise the command PEG */
2105         if ( ( rc = phantom_init_cmdpeg ( phantom ) ) != 0 )
2106                 goto err_init_cmdpeg;
2107
2108         /* Initialise the receive PEG */
2109         if ( ( rc = phantom_init_rcvpeg ( phantom ) ) != 0 )
2110                 goto err_init_rcvpeg;
2111
2112         /* Read MAC addresses */
2113         phantom_get_macaddr ( phantom, netdev->hw_addr );
2114
2115         /* Skip if boot disabled on NIC */
2116         if ( ( rc = phantom_check_boot_enable ( phantom ) ) != 0 )
2117                 goto err_check_boot_enable;
2118
2119         /* Register network devices */
2120         if ( ( rc = register_netdev ( netdev ) ) != 0 ) {
2121                 DBGC ( phantom, "Phantom %p could not register net device: "
2122                        "%s\n", phantom, strerror ( rc ) );
2123                 goto err_register_netdev;
2124         }
2125
2126         /* Register settings blocks */
2127         parent_settings = netdev_settings ( netdev );
2128         if ( ( rc = register_settings ( &phantom->settings,
2129                                         parent_settings, "clp" ) ) != 0 ) {
2130                 DBGC ( phantom, "Phantom %p could not register settings: "
2131                        "%s\n", phantom, strerror ( rc ) );
2132                 goto err_register_settings;
2133         }
2134
2135         return 0;
2136
2137         unregister_settings ( &phantom->settings );
2138  err_register_settings:
2139         unregister_netdev ( netdev );
2140  err_register_netdev:
2141  err_check_boot_enable:
2142  err_init_rcvpeg:
2143  err_init_cmdpeg:
2144  err_map_crb:
2145         netdev_nullify ( netdev );
2146         netdev_put ( netdev );
2147  err_alloc_etherdev:
2148         return rc;
2149 }
2150
2151 /**
2152  * Remove PCI device
2153  *
2154  * @v pci               PCI device
2155  */
2156 static void phantom_remove ( struct pci_device *pci ) {
2157         struct net_device *netdev = pci_get_drvdata ( pci );
2158         struct phantom_nic *phantom = netdev_priv ( netdev );
2159
2160         unregister_settings ( &phantom->settings );
2161         unregister_netdev ( netdev );
2162         netdev_nullify ( netdev );
2163         netdev_put ( netdev );
2164 }
2165
2166 /** Phantom PCI IDs */
2167 static struct pci_device_id phantom_nics[] = {
2168         PCI_ROM ( 0x4040, 0x0100, "nx", "NX", 0 ),
2169 };
2170
2171 /** Phantom PCI driver */
2172 struct pci_driver phantom_driver __pci_driver = {
2173         .ids = phantom_nics,
2174         .id_count = ( sizeof ( phantom_nics ) / sizeof ( phantom_nics[0] ) ),
2175         .probe = phantom_probe,
2176         .remove = phantom_remove,
2177 };