tizen 2.3.1 release
[external/qemu.git] / 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 tag magic */
1458 #define PHN_CLP_TAG_MAGIC 0xc19c1900UL
1459
1460 /** Phantom CLP settings tag magic mask */
1461 #define PHN_CLP_TAG_MAGIC_MASK 0xffffff00UL
1462
1463 /** Phantom CLP data
1464  *
1465  */
1466 union phantom_clp_data {
1467         /** Data bytes
1468          *
1469          * This field is right-aligned; if only N bytes are present
1470          * then bytes[0]..bytes[7-N] should be zero, and the data
1471          * should be in bytes[7-N+1] to bytes[7];
1472          */
1473         uint8_t bytes[8];
1474         /** Dwords for the CLP interface */
1475         struct {
1476                 /** High dword, in network byte order */
1477                 uint32_t hi;
1478                 /** Low dword, in network byte order */
1479                 uint32_t lo;
1480         } dwords;
1481 };
1482 #define PHN_CLP_BLKSIZE ( sizeof ( union phantom_clp_data ) )
1483
1484 /**
1485  * Wait for Phantom CLP command to complete
1486  *
1487  * @v phantom           Phantom NIC
1488  * @ret rc              Return status code
1489  */
1490 static int phantom_clp_wait ( struct phantom_nic *phantom ) {
1491         unsigned int retries;
1492         uint32_t status;
1493
1494         for ( retries = 0 ; retries < PHN_CLP_CMD_TIMEOUT_MS ; retries++ ) {
1495                 status = phantom_readl ( phantom, UNM_CAM_RAM_CLP_STATUS );
1496                 if ( status & UNM_CAM_RAM_CLP_STATUS_DONE )
1497                         return 0;
1498                 mdelay ( 1 );
1499         }
1500
1501         DBGC ( phantom, "Phantom %p timed out waiting for CLP command\n",
1502                phantom );
1503         return -ETIMEDOUT;
1504 }
1505
1506 /**
1507  * Issue Phantom CLP command
1508  *
1509  * @v phantom           Phantom NIC
1510  * @v port              Virtual port number
1511  * @v opcode            Opcode
1512  * @v data_in           Data in, or NULL
1513  * @v data_out          Data out, or NULL
1514  * @v offset            Offset within data
1515  * @v len               Data buffer length
1516  * @ret len             Total transfer length (for reads), or negative error
1517  */
1518 static int phantom_clp_cmd ( struct phantom_nic *phantom, unsigned int port,
1519                              unsigned int opcode, const void *data_in,
1520                              void *data_out, size_t offset, size_t len ) {
1521         union phantom_clp_data data;
1522         unsigned int index = ( offset / sizeof ( data ) );
1523         unsigned int last = 0;
1524         size_t in_frag_len;
1525         uint8_t *in_frag;
1526         uint32_t command;
1527         uint32_t status;
1528         size_t read_len;
1529         unsigned int error;
1530         size_t out_frag_len;
1531         uint8_t *out_frag;
1532         int rc;
1533
1534         /* Sanity checks */
1535         assert ( ( offset % sizeof ( data ) ) == 0 );
1536         if ( len > 255 ) {
1537                 DBGC ( phantom, "Phantom %p invalid CLP length %zd\n",
1538                        phantom, len );
1539                 return -EINVAL;
1540         }
1541
1542         /* Check that CLP interface is ready */
1543         if ( ( rc = phantom_clp_wait ( phantom ) ) != 0 )
1544                 return rc;
1545
1546         /* Copy data in */
1547         memset ( &data, 0, sizeof ( data ) );
1548         if ( data_in ) {
1549                 assert ( offset < len );
1550                 in_frag_len = ( len - offset );
1551                 if ( in_frag_len > sizeof ( data ) ) {
1552                         in_frag_len = sizeof ( data );
1553                 } else {
1554                         last = 1;
1555                 }
1556                 in_frag = &data.bytes[ sizeof ( data ) - in_frag_len ];
1557                 memcpy ( in_frag, ( data_in + offset ), in_frag_len );
1558                 phantom_writel ( phantom, be32_to_cpu ( data.dwords.lo ),
1559                                  UNM_CAM_RAM_CLP_DATA_LO );
1560                 phantom_writel ( phantom, be32_to_cpu ( data.dwords.hi ),
1561                                  UNM_CAM_RAM_CLP_DATA_HI );
1562         }
1563
1564         /* Issue CLP command */
1565         command = ( ( index << 24 ) | ( ( data_in ? len : 0 ) << 16 ) |
1566                     ( port << 8 ) | ( last << 7 ) | ( opcode << 0 ) );
1567         phantom_writel ( phantom, command, UNM_CAM_RAM_CLP_COMMAND );
1568         mb();
1569         phantom_writel ( phantom, UNM_CAM_RAM_CLP_STATUS_START,
1570                          UNM_CAM_RAM_CLP_STATUS );
1571
1572         /* Wait for command to complete */
1573         if ( ( rc = phantom_clp_wait ( phantom ) ) != 0 )
1574                 return rc;
1575
1576         /* Get command status */
1577         status = phantom_readl ( phantom, UNM_CAM_RAM_CLP_STATUS );
1578         read_len = ( ( status >> 16 ) & 0xff );
1579         error = ( ( status >> 8 ) & 0xff );
1580         if ( error ) {
1581                 DBGC ( phantom, "Phantom %p CLP command error %02x\n",
1582                        phantom, error );
1583                 return -EIO;
1584         }
1585
1586         /* Copy data out */
1587         if ( data_out ) {
1588                 data.dwords.lo = cpu_to_be32 ( phantom_readl ( phantom,
1589                                                   UNM_CAM_RAM_CLP_DATA_LO ) );
1590                 data.dwords.hi = cpu_to_be32 ( phantom_readl ( phantom,
1591                                                   UNM_CAM_RAM_CLP_DATA_HI ) );
1592                 out_frag_len = ( read_len - offset );
1593                 if ( out_frag_len > sizeof ( data ) )
1594                         out_frag_len = sizeof ( data );
1595                 out_frag = &data.bytes[ sizeof ( data ) - out_frag_len ];
1596                 if ( out_frag_len > ( len - offset ) )
1597                         out_frag_len = ( len - offset );
1598                 memcpy ( ( data_out + offset ), out_frag, out_frag_len );
1599         }
1600
1601         return read_len;
1602 }
1603
1604 /**
1605  * Store Phantom CLP setting
1606  *
1607  * @v phantom           Phantom NIC
1608  * @v port              Virtual port number
1609  * @v setting           Setting number
1610  * @v data              Data buffer
1611  * @v len               Length of data buffer
1612  * @ret rc              Return status code
1613  */
1614 static int phantom_clp_store ( struct phantom_nic *phantom, unsigned int port,
1615                                unsigned int setting, const void *data,
1616                                size_t len ) {
1617         unsigned int opcode = setting;
1618         size_t offset;
1619         int rc;
1620
1621         for ( offset = 0 ; offset < len ; offset += PHN_CLP_BLKSIZE ) {
1622                 if ( ( rc = phantom_clp_cmd ( phantom, port, opcode, data,
1623                                               NULL, offset, len ) ) < 0 )
1624                         return rc;
1625         }
1626         return 0;
1627 }
1628
1629 /**
1630  * Fetch Phantom CLP setting
1631  *
1632  * @v phantom           Phantom NIC
1633  * @v port              Virtual port number
1634  * @v setting           Setting number
1635  * @v data              Data buffer
1636  * @v len               Length of data buffer
1637  * @ret len             Length of setting, or negative error
1638  */
1639 static int phantom_clp_fetch ( struct phantom_nic *phantom, unsigned int port,
1640                                unsigned int setting, void *data, size_t len ) {
1641         unsigned int opcode = ( setting + 1 );
1642         size_t offset = 0;
1643         int read_len;
1644
1645         while ( 1 ) {
1646                 read_len = phantom_clp_cmd ( phantom, port, opcode, NULL,
1647                                              data, offset, len );
1648                 if ( read_len < 0 )
1649                         return read_len;
1650                 offset += PHN_CLP_BLKSIZE;
1651                 if ( offset >= ( unsigned ) read_len )
1652                         break;
1653                 if ( offset >= len )
1654                         break;
1655         }
1656         return read_len;
1657 }
1658
1659 /** A Phantom CLP setting */
1660 struct phantom_clp_setting {
1661         /** iPXE setting */
1662         struct setting *setting;
1663         /** Setting number */
1664         unsigned int clp_setting;
1665 };
1666
1667 /** Phantom CLP settings */
1668 static struct phantom_clp_setting clp_settings[] = {
1669         { &mac_setting, 0x01 },
1670 };
1671
1672 /**
1673  * Find Phantom CLP setting
1674  *
1675  * @v setting           iPXE setting
1676  * @v clp_setting       Setting number, or 0 if not found
1677  */
1678 static unsigned int
1679 phantom_clp_setting ( struct phantom_nic *phantom, struct setting *setting ) {
1680         struct phantom_clp_setting *clp_setting;
1681         unsigned int i;
1682
1683         /* Search the list of explicitly-defined settings */
1684         for ( i = 0 ; i < ( sizeof ( clp_settings ) /
1685                             sizeof ( clp_settings[0] ) ) ; i++ ) {
1686                 clp_setting = &clp_settings[i];
1687                 if ( setting_cmp ( setting, clp_setting->setting ) == 0 )
1688                         return clp_setting->clp_setting;
1689         }
1690
1691         /* Allow for use of numbered settings */
1692         if ( ( setting->tag & PHN_CLP_TAG_MAGIC_MASK ) == PHN_CLP_TAG_MAGIC )
1693                 return ( setting->tag & ~PHN_CLP_TAG_MAGIC_MASK );
1694
1695         DBGC2 ( phantom, "Phantom %p has no \"%s\" setting\n",
1696                 phantom, setting->name );
1697
1698         return 0;
1699 }
1700
1701 /**
1702  * Check applicability of Phantom CLP setting
1703  *
1704  * @v settings          Settings block
1705  * @v setting           Setting
1706  * @ret applies         Setting applies within this settings block
1707  */
1708 static int phantom_setting_applies ( struct settings *settings,
1709                                      struct setting *setting ) {
1710         struct phantom_nic *phantom =
1711                 container_of ( settings, struct phantom_nic, settings );
1712         unsigned int clp_setting;
1713
1714         /* Find Phantom setting equivalent to iPXE setting */
1715         clp_setting = phantom_clp_setting ( phantom, setting );
1716         return ( clp_setting != 0 );
1717 }
1718
1719 /**
1720  * Store Phantom CLP setting
1721  *
1722  * @v settings          Settings block
1723  * @v setting           Setting to store
1724  * @v data              Setting data, or NULL to clear setting
1725  * @v len               Length of setting data
1726  * @ret rc              Return status code
1727  */
1728 static int phantom_store_setting ( struct settings *settings,
1729                                    struct setting *setting,
1730                                    const void *data, size_t len ) {
1731         struct phantom_nic *phantom =
1732                 container_of ( settings, struct phantom_nic, settings );
1733         unsigned int clp_setting;
1734         int rc;
1735
1736         /* Find Phantom setting equivalent to iPXE setting */
1737         clp_setting = phantom_clp_setting ( phantom, setting );
1738         assert ( clp_setting != 0 );
1739
1740         /* Store setting */
1741         if ( ( rc = phantom_clp_store ( phantom, phantom->port,
1742                                         clp_setting, data, len ) ) != 0 ) {
1743                 DBGC ( phantom, "Phantom %p could not store setting \"%s\": "
1744                        "%s\n", phantom, setting->name, strerror ( rc ) );
1745                 return rc;
1746         }
1747
1748         return 0;
1749 }
1750
1751 /**
1752  * Fetch Phantom CLP setting
1753  *
1754  * @v settings          Settings block
1755  * @v setting           Setting to fetch
1756  * @v data              Buffer to fill with setting data
1757  * @v len               Length of buffer
1758  * @ret len             Length of setting data, or negative error
1759  */
1760 static int phantom_fetch_setting ( struct settings *settings,
1761                                    struct setting *setting,
1762                                    void *data, size_t len ) {
1763         struct phantom_nic *phantom =
1764                 container_of ( settings, struct phantom_nic, settings );
1765         unsigned int clp_setting;
1766         int read_len;
1767         int rc;
1768
1769         /* Find Phantom setting equivalent to iPXE setting */
1770         clp_setting = phantom_clp_setting ( phantom, setting );
1771         assert ( clp_setting != 0 );
1772
1773         /* Fetch setting */
1774         if ( ( read_len = phantom_clp_fetch ( phantom, phantom->port,
1775                                               clp_setting, data, len ) ) < 0 ){
1776                 rc = read_len;
1777                 DBGC ( phantom, "Phantom %p could not fetch setting \"%s\": "
1778                        "%s\n", phantom, setting->name, strerror ( rc ) );
1779                 return rc;
1780         }
1781
1782         return read_len;
1783 }
1784
1785 /** Phantom CLP settings operations */
1786 static struct settings_operations phantom_settings_operations = {
1787         .applies        = phantom_setting_applies,
1788         .store          = phantom_store_setting,
1789         .fetch          = phantom_fetch_setting,
1790 };
1791
1792 /***************************************************************************
1793  *
1794  * Initialisation
1795  *
1796  */
1797
1798 /**
1799  * Map Phantom CRB window
1800  *
1801  * @v phantom           Phantom NIC
1802  * @ret rc              Return status code
1803  */
1804 static int phantom_map_crb ( struct phantom_nic *phantom,
1805                              struct pci_device *pci ) {
1806         unsigned long bar0_start;
1807         unsigned long bar0_size;
1808
1809         bar0_start = pci_bar_start ( pci, PCI_BASE_ADDRESS_0 );
1810         bar0_size = pci_bar_size ( pci, PCI_BASE_ADDRESS_0 );
1811         DBGC ( phantom, "Phantom %p is " PCI_FMT " with BAR0 at %08lx+%lx\n",
1812                phantom, PCI_ARGS ( pci ), bar0_start, bar0_size );
1813
1814         if ( ! bar0_start ) {
1815                 DBGC ( phantom, "Phantom %p BAR not assigned; ignoring\n",
1816                        phantom );
1817                 return -EINVAL;
1818         }
1819
1820         switch ( bar0_size ) {
1821         case ( 128 * 1024 * 1024 ) :
1822                 DBGC ( phantom, "Phantom %p has 128MB BAR\n", phantom );
1823                 phantom->crb_access = phantom_crb_access_128m;
1824                 break;
1825         case ( 32 * 1024 * 1024 ) :
1826                 DBGC ( phantom, "Phantom %p has 32MB BAR\n", phantom );
1827                 phantom->crb_access = phantom_crb_access_32m;
1828                 break;
1829         case ( 2 * 1024 * 1024 ) :
1830                 DBGC ( phantom, "Phantom %p has 2MB BAR\n", phantom );
1831                 phantom->crb_access = phantom_crb_access_2m;
1832                 break;
1833         default:
1834                 DBGC ( phantom, "Phantom %p has bad BAR size\n", phantom );
1835                 return -EINVAL;
1836         }
1837
1838         phantom->bar0 = ioremap ( bar0_start, bar0_size );
1839         if ( ! phantom->bar0 ) {
1840                 DBGC ( phantom, "Phantom %p could not map BAR0\n", phantom );
1841                 return -EIO;
1842         }
1843
1844         /* Mark current CRB window as invalid, so that the first
1845          * read/write will set the current window.
1846          */
1847         phantom->crb_window = -1UL;
1848
1849         return 0;
1850 }
1851
1852 /**
1853  * Unhalt all PEGs
1854  *
1855  * @v phantom           Phantom NIC
1856  */
1857 static void phantom_unhalt_pegs ( struct phantom_nic *phantom ) {
1858         uint32_t halt_status;
1859
1860         halt_status = phantom_readl ( phantom, UNM_PEG_0_HALT_STATUS );
1861         phantom_writel ( phantom, halt_status, UNM_PEG_0_HALT_STATUS );
1862         halt_status = phantom_readl ( phantom, UNM_PEG_1_HALT_STATUS );
1863         phantom_writel ( phantom, halt_status, UNM_PEG_1_HALT_STATUS );
1864         halt_status = phantom_readl ( phantom, UNM_PEG_2_HALT_STATUS );
1865         phantom_writel ( phantom, halt_status, UNM_PEG_2_HALT_STATUS );
1866         halt_status = phantom_readl ( phantom, UNM_PEG_3_HALT_STATUS );
1867         phantom_writel ( phantom, halt_status, UNM_PEG_3_HALT_STATUS );
1868         halt_status = phantom_readl ( phantom, UNM_PEG_4_HALT_STATUS );
1869         phantom_writel ( phantom, halt_status, UNM_PEG_4_HALT_STATUS );
1870 }
1871
1872 /**
1873  * Initialise the Phantom command PEG
1874  *
1875  * @v phantom           Phantom NIC
1876  * @ret rc              Return status code
1877  */
1878 static int phantom_init_cmdpeg ( struct phantom_nic *phantom ) {
1879         uint32_t cold_boot;
1880         uint32_t sw_reset;
1881         unsigned int retries;
1882         uint32_t cmdpeg_state;
1883         uint32_t last_cmdpeg_state = 0;
1884
1885         /* Check for a previous initialisation.  This could have
1886          * happened if, for example, the BIOS used the UNDI API to
1887          * drive the NIC prior to a full PXE boot.
1888          */
1889         cmdpeg_state = phantom_readl ( phantom, UNM_NIC_REG_CMDPEG_STATE );
1890         if ( cmdpeg_state == UNM_NIC_REG_CMDPEG_STATE_INITIALIZE_ACK ) {
1891                 DBGC ( phantom, "Phantom %p command PEG already initialized\n",
1892                        phantom );
1893                 /* Unhalt the PEGs.  Previous firmware (e.g. BOFM) may
1894                  * have halted the PEGs to prevent internal bus
1895                  * collisions when the BIOS re-reads the expansion ROM.
1896                  */
1897                 phantom_unhalt_pegs ( phantom );
1898                 return 0;
1899         }
1900
1901         /* If this was a cold boot, check that the hardware came up ok */
1902         cold_boot = phantom_readl ( phantom, UNM_CAM_RAM_COLD_BOOT );
1903         if ( cold_boot == UNM_CAM_RAM_COLD_BOOT_MAGIC ) {
1904                 DBGC ( phantom, "Phantom %p coming up from cold boot\n",
1905                        phantom );
1906                 sw_reset = phantom_readl ( phantom, UNM_ROMUSB_GLB_SW_RESET );
1907                 if ( sw_reset != UNM_ROMUSB_GLB_SW_RESET_MAGIC ) {
1908                         DBGC ( phantom, "Phantom %p reset failed: %08x\n",
1909                                phantom, sw_reset );
1910                         return -EIO;
1911                 }
1912         } else {
1913                 DBGC ( phantom, "Phantom %p coming up from warm boot "
1914                        "(%08x)\n", phantom, cold_boot );
1915         }
1916         /* Clear cold-boot flag */
1917         phantom_writel ( phantom, 0, UNM_CAM_RAM_COLD_BOOT );
1918
1919         /* Set port modes */
1920         phantom_writel ( phantom, UNM_CAM_RAM_PORT_MODE_AUTO_NEG_1G,
1921                          UNM_CAM_RAM_WOL_PORT_MODE );
1922
1923         /* Pass dummy DMA area to card */
1924         phantom_write_hilo ( phantom, 0,
1925                              UNM_NIC_REG_DUMMY_BUF_ADDR_LO,
1926                              UNM_NIC_REG_DUMMY_BUF_ADDR_HI );
1927         phantom_writel ( phantom, UNM_NIC_REG_DUMMY_BUF_INIT,
1928                          UNM_NIC_REG_DUMMY_BUF );
1929
1930         /* Tell the hardware that tuning is complete */
1931         phantom_writel ( phantom, UNM_ROMUSB_GLB_PEGTUNE_DONE_MAGIC,
1932                          UNM_ROMUSB_GLB_PEGTUNE_DONE );
1933
1934         /* Wait for command PEG to finish initialising */
1935         DBGC ( phantom, "Phantom %p initialising command PEG (will take up to "
1936                "%d seconds)...\n", phantom, PHN_CMDPEG_INIT_TIMEOUT_SEC );
1937         for ( retries = 0; retries < PHN_CMDPEG_INIT_TIMEOUT_SEC; retries++ ) {
1938                 cmdpeg_state = phantom_readl ( phantom,
1939                                                UNM_NIC_REG_CMDPEG_STATE );
1940                 if ( cmdpeg_state != last_cmdpeg_state ) {
1941                         DBGC ( phantom, "Phantom %p command PEG state is "
1942                                "%08x after %d seconds...\n",
1943                                phantom, cmdpeg_state, retries );
1944                         last_cmdpeg_state = cmdpeg_state;
1945                 }
1946                 if ( cmdpeg_state == UNM_NIC_REG_CMDPEG_STATE_INITIALIZED ) {
1947                         /* Acknowledge the PEG initialisation */
1948                         phantom_writel ( phantom,
1949                                        UNM_NIC_REG_CMDPEG_STATE_INITIALIZE_ACK,
1950                                        UNM_NIC_REG_CMDPEG_STATE );
1951                         return 0;
1952                 }
1953                 mdelay ( 1000 );
1954         }
1955
1956         DBGC ( phantom, "Phantom %p timed out waiting for command PEG to "
1957                "initialise (status %08x)\n", phantom, cmdpeg_state );
1958         return -ETIMEDOUT;
1959 }
1960
1961 /**
1962  * Read Phantom MAC address
1963  *
1964  * @v phanton_port      Phantom NIC
1965  * @v hw_addr           Buffer to fill with MAC address
1966  */
1967 static void phantom_get_macaddr ( struct phantom_nic *phantom,
1968                                   uint8_t *hw_addr ) {
1969         union {
1970                 uint8_t mac_addr[2][ETH_ALEN];
1971                 uint32_t dwords[3];
1972         } u;
1973         unsigned long offset;
1974         int i;
1975
1976         /* Read the three dwords that include this MAC address and one other */
1977         offset = ( UNM_CAM_RAM_MAC_ADDRS +
1978                    ( 12 * ( phantom->port / 2 ) ) );
1979         for ( i = 0 ; i < 3 ; i++, offset += 4 ) {
1980                 u.dwords[i] = phantom_readl ( phantom, offset );
1981         }
1982
1983         /* Copy out the relevant MAC address */
1984         for ( i = 0 ; i < ETH_ALEN ; i++ ) {
1985                 hw_addr[ ETH_ALEN - i - 1 ] =
1986                         u.mac_addr[ phantom->port & 1 ][i];
1987         }
1988         DBGC ( phantom, "Phantom %p MAC address is %s\n",
1989                phantom, eth_ntoa ( hw_addr ) );
1990 }
1991
1992 /**
1993  * Check Phantom is enabled for boot
1994  *
1995  * @v phanton_port      Phantom NIC
1996  * @ret rc              Return status code
1997  *
1998  * This is something of an ugly hack to accommodate an OEM
1999  * requirement.  The NIC has only one expansion ROM BAR, rather than
2000  * one per port.  To allow individual ports to be selectively
2001  * enabled/disabled for PXE boot (as required), we must therefore
2002  * leave the expansion ROM always enabled, and place the per-port
2003  * enable/disable logic within the iPXE driver.
2004  */
2005 static int phantom_check_boot_enable ( struct phantom_nic *phantom ) {
2006         unsigned long boot_enable;
2007
2008         boot_enable = phantom_readl ( phantom, UNM_CAM_RAM_BOOT_ENABLE );
2009         if ( ! ( boot_enable & ( 1 << phantom->port ) ) ) {
2010                 DBGC ( phantom, "Phantom %p PXE boot is disabled\n",
2011                        phantom );
2012                 return -ENOTSUP;
2013         }
2014
2015         return 0;
2016 }
2017
2018 /**
2019  * Initialise Phantom receive PEG
2020  *
2021  * @v phantom           Phantom NIC
2022  * @ret rc              Return status code
2023  */
2024 static int phantom_init_rcvpeg ( struct phantom_nic *phantom ) {
2025         unsigned int retries;
2026         uint32_t rcvpeg_state;
2027         uint32_t last_rcvpeg_state = 0;
2028
2029         DBGC ( phantom, "Phantom %p initialising receive PEG (will take up to "
2030                "%d seconds)...\n", phantom, PHN_RCVPEG_INIT_TIMEOUT_SEC );
2031         for ( retries = 0; retries < PHN_RCVPEG_INIT_TIMEOUT_SEC; retries++ ) {
2032                 rcvpeg_state = phantom_readl ( phantom,
2033                                                UNM_NIC_REG_RCVPEG_STATE );
2034                 if ( rcvpeg_state != last_rcvpeg_state ) {
2035                         DBGC ( phantom, "Phantom %p receive PEG state is "
2036                                "%08x after %d seconds...\n",
2037                                phantom, rcvpeg_state, retries );
2038                         last_rcvpeg_state = rcvpeg_state;
2039                 }
2040                 if ( rcvpeg_state == UNM_NIC_REG_RCVPEG_STATE_INITIALIZED )
2041                         return 0;
2042                 mdelay ( 1000 );
2043         }
2044
2045         DBGC ( phantom, "Phantom %p timed out waiting for receive PEG to "
2046                "initialise (status %08x)\n", phantom, rcvpeg_state );
2047         return -ETIMEDOUT;
2048 }
2049
2050 /**
2051  * Probe PCI device
2052  *
2053  * @v pci               PCI device
2054  * @v id                PCI ID
2055  * @ret rc              Return status code
2056  */
2057 static int phantom_probe ( struct pci_device *pci ) {
2058         struct net_device *netdev;
2059         struct phantom_nic *phantom;
2060         struct settings *parent_settings;
2061         int rc;
2062
2063         /* Allocate Phantom device */
2064         netdev = alloc_etherdev ( sizeof ( *phantom ) );
2065         if ( ! netdev ) {
2066                 rc = -ENOMEM;
2067                 goto err_alloc_etherdev;
2068         }
2069         netdev_init ( netdev, &phantom_operations );
2070         phantom = netdev_priv ( netdev );
2071         pci_set_drvdata ( pci, netdev );
2072         netdev->dev = &pci->dev;
2073         memset ( phantom, 0, sizeof ( *phantom ) );
2074         phantom->port = PCI_FUNC ( pci->busdevfn );
2075         assert ( phantom->port < PHN_MAX_NUM_PORTS );
2076         settings_init ( &phantom->settings,
2077                         &phantom_settings_operations,
2078                         &netdev->refcnt, PHN_CLP_TAG_MAGIC );
2079
2080         /* Fix up PCI device */
2081         adjust_pci_device ( pci );
2082
2083         /* Map CRB */
2084         if ( ( rc = phantom_map_crb ( phantom, pci ) ) != 0 )
2085                 goto err_map_crb;
2086
2087         /* BUG5945 - need to hack PCI config space on P3 B1 silicon.
2088          * B2 will have this fixed; remove this hack when B1 is no
2089          * longer in use.
2090          */
2091         if ( PCI_FUNC ( pci->busdevfn ) == 0 ) {
2092                 unsigned int i;
2093                 for ( i = 0 ; i < 8 ; i++ ) {
2094                         uint32_t temp;
2095                         pci->busdevfn =
2096                                 PCI_BUSDEVFN ( PCI_BUS ( pci->busdevfn ),
2097                                                PCI_SLOT ( pci->busdevfn ), i );
2098                         pci_read_config_dword ( pci, 0xc8, &temp );
2099                         pci_read_config_dword ( pci, 0xc8, &temp );
2100                         pci_write_config_dword ( pci, 0xc8, 0xf1000 );
2101                 }
2102                 pci->busdevfn = PCI_BUSDEVFN ( PCI_BUS ( pci->busdevfn ),
2103                                                PCI_SLOT ( pci->busdevfn ), 0 );
2104         }
2105
2106         /* Initialise the command PEG */
2107         if ( ( rc = phantom_init_cmdpeg ( phantom ) ) != 0 )
2108                 goto err_init_cmdpeg;
2109
2110         /* Initialise the receive PEG */
2111         if ( ( rc = phantom_init_rcvpeg ( phantom ) ) != 0 )
2112                 goto err_init_rcvpeg;
2113
2114         /* Read MAC addresses */
2115         phantom_get_macaddr ( phantom, netdev->hw_addr );
2116
2117         /* Skip if boot disabled on NIC */
2118         if ( ( rc = phantom_check_boot_enable ( phantom ) ) != 0 )
2119                 goto err_check_boot_enable;
2120
2121         /* Register network devices */
2122         if ( ( rc = register_netdev ( netdev ) ) != 0 ) {
2123                 DBGC ( phantom, "Phantom %p could not register net device: "
2124                        "%s\n", phantom, strerror ( rc ) );
2125                 goto err_register_netdev;
2126         }
2127
2128         /* Register settings blocks */
2129         parent_settings = netdev_settings ( netdev );
2130         if ( ( rc = register_settings ( &phantom->settings,
2131                                         parent_settings, "clp" ) ) != 0 ) {
2132                 DBGC ( phantom, "Phantom %p could not register settings: "
2133                        "%s\n", phantom, strerror ( rc ) );
2134                 goto err_register_settings;
2135         }
2136
2137         return 0;
2138
2139         unregister_settings ( &phantom->settings );
2140  err_register_settings:
2141         unregister_netdev ( netdev );
2142  err_register_netdev:
2143  err_check_boot_enable:
2144  err_init_rcvpeg:
2145  err_init_cmdpeg:
2146  err_map_crb:
2147         netdev_nullify ( netdev );
2148         netdev_put ( netdev );
2149  err_alloc_etherdev:
2150         return rc;
2151 }
2152
2153 /**
2154  * Remove PCI device
2155  *
2156  * @v pci               PCI device
2157  */
2158 static void phantom_remove ( struct pci_device *pci ) {
2159         struct net_device *netdev = pci_get_drvdata ( pci );
2160         struct phantom_nic *phantom = netdev_priv ( netdev );
2161
2162         unregister_settings ( &phantom->settings );
2163         unregister_netdev ( netdev );
2164         netdev_nullify ( netdev );
2165         netdev_put ( netdev );
2166 }
2167
2168 /** Phantom PCI IDs */
2169 static struct pci_device_id phantom_nics[] = {
2170         PCI_ROM ( 0x4040, 0x0100, "nx", "NX", 0 ),
2171 };
2172
2173 /** Phantom PCI driver */
2174 struct pci_driver phantom_driver __pci_driver = {
2175         .ids = phantom_nics,
2176         .id_count = ( sizeof ( phantom_nics ) / sizeof ( phantom_nics[0] ) ),
2177         .probe = phantom_probe,
2178         .remove = phantom_remove,
2179 };