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