]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/staging/csr/csr_wifi_hip_card_sdio.c
staging: csr: Remove unused macros
[karo-tx-linux.git] / drivers / staging / csr / csr_wifi_hip_card_sdio.c
1 /*****************************************************************************
2
3             (c) Cambridge Silicon Radio Limited 2012
4             All rights reserved and confidential information of CSR
5
6             Refer to LICENSE.txt included with this source for details
7             on the license terms.
8
9 *****************************************************************************/
10
11 /*
12  * ---------------------------------------------------------------------------
13  * FILE: csr_wifi_hip_card_sdio.c
14  *
15  * PURPOSE: Implementation of the Card API for SDIO.
16  *
17  * NOTES:
18  *      CardInit() is called from the SDIO probe callback when a card is
19  *      inserted. This performs the basic SDIO initialisation, enabling i/o
20  *      etc.
21  *
22  * ---------------------------------------------------------------------------
23  */
24 #include "csr_wifi_hip_unifi.h"
25 #include "csr_wifi_hip_conversions.h"
26 #include "csr_wifi_hip_unifiversion.h"
27 #include "csr_wifi_hip_card.h"
28 #include "csr_wifi_hip_card_sdio.h"
29 #include "csr_wifi_hip_chiphelper.h"
30
31
32 /* Time to wait between attempts to read MAILBOX0 */
33 #define MAILBOX1_TIMEOUT                10  /* in millisecs */
34 #define MAILBOX1_ATTEMPTS               200 /* 2 seconds */
35
36 #define MAILBOX2_TIMEOUT                5   /* in millisecs */
37 #define MAILBOX2_ATTEMPTS               10  /* 50ms */
38
39 #define RESET_SETTLE_DELAY              25  /* in millisecs */
40
41 static CsrResult card_init_slots(card_t *card);
42 static CsrResult card_hw_init(card_t *card);
43 static CsrResult firmware_present_in_flash(card_t *card);
44 static void bootstrap_chip_hw(card_t *card);
45 static CsrResult unifi_reset_hardware(card_t *card);
46 static CsrResult unifi_hip_init(card_t *card);
47 static CsrResult card_access_panic(card_t *card);
48 static CsrResult unifi_read_chip_version(card_t *card);
49
50 /*
51  * ---------------------------------------------------------------------------
52  *  unifi_alloc_card
53  *
54  *      Allocate and initialise the card context structure.
55  *
56  *  Arguments:
57  *      sdio            Pointer to SDIO context pointer to pass to low
58  *                      level i/o functions.
59  *      ospriv          Pointer to O/S private struct to pass when calling
60  *                      callbacks to the higher level system.
61  *
62  *  Returns:
63  *      Pointer to card struct, which represents the driver context or
64  *      NULL if the allocation failed.
65  * ---------------------------------------------------------------------------
66  */
67 card_t* unifi_alloc_card(CsrSdioFunction *sdio, void *ospriv)
68 {
69     card_t *card;
70     CsrUint32 i;
71
72     func_enter();
73
74
75     card = (card_t *)CsrMemAlloc(sizeof(card_t));
76     if (card == NULL)
77     {
78         return NULL;
79     }
80     CsrMemSet(card, 0, sizeof(card_t));
81
82
83     card->sdio_if = sdio;
84     card->ospriv  = ospriv;
85
86     card->unifi_interrupt_seq = 1;
87
88     /* Make these invalid. */
89     card->proc_select = (CsrUint32)(-1);
90     card->dmem_page = (CsrUint32)(-1);
91     card->pmem_page = (CsrUint32)(-1);
92
93     card->bh_reason_host = 0;
94     card->bh_reason_unifi = 0;
95
96     for (i = 0; i < sizeof(card->tx_q_paused_flag) / sizeof(card->tx_q_paused_flag[0]); i++)
97     {
98         card->tx_q_paused_flag[i] = 0;
99     }
100     card->memory_resources_allocated = 0;
101
102     card->low_power_mode = UNIFI_LOW_POWER_DISABLED;
103     card->periodic_wake_mode = UNIFI_PERIODIC_WAKE_HOST_DISABLED;
104
105     card->host_state = UNIFI_HOST_STATE_AWAKE;
106     card->intmode = CSR_WIFI_INTMODE_DEFAULT;
107
108     /*
109      * Memory resources for buffers are allocated when the chip is initialised
110      * because we need configuration information from the firmware.
111      */
112
113     /*
114      * Initialise wait queues and lists
115      */
116     card->fh_command_queue.q_body = card->fh_command_q_body;
117     card->fh_command_queue.q_length = UNIFI_SOFT_COMMAND_Q_LENGTH;
118
119     for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
120     {
121         card->fh_traffic_queue[i].q_body = card->fh_traffic_q_body[i];
122         card->fh_traffic_queue[i].q_length = UNIFI_SOFT_TRAFFIC_Q_LENGTH;
123     }
124
125
126     /* Initialise mini-coredump pointers in case no coredump buffers
127      * are requested by the OS layer.
128      */
129     card->request_coredump_on_reset = 0;
130     card->dump_next_write = NULL;
131     card->dump_cur_read = NULL;
132     card->dump_buf = NULL;
133
134 #ifdef UNIFI_DEBUG
135     /* Determine offset of LSB in pointer for later alignment sanity check.
136      * Synergy integer types have specific widths, which cause compiler
137      * warnings when casting pointer types, e.g. on 64-bit systems.
138      */
139     {
140         CsrUint32 val = 0x01234567;
141
142         if (*((CsrUint8 *)&val) == 0x01)
143         {
144             card->lsb = sizeof(void *) - 1;     /* BE */
145         }
146         else
147         {
148             card->lsb = 0;                      /* LE */
149         }
150     }
151 #endif
152     func_exit();
153     return card;
154 } /* unifi_alloc_card() */
155
156
157 /*
158  * ---------------------------------------------------------------------------
159  *  unifi_init_card
160  *
161  *      Reset the hardware and perform HIP initialization
162  *
163  *  Arguments:
164  *      card        Pointer to card struct
165  *
166  *  Returns:
167  *      CsrResult code
168  *      CSR_RESULT_SUCCESS if successful
169  * ---------------------------------------------------------------------------
170  */
171 CsrResult unifi_init_card(card_t *card, CsrInt32 led_mask)
172 {
173     CsrResult r;
174
175     func_enter();
176
177     if (card == NULL)
178     {
179         func_exit_r(CSR_WIFI_HIP_RESULT_INVALID_VALUE);
180         return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
181     }
182
183     r = unifi_init(card);
184     if (r != CSR_RESULT_SUCCESS)
185     {
186         func_exit_r(r);
187         return r;
188     }
189
190     r = unifi_hip_init(card);
191     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
192     {
193         func_exit_r(r);
194         return r;
195     }
196     if (r != CSR_RESULT_SUCCESS)
197     {
198         unifi_error(card->ospriv, "Failed to start host protocol.\n");
199         func_exit_r(r);
200         return r;
201     }
202
203     func_exit();
204     return CSR_RESULT_SUCCESS;
205 }
206
207
208 /*
209  * ---------------------------------------------------------------------------
210  *  unifi_init
211  *
212  *      Init the hardware.
213  *
214  *  Arguments:
215  *      card        Pointer to card struct
216  *
217  *  Returns:
218  *      CsrResult code
219  *      CSR_RESULT_SUCCESS if successful
220  * ---------------------------------------------------------------------------
221  */
222 CsrResult unifi_init(card_t *card)
223 {
224     CsrResult r;
225     CsrResult csrResult;
226
227     func_enter();
228
229     if (card == NULL)
230     {
231         func_exit_r(CSR_WIFI_HIP_RESULT_INVALID_VALUE);
232         return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
233     }
234
235     /*
236      * Disable the SDIO interrupts while initialising UniFi.
237      * Re-enable them when f/w is running.
238      */
239     csrResult = CsrSdioInterruptDisable(card->sdio_if);
240     if (csrResult == CSR_SDIO_RESULT_NO_DEVICE)
241     {
242         return CSR_WIFI_HIP_RESULT_NO_DEVICE;
243     }
244
245     /*
246      * UniFi's PLL may start with a slow clock (~ 1 MHz) so initially
247      * set the SDIO bus clock to a similar value or SDIO accesses may
248      * fail.
249      */
250     csrResult = CsrSdioMaxBusClockFrequencySet(card->sdio_if, UNIFI_SDIO_CLOCK_SAFE_HZ);
251     if (csrResult != CSR_RESULT_SUCCESS)
252     {
253         r = ConvertCsrSdioToCsrHipResult(card, csrResult);
254         func_exit_r(r);
255         return r;
256     }
257     card->sdio_clock_speed = UNIFI_SDIO_CLOCK_SAFE_HZ;
258
259     /*
260      * Reset UniFi. Note, this only resets the WLAN function part of the chip,
261      * the SDIO interface is not reset.
262      */
263     unifi_trace(card->ospriv, UDBG1, "Resetting UniFi\n");
264     r = unifi_reset_hardware(card);
265     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
266     {
267         return r;
268     }
269     if (r != CSR_RESULT_SUCCESS)
270     {
271         unifi_error(card->ospriv, "Failed to reset UniFi\n");
272         func_exit_r(r);
273         return r;
274     }
275
276     /* Reset the power save mode, to be active until the MLME-reset is complete */
277     r = unifi_configure_low_power_mode(card,
278                                        UNIFI_LOW_POWER_DISABLED, UNIFI_PERIODIC_WAKE_HOST_DISABLED);
279     if (r != CSR_RESULT_SUCCESS)
280     {
281         unifi_error(card->ospriv, "Failed to set power save mode\n");
282         func_exit_r(r);
283         return r;
284     }
285
286     /*
287      * Set initial value of page registers.
288      * The page registers will be maintained by unifi_read...() and
289      * unifi_write...().
290      */
291     card->proc_select = (CsrUint32)(-1);
292     card->dmem_page = (CsrUint32)(-1);
293     card->pmem_page = (CsrUint32)(-1);
294     r = unifi_write_direct16(card, ChipHelper_HOST_WINDOW3_PAGE(card->helper) * 2, 0);
295     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
296     {
297         return r;
298     }
299     if (r != CSR_RESULT_SUCCESS)
300     {
301         unifi_error(card->ospriv, "Failed to write SHARED_DMEM_PAGE\n");
302         func_exit_r(r);
303         return r;
304     }
305     r = unifi_write_direct16(card, ChipHelper_HOST_WINDOW2_PAGE(card->helper) * 2, 0);
306     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
307     {
308         return r;
309     }
310     if (r != CSR_RESULT_SUCCESS)
311     {
312         unifi_error(card->ospriv, "Failed to write PROG_MEM2_PAGE\n");
313         func_exit_r(r);
314         return r;
315     }
316
317     /*
318      * If the driver has reset UniFi due to previous SDIO failure, this may
319      * have been due to a chip watchdog reset. In this case, the driver may
320      * have requested a mini-coredump which needs to be captured now the
321      * SDIO interface is alive.
322      */
323     (void)unifi_coredump_handle_request(card);
324
325     /*
326      * Probe to see if the UniFi has ROM/flash to boot from. CSR6xxx should do.
327      */
328     r = firmware_present_in_flash(card);
329     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
330     {
331         return r;
332     }
333     if (r == CSR_WIFI_HIP_RESULT_NOT_FOUND)
334     {
335         unifi_error(card->ospriv, "No firmware found\n");
336     }
337     else if (r != CSR_RESULT_SUCCESS)
338     {
339         unifi_error(card->ospriv, "Probe for Flash failed\n");
340     }
341
342     func_exit_r(r);
343     return r;
344 } /* unifi_init() */
345
346
347 /*
348  * ---------------------------------------------------------------------------
349  *  unifi_download
350  *
351  *      Load the firmware.
352  *
353  *  Arguments:
354  *      card        Pointer to card struct
355  *      led_mask    Loader LED mask
356  *
357  *  Returns:
358  *      CSR_RESULT_SUCCESS on success
359  *      CsrResult error code on failure.
360  * ---------------------------------------------------------------------------
361  */
362 CsrResult unifi_download(card_t *card, CsrInt32 led_mask)
363 {
364     CsrResult r;
365     void *dlpriv;
366
367     func_enter();
368
369     if (card == NULL)
370     {
371         func_exit_r(CSR_WIFI_HIP_RESULT_INVALID_VALUE);
372         return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
373     }
374
375     /* Set the loader led mask */
376     card->loader_led_mask = led_mask;
377
378     /* Get the firmware file information */
379     unifi_trace(card->ospriv, UDBG1, "downloading firmware...\n");
380
381     dlpriv = unifi_dl_fw_read_start(card, UNIFI_FW_STA);
382     if (dlpriv == NULL)
383     {
384         func_exit_r(CSR_WIFI_HIP_RESULT_NOT_FOUND);
385         return CSR_WIFI_HIP_RESULT_NOT_FOUND;
386     }
387
388     /* Download the firmware. */
389     r = unifi_dl_firmware(card, dlpriv);
390     if (r != CSR_RESULT_SUCCESS)
391     {
392         unifi_error(card->ospriv, "Failed to download firmware\n");
393         func_exit_r(r);
394         return r;
395     }
396
397     /* Free the firmware file information. */
398     unifi_fw_read_stop(card->ospriv, dlpriv);
399
400     func_exit();
401
402     return CSR_RESULT_SUCCESS;
403 } /* unifi_download() */
404
405
406 /*
407  * ---------------------------------------------------------------------------
408  *  unifi_hip_init
409  *
410  *      This function performs the f/w initialisation sequence as described
411  *      in the Unifi Host Interface Protocol Specification.
412  *      It allocates memory for host-side slot data and signal queues.
413  *
414  *  Arguments:
415  *      card        Pointer to card struct
416  *
417  *  Returns:
418  *      CSR_RESULT_SUCCESS on success or else a CSR error code
419  *
420  *  Notes:
421  *      The firmware must have been downloaded.
422  * ---------------------------------------------------------------------------
423  */
424 static CsrResult unifi_hip_init(card_t *card)
425 {
426     CsrResult r;
427     CsrResult csrResult;
428
429     func_enter();
430
431     r = card_hw_init(card);
432     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
433     {
434         return r;
435     }
436     if (r != CSR_RESULT_SUCCESS)
437     {
438         unifi_error(card->ospriv, "Failed to establish communication with UniFi\n");
439         func_exit_r(r);
440         return r;
441     }
442 #ifdef CSR_PRE_ALLOC_NET_DATA
443     /* if there is any preallocated netdata left from the prev session free it now */
444     prealloc_netdata_free(card);
445 #endif
446     /*
447      * Allocate memory for host-side slot data and signal queues.
448      * We need the config info read from the firmware to know how much
449      * memory to allocate.
450      */
451     r = card_init_slots(card);
452     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
453     {
454         return r;
455     }
456     if (r != CSR_RESULT_SUCCESS)
457     {
458         unifi_error(card->ospriv, "Init slots failed: %d\n", r);
459         func_exit_r(r);
460         return r;
461     }
462
463     unifi_trace(card->ospriv, UDBG2, "Sending first UniFi interrupt\n");
464
465     r = unifi_set_host_state(card, UNIFI_HOST_STATE_AWAKE);
466     if (r != CSR_RESULT_SUCCESS)
467     {
468         func_exit_r(r);
469         return r;
470     }
471
472     /* Enable the SDIO interrupts now that the f/w is running. */
473     csrResult = CsrSdioInterruptEnable(card->sdio_if);
474     if (csrResult == CSR_SDIO_RESULT_NO_DEVICE)
475     {
476         return CSR_WIFI_HIP_RESULT_NO_DEVICE;
477     }
478
479     /* Signal the UniFi to start handling messages */
480     r = CardGenInt(card);
481     if (r != CSR_RESULT_SUCCESS)
482     {
483         func_exit_r(r);
484         return r;
485     }
486
487     func_exit();
488
489     return CSR_RESULT_SUCCESS;
490 } /* unifi_hip_init() */
491
492
493 /*
494  * ---------------------------------------------------------------------------
495  *  _build_sdio_config_data
496  *
497  *      Unpack the SDIO configuration information from a buffer read from
498  *      UniFi into a host structure.
499  *      The data is byte-swapped for a big-endian host if necessary by the
500  *      UNPACK... macros.
501  *
502  *  Arguments:
503  *      card            Pointer to card struct
504  *      cfg_data        Destination structure to unpack into.
505  *      cfg_data_buf    Source buffer to read from. This should be the raw
506  *                      data read from UniFi.
507  *
508  *  Returns:
509  *      None.
510  * ---------------------------------------------------------------------------
511  */
512 static void _build_sdio_config_data(sdio_config_data_t *cfg_data,
513                                     const CsrUint8     *cfg_data_buf)
514 {
515     CsrInt16 offset = 0;
516
517     cfg_data->version = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
518     offset += SIZEOF_UINT16;
519
520     cfg_data->sdio_ctrl_offset = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
521     offset += SIZEOF_UINT16;
522
523     cfg_data->fromhost_sigbuf_handle = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
524     offset += SIZEOF_UINT16;
525
526     cfg_data->tohost_sigbuf_handle = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
527     offset += SIZEOF_UINT16;
528
529     cfg_data->num_fromhost_sig_frags = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
530     offset += SIZEOF_UINT16;
531
532     cfg_data->num_tohost_sig_frags = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
533     offset += SIZEOF_UINT16;
534
535     cfg_data->num_fromhost_data_slots = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
536     offset += SIZEOF_UINT16;
537
538     cfg_data->num_tohost_data_slots = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
539     offset += SIZEOF_UINT16;
540
541     cfg_data->data_slot_size = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
542     offset += SIZEOF_UINT16;
543
544     cfg_data->initialised = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
545     offset += SIZEOF_UINT16;
546
547     cfg_data->overlay_size = CSR_GET_UINT32_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
548     offset += SIZEOF_UINT32;
549
550     cfg_data->data_slot_round = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
551     offset += SIZEOF_UINT16;
552
553     cfg_data->sig_frag_size = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
554     offset += SIZEOF_UINT16;
555
556     cfg_data->tohost_signal_padding = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(cfg_data_buf + offset);
557 } /* _build_sdio_config_data() */
558
559
560 /*
561  * - Function ----------------------------------------------------------------
562  * card_hw_init()
563  *
564  *      Perform the initialisation procedure described in the UniFi Host
565  *      Interface Protocol document (section 3.3.8) and read the run-time
566  *      configuration information from the UniFi. This is stuff like number
567  *      of bulk data slots etc.
568  *
569  *      The card enumeration and SD initialisation has already been done by
570  *      the SDIO library, see card_sdio_init().
571  *
572  *      The initialisation is done when firmware is ready, i.e. this may need
573  *      to be called after a f/w download operation.
574  *
575  *      The initialisation procedure goes like this:
576  *       - Wait for UniFi to start-up by polling SHARED_MAILBOX1
577  *       - Find the symbol table and look up SLT_SDIO_SLOT_CONFIG
578  *       - Read the config structure
579  *       - Check the "SDIO initialised" flag, if not zero do a h/w reset and
580  *         start again
581  *       - Decide the number of bulk data slots to allocate, allocate them and
582  *         set "SDIO initialised" flag (and generate an interrupt) to say so.
583  *
584  * Arguments:
585  *      card        Pointer to card struct
586  *
587  * Returns:
588  *      CSR_RESULT_SUCEESS on success,
589  *      a CSR error code on failure
590  *
591  * Notes:
592  *      All data in the f/w is stored in a little endian format, without any
593  *      padding bytes. Every read from this memory has to be transformed in
594  *      host (cpu specific) format, before it is stored in driver's parameters
595  *      or/and structures. Athough unifi_card_read16() and unifi_read32() do perform
596  *      the convertion internally, unifi_readn() does not.
597  * ---------------------------------------------------------------------------
598  */
599 static CsrResult card_hw_init(card_t *card)
600 {
601     CsrUint32 slut_address;
602     CsrUint16 initialised;
603     CsrUint16 finger_print;
604     symbol_t slut;
605     sdio_config_data_t *cfg_data;
606     CsrUint8 cfg_data_buf[SDIO_CONFIG_DATA_SIZE];
607     CsrResult r;
608     void *dlpriv;
609     CsrInt16 major, minor;
610     CsrInt16 search_4slut_again;
611     CsrResult csrResult;
612
613     func_enter();
614
615     /*
616      * The device revision from the TPLMID_MANF and TPLMID_CARD fields
617      * of the CIS are available as
618      *   card->sdio_if->pDevice->ManfID
619      *   card->sdio_if->pDevice->AppID
620      */
621
622     /*
623      * Run in a loop so we can patch.
624      */
625     do
626     {
627         /* Reset these each time around the loop. */
628         search_4slut_again = 0;
629         cfg_data = NULL;
630
631         r = card_wait_for_firmware_to_start(card, &slut_address);
632         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
633         {
634             return r;
635         }
636         if (r != CSR_RESULT_SUCCESS)
637         {
638             unifi_error(card->ospriv, "Firmware hasn't started\n");
639             func_exit_r(r);
640             return r;
641         }
642         unifi_trace(card->ospriv, UDBG4, "SLUT addr 0x%lX\n", slut_address);
643
644         /*
645          * Firmware has started, but doesn't know full clock configuration yet
646          * as some of the information may be in the MIB. Therefore we set an
647          * initial SDIO clock speed, faster than UNIFI_SDIO_CLOCK_SAFE_HZ, for
648          * the patch download and subsequent firmware initialisation, and
649          * full speed UNIFI_SDIO_CLOCK_MAX_HZ will be set once the f/w tells us
650          * that it is ready.
651          */
652         csrResult = CsrSdioMaxBusClockFrequencySet(card->sdio_if, UNIFI_SDIO_CLOCK_INIT_HZ);
653         if (csrResult != CSR_RESULT_SUCCESS)
654         {
655             r = ConvertCsrSdioToCsrHipResult(card, csrResult);
656             func_exit_r(r);
657             return r;
658         }
659         card->sdio_clock_speed = UNIFI_SDIO_CLOCK_INIT_HZ;
660
661         /*
662          * Check the SLUT fingerprint.
663          * The slut_address is a generic pointer so we must use unifi_card_read16().
664          */
665         unifi_trace(card->ospriv, UDBG4, "Looking for SLUT finger print\n");
666         finger_print = 0;
667         r = unifi_card_read16(card, slut_address, &finger_print);
668         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
669         {
670             return r;
671         }
672         if (r != CSR_RESULT_SUCCESS)
673         {
674             unifi_error(card->ospriv, "Failed to read SLUT finger print\n");
675             func_exit_r(r);
676             return r;
677         }
678
679         if (finger_print != SLUT_FINGERPRINT)
680         {
681             unifi_error(card->ospriv, "Failed to find Symbol lookup table fingerprint\n");
682             func_exit_r(CSR_RESULT_FAILURE);
683             return CSR_RESULT_FAILURE;
684         }
685
686         /* Symbol table starts imedately after the fingerprint */
687         slut_address += 2;
688
689         /* Search the table until either the end marker is found, or the
690          * loading of patch firmware invalidates the current table.
691          */
692         while (!search_4slut_again)
693         {
694             CsrUint16 s;
695             CsrUint32 l;
696
697             r = unifi_card_read16(card, slut_address, &s);
698             if (r != CSR_RESULT_SUCCESS)
699             {
700                 func_exit_r(r);
701                 return r;
702             }
703             slut_address += 2;
704
705             if (s == CSR_SLT_END)
706             {
707                 unifi_trace(card->ospriv, UDBG3, "  found CSR_SLT_END\n");
708                 break;
709             }
710
711             r = unifi_read32(card, slut_address, &l);
712             if (r != CSR_RESULT_SUCCESS)
713             {
714                 func_exit_r(r);
715                 return r;
716             }
717             slut_address += 4;
718
719             slut.id = s;
720             slut.obj = l;
721
722             unifi_trace(card->ospriv, UDBG3, "  found SLUT id %02d.%08lx\n", slut.id, slut.obj);
723             switch (slut.id)
724             {
725                 case CSR_SLT_SDIO_SLOT_CONFIG:
726                     cfg_data = &card->config_data;
727                     /*
728                      * unifi_card_readn reads n bytes from the card, where data is stored
729                      * in a little endian format, without any padding bytes. So, we
730                      * can not just pass the cfg_data pointer or use the
731                      * sizeof(sdio_config_data_t) since the structure in the host can
732                      * be big endian formatted or have padding bytes for alignment.
733                      * We use a char buffer to read the data from the card.
734                      */
735                     r = unifi_card_readn(card, slut.obj, cfg_data_buf, SDIO_CONFIG_DATA_SIZE);
736                     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
737                     {
738                         return r;
739                     }
740                     if (r != CSR_RESULT_SUCCESS)
741                     {
742                         unifi_error(card->ospriv, "Failed to read config data\n");
743                         func_exit_r(r);
744                         return r;
745                     }
746                     /* .. and then we copy the data to the host structure */
747                     _build_sdio_config_data(cfg_data, cfg_data_buf);
748
749                     /* Make sure the from host data slots are what we expect
750                         we reserve 2 for commands and there should be at least
751                         1 left for each access category */
752                     if ((cfg_data->num_fromhost_data_slots < UNIFI_RESERVED_COMMAND_SLOTS)
753                         || (cfg_data->num_fromhost_data_slots - UNIFI_RESERVED_COMMAND_SLOTS) / UNIFI_NO_OF_TX_QS == 0)
754                     {
755                         unifi_error(card->ospriv, "From host data slots %d\n", cfg_data->num_fromhost_data_slots);
756                         unifi_error(card->ospriv, "need to be (queues * x + 2) (UNIFI_RESERVED_COMMAND_SLOTS for commands)\n");
757                         func_exit_r(CSR_RESULT_FAILURE);
758                         return CSR_RESULT_FAILURE;
759                     }
760
761                     /* Configure SDIO to-block-size padding */
762                     if (card->sdio_io_block_pad)
763                     {
764                     /*
765                      * Firmware limits the maximum padding size via data_slot_round.
766                      * Therefore when padding to whole block sizes, the block size
767                      * must be configured correctly by adjusting CSR_WIFI_HIP_SDIO_BLOCK_SIZE.
768                      */
769                         if (cfg_data->data_slot_round < card->sdio_io_block_size)
770                         {
771                             unifi_error(card->ospriv,
772                                         "Configuration error: Block size of %d exceeds f/w data_slot_round of %d\n",
773                                         card->sdio_io_block_size, cfg_data->data_slot_round);
774                             return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
775                         }
776
777                         /*
778                          * To force the To-Host signals to be rounded up to the SDIO block
779                          * size, we need to write the To-Host Signal Padding Fragments
780                          * field of the SDIO configuration in UniFi.
781                          */
782                         if ((card->sdio_io_block_size % cfg_data->sig_frag_size) != 0)
783                         {
784                             unifi_error(card->ospriv, "Configuration error: Can not pad to-host signals.\n");
785                             func_exit_r(CSR_WIFI_HIP_RESULT_INVALID_VALUE);
786                             return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
787                         }
788                         cfg_data->tohost_signal_padding = (CsrUint16) (card->sdio_io_block_size / cfg_data->sig_frag_size);
789                         unifi_info(card->ospriv, "SDIO block size %d requires %d padding chunks\n",
790                                    card->sdio_io_block_size, cfg_data->tohost_signal_padding);
791                         r = unifi_card_write16(card, slut.obj + SDIO_TO_HOST_SIG_PADDING_OFFSET, cfg_data->tohost_signal_padding);
792                         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
793                         {
794                             return r;
795                         }
796                         if (r != CSR_RESULT_SUCCESS)
797                         {
798                             unifi_error(card->ospriv, "Failed to write To-Host Signal Padding Fragments\n");
799                             func_exit_r(r);
800                             return r;
801                         }
802                     }
803
804                     /* Reconstruct the Generic Pointer address of the
805                      * SDIO Control Data Struct.
806                      */
807                     card->sdio_ctrl_addr = cfg_data->sdio_ctrl_offset | (UNIFI_SH_DMEM << 24);
808                     card->init_flag_addr = slut.obj + SDIO_INIT_FLAG_OFFSET;
809                     break;
810
811                 case CSR_SLT_BUILD_ID_NUMBER:
812                 {
813                     CsrUint32 n;
814                     r = unifi_read32(card, slut.obj, &n);
815                     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
816                     {
817                         return r;
818                     }
819                     if (r != CSR_RESULT_SUCCESS)
820                     {
821                         unifi_error(card->ospriv, "Failed to read build id\n");
822                         func_exit_r(r);
823                         return r;
824                     }
825                     card->build_id = n;
826                 }
827                 break;
828
829                 case CSR_SLT_BUILD_ID_STRING:
830                     r = unifi_readnz(card, slut.obj, card->build_id_string,
831                                      sizeof(card->build_id_string));
832                     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
833                     {
834                         return r;
835                     }
836                     if (r != CSR_RESULT_SUCCESS)
837                     {
838                         unifi_error(card->ospriv, "Failed to read build string\n");
839                         func_exit_r(r);
840                         return r;
841                     }
842                     break;
843
844                 case CSR_SLT_PERSISTENT_STORE_DB:
845                     break;
846
847                 case CSR_SLT_BOOT_LOADER_CONTROL:
848
849                     /* This command copies most of the station firmware
850                      * image from ROM into program RAM.  It also clears
851                      * out the zerod data and sets up the initialised
852                      * data. */
853                     r = unifi_do_loader_op(card, slut.obj + 6, UNIFI_BOOT_LOADER_LOAD_STA);
854                     if (r != CSR_RESULT_SUCCESS)
855                     {
856                         unifi_error(card->ospriv, "Failed to write loader load image command\n");
857                         func_exit_r(r);
858                         return r;
859                     }
860
861                     dlpriv = unifi_dl_fw_read_start(card, UNIFI_FW_STA);
862
863                     /* dlpriv might be NULL, we still need to do the do_loader_op step. */
864                     if (dlpriv != NULL)
865                     {
866                     /* Download the firmware. */
867                         r = unifi_dl_patch(card, dlpriv, slut.obj);
868
869                     /* Free the firmware file information. */
870                         unifi_fw_read_stop(card->ospriv, dlpriv);
871
872                         if (r != CSR_RESULT_SUCCESS)
873                         {
874                             unifi_error(card->ospriv, "Failed to patch firmware\n");
875                             func_exit_r(r);
876                             return r;
877                         }
878                     }
879
880                     /* This command starts the firmware image that we want (the
881                     * station by default) with any patches required applied. */
882                     r = unifi_do_loader_op(card, slut.obj + 6, UNIFI_BOOT_LOADER_RESTART);
883                     if (r != CSR_RESULT_SUCCESS)
884                     {
885                         unifi_error(card->ospriv, "Failed to write loader restart command\n");
886                         func_exit_r(r);
887                         return r;
888                     }
889
890                     /* The now running patch f/w defines a new SLUT data structure -
891                      * the current one is no longer valid. We must drop out of the
892                      * processing loop and enumerate the new SLUT (which may appear
893                      * at a different offset).
894                      */
895                     search_4slut_again = 1;
896                     break;
897
898                 case CSR_SLT_PANIC_DATA_PHY:
899                     card->panic_data_phy_addr = slut.obj;
900                     break;
901
902                 case CSR_SLT_PANIC_DATA_MAC:
903                     card->panic_data_mac_addr = slut.obj;
904                     break;
905
906                 default:
907                     /* do nothing */
908                     break;
909             }
910         } /* while */
911     } while (search_4slut_again);
912
913     /* Did we find the Config Data ? */
914     if (cfg_data == NULL)
915     {
916         unifi_error(card->ospriv, "Failed to find SDIO_SLOT_CONFIG Symbol\n");
917         func_exit_r(CSR_RESULT_FAILURE);
918         return CSR_RESULT_FAILURE;
919     }
920
921     /*
922      * Has ths card already been initialised?
923      * If so, return an error so we do a h/w reset and start again.
924      */
925     r = unifi_card_read16(card, card->init_flag_addr, &initialised);
926     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
927     {
928         return r;
929     }
930     if (r != CSR_RESULT_SUCCESS)
931     {
932         unifi_error(card->ospriv, "Failed to read init flag at %08lx\n",
933                     card->init_flag_addr);
934         func_exit_r(r);
935         return r;
936     }
937     if (initialised != 0)
938     {
939         func_exit_r(CSR_RESULT_FAILURE);
940         return CSR_RESULT_FAILURE;
941     }
942
943
944     /*
945      * Now check the UniFi firmware version
946      */
947     major = (cfg_data->version >> 8) & 0xFF;
948     minor = cfg_data->version & 0xFF;
949     unifi_info(card->ospriv, "UniFi f/w protocol version %d.%d (driver %d.%d)\n",
950                major, minor,
951                UNIFI_HIP_MAJOR_VERSION, UNIFI_HIP_MINOR_VERSION);
952
953     unifi_info(card->ospriv, "Firmware build %u: %s\n",
954                card->build_id, card->build_id_string);
955
956     if (major != UNIFI_HIP_MAJOR_VERSION)
957     {
958         unifi_error(card->ospriv, "UniFi f/w protocol major version (%d) is different from driver (v%d.%d)\n",
959                     major, UNIFI_HIP_MAJOR_VERSION, UNIFI_HIP_MINOR_VERSION);
960 #ifndef CSR_WIFI_DISABLE_HIP_VERSION_CHECK
961         func_exit_r(CSR_RESULT_FAILURE);
962         return CSR_RESULT_FAILURE;
963 #endif
964     }
965     if (minor < UNIFI_HIP_MINOR_VERSION)
966     {
967         unifi_error(card->ospriv, "UniFi f/w protocol version (v%d.%d) is older than minimum required by driver (v%d.%d).\n",
968                     major, minor,
969                     UNIFI_HIP_MAJOR_VERSION, UNIFI_HIP_MINOR_VERSION);
970 #ifndef CSR_WIFI_DISABLE_HIP_VERSION_CHECK
971         func_exit_r(CSR_RESULT_FAILURE);
972         return CSR_RESULT_FAILURE;
973 #endif
974     }
975
976     /* Read panic codes from a previous firmware panic. If the firmware has
977      * not panicked since power was applied (e.g. power-off hard reset)
978      * the stored panic codes will not be updated.
979      */
980     unifi_read_panic(card);
981
982     func_exit();
983     return CSR_RESULT_SUCCESS;
984 } /* card_hw_init() */
985
986
987 /*
988  * ---------------------------------------------------------------------------
989  *  card_wait_for_unifi_to_reset
990  *
991  *      Waits for a reset to complete by polling the WLAN function enable
992  *      bit (which is cleared on reset).
993  *
994  *  Arguments:
995  *      card            Pointer to card struct
996  *
997  *  Returns:
998  *      CSR_RESULT_SUCCESS on success, CSR error code on failure.
999  * ---------------------------------------------------------------------------
1000  */
1001 static CsrResult card_wait_for_unifi_to_reset(card_t *card)
1002 {
1003     CsrInt16 i;
1004     CsrResult r;
1005     CsrUint8 io_enable;
1006     CsrResult csrResult;
1007
1008     func_enter();
1009
1010     r = CSR_RESULT_SUCCESS;
1011     for (i = 0; i < MAILBOX2_ATTEMPTS; i++)
1012     {
1013         unifi_trace(card->ospriv, UDBG1, "waiting for reset to complete, attempt %d\n", i);
1014         if (card->chip_id > SDIO_CARD_ID_UNIFI_2)
1015         {
1016             /* It's quite likely that this read will timeout for the
1017              * first few tries - especially if we have reset via
1018              * DBG_RESET.
1019              */
1020 #if defined (CSR_WIFI_HIP_DEBUG_OFFLINE) && defined (CSR_WIFI_HIP_SDIO_TRACE)
1021             unifi_debug_log_to_buf("m0@%02X=", SDIO_IO_READY);
1022 #endif
1023             csrResult = CsrSdioF0Read8(card->sdio_if, SDIO_IO_READY, &io_enable);
1024 #if defined (CSR_WIFI_HIP_DEBUG_OFFLINE) && defined (CSR_WIFI_HIP_SDIO_TRACE)
1025             if (csrResult != CSR_RESULT_SUCCESS)
1026             {
1027                 unifi_debug_log_to_buf("error=%X\n", csrResult);
1028             }
1029             else
1030             {
1031                 unifi_debug_log_to_buf("%X\n", io_enable);
1032             }
1033 #endif
1034             if (csrResult == CSR_SDIO_RESULT_NO_DEVICE)
1035             {
1036                 return CSR_WIFI_HIP_RESULT_NO_DEVICE;
1037             }
1038             r = CSR_RESULT_SUCCESS;
1039             if (csrResult != CSR_RESULT_SUCCESS)
1040             {
1041                 r = ConvertCsrSdioToCsrHipResult(card, csrResult);
1042             }
1043         }
1044         else
1045         {
1046             r = sdio_read_f0(card, SDIO_IO_ENABLE, &io_enable);
1047         }
1048         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
1049         {
1050             return r;
1051         }
1052         if (r == CSR_RESULT_SUCCESS)
1053         {
1054             CsrUint16 mbox2;
1055             CsrInt16 enabled = io_enable & (1 << card->function);
1056
1057             if (!enabled)
1058             {
1059                 unifi_trace(card->ospriv, UDBG1,
1060                             "Reset complete (function %d is disabled) in ~ %u msecs\n",
1061                             card->function, i * MAILBOX2_TIMEOUT);
1062
1063                 /* Enable WLAN function and verify MAILBOX2 is zero'd */
1064                 csrResult = CsrSdioFunctionEnable(card->sdio_if);
1065                 if (csrResult != CSR_RESULT_SUCCESS)
1066                 {
1067                     r = ConvertCsrSdioToCsrHipResult(card, csrResult);
1068                     unifi_error(card->ospriv, "CsrSdioFunctionEnable failed %d\n", r);
1069                     break;
1070                 }
1071             }
1072
1073             r = unifi_read_direct16(card, ChipHelper_SDIO_HIP_HANDSHAKE(card->helper) * 2, &mbox2);
1074             if (r != CSR_RESULT_SUCCESS)
1075             {
1076                 unifi_error(card->ospriv, "read HIP_HANDSHAKE failed %d\n", r);
1077                 break;
1078             }
1079             if (mbox2 != 0)
1080             {
1081                 unifi_error(card->ospriv, "MAILBOX2 non-zero after reset (mbox2 = %04x)\n", mbox2);
1082                 r = CSR_RESULT_FAILURE;
1083             }
1084             break;
1085         }
1086         else
1087         {
1088             if (card->chip_id > SDIO_CARD_ID_UNIFI_2)
1089             {
1090                 /* We ignore read failures for the first few reads,
1091                  * they are probably benign. */
1092                 if (i > MAILBOX2_ATTEMPTS / 4)
1093                 {
1094                     unifi_trace(card->ospriv, UDBG1, "Failed to read CCCR IO Ready register while polling for reset\n");
1095                 }
1096             }
1097             else
1098             {
1099                 unifi_trace(card->ospriv, UDBG1, "Failed to read CCCR IO Enable register while polling for reset\n");
1100             }
1101         }
1102         CsrThreadSleep(MAILBOX2_TIMEOUT);
1103     }
1104
1105     if (r == CSR_RESULT_SUCCESS && i == MAILBOX2_ATTEMPTS)
1106     {
1107         unifi_trace(card->ospriv, UDBG1, "Timeout waiting for UniFi to complete reset\n");
1108         r = CSR_RESULT_FAILURE;
1109     }
1110
1111     func_exit();
1112     return r;
1113 } /* card_wait_for_unifi_to_reset() */
1114
1115
1116 /*
1117  * ---------------------------------------------------------------------------
1118  *  card_wait_for_unifi_to_disable
1119  *
1120  *      Waits for the function to become disabled by polling the
1121  *      IO_READY bit.
1122  *
1123  *  Arguments:
1124  *      card            Pointer to card struct
1125  *
1126  *  Returns:
1127  *      CSR_RESULT_SUCCESS on success, CSR error code on failure.
1128  *
1129  *  Notes: This function can only be used with
1130  *         card->chip_id > SDIO_CARD_ID_UNIFI_2
1131  * ---------------------------------------------------------------------------
1132  */
1133 static CsrResult card_wait_for_unifi_to_disable(card_t *card)
1134 {
1135     CsrInt16 i;
1136     CsrResult r;
1137     CsrUint8 io_enable;
1138     CsrResult csrResult;
1139
1140     func_enter();
1141
1142     if (card->chip_id <= SDIO_CARD_ID_UNIFI_2)
1143     {
1144         unifi_error(card->ospriv,
1145                     "Function reset method not supported for chip_id=%d\n",
1146                     card->chip_id);
1147         func_exit();
1148         return CSR_RESULT_FAILURE;
1149     }
1150
1151     r = CSR_RESULT_SUCCESS;
1152     for (i = 0; i < MAILBOX2_ATTEMPTS; i++)
1153     {
1154         unifi_trace(card->ospriv, UDBG1, "waiting for disable to complete, attempt %d\n", i);
1155
1156         /*
1157          * It's quite likely that this read will timeout for the
1158          * first few tries - especially if we have reset via
1159          * DBG_RESET.
1160          */
1161 #if defined (CSR_WIFI_HIP_DEBUG_OFFLINE) && defined (CSR_WIFI_HIP_SDIO_TRACE)
1162         unifi_debug_log_to_buf("r0@%02X=", SDIO_IO_READY);
1163 #endif
1164         csrResult = CsrSdioF0Read8(card->sdio_if, SDIO_IO_READY, &io_enable);
1165 #if defined (CSR_WIFI_HIP_DEBUG_OFFLINE) && defined (CSR_WIFI_HIP_SDIO_TRACE)
1166         if (csrResult != CSR_RESULT_SUCCESS)
1167         {
1168             unifi_debug_log_to_buf("error=%X\n", csrResult);
1169         }
1170         else
1171         {
1172             unifi_debug_log_to_buf("%X\n", io_enable);
1173         }
1174 #endif
1175         if (csrResult == CSR_SDIO_RESULT_NO_DEVICE)
1176         {
1177             return CSR_WIFI_HIP_RESULT_NO_DEVICE;
1178         }
1179         if (csrResult == CSR_RESULT_SUCCESS)
1180         {
1181             CsrInt16 enabled = io_enable & (1 << card->function);
1182             r = CSR_RESULT_SUCCESS;
1183             if (!enabled)
1184             {
1185                 unifi_trace(card->ospriv, UDBG1,
1186                             "Disable complete (function %d is disabled) in ~ %u msecs\n",
1187                             card->function, i * MAILBOX2_TIMEOUT);
1188
1189                 break;
1190             }
1191         }
1192         else
1193         {
1194             /*
1195              * We ignore read failures for the first few reads,
1196              * they are probably benign.
1197              */
1198             r = ConvertCsrSdioToCsrHipResult(card, csrResult);
1199             if (i > (MAILBOX2_ATTEMPTS / 4))
1200             {
1201                 unifi_trace(card->ospriv, UDBG1,
1202                             "Failed to read CCCR IO Ready register while polling for disable\n");
1203             }
1204         }
1205         CsrThreadSleep(MAILBOX2_TIMEOUT);
1206     }
1207
1208     if ((r == CSR_RESULT_SUCCESS) && (i == MAILBOX2_ATTEMPTS))
1209     {
1210         unifi_trace(card->ospriv, UDBG1, "Timeout waiting for UniFi to complete disable\n");
1211         r = CSR_RESULT_FAILURE;
1212     }
1213
1214     func_exit();
1215     return r;
1216 } /* card_wait_for_unifi_to_reset() */
1217
1218
1219 /*
1220  * ---------------------------------------------------------------------------
1221  *  card_wait_for_firmware_to_start
1222  *
1223  *      Polls the MAILBOX1 register for a non-zero value.
1224  *      Then reads MAILBOX0 and forms the two values into a 32-bit address
1225  *      which is returned to the caller.
1226  *
1227  *  Arguments:
1228  *      card            Pointer to card struct
1229  *      paddr           Pointer to receive the UniFi address formed
1230  *                      by concatenating MAILBOX1 and MAILBOX0.
1231  *
1232  *  Returns:
1233  *      CSR_RESULT_SUCCESS on success, CSR error code on failure.
1234  * ---------------------------------------------------------------------------
1235  */
1236 CsrResult card_wait_for_firmware_to_start(card_t *card, CsrUint32 *paddr)
1237 {
1238     CsrInt32 i;
1239     CsrUint16 mbox0, mbox1;
1240     CsrResult r;
1241
1242     func_enter();
1243
1244     /*
1245      * Wait for UniFi to initialise its data structures by polling
1246      * the SHARED_MAILBOX1 register.
1247      * Experience shows this is typically 120ms.
1248      */
1249     CsrThreadSleep(MAILBOX1_TIMEOUT);
1250
1251     mbox1 = 0;
1252     unifi_trace(card->ospriv, UDBG1, "waiting for MAILBOX1 to be non-zero...\n");
1253     for (i = 0; i < MAILBOX1_ATTEMPTS; i++)
1254     {
1255         r = unifi_read_direct16(card, ChipHelper_MAILBOX1(card->helper) * 2, &mbox1);
1256         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
1257         {
1258             return r;
1259         }
1260         if (r != CSR_RESULT_SUCCESS)
1261         {
1262             /* These reads can fail if UniFi isn't up yet, so try again */
1263             unifi_warning(card->ospriv, "Failed to read UniFi Mailbox1 register\n");
1264         }
1265
1266         if ((r == CSR_RESULT_SUCCESS) && (mbox1 != 0))
1267         {
1268             unifi_trace(card->ospriv, UDBG1, "MAILBOX1 ready (0x%04X) in %u millisecs\n",
1269                         mbox1, i * MAILBOX1_TIMEOUT);
1270
1271             /* Read the MAILBOX1 again in case we caught the value as it
1272              * changed. */
1273             r = unifi_read_direct16(card, ChipHelper_MAILBOX1(card->helper) * 2, &mbox1);
1274             if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
1275             {
1276                 return r;
1277             }
1278             if (r != CSR_RESULT_SUCCESS)
1279             {
1280                 unifi_error(card->ospriv, "Failed to read UniFi Mailbox1 register for second time\n");
1281                 func_exit_r(r);
1282                 return r;
1283             }
1284             unifi_trace(card->ospriv, UDBG1, "MAILBOX1 value=0x%04X\n", mbox1);
1285
1286             break;
1287         }
1288
1289         CsrThreadSleep(MAILBOX1_TIMEOUT);
1290         if ((i % 100) == 99)
1291         {
1292             unifi_trace(card->ospriv, UDBG2, "MAILBOX1 not ready (0x%X), still trying...\n", mbox1);
1293         }
1294     }
1295
1296     if ((r == CSR_RESULT_SUCCESS) && (mbox1 == 0))
1297     {
1298         unifi_trace(card->ospriv, UDBG1, "Timeout waiting for firmware to start, Mailbox1 still 0 after %d ms\n",
1299                     MAILBOX1_ATTEMPTS * MAILBOX1_TIMEOUT);
1300         func_exit_r(CSR_RESULT_FAILURE);
1301         return CSR_RESULT_FAILURE;
1302     }
1303
1304
1305     /*
1306      * Complete the reset handshake by setting MAILBOX2 to 0xFFFF
1307      */
1308     r = unifi_write_direct16(card, ChipHelper_SDIO_HIP_HANDSHAKE(card->helper) * 2, 0xFFFF);
1309     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
1310     {
1311         return r;
1312     }
1313     if (r != CSR_RESULT_SUCCESS)
1314     {
1315         unifi_error(card->ospriv, "Failed to write f/w startup handshake to MAILBOX2\n");
1316         func_exit_r(r);
1317         return r;
1318     }
1319
1320
1321     /*
1322      * Read the Symbol Look Up Table (SLUT) offset.
1323      * Top 16 bits are in mbox1, read the lower 16 bits from mbox0.
1324      */
1325     mbox0 = 0;
1326     r = unifi_read_direct16(card, ChipHelper_MAILBOX0(card->helper) * 2, &mbox0);
1327     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
1328     {
1329         return r;
1330     }
1331     if (r != CSR_RESULT_SUCCESS)
1332     {
1333         unifi_error(card->ospriv, "Failed to read UniFi Mailbox0 register\n");
1334         func_exit_r(r);
1335         return r;
1336     }
1337
1338     *paddr = (((CsrUint32)mbox1 << 16) | mbox0);
1339
1340     func_exit();
1341     return CSR_RESULT_SUCCESS;
1342 } /* card_wait_for_firmware_to_start() */
1343
1344
1345 /*
1346  * ---------------------------------------------------------------------------
1347  *  unifi_capture_panic
1348  *
1349  *      Attempt to capture panic codes from the firmware. This may involve
1350  *      warm reset of the chip to regain access following a watchdog reset.
1351  *
1352  *  Arguments:
1353  *      card            Pointer to card struct
1354  *
1355  *  Returns:
1356  *      CSR_RESULT_SUCCESS if panic codes were captured, or none available
1357  *      CSR_RESULT_FAILURE if the driver could not access function 1
1358  * ---------------------------------------------------------------------------
1359  */
1360 CsrResult unifi_capture_panic(card_t *card)
1361 {
1362     func_enter();
1363
1364     /* The firmware must have previously initialised to read the panic addresses
1365      * from the SLUT
1366      */
1367     if (!card->panic_data_phy_addr || !card->panic_data_mac_addr)
1368     {
1369         func_exit();
1370         return CSR_RESULT_SUCCESS;
1371     }
1372
1373     /* Ensure we can access function 1 following a panic/watchdog reset */
1374     if (card_access_panic(card) == CSR_RESULT_SUCCESS)
1375     {
1376         /* Read the panic codes */
1377         unifi_read_panic(card);
1378     }
1379     else
1380     {
1381         unifi_info(card->ospriv, "Unable to read panic codes");
1382     }
1383
1384     func_exit();
1385     return CSR_RESULT_SUCCESS;
1386 }
1387
1388
1389 /*
1390  * ---------------------------------------------------------------------------
1391  *  card_access_panic
1392  *      Attempt to read the WLAN SDIO function in order to read panic codes
1393  *      and perform various reset steps to regain access if the read fails.
1394  *
1395  *  Arguments:
1396  *      card            Pointer to card struct
1397  *
1398  *  Returns:
1399  *      CSR_RESULT_SUCCESS if panic codes can be read
1400  *      CSR error code if panic codes can not be read
1401  * ---------------------------------------------------------------------------
1402  */
1403 static CsrResult card_access_panic(card_t *card)
1404 {
1405     CsrUint16 data_u16 = 0;
1406     CsrInt32 i;
1407     CsrResult r, sr;
1408
1409     func_enter();
1410
1411     /* A chip version of zero means that the version never got succesfully read
1412      * during reset. In this case give up because it will not be possible to
1413      * verify the chip version.
1414      */
1415     if (!card->chip_version)
1416     {
1417         unifi_info(card->ospriv, "Unknown chip version\n");
1418         return CSR_RESULT_FAILURE;
1419     }
1420
1421     /* Ensure chip is awake or access to function 1 will fail */
1422     r = unifi_set_host_state(card, UNIFI_HOST_STATE_AWAKE);
1423     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
1424     {
1425         return r;
1426     }
1427     if (r != CSR_RESULT_SUCCESS)
1428     {
1429         unifi_error(card->ospriv, "unifi_set_host_state() failed %d\n", r);
1430         return CSR_RESULT_FAILURE; /* Card is probably unpowered */
1431     }
1432     CsrThreadSleep(20);
1433
1434     for (i = 0; i < 3; i++)
1435     {
1436         sr = CsrSdioRead16(card->sdio_if, CHIP_HELPER_UNIFI_GBL_CHIP_VERSION * 2, &data_u16);
1437         if (sr != CSR_RESULT_SUCCESS || data_u16 != card->chip_version)
1438         {
1439             unifi_info(card->ospriv, "Failed to read valid chip version sr=%d (0x%04x want 0x%04x) try %d\n",
1440                        sr, data_u16, card->chip_version, i);
1441
1442             /* Set clock speed low */
1443             sr = CsrSdioMaxBusClockFrequencySet(card->sdio_if, UNIFI_SDIO_CLOCK_SAFE_HZ);
1444             if (sr != CSR_RESULT_SUCCESS)
1445             {
1446                 unifi_error(card->ospriv, "CsrSdioMaxBusClockFrequencySet() failed1 %d\n", sr);
1447                 r = ConvertCsrSdioToCsrHipResult(card, sr);
1448             }
1449             card->sdio_clock_speed = UNIFI_SDIO_CLOCK_SAFE_HZ;
1450
1451             /* First try re-enabling function in case a f/w watchdog reset disabled it */
1452             if (i == 0)
1453             {
1454                 unifi_info(card->ospriv, "Try function enable\n");
1455                 sr = CsrSdioFunctionEnable(card->sdio_if);
1456                 if (sr != CSR_RESULT_SUCCESS)
1457                 {
1458                     r = ConvertCsrSdioToCsrHipResult(card, sr);
1459                     unifi_error(card->ospriv, "CsrSdioFunctionEnable failed %d (HIP %d)\n", sr, r);
1460                 }
1461                 continue;
1462             }
1463
1464             /* Second try, set awake */
1465             unifi_info(card->ospriv, "Try set awake\n");
1466
1467             /* Ensure chip is awake */
1468             r = unifi_set_host_state(card, UNIFI_HOST_STATE_AWAKE);
1469             if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
1470             {
1471                 return r;
1472             }
1473             if (r != CSR_RESULT_SUCCESS)
1474             {
1475                 unifi_error(card->ospriv, "unifi_set_host_state() failed2 %d\n", r);
1476             }
1477
1478             /* Set clock speed low in case setting the host state raised it, which
1479              * would only happen if host state was previously TORPID
1480              */
1481             sr = CsrSdioMaxBusClockFrequencySet(card->sdio_if, UNIFI_SDIO_CLOCK_SAFE_HZ);
1482             if (sr != CSR_RESULT_SUCCESS)
1483             {
1484                 unifi_error(card->ospriv, "CsrSdioMaxBusClockFrequencySet() failed2 %d\n", sr);
1485             }
1486             card->sdio_clock_speed = UNIFI_SDIO_CLOCK_SAFE_HZ;
1487
1488             if (i == 1)
1489             {
1490                 continue;
1491             }
1492
1493             /* Perform a s/w reset to preserve as much as the card state as possible,
1494              * (mainly the preserve RAM). The context will be lost for coredump - but as we
1495              * were unable to access the WLAN function for panic, the coredump would have
1496              * also failed without a reset.
1497              */
1498             unifi_info(card->ospriv, "Try s/w reset\n");
1499
1500             r = unifi_card_hard_reset(card);
1501             if (r != CSR_RESULT_SUCCESS)
1502             {
1503                 unifi_error(card->ospriv, "unifi_card_hard_reset() failed %d\n", r);
1504             }
1505         }
1506         else
1507         {
1508             if (i > 0)
1509             {
1510                 unifi_info(card->ospriv, "Read chip version 0x%x after %d retries\n", data_u16, i);
1511             }
1512             break;
1513         }
1514     }
1515
1516     r = ConvertCsrSdioToCsrHipResult(card, sr);
1517     func_exit_r(r);
1518     return r;
1519 }
1520
1521
1522 /*
1523  * ---------------------------------------------------------------------------
1524  *  unifi_read_panic
1525  *      Reads, saves and prints panic codes stored by the firmware in UniFi's
1526  *      preserve RAM by the last panic that occurred since chip was powered.
1527  *      Nothing is saved if the panic codes are read as zero.
1528  *
1529  *  Arguments:
1530  *      card            Pointer to card struct
1531  *
1532  *  Returns:
1533  * ---------------------------------------------------------------------------
1534  */
1535 void unifi_read_panic(card_t *card)
1536 {
1537     CsrResult r;
1538     CsrUint16 p_code, p_arg;
1539
1540     func_enter();
1541
1542     /* The firmware must have previously initialised to read the panic addresses
1543      * from the SLUT
1544      */
1545     if (!card->panic_data_phy_addr || !card->panic_data_mac_addr)
1546     {
1547         return;
1548     }
1549
1550     /* Get the panic data from PHY */
1551     r = unifi_card_read16(card, card->panic_data_phy_addr, &p_code);
1552     if (r != CSR_RESULT_SUCCESS)
1553     {
1554         unifi_error(card->ospriv, "capture_panic: unifi_read16 %08x failed %d\n", card->panic_data_phy_addr, r);
1555         p_code = 0;
1556     }
1557     if (p_code)
1558     {
1559         r = unifi_card_read16(card, card->panic_data_phy_addr + 2, &p_arg);
1560         if (r != CSR_RESULT_SUCCESS)
1561         {
1562             unifi_error(card->ospriv, "capture_panic: unifi_read16 %08x failed %d\n", card->panic_data_phy_addr + 2, r);
1563         }
1564         unifi_error(card->ospriv, "Last UniFi PHY PANIC %04x arg %04x\n", p_code, p_arg);
1565         card->last_phy_panic_code = p_code;
1566         card->last_phy_panic_arg = p_arg;
1567     }
1568
1569     /* Get the panic data from MAC */
1570     r = unifi_card_read16(card, card->panic_data_mac_addr, &p_code);
1571     if (r != CSR_RESULT_SUCCESS)
1572     {
1573         unifi_error(card->ospriv, "capture_panic: unifi_read16 %08x failed %d\n", card->panic_data_mac_addr, r);
1574         p_code = 0;
1575     }
1576     if (p_code)
1577     {
1578         r = unifi_card_read16(card, card->panic_data_mac_addr + 2, &p_arg);
1579         if (r != CSR_RESULT_SUCCESS)
1580         {
1581             unifi_error(card->ospriv, "capture_panic: unifi_read16 %08x failed %d\n", card->panic_data_mac_addr + 2, r);
1582         }
1583         unifi_error(card->ospriv, "Last UniFi MAC PANIC %04x arg %04x\n", p_code, p_arg);
1584         card->last_mac_panic_code = p_code;
1585         card->last_mac_panic_arg = p_arg;
1586     }
1587
1588     func_exit();
1589 }
1590
1591
1592 /*
1593  * ---------------------------------------------------------------------------
1594  *  card_allocate_memory_resources
1595  *
1596  *      Allocates memory for the from-host, to-host bulk data slots,
1597  *      soft queue buffers and bulk data buffers.
1598  *
1599  *  Arguments:
1600  *      card            Pointer to card struct
1601  *
1602  *  Returns:
1603  *      CSR_RESULT_SUCCESS on success, CSR error code on failure.
1604  * ---------------------------------------------------------------------------
1605  */
1606 static CsrResult card_allocate_memory_resources(card_t *card)
1607 {
1608     CsrInt16 n, i, k, r;
1609     sdio_config_data_t *cfg_data;
1610
1611     func_enter();
1612
1613     /* Reset any state carried forward from a previous life */
1614     card->fh_command_queue.q_rd_ptr = 0;
1615     card->fh_command_queue.q_wr_ptr = 0;
1616     (void)CsrSnprintf(card->fh_command_queue.name, UNIFI_QUEUE_NAME_MAX_LENGTH,
1617                       "fh_cmd_q");
1618     for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
1619     {
1620         card->fh_traffic_queue[i].q_rd_ptr = 0;
1621         card->fh_traffic_queue[i].q_wr_ptr = 0;
1622         (void)CsrSnprintf(card->fh_traffic_queue[i].name,
1623                           UNIFI_QUEUE_NAME_MAX_LENGTH, "fh_data_q%d", i);
1624     }
1625 #ifndef CSR_WIFI_HIP_TA_DISABLE
1626     unifi_ta_sampling_init(card);
1627 #endif
1628     /* Convenience short-cut */
1629     cfg_data = &card->config_data;
1630
1631     /*
1632      * Allocate memory for the from-host and to-host signal buffers.
1633      */
1634     card->fh_buffer.buf = CsrMemAllocDma(UNIFI_FH_BUF_SIZE);
1635     if (card->fh_buffer.buf == NULL)
1636     {
1637         unifi_error(card->ospriv, "Failed to allocate memory for F-H signals\n");
1638         func_exit_r(CSR_WIFI_HIP_RESULT_NO_MEMORY);
1639         return CSR_WIFI_HIP_RESULT_NO_MEMORY;
1640     }
1641     card->fh_buffer.bufsize = UNIFI_FH_BUF_SIZE;
1642     card->fh_buffer.ptr = card->fh_buffer.buf;
1643     card->fh_buffer.count = 0;
1644
1645     card->th_buffer.buf = CsrMemAllocDma(UNIFI_FH_BUF_SIZE);
1646     if (card->th_buffer.buf == NULL)
1647     {
1648         unifi_error(card->ospriv, "Failed to allocate memory for T-H signals\n");
1649         func_exit_r(CSR_WIFI_HIP_RESULT_NO_MEMORY);
1650         return CSR_WIFI_HIP_RESULT_NO_MEMORY;
1651     }
1652     card->th_buffer.bufsize = UNIFI_FH_BUF_SIZE;
1653     card->th_buffer.ptr = card->th_buffer.buf;
1654     card->th_buffer.count = 0;
1655
1656
1657     /*
1658      * Allocate memory for the from-host and to-host bulk data slots.
1659      * This is done as separate CsrPmemAllocs because lots of smaller
1660      * allocations are more likely to succeed than one huge one.
1661      */
1662
1663     /* Allocate memory for the array of pointers */
1664     n = cfg_data->num_fromhost_data_slots;
1665
1666     unifi_trace(card->ospriv, UDBG3, "Alloc from-host resources, %d slots.\n", n);
1667     card->from_host_data =
1668         (slot_desc_t *)CsrMemAlloc(n * sizeof(slot_desc_t));
1669     if (card->from_host_data == NULL)
1670     {
1671         unifi_error(card->ospriv, "Failed to allocate memory for F-H bulk data array\n");
1672         func_exit_r(CSR_WIFI_HIP_RESULT_NO_MEMORY);
1673         return CSR_WIFI_HIP_RESULT_NO_MEMORY;
1674     }
1675
1676     /* Initialise from-host bulk data slots */
1677     for (i = 0; i < n; i++)
1678     {
1679         UNIFI_INIT_BULK_DATA(&card->from_host_data[i].bd);
1680     }
1681
1682     /* Allocate memory for the array used for slot host tag mapping */
1683     card->fh_slot_host_tag_record =
1684         (CsrUint32 *)CsrMemAlloc(n * sizeof(CsrUint32));
1685
1686     if (card->fh_slot_host_tag_record == NULL)
1687     {
1688         unifi_error(card->ospriv, "Failed to allocate memory for F-H slot host tag mapping array\n");
1689         func_exit_r(CSR_WIFI_HIP_RESULT_NO_MEMORY);
1690         return CSR_WIFI_HIP_RESULT_NO_MEMORY;
1691     }
1692
1693     /* Initialise host tag entries for from-host bulk data slots */
1694     for (i = 0; i < n; i++)
1695     {
1696         card->fh_slot_host_tag_record[i] = CSR_WIFI_HIP_RESERVED_HOST_TAG;
1697     }
1698
1699
1700     /* Allocate memory for the array of pointers */
1701     n = cfg_data->num_tohost_data_slots;
1702
1703     unifi_trace(card->ospriv, UDBG3, "Alloc to-host resources, %d slots.\n", n);
1704     card->to_host_data =
1705         (bulk_data_desc_t *)CsrMemAlloc(n * sizeof(bulk_data_desc_t));
1706     if (card->to_host_data == NULL)
1707     {
1708         unifi_error(card->ospriv, "Failed to allocate memory for T-H bulk data array\n");
1709         func_exit_r(CSR_WIFI_HIP_RESULT_NO_MEMORY);
1710         return CSR_WIFI_HIP_RESULT_NO_MEMORY;
1711     }
1712
1713     /* Initialise to-host bulk data slots */
1714     for (i = 0; i < n; i++)
1715     {
1716         UNIFI_INIT_BULK_DATA(&card->to_host_data[i]);
1717     }
1718
1719     /*
1720      * Initialise buffers for soft Q
1721      */
1722     for (i = 0; i < UNIFI_SOFT_COMMAND_Q_LENGTH; i++)
1723     {
1724         for (r = 0; r < UNIFI_MAX_DATA_REFERENCES; r++)
1725         {
1726             UNIFI_INIT_BULK_DATA(&card->fh_command_q_body[i].bulkdata[r]);
1727         }
1728     }
1729
1730     for (k = 0; k < UNIFI_NO_OF_TX_QS; k++)
1731     {
1732         for (i = 0; i < UNIFI_SOFT_TRAFFIC_Q_LENGTH; i++)
1733         {
1734             for (r = 0; r < UNIFI_MAX_DATA_REFERENCES; r++)
1735             {
1736                 UNIFI_INIT_BULK_DATA(&card->fh_traffic_q_body[k][i].bulkdata[r]);
1737             }
1738         }
1739     }
1740
1741     card->memory_resources_allocated = 1;
1742
1743     func_exit();
1744     return CSR_RESULT_SUCCESS;
1745 } /* card_allocate_memory_resources() */
1746
1747
1748 /*
1749  * ---------------------------------------------------------------------------
1750  *  unifi_free_bulk_data
1751  *
1752  *      Free the data associated to a bulk data structure.
1753  *
1754  *  Arguments:
1755  *      card            Pointer to card struct
1756  *      bulk_data_slot  Pointer to bulk data structure
1757  *
1758  *  Returns:
1759  *      None.
1760  *
1761  * ---------------------------------------------------------------------------
1762  */
1763 static void unifi_free_bulk_data(card_t *card, bulk_data_desc_t *bulk_data_slot)
1764 {
1765     if (bulk_data_slot->data_length != 0)
1766     {
1767         unifi_net_data_free(card->ospriv, bulk_data_slot);
1768     }
1769 } /* unifi_free_bulk_data() */
1770
1771
1772 /*
1773  * ---------------------------------------------------------------------------
1774  *  card_free_memory_resources
1775  *
1776  *      Frees memory allocated for the from-host, to-host bulk data slots,
1777  *      soft queue buffers and bulk data buffers.
1778  *
1779  *  Arguments:
1780  *      card            Pointer to card struct
1781  *
1782  *  Returns:
1783  *      None.
1784  * ---------------------------------------------------------------------------
1785  */
1786 static void card_free_memory_resources(card_t *card)
1787 {
1788     func_enter();
1789
1790     unifi_trace(card->ospriv, UDBG1, "Freeing card memory resources.\n");
1791
1792     /* Clear our internal queues */
1793     unifi_cancel_pending_signals(card);
1794
1795
1796     if (card->to_host_data)
1797     {
1798         CsrMemFree(card->to_host_data);
1799         card->to_host_data = NULL;
1800     }
1801
1802     if (card->from_host_data)
1803     {
1804         CsrMemFree(card->from_host_data);
1805         card->from_host_data = NULL;
1806     }
1807
1808     /* free the memory for slot host tag mapping array */
1809     if (card->fh_slot_host_tag_record)
1810     {
1811         CsrMemFree(card->fh_slot_host_tag_record);
1812         card->fh_slot_host_tag_record = NULL;
1813     }
1814
1815     if (card->fh_buffer.buf)
1816     {
1817         CsrMemFreeDma(card->fh_buffer.buf);
1818     }
1819     card->fh_buffer.ptr = card->fh_buffer.buf = NULL;
1820     card->fh_buffer.bufsize = 0;
1821     card->fh_buffer.count = 0;
1822
1823     if (card->th_buffer.buf)
1824     {
1825         CsrMemFreeDma(card->th_buffer.buf);
1826     }
1827     card->th_buffer.ptr = card->th_buffer.buf = NULL;
1828     card->th_buffer.bufsize = 0;
1829     card->th_buffer.count = 0;
1830
1831
1832     card->memory_resources_allocated = 0;
1833
1834     func_exit();
1835 } /* card_free_memory_resources() */
1836
1837
1838 static void card_init_soft_queues(card_t *card)
1839 {
1840     CsrInt16 i;
1841
1842     func_enter();
1843
1844     unifi_trace(card->ospriv, UDBG1, "Initialising internal signal queues.\n");
1845     /* Reset any state carried forward from a previous life */
1846     card->fh_command_queue.q_rd_ptr = 0;
1847     card->fh_command_queue.q_wr_ptr = 0;
1848     (void)CsrSnprintf(card->fh_command_queue.name, UNIFI_QUEUE_NAME_MAX_LENGTH,
1849                       "fh_cmd_q");
1850     for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
1851     {
1852         card->fh_traffic_queue[i].q_rd_ptr = 0;
1853         card->fh_traffic_queue[i].q_wr_ptr = 0;
1854         (void)CsrSnprintf(card->fh_traffic_queue[i].name,
1855                           UNIFI_QUEUE_NAME_MAX_LENGTH, "fh_data_q%d", i);
1856     }
1857 #ifndef CSR_WIFI_HIP_TA_DISABLE
1858     unifi_ta_sampling_init(card);
1859 #endif
1860     func_exit();
1861 }
1862
1863
1864 /*
1865  * ---------------------------------------------------------------------------
1866  *  unifi_cancel_pending_signals
1867  *
1868  *      Free the signals and associated bulk data, pending in the core.
1869  *
1870  *  Arguments:
1871  *      card        Pointer to card struct
1872  *
1873  *  Returns:
1874  *      None.
1875  * ---------------------------------------------------------------------------
1876  */
1877 void unifi_cancel_pending_signals(card_t *card)
1878 {
1879     CsrInt16 i, n, r;
1880     func_enter();
1881
1882     unifi_trace(card->ospriv, UDBG1, "Canceling pending signals.\n");
1883
1884     if (card->to_host_data)
1885     {
1886         /*
1887          * Free any bulk data buffers allocated for the t-h slots
1888          * This will clear all buffers that did not make it to
1889          * unifi_receive_event() before cancel was request.
1890          */
1891         n = card->config_data.num_tohost_data_slots;
1892         unifi_trace(card->ospriv, UDBG3, "Freeing to-host resources, %d slots.\n", n);
1893         for (i = 0; i < n; i++)
1894         {
1895             unifi_free_bulk_data(card, &card->to_host_data[i]);
1896         }
1897     }
1898
1899     /*
1900      * If any of the from-host bulk data has reached the card->from_host_data
1901      * but not UniFi, we need to free the buffers here.
1902      */
1903     if (card->from_host_data)
1904     {
1905         /* Free any bulk data buffers allocated for the f-h slots */
1906         n = card->config_data.num_fromhost_data_slots;
1907         unifi_trace(card->ospriv, UDBG3, "Freeing from-host resources, %d slots.\n", n);
1908         for (i = 0; i < n; i++)
1909         {
1910             unifi_free_bulk_data(card, &card->from_host_data[i].bd);
1911         }
1912
1913         for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
1914         {
1915             card->dynamic_slot_data.from_host_used_slots[i] = 0;
1916             card->dynamic_slot_data.from_host_max_slots[i] = 0;
1917             card->dynamic_slot_data.from_host_reserved_slots[i] = 0;
1918         }
1919     }
1920
1921     /*
1922      * Free any bulk data buffers allocated in the soft queues.
1923      * This covers the case where a bulk data pointer has reached the soft queue
1924      * but not the card->from_host_data.
1925      */
1926     unifi_trace(card->ospriv, UDBG3, "Freeing cmd q resources.\n");
1927     for (i = 0; i < UNIFI_SOFT_COMMAND_Q_LENGTH; i++)
1928     {
1929         for (r = 0; r < UNIFI_MAX_DATA_REFERENCES; r++)
1930         {
1931             unifi_free_bulk_data(card, &card->fh_command_q_body[i].bulkdata[r]);
1932         }
1933     }
1934
1935     unifi_trace(card->ospriv, UDBG3, "Freeing traffic q resources.\n");
1936     for (n = 0; n < UNIFI_NO_OF_TX_QS; n++)
1937     {
1938         for (i = 0; i < UNIFI_SOFT_TRAFFIC_Q_LENGTH; i++)
1939         {
1940             for (r = 0; r < UNIFI_MAX_DATA_REFERENCES; r++)
1941             {
1942                 unifi_free_bulk_data(card, &card->fh_traffic_q_body[n][i].bulkdata[r]);
1943             }
1944         }
1945     }
1946
1947     card_init_soft_queues(card);
1948
1949     func_exit();
1950 } /* unifi_cancel_pending_signals() */
1951
1952
1953 /*
1954  * ---------------------------------------------------------------------------
1955  *  unifi_free_card
1956  *
1957  *      Free the memory allocated for the card structure and buffers.
1958  *
1959  *  Notes:
1960  *      The porting layer is responsible for freeing any mini-coredump buffers
1961  *      allocated when it called unifi_coredump_init(), by calling
1962  *      unifi_coredump_free() before calling this function.
1963  *
1964  *  Arguments:
1965  *      card        Pointer to card struct
1966  *
1967  *  Returns:
1968  *      None.
1969  * ---------------------------------------------------------------------------
1970  */
1971 void unifi_free_card(card_t *card)
1972 {
1973     func_enter();
1974 #ifdef CSR_PRE_ALLOC_NET_DATA
1975     prealloc_netdata_free(card);
1976 #endif
1977     /* Free any memory allocated. */
1978     card_free_memory_resources(card);
1979
1980     /* Warn if caller didn't free coredump buffers */
1981     if (card->dump_buf)
1982     {
1983         unifi_error(card->ospriv, "Caller should call unifi_coredump_free()\n");
1984         unifi_coredump_free(card); /* free anyway to prevent memory leak */
1985     }
1986
1987     CsrMemFree(card);
1988
1989     func_exit();
1990 } /* unifi_free_card() */
1991
1992
1993 /*
1994  * ---------------------------------------------------------------------------
1995  *  card_init_slots
1996  *
1997  *      Allocate memory for host-side slot data and signal queues.
1998  *
1999  * Arguments:
2000  *      card            Pointer to card object
2001  *
2002  * Returns:
2003  *      CSR error code.
2004  * ---------------------------------------------------------------------------
2005  */
2006 static CsrResult card_init_slots(card_t *card)
2007 {
2008     CsrResult r;
2009     CsrUint8 i;
2010
2011     func_enter();
2012
2013     /* Allocate the buffers we need, only once. */
2014     if (card->memory_resources_allocated == 1)
2015     {
2016         card_free_memory_resources(card);
2017     }
2018     else
2019     {
2020         /* Initialise our internal command and traffic queues */
2021         card_init_soft_queues(card);
2022     }
2023
2024     r = card_allocate_memory_resources(card);
2025     if (r != CSR_RESULT_SUCCESS)
2026     {
2027         unifi_error(card->ospriv, "Failed to allocate card memory resources.\n");
2028         card_free_memory_resources(card);
2029         func_exit_r(r);
2030         return r;
2031     }
2032
2033     if (card->sdio_ctrl_addr == 0)
2034     {
2035         unifi_error(card->ospriv, "Failed to find config struct!\n");
2036         func_exit_r(CSR_WIFI_HIP_RESULT_INVALID_VALUE);
2037         return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
2038     }
2039
2040     /*
2041      * Set initial counts.
2042      */
2043
2044     card->from_host_data_head = 0;
2045
2046     /* Get initial signal counts from UniFi, in case it has not been reset. */
2047     {
2048         CsrUint16 s;
2049
2050         /* Get the from-host-signals-written count */
2051         r = unifi_card_read16(card, card->sdio_ctrl_addr + 0, &s);
2052         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2053         {
2054             return r;
2055         }
2056         if (r != CSR_RESULT_SUCCESS)
2057         {
2058             unifi_error(card->ospriv, "Failed to read from-host sig written count\n");
2059             func_exit_r(r);
2060             return r;
2061         }
2062         card->from_host_signals_w = (CsrInt16)s;
2063
2064         /* Get the to-host-signals-written count */
2065         r = unifi_card_read16(card, card->sdio_ctrl_addr + 6, &s);
2066         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2067         {
2068             return r;
2069         }
2070         if (r != CSR_RESULT_SUCCESS)
2071         {
2072             unifi_error(card->ospriv, "Failed to read to-host sig read count\n");
2073             func_exit_r(r);
2074             return r;
2075         }
2076         card->to_host_signals_r = (CsrInt16)s;
2077     }
2078
2079     /* Set Initialised flag. */
2080     r = unifi_card_write16(card, card->init_flag_addr, 0x0001);
2081     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2082     {
2083         return r;
2084     }
2085     if (r != CSR_RESULT_SUCCESS)
2086     {
2087         unifi_error(card->ospriv, "Failed to write initialised flag\n");
2088         func_exit_r(r);
2089         return r;
2090     }
2091
2092     /* Dynamic queue reservation */
2093     CsrMemSet(&card->dynamic_slot_data, 0, sizeof(card_dynamic_slot_t));
2094
2095     for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
2096     {
2097         card->dynamic_slot_data.from_host_max_slots[i] = card->config_data.num_fromhost_data_slots -
2098                                                          UNIFI_RESERVED_COMMAND_SLOTS;
2099         card->dynamic_slot_data.queue_stable[i] = FALSE;
2100     }
2101
2102     card->dynamic_slot_data.packets_interval = UNIFI_PACKETS_INTERVAL;
2103
2104     func_exit();
2105     return CSR_RESULT_SUCCESS;
2106 } /* card_init_slots() */
2107
2108
2109 /*
2110  * ---------------------------------------------------------------------------
2111  *  unifi_set_udi_hook
2112  *
2113  *      Registers the udi hook that reports the sent signals to the core.
2114  *
2115  *  Arguments:
2116  *      card            Pointer to the card context struct
2117  *      udi_fn          Pointer to the callback function.
2118  *
2119  *  Returns:
2120  *      CSR_WIFI_HIP_RESULT_INVALID_VALUE if the card pointer is invalid,
2121  *      CSR_RESULT_SUCCESS on success.
2122  * ---------------------------------------------------------------------------
2123  */
2124 CsrResult unifi_set_udi_hook(card_t *card, udi_func_t udi_fn)
2125 {
2126     if (card == NULL)
2127     {
2128         return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
2129     }
2130
2131     if (card->udi_hook == NULL)
2132     {
2133         card->udi_hook = udi_fn;
2134     }
2135
2136     return CSR_RESULT_SUCCESS;
2137 } /* unifi_set_udi_hook() */
2138
2139
2140 /*
2141  * ---------------------------------------------------------------------------
2142  *  unifi_remove_udi_hook
2143  *
2144  *      Removes the udi hook that reports the sent signals from the core.
2145  *
2146  *  Arguments:
2147  *      card            Pointer to the card context struct
2148  *      udi_fn          Pointer to the callback function.
2149  *
2150  *  Returns:
2151  *      CSR_WIFI_HIP_RESULT_INVALID_VALUE if the card pointer is invalid,
2152  *      CSR_RESULT_SUCCESS on success.
2153  * ---------------------------------------------------------------------------
2154  */
2155 CsrResult unifi_remove_udi_hook(card_t *card, udi_func_t udi_fn)
2156 {
2157     if (card == NULL)
2158     {
2159         return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
2160     }
2161
2162     if (card->udi_hook == udi_fn)
2163     {
2164         card->udi_hook = NULL;
2165     }
2166
2167     return CSR_RESULT_SUCCESS;
2168 } /* unifi_remove_udi_hook() */
2169
2170
2171 static void CardReassignDynamicReservation(card_t *card)
2172 {
2173     CsrUint8 i;
2174
2175     func_enter();
2176
2177     unifi_trace(card->ospriv, UDBG5, "Packets Txed %d %d %d %d\n",
2178                 card->dynamic_slot_data.packets_txed[0],
2179                 card->dynamic_slot_data.packets_txed[1],
2180                 card->dynamic_slot_data.packets_txed[2],
2181                 card->dynamic_slot_data.packets_txed[3]);
2182
2183     /* Clear reservation and recalculate max slots */
2184     for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
2185     {
2186         card->dynamic_slot_data.queue_stable[i] = FALSE;
2187         card->dynamic_slot_data.from_host_reserved_slots[i] = 0;
2188         card->dynamic_slot_data.from_host_max_slots[i] = card->config_data.num_fromhost_data_slots -
2189                                                          UNIFI_RESERVED_COMMAND_SLOTS;
2190         card->dynamic_slot_data.packets_txed[i] = 0;
2191
2192         unifi_trace(card->ospriv, UDBG5, "CardReassignDynamicReservation: queue %d reserved %d Max %d\n", i,
2193                     card->dynamic_slot_data.from_host_reserved_slots[i],
2194                     card->dynamic_slot_data.from_host_max_slots[i]);
2195     }
2196
2197     card->dynamic_slot_data.total_packets_txed = 0;
2198     func_exit();
2199 }
2200
2201
2202 /* Algorithm to dynamically reserve slots. The logic is based mainly on the outstanding queue
2203  * length. Slots are reserved for particular queues during an interval and cleared after the interval.
2204  * Each queue has three associated variables.. a) used slots - the number of slots currently occupied
2205  * by the queue b) reserved slots - number of slots reserved specifically for the queue c) max slots - total
2206  * slots that this queue can actually use (may be higher than reserved slots and is dependent on reserved slots
2207  * for other queues).
2208  * This function is called when there are no slots available for a queue. It checks to see if there are enough
2209  * unreserved slots sufficient for this request. If available these slots are reserved for the queue.
2210  * If there are not enough unreserved slots, a fair share for each queue is calculated based on the total slots
2211  * and the number of active queues (any queue with existing reservation is considered active). Queues needing
2212  * less than their fair share are allowed to have the previously reserved slots. The remaining slots are
2213  * distributed evenly among queues that need more than the fair share
2214  *
2215  * A better scheme would take current bandwidth per AC into consideration when reserving slots. An
2216  * implementation scheme could consider the relative time/service period for slots in an AC. If the firmware
2217  * services other ACs faster than a particular AC (packets wait in the slots longer) then it is fair to reserve
2218  * less slots for the AC
2219  */
2220 static void CardCheckDynamicReservation(card_t *card, unifi_TrafficQueue queue)
2221 {
2222     CsrUint16 q_len, active_queues = 0, excess_queue_slots, div_extra_slots,
2223               queue_fair_share, reserved_slots = 0, q, excess_need_queues = 0, unmovable_slots = 0;
2224     CsrInt32 i;
2225     q_t *sigq;
2226     CsrUint16 num_data_slots = card->config_data.num_fromhost_data_slots - UNIFI_RESERVED_COMMAND_SLOTS;
2227
2228     func_enter();
2229
2230     /* Calculate the pending queue length */
2231     sigq = &card->fh_traffic_queue[queue];
2232     q_len = CSR_WIFI_HIP_Q_SLOTS_USED(sigq);
2233
2234     if (q_len <= card->dynamic_slot_data.from_host_reserved_slots[queue])
2235     {
2236         unifi_trace(card->ospriv, UDBG5, "queue %d q_len %d already has that many reserved slots, exiting\n", queue, q_len);
2237         func_exit();
2238         return;
2239     }
2240
2241     /* Upper limit */
2242     if (q_len > num_data_slots)
2243     {
2244         q_len = num_data_slots;
2245     }
2246
2247     for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
2248     {
2249         if (i != (CsrInt32)queue)
2250         {
2251             reserved_slots += card->dynamic_slot_data.from_host_reserved_slots[i];
2252         }
2253         if ((i == (CsrInt32)queue) || (card->dynamic_slot_data.from_host_reserved_slots[i] > 0))
2254         {
2255             active_queues++;
2256         }
2257     }
2258
2259     unifi_trace(card->ospriv, UDBG5, "CardCheckDynamicReservation: queue %d q_len %d\n", queue, q_len);
2260     unifi_trace(card->ospriv, UDBG5, "Active queues %d reserved slots on other queues %d\n",
2261                 active_queues, reserved_slots);
2262
2263     if (reserved_slots + q_len <= num_data_slots)
2264     {
2265         card->dynamic_slot_data.from_host_reserved_slots[queue] = q_len;
2266         if (q_len == num_data_slots)
2267         {
2268             /* This is the common case when just 1 stream is going */
2269             card->dynamic_slot_data.queue_stable[queue] = TRUE;
2270         }
2271     }
2272     else
2273     {
2274         queue_fair_share = num_data_slots / active_queues;
2275         unifi_trace(card->ospriv, UDBG5, "queue fair share %d\n", queue_fair_share);
2276
2277         /* Evenly distribute slots among active queues */
2278         /* Find out the queues that need excess of fair share. Also find slots allocated
2279          * to queues less than their fair share, these slots cannot be reallocated (unmovable slots) */
2280
2281         card->dynamic_slot_data.from_host_reserved_slots[queue] = q_len;
2282
2283         for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
2284         {
2285             if (card->dynamic_slot_data.from_host_reserved_slots[i] > queue_fair_share)
2286             {
2287                 excess_need_queues++;
2288             }
2289             else
2290             {
2291                 unmovable_slots += card->dynamic_slot_data.from_host_reserved_slots[i];
2292             }
2293         }
2294
2295         unifi_trace(card->ospriv, UDBG5, "Excess need queues %d\n", excess_need_queues);
2296
2297         /* Now find the slots per excess demand queue */
2298         excess_queue_slots = (num_data_slots - unmovable_slots) / excess_need_queues;
2299         div_extra_slots = (num_data_slots - unmovable_slots) - excess_queue_slots * excess_need_queues;
2300         for (i = UNIFI_NO_OF_TX_QS - 1; i >= 0; i--)
2301         {
2302             if (card->dynamic_slot_data.from_host_reserved_slots[i] > excess_queue_slots)
2303             {
2304                 card->dynamic_slot_data.from_host_reserved_slots[i] = excess_queue_slots;
2305                 if (div_extra_slots > 0)
2306                 {
2307                     card->dynamic_slot_data.from_host_reserved_slots[i]++;
2308                     div_extra_slots--;
2309                 }
2310                 /* No more slots will be allocated to this queue during the current interval */
2311                 card->dynamic_slot_data.queue_stable[i] = TRUE;
2312                 unifi_trace(card->ospriv, UDBG5, "queue stable %d\n", i);
2313             }
2314         }
2315     }
2316
2317     /* Redistribute max slots */
2318     for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
2319     {
2320         reserved_slots = 0;
2321         for (q = 0; q < UNIFI_NO_OF_TX_QS; q++)
2322         {
2323             if (i != q)
2324             {
2325                 reserved_slots += card->dynamic_slot_data.from_host_reserved_slots[q];
2326             }
2327         }
2328
2329         card->dynamic_slot_data.from_host_max_slots[i] = num_data_slots - reserved_slots;
2330         unifi_trace(card->ospriv, UDBG5, "queue %d reserved %d Max %d\n", i,
2331                     card->dynamic_slot_data.from_host_reserved_slots[i],
2332                     card->dynamic_slot_data.from_host_max_slots[i]);
2333     }
2334
2335     func_exit();
2336 }
2337
2338
2339 /*
2340  * ---------------------------------------------------------------------------
2341  *  CardClearFromHostDataSlot
2342  *
2343  *      Clear a the given data slot, making it available again.
2344  *
2345  *  Arguments:
2346  *      card            Pointer to Card object
2347  *      slot            Index of the signal slot to clear.
2348  *
2349  *  Returns:
2350  *      None.
2351  * ---------------------------------------------------------------------------
2352  */
2353 void CardClearFromHostDataSlot(card_t *card, const CsrInt16 slot)
2354 {
2355     CsrUint8 queue = card->from_host_data[slot].queue;
2356     const void *os_data_ptr = card->from_host_data[slot].bd.os_data_ptr;
2357
2358     func_enter();
2359
2360     if (card->from_host_data[slot].bd.data_length == 0)
2361     {
2362         unifi_warning(card->ospriv,
2363                       "Surprise: request to clear an already free FH data slot: %d\n",
2364                       slot);
2365         func_exit();
2366         return;
2367     }
2368
2369     if (os_data_ptr == NULL)
2370     {
2371         unifi_warning(card->ospriv,
2372                       "Clearing FH data slot %d: has null payload, len=%d\n",
2373                       slot, card->from_host_data[slot].bd.data_length);
2374     }
2375
2376     /* Free card->from_host_data[slot].bd.os_net_ptr here. */
2377     /* Mark slot as free by setting length to 0. */
2378     unifi_free_bulk_data(card, &card->from_host_data[slot].bd);
2379     if (queue < UNIFI_NO_OF_TX_QS)
2380     {
2381         if (card->dynamic_slot_data.from_host_used_slots[queue] == 0)
2382         {
2383             unifi_error(card->ospriv, "Goofed up used slots q = %d used slots = %d\n",
2384                         queue,
2385                         card->dynamic_slot_data.from_host_used_slots[queue]);
2386         }
2387         else
2388         {
2389             card->dynamic_slot_data.from_host_used_slots[queue]--;
2390         }
2391         card->dynamic_slot_data.packets_txed[queue]++;
2392         card->dynamic_slot_data.total_packets_txed++;
2393         if (card->dynamic_slot_data.total_packets_txed >= card->dynamic_slot_data.packets_interval)
2394         {
2395             CardReassignDynamicReservation(card);
2396         }
2397     }
2398
2399     unifi_trace(card->ospriv, UDBG4, "CardClearFromHostDataSlot: slot %d recycled %p\n", slot, os_data_ptr);
2400
2401     func_exit();
2402 } /* CardClearFromHostDataSlot() */
2403
2404
2405 #ifdef CSR_WIFI_REQUEUE_PACKET_TO_HAL
2406 /*
2407  * ---------------------------------------------------------------------------
2408  *  CardClearFromHostDataSlotWithoutFreeingBulkData
2409  *
2410  *      Clear the given data slot with out freeing the bulk data.
2411  *
2412  *  Arguments:
2413  *      card            Pointer to Card object
2414  *      slot            Index of the signal slot to clear.
2415  *
2416  *  Returns:
2417  *      None.
2418  * ---------------------------------------------------------------------------
2419  */
2420 void CardClearFromHostDataSlotWithoutFreeingBulkData(card_t *card, const CsrInt16 slot)
2421 {
2422     CsrUint8 queue = card->from_host_data[slot].queue;
2423
2424     /* Initialise the from_host data slot so it can be re-used,
2425      * Set length field in from_host_data array to 0.
2426      */
2427     UNIFI_INIT_BULK_DATA(&card->from_host_data[slot].bd);
2428
2429     queue = card->from_host_data[slot].queue;
2430
2431     if (queue < UNIFI_NO_OF_TX_QS)
2432     {
2433         if (card->dynamic_slot_data.from_host_used_slots[queue] == 0)
2434         {
2435             unifi_error(card->ospriv, "Goofed up used slots q = %d used slots = %d\n",
2436                         queue,
2437                         card->dynamic_slot_data.from_host_used_slots[queue]);
2438         }
2439         else
2440         {
2441             card->dynamic_slot_data.from_host_used_slots[queue]--;
2442         }
2443         card->dynamic_slot_data.packets_txed[queue]++;
2444         card->dynamic_slot_data.total_packets_txed++;
2445         if (card->dynamic_slot_data.total_packets_txed >=
2446             card->dynamic_slot_data.packets_interval)
2447         {
2448             CardReassignDynamicReservation(card);
2449         }
2450     }
2451 } /* CardClearFromHostDataSlotWithoutFreeingBulkData() */
2452
2453
2454 #endif
2455
2456 CsrUint16 CardGetDataSlotSize(card_t *card)
2457 {
2458     return card->config_data.data_slot_size;
2459 } /* CardGetDataSlotSize() */
2460
2461
2462 /*
2463  * ---------------------------------------------------------------------------
2464  *  CardGetFreeFromHostDataSlots
2465  *
2466  *      Retrieve the number of from-host bulk data slots available.
2467  *
2468  *  Arguments:
2469  *      card            Pointer to the card context struct
2470  *
2471  *  Returns:
2472  *      Number of free from-host bulk data slots.
2473  * ---------------------------------------------------------------------------
2474  */
2475 CsrUint16 CardGetFreeFromHostDataSlots(card_t *card)
2476 {
2477     CsrUint16 i, n = 0;
2478
2479     func_enter();
2480
2481     /* First two slots reserved for MLME */
2482     for (i = 0; i < card->config_data.num_fromhost_data_slots; i++)
2483     {
2484         if (card->from_host_data[i].bd.data_length == 0)
2485         {
2486             /* Free slot */
2487             n++;
2488         }
2489     }
2490
2491     func_exit();
2492     return n;
2493 } /* CardGetFreeFromHostDataSlots() */
2494
2495
2496 /*
2497  * ---------------------------------------------------------------------------
2498  *  CardAreAllFromHostDataSlotsEmpty
2499  *
2500  *      Returns the state of from-host bulk data slots.
2501  *
2502  *  Arguments:
2503  *      card            Pointer to the card context struct
2504  *
2505  *  Returns:
2506  *      1       The from-host bulk data slots are all empty (available).
2507  *      0       Some or all the from-host bulk data slots are in use.
2508  * ---------------------------------------------------------------------------
2509  */
2510 CsrUint16 CardAreAllFromHostDataSlotsEmpty(card_t *card)
2511 {
2512     CsrUint16 i;
2513
2514     for (i = 0; i < card->config_data.num_fromhost_data_slots; i++)
2515     {
2516         if (card->from_host_data[i].bd.data_length != 0)
2517         {
2518             return 0;
2519         }
2520     }
2521
2522     return 1;
2523 } /* CardGetFreeFromHostDataSlots() */
2524
2525
2526 static CsrResult unifi_identify_hw(card_t *card)
2527 {
2528     func_enter();
2529
2530     card->chip_id = card->sdio_if->sdioId.cardId;
2531     card->function = card->sdio_if->sdioId.sdioFunction;
2532     card->sdio_io_block_size = card->sdio_if->blockSize;
2533
2534     /* If SDIO controller doesn't support byte mode CMD53, pad transfers to block sizes */
2535     card->sdio_io_block_pad = (card->sdio_if->features & CSR_SDIO_FEATURE_BYTE_MODE)?FALSE : TRUE;
2536
2537     /*
2538      * Setup the chip helper so that we can access the registers (and
2539      * also tell what sub-type of HIP we should use).
2540      */
2541     card->helper = ChipHelper_GetVersionSdio((CsrUint8)card->chip_id);
2542     if (!card->helper)
2543     {
2544         unifi_error(card->ospriv, "Null ChipHelper\n");
2545     }
2546
2547     unifi_info(card->ospriv, "Chip ID 0x%02X  Function %u  Block Size %u  Name %s(%s)\n",
2548                card->chip_id, card->function, card->sdio_io_block_size,
2549                ChipHelper_MarketingName(card->helper),
2550                ChipHelper_FriendlyName(card->helper));
2551
2552     func_exit();
2553     return CSR_RESULT_SUCCESS;
2554 } /* unifi_identify_hw() */
2555
2556
2557 static CsrResult unifi_prepare_hw(card_t *card)
2558 {
2559     CsrResult r;
2560     CsrResult csrResult;
2561     enum unifi_host_state old_state = card->host_state;
2562
2563     func_enter();
2564
2565     r = unifi_identify_hw(card);
2566     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2567     {
2568         return r;
2569     }
2570     if (r != CSR_RESULT_SUCCESS)
2571     {
2572         unifi_error(card->ospriv, "Failed to identify hw\n");
2573         func_exit_r(r);
2574         return r;
2575     }
2576
2577     unifi_trace(card->ospriv, UDBG1,
2578                 "%s mode SDIO\n", card->sdio_io_block_pad?"Block" : "Byte");
2579     /*
2580      * Chip must be a awake or blocks that are asleep may not get
2581      * reset.  We can only do this after we have read the chip_id.
2582      */
2583     r = unifi_set_host_state(card, UNIFI_HOST_STATE_AWAKE);
2584     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2585     {
2586         return r;
2587     }
2588
2589     if (old_state == UNIFI_HOST_STATE_TORPID)
2590     {
2591         /* Ensure the initial clock rate is set; if a reset occured when the chip was
2592          * TORPID, unifi_set_host_state() may have raised it to MAX.
2593          */
2594         csrResult = CsrSdioMaxBusClockFrequencySet(card->sdio_if, UNIFI_SDIO_CLOCK_INIT_HZ);
2595         if (csrResult != CSR_RESULT_SUCCESS)
2596         {
2597             r = ConvertCsrSdioToCsrHipResult(card, csrResult);
2598             func_exit_r(r);
2599             return r;
2600         }
2601         card->sdio_clock_speed = UNIFI_SDIO_CLOCK_INIT_HZ;
2602     }
2603
2604     /*
2605      * The WLAN function must be enabled to access MAILBOX2 and DEBUG_RST
2606      * registers.
2607      */
2608     csrResult = CsrSdioFunctionEnable(card->sdio_if);
2609     if (csrResult == CSR_SDIO_RESULT_NO_DEVICE)
2610     {
2611         return CSR_WIFI_HIP_RESULT_NO_DEVICE;
2612     }
2613     if (csrResult != CSR_RESULT_SUCCESS)
2614     {
2615         r = ConvertCsrSdioToCsrHipResult(card, csrResult);
2616         /* Can't enable WLAN function. Try resetting the SDIO block. */
2617         unifi_error(card->ospriv, "Failed to re-enable function %d.\n", card->function);
2618         func_exit_r(r);
2619         return r;
2620     }
2621
2622     /*
2623      * Poke some registers to make sure the PLL has started,
2624      * otherwise memory accesses are likely to fail.
2625      */
2626     bootstrap_chip_hw(card);
2627
2628     /* Try to read the chip version from register. */
2629     r = unifi_read_chip_version(card);
2630     if (r != CSR_RESULT_SUCCESS)
2631     {
2632         func_exit_r(r);
2633         return r;
2634     }
2635
2636     func_exit();
2637     return CSR_RESULT_SUCCESS;
2638 } /* unifi_prepare_hw() */
2639
2640
2641 static CsrResult unifi_read_chip_version(card_t *card)
2642 {
2643     CsrUint32 gbl_chip_version;
2644     CsrResult r;
2645     CsrUint16 ver;
2646
2647     func_enter();
2648
2649     gbl_chip_version = ChipHelper_GBL_CHIP_VERSION(card->helper);
2650
2651     /* Try to read the chip version from register. */
2652     if (gbl_chip_version != 0)
2653     {
2654         r = unifi_read_direct16(card, gbl_chip_version * 2, &ver);
2655         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2656         {
2657             return r;
2658         }
2659         if (r != CSR_RESULT_SUCCESS)
2660         {
2661             unifi_error(card->ospriv, "Failed to read GBL_CHIP_VERSION\n");
2662             func_exit_r(r);
2663             return r;
2664         }
2665         card->chip_version = ver;
2666     }
2667     else
2668     {
2669         unifi_info(card->ospriv, "Unknown Chip ID, cannot locate GBL_CHIP_VERSION\n");
2670         r = CSR_RESULT_FAILURE;
2671     }
2672
2673     unifi_info(card->ospriv, "Chip Version 0x%04X\n", card->chip_version);
2674
2675     func_exit_r(r);
2676     return r;
2677 } /* unifi_read_chip_version() */
2678
2679
2680 /*
2681  * ---------------------------------------------------------------------------
2682  *  unifi_reset_hardware
2683  *
2684  *      Execute the UniFi reset sequence.
2685  *
2686  *      Note: This may fail if the chip is going TORPID so retry at
2687  *      least once.
2688  *
2689  *  Arguments:
2690  *      card - pointer to card context structure
2691  *
2692  *  Returns:
2693  *      CSR_RESULT_SUCCESS on success, CSR error otherwise.
2694  *
2695  *  Notes:
2696  *      Some platforms (e.g. Windows Vista) do not allow access to registers
2697  *      that are necessary for a software soft reset.
2698  * ---------------------------------------------------------------------------
2699  */
2700 static CsrResult unifi_reset_hardware(card_t *card)
2701 {
2702     CsrResult r;
2703     CsrUint16 new_block_size = UNIFI_IO_BLOCK_SIZE;
2704     CsrResult csrResult;
2705
2706     func_enter();
2707
2708     /* Errors returned by unifi_prepare_hw() are not critical at this point */
2709     r = unifi_prepare_hw(card);
2710     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2711     {
2712         return r;
2713     }
2714
2715     /* First try SDIO controller reset, which may power cycle the UniFi, assert
2716      * its reset line, or not be implemented depending on the platform.
2717      */
2718     unifi_info(card->ospriv, "Calling CsrSdioHardReset\n");
2719     csrResult = CsrSdioHardReset(card->sdio_if);
2720     if (csrResult == CSR_RESULT_SUCCESS)
2721     {
2722         unifi_info(card->ospriv, "CsrSdioHardReset succeeded on reseting UniFi\n");
2723         r = unifi_prepare_hw(card);
2724         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2725         {
2726             return r;
2727         }
2728         if (r != CSR_RESULT_SUCCESS)
2729         {
2730             unifi_error(card->ospriv, "unifi_prepare_hw failed after hard reset\n");
2731             func_exit_r(r);
2732             return r;
2733         }
2734     }
2735     else if (csrResult == CSR_SDIO_RESULT_NO_DEVICE)
2736     {
2737         return CSR_WIFI_HIP_RESULT_NO_DEVICE;
2738     }
2739     else
2740     {
2741         /* Falling back to software hard reset methods */
2742         unifi_info(card->ospriv, "Falling back to software hard reset\n");
2743         r = unifi_card_hard_reset(card);
2744         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2745         {
2746             return r;
2747         }
2748         if (r != CSR_RESULT_SUCCESS)
2749         {
2750             unifi_error(card->ospriv, "software hard reset failed\n");
2751             func_exit_r(r);
2752             return r;
2753         }
2754
2755         /* If we fell back to unifi_card_hard_reset() methods, chip version may
2756          * not have been read. (Note in the unlikely event that it is zero,
2757          * it will be harmlessly read again)
2758          */
2759         if (card->chip_version == 0)
2760         {
2761             r = unifi_read_chip_version(card);
2762             if (r != CSR_RESULT_SUCCESS)
2763             {
2764                 func_exit_r(r);
2765                 return r;
2766             }
2767         }
2768     }
2769
2770 #ifdef CSR_WIFI_HIP_SDIO_BLOCK_SIZE
2771     new_block_size = CSR_WIFI_HIP_SDIO_BLOCK_SIZE;
2772 #endif
2773
2774     /* After hard reset, we need to restore the SDIO block size */
2775     csrResult = CsrSdioBlockSizeSet(card->sdio_if, new_block_size);
2776     r = ConvertCsrSdioToCsrHipResult(card, csrResult);
2777
2778     /* Warn if a different block size was achieved by the transport */
2779     if (card->sdio_if->blockSize != new_block_size)
2780     {
2781         unifi_info(card->ospriv,
2782                    "Actually got block size %d\n", card->sdio_if->blockSize);
2783     }
2784
2785     /* sdio_io_block_size always needs be updated from the achieved block size,
2786      * as it is used by the OS layer to allocate memory in unifi_net_malloc().
2787      * Controllers which don't support block mode (e.g. CSPI) will report a
2788      * block size of zero.
2789      */
2790     if (card->sdio_if->blockSize == 0)
2791     {
2792         unifi_info(card->ospriv, "Block size 0, block mode not available\n");
2793
2794         /* Set sdio_io_block_size to 1 so that unifi_net_data_malloc() has a
2795          * sensible rounding value. Elsewhere padding will already be
2796          * disabled because the controller supports byte mode.
2797          */
2798         card->sdio_io_block_size = 1;
2799
2800         /* Controller features must declare support for byte mode */
2801         if (!(card->sdio_if->features & CSR_SDIO_FEATURE_BYTE_MODE))
2802         {
2803             unifi_error(card->ospriv, "Requires byte mode\n");
2804             r = CSR_WIFI_HIP_RESULT_INVALID_VALUE;
2805         }
2806     }
2807     else
2808     {
2809         /* Padding will be enabled if CSR_SDIO_FEATURE_BYTE_MODE isn't set */
2810         card->sdio_io_block_size = card->sdio_if->blockSize;
2811     }
2812
2813
2814     func_exit_r(r);
2815     return r;
2816 } /* unifi_reset_hardware() */
2817
2818
2819 /*
2820  * ---------------------------------------------------------------------------
2821  *  card_reset_method_io_enable
2822  *
2823  *      Issue a hard reset to the hw writing the IO_ENABLE.
2824  *
2825  *  Arguments:
2826  *      card            Pointer to Card object
2827  *
2828  *  Returns:
2829  *      0 on success,
2830  *      CSR_WIFI_HIP_RESULT_NO_DEVICE   if the card was ejected
2831  *      CSR_RESULT_FAILURE         if an SDIO error occurred or if a response
2832  *                                 was not seen in the expected time
2833  * ---------------------------------------------------------------------------
2834  */
2835 static CsrResult card_reset_method_io_enable(card_t *card)
2836 {
2837     CsrResult r;
2838     CsrResult csrResult;
2839
2840     func_enter();
2841
2842     /*
2843      * This resets only function 1, so should be used in
2844      * preference to the method below (CSR_FUNC_EN)
2845      */
2846     unifi_trace(card->ospriv, UDBG1, "Hard reset (IO_ENABLE)\n");
2847
2848     csrResult = CsrSdioFunctionDisable(card->sdio_if);
2849     if (csrResult == CSR_SDIO_RESULT_NO_DEVICE)
2850     {
2851         return CSR_WIFI_HIP_RESULT_NO_DEVICE;
2852     }
2853     if (csrResult != CSR_RESULT_SUCCESS)
2854     {
2855         r = ConvertCsrSdioToCsrHipResult(card, csrResult);
2856         unifi_warning(card->ospriv, "SDIO error writing IO_ENABLE: %d\n", r);
2857     }
2858     else
2859     {
2860         /* Delay here to let the reset take affect. */
2861         CsrThreadSleep(RESET_SETTLE_DELAY);
2862
2863         r = card_wait_for_unifi_to_disable(card);
2864         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2865         {
2866             return r;
2867         }
2868
2869         if (r == CSR_RESULT_SUCCESS)
2870         {
2871             r = card_wait_for_unifi_to_reset(card);
2872             if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2873             {
2874                 return r;
2875             }
2876         }
2877     }
2878
2879     if (r != CSR_RESULT_SUCCESS)
2880     {
2881         unifi_trace(card->ospriv, UDBG1, "Hard reset (CSR_FUNC_EN)\n");
2882
2883         r = sdio_write_f0(card, SDIO_CSR_FUNC_EN, 0);
2884         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2885         {
2886             return r;
2887         }
2888         if (r != CSR_RESULT_SUCCESS)
2889         {
2890             unifi_warning(card->ospriv, "SDIO error writing SDIO_CSR_FUNC_EN: %d\n", r);
2891             func_exit_r(r);
2892             return r;
2893         }
2894         else
2895         {
2896             /* Delay here to let the reset take affect. */
2897             CsrThreadSleep(RESET_SETTLE_DELAY);
2898
2899             r = card_wait_for_unifi_to_reset(card);
2900             if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2901             {
2902                 return r;
2903             }
2904         }
2905     }
2906
2907     if (r != CSR_RESULT_SUCCESS)
2908     {
2909         unifi_warning(card->ospriv, "card_reset_method_io_enable failed to reset UniFi\n");
2910     }
2911
2912     func_exit();
2913     return r;
2914 } /* card_reset_method_io_enable() */
2915
2916
2917 /*
2918  * ---------------------------------------------------------------------------
2919  *  card_reset_method_dbg_reset
2920  *
2921  *      Issue a hard reset to the hw writing the DBG_RESET.
2922  *
2923  *  Arguments:
2924  *      card            Pointer to Card object
2925  *
2926  *  Returns:
2927  *      CSR_RESULT_SUCCESS         on success,
2928  *      CSR_WIFI_HIP_RESULT_NO_DEVICE   if the card was ejected
2929  *      CSR_RESULT_FAILURE         if an SDIO error occurred or if a response
2930  *                                 was not seen in the expected time
2931  * ---------------------------------------------------------------------------
2932  */
2933 static CsrResult card_reset_method_dbg_reset(card_t *card)
2934 {
2935     CsrResult r;
2936
2937     func_enter();
2938
2939     /*
2940      * Prepare UniFi for h/w reset
2941      */
2942     if (card->host_state == UNIFI_HOST_STATE_TORPID)
2943     {
2944         r = unifi_set_host_state(card, UNIFI_HOST_STATE_DROWSY);
2945         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2946         {
2947             return r;
2948         }
2949         if (r != CSR_RESULT_SUCCESS)
2950         {
2951             unifi_error(card->ospriv, "Failed to set UNIFI_HOST_STATE_DROWSY\n");
2952             func_exit_r(r);
2953             return r;
2954         }
2955         CsrThreadSleep(5);
2956     }
2957
2958     r = unifi_card_stop_processor(card, UNIFI_PROC_BOTH);
2959     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2960     {
2961         return r;
2962     }
2963     if (r != CSR_RESULT_SUCCESS)
2964     {
2965         unifi_error(card->ospriv, "Can't stop processors\n");
2966         func_exit();
2967         return r;
2968     }
2969
2970     unifi_trace(card->ospriv, UDBG1, "Hard reset (DBG_RESET)\n");
2971
2972     /*
2973      * This register write may fail. The debug reset resets
2974      * parts of the Function 0 sections of the chip, and
2975      * therefore the response cannot be sent back to the host.
2976      */
2977     r = unifi_write_direct_8_or_16(card, ChipHelper_DBG_RESET(card->helper) * 2, 1);
2978     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2979     {
2980         return r;
2981     }
2982     if (r != CSR_RESULT_SUCCESS)
2983     {
2984         unifi_warning(card->ospriv, "SDIO error writing DBG_RESET: %d\n", r);
2985         func_exit_r(r);
2986         return r;
2987     }
2988
2989     /* Delay here to let the reset take affect. */
2990     CsrThreadSleep(RESET_SETTLE_DELAY);
2991
2992     r = card_wait_for_unifi_to_reset(card);
2993     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
2994     {
2995         return r;
2996     }
2997     if (r != CSR_RESULT_SUCCESS)
2998     {
2999         unifi_warning(card->ospriv, "card_reset_method_dbg_reset failed to reset UniFi\n");
3000     }
3001
3002     func_exit();
3003     return r;
3004 } /* card_reset_method_dbg_reset() */
3005
3006
3007 /*
3008  * ---------------------------------------------------------------------------
3009  *  unifi_card_hard_reset
3010  *
3011  *      Issue reset to hardware, by writing to registers on the card.
3012  *      Power to the card is preserved.
3013  *
3014  *  Arguments:
3015  *      card            Pointer to Card object
3016  *
3017  *  Returns:
3018  *      CSR_RESULT_SUCCESS         on success,
3019  *      CSR_WIFI_HIP_RESULT_NO_DEVICE   if the card was ejected
3020  *      CSR_RESULT_FAILURE         if an SDIO error occurred or if a response
3021  *                                 was not seen in the expected time
3022  * ---------------------------------------------------------------------------
3023  */
3024 CsrResult unifi_card_hard_reset(card_t *card)
3025 {
3026     CsrResult r;
3027     const struct chip_helper_reset_values *init_data;
3028     CsrUint32 chunks;
3029
3030     func_enter();
3031
3032     /* Clear cache of page registers */
3033     card->proc_select = (CsrUint32)(-1);
3034     card->dmem_page = (CsrUint32)(-1);
3035     card->pmem_page = (CsrUint32)(-1);
3036
3037     /*
3038      * We need to have a valid card->helper before we use software hard reset.
3039      * If unifi_identify_hw() fails to get the card ID, it probably means
3040      * that there is no way to talk to the h/w.
3041      */
3042     r = unifi_identify_hw(card);
3043     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3044     {
3045         return r;
3046     }
3047     if (r != CSR_RESULT_SUCCESS)
3048     {
3049         unifi_error(card->ospriv, "unifi_card_hard_reset failed to identify h/w\n");
3050         func_exit();
3051         return r;
3052     }
3053
3054     /* Search for some reset code. */
3055     chunks = ChipHelper_HostResetSequence(card->helper, &init_data);
3056     if (chunks != 0)
3057     {
3058         unifi_error(card->ospriv,
3059                     "Hard reset (Code download) is unsupported\n");
3060
3061         func_exit_r(CSR_RESULT_FAILURE);
3062         return CSR_RESULT_FAILURE;
3063     }
3064
3065     if (card->chip_id > SDIO_CARD_ID_UNIFI_2)
3066     {
3067         /* The HIP spec considers this a bus-specific reset.
3068          * This resets only function 1, so should be used in
3069          * preference to the method below (CSR_FUNC_EN)
3070          * If this method fails, it means that the f/w is probably
3071          * not running. In this case, try the DBG_RESET method.
3072          */
3073         r = card_reset_method_io_enable(card);
3074         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3075         {
3076             return r;
3077         }
3078         if (r == CSR_RESULT_SUCCESS)
3079         {
3080             func_exit();
3081             return r;
3082         }
3083     }
3084
3085     /* Software hard reset */
3086     r = card_reset_method_dbg_reset(card);
3087
3088     func_exit_r(r);
3089     return r;
3090 } /* unifi_card_hard_reset() */
3091
3092
3093 /*
3094  * ---------------------------------------------------------------------------
3095  *
3096  *  CardGenInt
3097  *
3098  *      Prod the card.
3099  *      This function causes an internal interrupt to be raised in the
3100  *      UniFi chip. It is used to signal the firmware that some action has
3101  *      been completed.
3102  *      The UniFi Host Interface asks that the value used increments for
3103  *      debugging purposes.
3104  *
3105  *  Arguments:
3106  *      card            Pointer to Card object
3107  *
3108  *  Returns:
3109  *      CSR_RESULT_SUCCESS         on success,
3110  *      CSR_WIFI_HIP_RESULT_NO_DEVICE   if the card was ejected
3111  *      CSR_RESULT_FAILURE         if an SDIO error occurred or if a response
3112  *                                 was not seen in the expected time
3113  * ---------------------------------------------------------------------------
3114  */
3115 CsrResult CardGenInt(card_t *card)
3116 {
3117     CsrResult r;
3118
3119     func_enter();
3120
3121     if (card->chip_id > SDIO_CARD_ID_UNIFI_2)
3122     {
3123         r = sdio_write_f0(card, SDIO_CSR_FROM_HOST_SCRATCH0,
3124                           (CsrUint8)card->unifi_interrupt_seq);
3125     }
3126     else
3127     {
3128         r = unifi_write_direct_8_or_16(card,
3129                                        ChipHelper_SHARED_IO_INTERRUPT(card->helper) * 2,
3130                                        (CsrUint8)card->unifi_interrupt_seq);
3131     }
3132     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3133     {
3134         return r;
3135     }
3136     if (r != CSR_RESULT_SUCCESS)
3137     {
3138         unifi_error(card->ospriv, "SDIO error writing UNIFI_SHARED_IO_INTERRUPT: %d\n", r);
3139         func_exit_r(r);
3140         return r;
3141     }
3142
3143     card->unifi_interrupt_seq++;
3144
3145     func_exit();
3146     return CSR_RESULT_SUCCESS;
3147 } /* CardGenInt() */
3148
3149
3150 /*
3151  * ---------------------------------------------------------------------------
3152  *  CardEnableInt
3153  *
3154  *      Enable the outgoing SDIO interrupt from UniFi to the host.
3155  *
3156  *  Arguments:
3157  *      card            Pointer to Card object
3158  *
3159  *  Returns:
3160  *      CSR_RESULT_SUCCESS            on success,
3161  *      CSR_WIFI_HIP_RESULT_NO_DEVICE      if the card was ejected
3162  *      CSR_RESULT_FAILURE            if an SDIO error occurred,
3163  * ---------------------------------------------------------------------------
3164  */
3165 CsrResult CardEnableInt(card_t *card)
3166 {
3167     CsrResult r;
3168     CsrUint8 int_enable;
3169
3170     r = sdio_read_f0(card, SDIO_INT_ENABLE, &int_enable);
3171     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3172     {
3173         return r;
3174     }
3175     if (r != CSR_RESULT_SUCCESS)
3176     {
3177         unifi_error(card->ospriv, "SDIO error reading SDIO_INT_ENABLE\n");
3178         return r;
3179     }
3180
3181     int_enable |= (1 << card->function) | UNIFI_SD_INT_ENABLE_IENM;
3182
3183     r = sdio_write_f0(card, SDIO_INT_ENABLE, int_enable);
3184     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3185     {
3186         return r;
3187     }
3188     if (r != CSR_RESULT_SUCCESS)
3189     {
3190         unifi_error(card->ospriv, "SDIO error writing SDIO_INT_ENABLE\n");
3191         return r;
3192     }
3193
3194     return CSR_RESULT_SUCCESS;
3195 } /* CardEnableInt() */
3196
3197
3198 /*
3199  * ---------------------------------------------------------------------------
3200  *  CardDisableInt
3201  *
3202  *      Disable the outgoing SDIO interrupt from UniFi to the host.
3203  *
3204  *  Arguments:
3205  *      card            Pointer to Card object
3206  *
3207  *  Returns:
3208  *      CSR_RESULT_SUCCESS            on success,
3209  *      CSR_WIFI_HIP_RESULT_NO_DEVICE      if the card was ejected
3210  *      CSR_RESULT_FAILURE            if an SDIO error occurred,
3211  * ---------------------------------------------------------------------------
3212  */
3213 CsrResult CardDisableInt(card_t *card)
3214 {
3215     CsrResult r;
3216     CsrUint8 int_enable;
3217
3218     r = sdio_read_f0(card, SDIO_INT_ENABLE, &int_enable);
3219     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3220     {
3221         return r;
3222     }
3223     if (r != CSR_RESULT_SUCCESS)
3224     {
3225         unifi_error(card->ospriv, "SDIO error reading SDIO_INT_ENABLE\n");
3226         return r;
3227     }
3228
3229     int_enable &= ~(1 << card->function);
3230
3231     r = sdio_write_f0(card, SDIO_INT_ENABLE, int_enable);
3232     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3233     {
3234         return r;
3235     }
3236     if (r != CSR_RESULT_SUCCESS)
3237     {
3238         unifi_error(card->ospriv, "SDIO error writing SDIO_INT_ENABLE\n");
3239         return r;
3240     }
3241
3242     return CSR_RESULT_SUCCESS;
3243 } /* CardDisableInt() */
3244
3245
3246 /*
3247  * ---------------------------------------------------------------------------
3248  *  CardPendingInt
3249  *
3250  *      Determine whether UniFi is currently asserting the SDIO interrupt
3251  *      request.
3252  *
3253  *  Arguments:
3254  *      card            Pointer to Card object
3255  *      pintr           Pointer to location to write interrupt status,
3256  *                          TRUE if interrupt pending,
3257  *                          FALSE if no interrupt pending.
3258  *  Returns:
3259  *      CSR_RESULT_SUCCESS            interrupt status read successfully
3260  *      CSR_WIFI_HIP_RESULT_NO_DEVICE      if the card was ejected
3261  *      CSR_RESULT_FAILURE            if an SDIO error occurred,
3262  * ---------------------------------------------------------------------------
3263  */
3264 CsrResult CardPendingInt(card_t *card, CsrBool *pintr)
3265 {
3266     CsrResult r;
3267     CsrUint8 pending;
3268
3269     *pintr = FALSE;
3270
3271     r = sdio_read_f0(card, SDIO_INT_PENDING, &pending);
3272     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3273     {
3274         return r;
3275     }
3276     if (r != CSR_RESULT_SUCCESS)
3277     {
3278         unifi_error(card->ospriv, "SDIO error reading SDIO_INT_PENDING\n");
3279         return r;
3280     }
3281
3282     *pintr = (pending & (1 << card->function))?TRUE : FALSE;
3283
3284     return CSR_RESULT_SUCCESS;
3285 } /* CardPendingInt() */
3286
3287
3288 /*
3289  * ---------------------------------------------------------------------------
3290  *  CardClearInt
3291  *
3292  *      Clear the UniFi SDIO interrupt request.
3293  *
3294  *  Arguments:
3295  *      card            Pointer to Card object
3296  *
3297  *  Returns:
3298  *      CSR_RESULT_SUCCESS          if pending interrupt was cleared, or no pending interrupt.
3299  *      CSR_WIFI_HIP_RESULT_NO_DEVICE    if the card was ejected
3300  *      CSR_RESULT_FAILURE          if an SDIO error occurred,
3301  * ---------------------------------------------------------------------------
3302  */
3303 CsrResult CardClearInt(card_t *card)
3304 {
3305     CsrResult r;
3306     CsrBool intr;
3307
3308     if (card->chip_id > SDIO_CARD_ID_UNIFI_2)
3309     {
3310         /* CardPendingInt() sets intr, if there is a pending interrupt */
3311         r = CardPendingInt(card, &intr);
3312         if (intr == FALSE)
3313         {
3314             return r;
3315         }
3316
3317         r = sdio_write_f0(card, SDIO_CSR_HOST_INT_CLEAR, 1);
3318         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3319         {
3320             return r;
3321         }
3322         if (r != CSR_RESULT_SUCCESS)
3323         {
3324             unifi_error(card->ospriv, "SDIO error writing SDIO_CSR_HOST_INT_CLEAR\n");
3325         }
3326     }
3327     else
3328     {
3329         r = unifi_write_direct_8_or_16(card,
3330                                        ChipHelper_SDIO_HOST_INT(card->helper) * 2,
3331                                        0);
3332         if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3333         {
3334             return r;
3335         }
3336         if (r != CSR_RESULT_SUCCESS)
3337         {
3338             unifi_error(card->ospriv, "SDIO error writing UNIFI_SDIO_HOST_INT\n");
3339         }
3340     }
3341
3342     return r;
3343 } /* CardClearInt() */
3344
3345
3346 /*
3347  * ---------------------------------------------------------------------------
3348  *  CardIntEnabled
3349  *
3350  *      Determine whether UniFi is currently asserting the SDIO interrupt
3351  *      request.
3352  *
3353  *  Arguments:
3354  *      card            Pointer to Card object
3355  *      enabled         Pointer to location to write interrupt enable status,
3356  *                          TRUE if interrupts enabled,
3357  *                          FALSE if interupts disabled.
3358  *
3359  *  Returns:
3360  *      CSR_WIFI_HIP_RESULT_NO_DEVICE      if the card was ejected
3361  *      CSR_RESULT_FAILURE            if an SDIO error occurred,
3362  * ---------------------------------------------------------------------------
3363  */
3364 CsrResult CardIntEnabled(card_t *card, CsrBool *enabled)
3365 {
3366     CsrResult r;
3367     CsrUint8 int_enable;
3368
3369     r = sdio_read_f0(card, SDIO_INT_ENABLE, &int_enable);
3370     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3371     {
3372         return r;
3373     }
3374     if (r != CSR_RESULT_SUCCESS)
3375     {
3376         unifi_error(card->ospriv, "SDIO error reading SDIO_INT_ENABLE\n");
3377         return r;
3378     }
3379
3380     *enabled = (int_enable & (1 << card->function))?TRUE : FALSE;
3381
3382     return CSR_RESULT_SUCCESS;
3383 } /* CardIntEnabled() */
3384
3385
3386 /*
3387  * ---------------------------------------------------------------------------
3388  *  CardWriteBulkData
3389  *      Allocate slot in the pending bulkdata arrays and assign it to a signal's
3390  *      bulkdata reference. The slot is then ready for UniFi's bulkdata commands
3391  *      to transfer the data to/from the host.
3392  *
3393  *  Arguments:
3394  *      card            Pointer to Card object
3395  *      csptr           Pending signal pointer, including bulkdata ref
3396  *      queue           Traffic queue that this signal is using
3397  *
3398  *  Returns:
3399  *      CSR_RESULT_SUCCESS if a free slot was assigned
3400  *      CSR_RESULT_FAILURE if no slot was available
3401  * ---------------------------------------------------------------------------
3402  */
3403 CsrResult CardWriteBulkData(card_t *card, card_signal_t *csptr, unifi_TrafficQueue queue)
3404 {
3405     CsrUint16 i, slots[UNIFI_MAX_DATA_REFERENCES], j = 0;
3406     CsrUint8 *packed_sigptr, num_slots_required = 0;
3407     bulk_data_desc_t *bulkdata = csptr->bulkdata;
3408     CsrInt16 h, nslots;
3409
3410     func_enter();
3411
3412     /* Count the number of slots required */
3413     for (i = 0; i < UNIFI_MAX_DATA_REFERENCES; i++)
3414     {
3415         if (bulkdata[i].data_length != 0)
3416         {
3417             num_slots_required++;
3418         }
3419     }
3420
3421     /* Get the slot numbers */
3422     if (num_slots_required != 0)
3423     {
3424         /* Last 2 slots for MLME */
3425         if (queue == UNIFI_TRAFFIC_Q_MLME)
3426         {
3427             h = card->config_data.num_fromhost_data_slots - UNIFI_RESERVED_COMMAND_SLOTS;
3428             for (i = 0; i < card->config_data.num_fromhost_data_slots; i++)
3429             {
3430                 if (card->from_host_data[h].bd.data_length == 0)
3431                 {
3432                     /* Free data slot, claim it */
3433                     slots[j++] = h;
3434                     if (j == num_slots_required)
3435                     {
3436                         break;
3437                     }
3438                 }
3439
3440                 if (++h >= card->config_data.num_fromhost_data_slots)
3441                 {
3442                     h = 0;
3443                 }
3444             }
3445         }
3446         else
3447         {
3448             if (card->dynamic_slot_data.from_host_used_slots[queue]
3449                 < card->dynamic_slot_data.from_host_max_slots[queue])
3450             {
3451                 /* Data commands get a free slot only after a few checks */
3452                 nslots = card->config_data.num_fromhost_data_slots - UNIFI_RESERVED_COMMAND_SLOTS;
3453
3454                 h = card->from_host_data_head;
3455
3456                 for (i = 0; i < nslots; i++)
3457                 {
3458                     if (card->from_host_data[h].bd.data_length == 0)
3459                     {
3460                         /* Free data slot, claim it */
3461                         slots[j++] = h;
3462                         if (j == num_slots_required)
3463                         {
3464                             break;
3465                         }
3466                     }
3467
3468                     if (++h >= nslots)
3469                     {
3470                         h = 0;
3471                     }
3472                 }
3473                 card->from_host_data_head = h;
3474             }
3475         }
3476
3477         /* Required number of slots are not available, bail out */
3478         if (j != num_slots_required)
3479         {
3480             unifi_trace(card->ospriv, UDBG5, "CardWriteBulkData: didn't find free slot/s\n");
3481
3482             /* If we haven't already reached the stable state we can ask for reservation */
3483             if ((queue != UNIFI_TRAFFIC_Q_MLME) && (card->dynamic_slot_data.queue_stable[queue] == FALSE))
3484             {
3485                 CardCheckDynamicReservation(card, queue);
3486             }
3487
3488             for (i = 0; i < card->config_data.num_fromhost_data_slots; i++)
3489             {
3490                 unifi_trace(card->ospriv, UDBG5, "fh data slot %d: %d\n", i, card->from_host_data[i].bd.data_length);
3491             }
3492             func_exit();
3493             return CSR_RESULT_FAILURE;
3494         }
3495     }
3496
3497     packed_sigptr = csptr->sigbuf;
3498
3499     /* Fill in the slots with data */
3500     j = 0;
3501     for (i = 0; i < UNIFI_MAX_DATA_REFERENCES; i++)
3502     {
3503         if (bulkdata[i].data_length == 0)
3504         {
3505             /* Zero-out the DATAREF in the signal */
3506             SET_PACKED_DATAREF_SLOT(packed_sigptr, i, 0);
3507             SET_PACKED_DATAREF_LEN(packed_sigptr, i, 0);
3508         }
3509         else
3510         {
3511             /*
3512              * Fill in the slot number in the SIGNAL structure but
3513              * preserve the offset already in there
3514              */
3515             SET_PACKED_DATAREF_SLOT(packed_sigptr, i, slots[j] | (((CsrUint16)packed_sigptr[SIZEOF_SIGNAL_HEADER + (i * SIZEOF_DATAREF) + 1]) << 8));
3516             SET_PACKED_DATAREF_LEN(packed_sigptr, i, bulkdata[i].data_length);
3517
3518             /* Do not copy the data, just store the information to them */
3519             card->from_host_data[slots[j]].bd.os_data_ptr = bulkdata[i].os_data_ptr;
3520             card->from_host_data[slots[j]].bd.os_net_buf_ptr = bulkdata[i].os_net_buf_ptr;
3521             card->from_host_data[slots[j]].bd.data_length = bulkdata[i].data_length;
3522             card->from_host_data[slots[j]].bd.net_buf_length = bulkdata[i].net_buf_length;
3523             card->from_host_data[slots[j]].queue = queue;
3524
3525             unifi_trace(card->ospriv, UDBG4, "CardWriteBulkData sig=0x%x, fh slot %d = %p\n",
3526                         GET_SIGNAL_ID(packed_sigptr), i, bulkdata[i].os_data_ptr);
3527
3528             /* Sanity-check that the bulk data desc being assigned to the slot
3529              * actually has a payload.
3530              */
3531             if (!bulkdata[i].os_data_ptr)
3532             {
3533                 unifi_error(card->ospriv, "Assign null os_data_ptr (len=%d) fh slot %d, i=%d, q=%d, sig=0x%x",
3534                             bulkdata[i].data_length, slots[j], i, queue, GET_SIGNAL_ID(packed_sigptr));
3535             }
3536
3537             j++;
3538             if (queue < UNIFI_NO_OF_TX_QS)
3539             {
3540                 card->dynamic_slot_data.from_host_used_slots[queue]++;
3541             }
3542         }
3543     }
3544
3545     func_exit();
3546
3547     return CSR_RESULT_SUCCESS;
3548 } /*  CardWriteBulkData() */
3549
3550
3551 /*
3552  * ---------------------------------------------------------------------------
3553  *  card_find_data_slot
3554  *
3555  *      Dereference references to bulk data slots into pointers to real data.
3556  *
3557  *  Arguments:
3558  *      card            Pointer to the card struct.
3559  *      slot            Slot number from a signal structure
3560  *
3561  *  Returns:
3562  *      Pointer to entry in bulk_data_slot array.
3563  * ---------------------------------------------------------------------------
3564  */
3565 bulk_data_desc_t* card_find_data_slot(card_t *card, CsrInt16 slot)
3566 {
3567     CsrInt16 sn;
3568     bulk_data_desc_t *bd;
3569
3570     sn = slot & 0x7FFF;
3571
3572     /* ?? check sanity of slot number ?? */
3573
3574     if (slot & SLOT_DIR_TO_HOST)
3575     {
3576         bd = &card->to_host_data[sn];
3577     }
3578     else
3579     {
3580         bd = &card->from_host_data[sn].bd;
3581     }
3582
3583     return bd;
3584 } /* card_find_data_slot() */
3585
3586
3587 /*
3588  * ---------------------------------------------------------------------------
3589  *  firmware_present_in_flash
3590  *
3591  *      Probe for external Flash that looks like it might contain firmware.
3592  *
3593  *      If Flash is not present, reads always return 0x0008.
3594  *      If Flash is present, but empty, reads return 0xFFFF.
3595  *      Anything else is considered to be firmware.
3596  *
3597  *  Arguments:
3598  *      card        Pointer to card struct
3599  *
3600  *  Returns:
3601  *      CSR_RESULT_SUCCESS                 firmware is present in ROM or flash
3602  *      CSR_WIFI_HIP_RESULT_NOT_FOUND      firmware is not present in ROM or flash
3603  *      CSR_WIFI_HIP_RESULT_NO_DEVICE      if the card was ejected
3604  *      CSR_RESULT_FAILURE                 if an SDIO error occurred
3605  * ---------------------------------------------------------------------------
3606  */
3607 static CsrResult firmware_present_in_flash(card_t *card)
3608 {
3609     CsrResult r;
3610     CsrUint16 m1, m5;
3611
3612     if (ChipHelper_HasRom(card->helper))
3613     {
3614         return CSR_RESULT_SUCCESS;
3615     }
3616     if (!ChipHelper_HasFlash(card->helper))
3617     {
3618         return CSR_WIFI_HIP_RESULT_NOT_FOUND;
3619     }
3620
3621     /*
3622      * Examine the Flash locations that are the power-on default reset
3623      * vectors of the XAP processors.
3624      * These are words 1 and 5 in Flash.
3625      */
3626     r = unifi_card_read16(card, UNIFI_MAKE_GP(EXT_FLASH, 2), &m1);
3627     if (r != CSR_RESULT_SUCCESS)
3628     {
3629         return r;
3630     }
3631
3632     r = unifi_card_read16(card, UNIFI_MAKE_GP(EXT_FLASH, 10), &m5);
3633     if (r != CSR_RESULT_SUCCESS)
3634     {
3635         return r;
3636     }
3637
3638     /* Check for uninitialised/missing flash */
3639     if ((m1 == 0x0008) || (m1 == 0xFFFF) ||
3640         (m1 == 0x0004) || (m5 == 0x0004) ||
3641         (m5 == 0x0008) || (m5 == 0xFFFF))
3642     {
3643         return CSR_WIFI_HIP_RESULT_NOT_FOUND;
3644     }
3645
3646     return CSR_RESULT_SUCCESS;
3647 } /* firmware_present_in_flash() */
3648
3649
3650 /*
3651  * ---------------------------------------------------------------------------
3652  *  bootstrap_chip_hw
3653  *
3654  *      Perform chip specific magic to "Get It Working" TM.  This will
3655  *      increase speed of PLLs in analogue and maybe enable some
3656  *      on-chip regulators.
3657  *
3658  *  Arguments:
3659  *      card            Pointer to card struct
3660  *
3661  *  Returns:
3662  *      None.
3663  * ---------------------------------------------------------------------------
3664  */
3665 static void bootstrap_chip_hw(card_t *card)
3666 {
3667     const struct chip_helper_init_values *vals;
3668     CsrUint32 i, len;
3669     void *sdio = card->sdio_if;
3670     CsrResult csrResult;
3671
3672     len = ChipHelper_ClockStartupSequence(card->helper, &vals);
3673     if (len != 0)
3674     {
3675         for (i = 0; i < len; i++)
3676         {
3677             csrResult = CsrSdioWrite16(sdio, vals[i].addr * 2, vals[i].value);
3678             if (csrResult != CSR_RESULT_SUCCESS)
3679             {
3680                 unifi_warning(card->ospriv, "Failed to write bootstrap value %d\n", i);
3681                 /* Might not be fatal */
3682             }
3683
3684             CsrThreadSleep(1);
3685         }
3686     }
3687 } /* bootstrap_chip_hw() */
3688
3689
3690 /*
3691  * ---------------------------------------------------------------------------
3692  *  unifi_card_stop_processor
3693  *
3694  *      Stop the UniFi XAP processors.
3695  *
3696  *  Arguments:
3697  *      card            Pointer to card struct
3698  *      which           One of UNIFI_PROC_MAC, UNIFI_PROC_PHY, UNIFI_PROC_BOTH
3699  *
3700  *  Returns:
3701  *      CSR_RESULT_SUCCESS if successful, or CSR error code
3702  * ---------------------------------------------------------------------------
3703  */
3704 CsrResult unifi_card_stop_processor(card_t *card, enum unifi_dbg_processors_select which)
3705 {
3706     CsrResult r = CSR_RESULT_SUCCESS;
3707     CsrUint8 status;
3708     CsrInt16 retry = 100;
3709
3710     while (retry--)
3711     {
3712         /* Select both XAPs */
3713         r = unifi_set_proc_select(card, which);
3714         if (r != CSR_RESULT_SUCCESS)
3715         {
3716             break;
3717         }
3718
3719         /* Stop processors */
3720         r = unifi_write_direct16(card, ChipHelper_DBG_EMU_CMD(card->helper) * 2, 2);
3721         if (r != CSR_RESULT_SUCCESS)
3722         {
3723             break;
3724         }
3725
3726         /* Read status */
3727         r = unifi_read_direct_8_or_16(card,
3728                                       ChipHelper_DBG_HOST_STOP_STATUS(card->helper) * 2,
3729                                       &status);
3730         if (r != CSR_RESULT_SUCCESS)
3731         {
3732             break;
3733         }
3734
3735         if ((status & 1) == 1)
3736         {
3737             /* Success! */
3738             return CSR_RESULT_SUCCESS;
3739         }
3740
3741         /* Processors didn't stop, try again */
3742     }
3743
3744     if (r != CSR_RESULT_SUCCESS)
3745     {
3746         /* An SDIO error occurred */
3747         unifi_error(card->ospriv, "Failed to stop processors: SDIO error\n");
3748     }
3749     else
3750     {
3751         /* If we reach here, we didn't the status in time. */
3752         unifi_error(card->ospriv, "Failed to stop processors: timeout waiting for stopped status\n");
3753         r = CSR_RESULT_FAILURE;
3754     }
3755
3756     return r;
3757 } /* unifi_card_stop_processor() */
3758
3759
3760 /*
3761  * ---------------------------------------------------------------------------
3762  *  card_start_processor
3763  *
3764  *      Start the UniFi XAP processors.
3765  *
3766  *  Arguments:
3767  *      card            Pointer to card struct
3768  *      which           One of UNIFI_PROC_MAC, UNIFI_PROC_PHY, UNIFI_PROC_BOTH
3769  *
3770  *  Returns:
3771  *      CSR_RESULT_SUCCESS or CSR error code
3772  * ---------------------------------------------------------------------------
3773  */
3774 CsrResult card_start_processor(card_t *card, enum unifi_dbg_processors_select which)
3775 {
3776     CsrResult r;
3777
3778     /* Select both XAPs */
3779     r = unifi_set_proc_select(card, which);
3780     if (r != CSR_RESULT_SUCCESS)
3781     {
3782         unifi_error(card->ospriv, "unifi_set_proc_select failed: %d.\n", r);
3783         return r;
3784     }
3785
3786
3787     r = unifi_write_direct_8_or_16(card,
3788                                    ChipHelper_DBG_EMU_CMD(card->helper) * 2, 8);
3789     if (r != CSR_RESULT_SUCCESS)
3790     {
3791         return r;
3792     }
3793
3794     r = unifi_write_direct_8_or_16(card,
3795                                    ChipHelper_DBG_EMU_CMD(card->helper) * 2, 0);
3796     if (r != CSR_RESULT_SUCCESS)
3797     {
3798         return r;
3799     }
3800
3801     return CSR_RESULT_SUCCESS;
3802 } /* card_start_processor() */
3803
3804
3805 /*
3806  * ---------------------------------------------------------------------------
3807  *  unifi_set_interrupt_mode
3808  *
3809  *      Configure the interrupt processing mode used by the HIP
3810  *
3811  *  Arguments:
3812  *      card            Pointer to card struct
3813  *      mode            Interrupt mode to apply
3814  *
3815  *  Returns:
3816  *      None
3817  * ---------------------------------------------------------------------------
3818  */
3819 void unifi_set_interrupt_mode(card_t *card, CsrUint32 mode)
3820 {
3821     if (mode == CSR_WIFI_INTMODE_RUN_BH_ONCE)
3822     {
3823         unifi_info(card->ospriv, "Scheduled interrupt mode");
3824     }
3825     card->intmode = mode;
3826 } /* unifi_set_interrupt_mode() */
3827
3828
3829 /*
3830  * ---------------------------------------------------------------------------
3831  *  unifi_start_processors
3832  *
3833  *      Start all UniFi XAP processors.
3834  *
3835  *  Arguments:
3836  *      card            Pointer to card struct
3837  *
3838  *  Returns:
3839  *      CSR_RESULT_SUCCESS on success, CSR error code on error
3840  * ---------------------------------------------------------------------------
3841  */
3842 CsrResult unifi_start_processors(card_t *card)
3843 {
3844     return card_start_processor(card, UNIFI_PROC_BOTH);
3845 } /* unifi_start_processors() */
3846
3847
3848 /*
3849  * ---------------------------------------------------------------------------
3850  *  unifi_request_max_sdio_clock
3851  *
3852  *      Requests that the maximum SDIO clock rate is set at the next suitable
3853  *      opportunity (e.g. when the BH next runs, so as not to interfere with
3854  *      any current operation).
3855  *
3856  *  Arguments:
3857  *      card            Pointer to card struct
3858  *
3859  *  Returns:
3860  *      None
3861  * ---------------------------------------------------------------------------
3862  */
3863 void unifi_request_max_sdio_clock(card_t *card)
3864 {
3865     card->request_max_clock = 1;
3866 } /* unifi_request_max_sdio_clock() */
3867
3868
3869 /*
3870  * ---------------------------------------------------------------------------
3871  *  unifi_set_host_state
3872  *
3873  *      Set the host deep-sleep state.
3874  *
3875  *      If transitioning to TORPID, the SDIO driver will be notified
3876  *      that the SD bus will be unused (idle) and conversely, when
3877  *      transitioning from TORPID that the bus will be used (active).
3878  *
3879  *  Arguments:
3880  *      card            Pointer to card struct
3881  *      state           New deep-sleep state.
3882  *
3883  *  Returns:
3884  *      CSR_RESULT_SUCCESS            on success
3885  *      CSR_WIFI_HIP_RESULT_NO_DEVICE      if the card was ejected
3886  *      CSR_RESULT_FAILURE            if an SDIO error occurred
3887  *
3888  *  Notes:
3889  *      We need to reduce the SDIO clock speed before trying to wake up the
3890  *      chip. Actually, in the implementation below we reduce the clock speed
3891  *      not just before we try to wake up the chip, but when we put the chip to
3892  *      deep sleep. This means that if the f/w wakes up on its' own, we waste
3893  *      a reduce/increace cycle. However, trying to eliminate this overhead is
3894  *      proved difficult, as the current state machine in the HIP lib does at
3895  *      least a CMD52 to disable the interrupts before we configure the host
3896  *      state.
3897  * ---------------------------------------------------------------------------
3898  */
3899 CsrResult unifi_set_host_state(card_t *card, enum unifi_host_state state)
3900 {
3901     CsrResult r = CSR_RESULT_SUCCESS;
3902     CsrResult csrResult;
3903     static const CsrCharString *const states[] = {
3904         "AWAKE", "DROWSY", "TORPID"
3905     };
3906     static const CsrUint8 state_csr_host_wakeup[] = {
3907         1, 3, 0
3908     };
3909     static const CsrUint8 state_io_abort[] = {
3910         0, 2, 3
3911     };
3912
3913     unifi_trace(card->ospriv, UDBG4, "State %s to %s\n",
3914                 states[card->host_state], states[state]);
3915
3916     if (card->host_state == UNIFI_HOST_STATE_TORPID)
3917     {
3918         CsrSdioFunctionActive(card->sdio_if);
3919     }
3920
3921     /* Write the new state to UniFi. */
3922     if (card->chip_id > SDIO_CARD_ID_UNIFI_2)
3923     {
3924         r = sdio_write_f0(card, SDIO_CSR_HOST_WAKEUP,
3925                           (CsrUint8)((card->function << 4) | state_csr_host_wakeup[state]));
3926     }
3927     else
3928     {
3929         r = sdio_write_f0(card, SDIO_IO_ABORT, state_io_abort[state]);
3930     }
3931
3932     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
3933     {
3934         return r;
3935     }
3936     if (r != CSR_RESULT_SUCCESS)
3937     {
3938         unifi_error(card->ospriv, "Failed to write UniFi deep sleep state\n");
3939     }
3940     else
3941     {
3942         /*
3943          * If the chip was in state TORPID then we can now increase
3944          * the maximum bus clock speed.
3945          */
3946         if (card->host_state == UNIFI_HOST_STATE_TORPID)
3947         {
3948             csrResult = CsrSdioMaxBusClockFrequencySet(card->sdio_if,
3949                                                        UNIFI_SDIO_CLOCK_MAX_HZ);
3950             r = ConvertCsrSdioToCsrHipResult(card, csrResult);
3951             /* Non-fatal error */
3952             if (r != CSR_RESULT_SUCCESS && r != CSR_WIFI_HIP_RESULT_NO_DEVICE)
3953             {
3954                 unifi_warning(card->ospriv,
3955                               "Failed to increase the SDIO clock speed\n");
3956             }
3957             else
3958             {
3959                 card->sdio_clock_speed = UNIFI_SDIO_CLOCK_MAX_HZ;
3960             }
3961         }
3962
3963         /*
3964          * Cache the current state in the card structure to avoid
3965          * unnecessary SDIO reads.
3966          */
3967         card->host_state = state;
3968
3969         if (state == UNIFI_HOST_STATE_TORPID)
3970         {
3971             /*
3972              * If the chip is now in state TORPID then we must now decrease
3973              * the maximum bus clock speed.
3974              */
3975             csrResult = CsrSdioMaxBusClockFrequencySet(card->sdio_if,
3976                                                        UNIFI_SDIO_CLOCK_SAFE_HZ);
3977             r = ConvertCsrSdioToCsrHipResult(card, csrResult);
3978             if (r != CSR_RESULT_SUCCESS && r != CSR_WIFI_HIP_RESULT_NO_DEVICE)
3979             {
3980                 unifi_warning(card->ospriv,
3981                               "Failed to decrease the SDIO clock speed\n");
3982             }
3983             else
3984             {
3985                 card->sdio_clock_speed = UNIFI_SDIO_CLOCK_SAFE_HZ;
3986             }
3987             CsrSdioFunctionIdle(card->sdio_if);
3988         }
3989     }
3990
3991     return r;
3992 } /* unifi_set_host_state() */
3993
3994
3995 /*
3996  * ---------------------------------------------------------------------------
3997  *  unifi_card_info
3998  *
3999  *      Update the card information data structure
4000  *
4001  *  Arguments:
4002  *      card            Pointer to card struct
4003  *      card_info       Pointer to info structure to update
4004  *
4005  *  Returns:
4006  *      None
4007  * ---------------------------------------------------------------------------
4008  */
4009 void unifi_card_info(card_t *card, card_info_t *card_info)
4010 {
4011     card_info->chip_id = card->chip_id;
4012     card_info->chip_version = card->chip_version;
4013     card_info->fw_build = card->build_id;
4014     card_info->fw_hip_version = card->config_data.version;
4015     card_info->sdio_block_size = card->sdio_io_block_size;
4016 } /* unifi_card_info() */
4017
4018
4019 /*
4020  * ---------------------------------------------------------------------------
4021  *  unifi_check_io_status
4022  *
4023  *      Check UniFi for spontaneous reset and pending interrupt.
4024  *
4025  *  Arguments:
4026  *      card            Pointer to card struct
4027  *      status          Pointer to location to write chip status:
4028  *                        0 if UniFi is running, and no interrupt pending
4029  *                        1 if UniFi has spontaneously reset
4030  *                        2 if there is a pending interrupt
4031  *  Returns:
4032  *      CSR_RESULT_SUCCESS if OK, or CSR error
4033  * ---------------------------------------------------------------------------
4034  */
4035 CsrResult unifi_check_io_status(card_t *card, CsrInt32 *status)
4036 {
4037     CsrUint8 io_en;
4038     CsrResult r;
4039     CsrBool pending;
4040
4041     *status = 0;
4042
4043     r = sdio_read_f0(card, SDIO_IO_ENABLE, &io_en);
4044     if (r == CSR_WIFI_HIP_RESULT_NO_DEVICE)
4045     {
4046         return r;
4047     }
4048     if (r != CSR_RESULT_SUCCESS)
4049     {
4050         unifi_error(card->ospriv, "Failed to read SDIO_IO_ENABLE to check for spontaneous reset\n");
4051         return r;
4052     }
4053
4054     if ((io_en & (1 << card->function)) == 0)
4055     {
4056         CsrInt32 fw_count;
4057         *status = 1;
4058         unifi_error(card->ospriv, "UniFi has spontaneously reset.\n");
4059
4060         /*
4061          * These reads are very likely to fail. We want to know if the function is really
4062          * disabled or the SDIO driver just returns rubbish.
4063          */
4064         fw_count = unifi_read_shared_count(card, card->sdio_ctrl_addr + 4);
4065         if (fw_count < 0)
4066         {
4067             unifi_error(card->ospriv, "Failed to read to-host sig written count\n");
4068         }
4069         else
4070         {
4071             unifi_error(card->ospriv, "thsw: %u (driver thinks is %u)\n",
4072                         fw_count, card->to_host_signals_w);
4073         }
4074         fw_count = unifi_read_shared_count(card, card->sdio_ctrl_addr + 2);
4075         if (fw_count < 0)
4076         {
4077             unifi_error(card->ospriv, "Failed to read from-host sig read count\n");
4078         }
4079         else
4080         {
4081             unifi_error(card->ospriv, "fhsr: %u (driver thinks is %u)\n",
4082                         fw_count, card->from_host_signals_r);
4083         }
4084
4085         return r;
4086     }
4087
4088     unifi_info(card->ospriv, "UniFi function %d is enabled.\n", card->function);
4089
4090     /* See if we missed an SDIO interrupt */
4091     r = CardPendingInt(card, &pending);
4092     if (pending)
4093     {
4094         unifi_error(card->ospriv, "There is an unhandled pending interrupt.\n");
4095         *status = 2;
4096         return r;
4097     }
4098
4099     return r;
4100 } /* unifi_check_io_status() */
4101
4102
4103 void unifi_get_hip_qos_info(card_t *card, unifi_HipQosInfo *hipqosinfo)
4104 {
4105     CsrInt32 count_fhr;
4106     CsrInt16 t;
4107     CsrUint32 occupied_fh;
4108
4109     q_t *sigq;
4110     CsrUint16 nslots, i;
4111
4112     CsrMemSet(hipqosinfo, 0, sizeof(unifi_HipQosInfo));
4113
4114     nslots = card->config_data.num_fromhost_data_slots;
4115
4116     for (i = 0; i < nslots; i++)
4117     {
4118         if (card->from_host_data[i].bd.data_length == 0)
4119         {
4120             hipqosinfo->free_fh_bulkdata_slots++;
4121         }
4122     }
4123
4124     for (i = 0; i < UNIFI_NO_OF_TX_QS; i++)
4125     {
4126         sigq = &card->fh_traffic_queue[i];
4127         t = sigq->q_wr_ptr - sigq->q_rd_ptr;
4128         if (t < 0)
4129         {
4130             t += sigq->q_length;
4131         }
4132         hipqosinfo->free_fh_sig_queue_slots[i] = (sigq->q_length - t) - 1;
4133     }
4134
4135     count_fhr = unifi_read_shared_count(card, card->sdio_ctrl_addr + 2);
4136     if (count_fhr < 0)
4137     {
4138         unifi_error(card->ospriv, "Failed to read from-host sig read count - %d\n", count_fhr);
4139         hipqosinfo->free_fh_fw_slots = 0xfa;
4140         return;
4141     }
4142
4143     occupied_fh = (card->from_host_signals_w - count_fhr) % 128;
4144
4145     hipqosinfo->free_fh_fw_slots = (CsrUint16)(card->config_data.num_fromhost_sig_frags - occupied_fh);
4146 }
4147
4148
4149
4150 CsrResult ConvertCsrSdioToCsrHipResult(card_t *card, CsrResult csrResult)
4151 {
4152     CsrResult r = CSR_RESULT_FAILURE;
4153
4154     switch (csrResult)
4155     {
4156         case CSR_RESULT_SUCCESS:
4157             r = CSR_RESULT_SUCCESS;
4158             break;
4159         /* Timeout errors */
4160         case CSR_SDIO_RESULT_TIMEOUT:
4161         /* Integrity errors */
4162         case CSR_SDIO_RESULT_CRC_ERROR:
4163             r = CSR_RESULT_FAILURE;
4164             break;
4165         case CSR_SDIO_RESULT_NO_DEVICE:
4166             r = CSR_WIFI_HIP_RESULT_NO_DEVICE;
4167             break;
4168         case CSR_SDIO_RESULT_INVALID_VALUE:
4169             r = CSR_WIFI_HIP_RESULT_INVALID_VALUE;
4170             break;
4171         case CSR_RESULT_FAILURE:
4172             r = CSR_RESULT_FAILURE;
4173             break;
4174         default:
4175             unifi_warning(card->ospriv, "Unrecognised csrResult error code: %d\n", csrResult);
4176             break;
4177     }
4178
4179     return r;
4180 } /* ConvertCsrSdioToCsrHipResult() */
4181
4182