summaryrefslogtreecommitdiffstats
path: root/nuttx/arch/arm/src/imx/imx_spi.c
blob: f1b3262a0340fdd7643e486fb1bb6652dead6fc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
/****************************************************************************
 * arch/arm/src/imx/imx_spi.c
 *
 *   Copyright (C) 2009 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <spudmonkey@racsa.co.cr>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>
#include <sys/types.h>
#include <errno.h>
#include <debug.h>

#include <nuttx/arch.h>
#include <nuttx/spi.h>

#include <arch/irq.h>
#include <arch/board/board.h>

#include "up_internal.h"
#include "up_arch.h"

#include "chip.h"
#include "imx_gpio.h"
#include "imx_cspi.h"

/****************************************************************************
 * Definitions
 ****************************************************************************/

/* The i.MX1/L supports 2 SPI interfaces.  Which have been enabled? */

#ifndef CONFIG_SPI1_DISABLE
#  define SPI1_NDX 0           /* Index to SPI1 in g_spidev[] */
#  ifndef CONFIG_SPI2_DISABLE
#   define SPI2_NDX 1          /* Index to SPI2 in g_spidev[] */
#   define NSPIS 2             /* Two SPI interfaces: SPI1 & SPI2 */
#  else
#   define NSPIS 1             /* One SPI interface: SPI1 */
#  endif
#else
#  ifndef CONFIG_SPI2_DISABLE
#   define SPI2_NDX 0          /* Index to SPI2 in g_spidev[] */
#   define NSPIS 1             /* One SPI interface: SPI2 */
#  else
#   define NSPIS 0             /* No SPI interfaces */
#  endif
#endif

/* Compile the rest of the file only if at least one SPI interface has been
 * enabled.
 */

#if NSPIS > 0

/* The number of words that will fit in the Tx FIFO */

#define IMX_TXFIFO_WORDS 8

/****************************************************************************
 * Private Type Definitions
 ****************************************************************************/

struct imx_spidev_s
{
  const struct spi_ops_s *ops;  /* Common SPI operations */
#ifndef CONFIG_SPI_POLLWAIT
  sem_t  sem;                   /* Wait for transfer to complete */
#endif

  /* These following are the source and destination buffers of the transfer.
   * they are retained in this structure so that they will be accessible
   * from an interrupt handler.  The actual type of the buffer is ubyte is
   * nbits <=8 and uint16 is nbits >8.
   */

  void  *txbuffer;              /* Source buffer */
  void  *rxbuffer;              /* Destination buffer */

  /* These are functions pointers that are configured to perform the
   * appropriate transfer for the particular kind of exchange that is
   * occurring.  Differnt functions may be selected depending on (1)
   * if the tx or txbuffer is NULL and depending on the number of bits
   * per word.
   */

  void  (*txword)(struct imx_spidev_s *priv);
  void  (*rxword)(struct imx_spidev_s *priv);

  uint32 base;                  /* SPI register base address */
  uint32 frequency;             /* Current desired SCLK frequency */
  uint32 actual;                /* Current actual SCLK frequency */

  int    ntxwords;              /* Number of words left to transfer on the Tx FIFO */
  int    nrxwords;              /* Number of words received on the Rx FIFO */
  int    nwords;                /* Number of words to be exchanged */

  ubyte  mode;                  /* Current mode */
  ubyte  nbits;                 /* Current number of bits per word */
#ifndef CONFIG_SPI_POLLWAIT
  ubyte  irq;                   /* SPI IRQ number */
#endif
};

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

 /* SPI register access */
 
static inline uint32 spi_getreg(struct imx_spidev_s *priv, unsigned int offset);
static inline void spi_putreg(struct imx_spidev_s *priv, unsigned int offset, uint32 value);

/* SPI data transfer */

static void   spi_txnull(struct imx_spidev_s *priv);
static void   spi_txuint16(struct imx_spidev_s *priv);
static void   spi_txubyte(struct imx_spidev_s *priv);
static void   spi_rxnull(struct imx_spidev_s *priv);
static void   spi_rxuint16(struct imx_spidev_s *priv);
static void   spi_rxubyte(struct imx_spidev_s *priv);
static int    spi_performtx(struct imx_spidev_s *priv);
static inline void spi_performrx(struct imx_spidev_s *priv);
static int    spi_transfer(struct imx_spidev_s *priv, const void *txbuffer,
                           void *rxbuffer, unsigned int nwords);

/* Interrupt handling */

#ifndef CONFIG_SPI_POLLWAIT
static inline struct imx_spidev_s *spi_mapirq(int irq);
static int    spi_interrupt(int irq, void *context);
#endif

/* SPI methods */

static uint32 spi_setfrequency(FAR struct spi_dev_s *dev, uint32 frequency);
static void   spi_setmode(FAR struct spi_dev_s *dev, enum spi_mode_e mode);
static void   spi_setbits(FAR struct spi_dev_s *dev, int nbits);
static uint16 spi_send(FAR struct spi_dev_s *dev, uint16 wd);
#ifdef CONFIG_SPI_EXCHANGE
static void   spi_exchange(FAR struct spi_dev_s *dev, FAR const void *txbuffer,
                           FAR void *rxbuffer, size_t nwords);
#else
static void   spi_sndblock(FAR struct spi_dev_s *dev, FAR const void *buffer, size_t nwords);
static void   spi_recvblock(FAR struct spi_dev_s *dev, FAR void *buffer, size_t nwords);
#endif

/****************************************************************************
 * Private Data
 ****************************************************************************/

/* Common SPI operations */

static const struct spi_ops_s g_spiops =
{
  .select       = imx_spiselect,    /* Provided externally by board logic */
  .setfrequency = spi_setfrequency,
  .setmode      = spi_setmode,
  .setbits      = spi_setbits,
  .status       = imx_spistatus,    /* Provided externally by board logic */
  .send         = spi_send,
#ifdef CONFIG_SPI_EXCHANGE
  .exchange     = spi_exchange,
#else
  .sndblock     = spi_sndblock,
  .recvblock    = spi_recvblock,
#endif
};

/* This supports is up to two SPI busses/ports */

static struct imx_spidev_s g_spidev[] =
{
#ifndef CONFIG_SPI1_DISABLE
  {
    .ops  = &g_spiops,
    .base = IMX_CSPI1_VBASE,
#ifndef CONFIG_SPI_POLLWAIT
    .irq  = IMX_IRQ_CSPI1,
#endif
  },
#endif
#ifndef CONFIG_SPI2_DISABLE
  {
    .ops  = &g_spiops,
    .base = IMX_CSPI2_VBASE,
#ifndef CONFIG_SPI_POLLWAIT
    .irq  = IMX_IRQ_CSPI2,
#endif
  },
#endif
};

/****************************************************************************
 * Public Data
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Name: spi_getreg
 *
 * Description:
 *   Read the SPI register at this offeset
 *
 * Input Parameters:
 *   priv   - Device-specific state data
 *   offset - Offset to the SPI register from the register base address
 *
 * Returned Value:
 *   Value of the register at this offset
 *
 ****************************************************************************/

static inline uint32 spi_getreg(struct imx_spidev_s *priv, unsigned int offset)
{
  return getreg32(priv->base + offset);
}

/****************************************************************************
 * Name: spi_putreg
 *
 * Description:
 *   Write the value to the SPI register at this offeset
 *
 * Input Parameters:
 *   priv   - Device-specific state data
 *   offset - Offset to the SPI register from the register base address
 *   value  - Value to write
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

static inline void spi_putreg(struct imx_spidev_s *priv, unsigned int offset, uint32 value)
{
  putreg32(value, priv->base + offset);
}

/****************************************************************************
 * Name: spi_txnull, spi_txuint16, and spi_txubyte
 *
 * Description:
 *   Transfer all ones, a ubyte, or uint16 to Tx FIFO and update the txbuffer
 *   pointer appropriately.  The selected function dependes on (1) if there
 *   is a source txbuffer provided, and (2) if the number of bits per
 *   word is <=8 or >8.
 *
 * Input Parameters:
 *   priv   - Device-specific state data
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

static void spi_txnull(struct imx_spidev_s *priv)
{
  spi_putreg(priv, CSPI_TXD_OFFSET, 0xffff);
}

static void spi_txuint16(struct imx_spidev_s *priv)
{
  uint16 *ptr = (uint16*)priv->txbuffer;
  spi_putreg(priv, CSPI_TXD_OFFSET, *ptr++);
  priv->txbuffer = (void*)ptr;
}

static void spi_txubyte(struct imx_spidev_s *priv)
{
  ubyte *ptr = (ubyte*)priv->txbuffer;
  spi_putreg(priv, CSPI_TXD_OFFSET, *ptr++);
  priv->txbuffer = (void*)ptr;
}

/****************************************************************************
 * Name: spi_rxnull, spi_rxuint16, and spi_rxubyte
 *
 * Description:
 *   Discard input, save a ubyte, or or save a uint16 from Tx FIFO in the
 *   user rxvbuffer and update the rxbuffer pointer appropriately.  The
 *   selected function dependes on (1) if there is a desination rxbuffer
 *   provided, and (2) if the number of bits per word is <=8 or >8.
 *
 * Input Parameters:
 *   priv   - Device-specific state data
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

static void spi_rxnull(struct imx_spidev_s *priv)
{
  (void)spi_getreg(priv, CSPI_RXD_OFFSET);
}

static void spi_rxuint16(struct imx_spidev_s *priv)
{
  uint16 *ptr = (uint16*)priv->rxbuffer;
  *ptr++ = (uint16)spi_getreg(priv, CSPI_TXD_OFFSET);
  priv->rxbuffer = (void*)ptr;
}

static void spi_rxubyte(struct imx_spidev_s *priv)
{
  ubyte *ptr = (ubyte*)priv->rxbuffer;
  *ptr++ = (ubyte)spi_getreg(priv, CSPI_TXD_OFFSET);
  priv->rxbuffer = (void*)ptr;
}

/****************************************************************************
 * Name: spi_performtx
 *
 * Description:
 *   If the Tx FIFO is empty, then transfer as many words as we can to
 *   the FIFO.
 *
 * Input Parameters:
 *   priv   - Device-specific state data
 *
 * Returned Value:
 *   The number of words written to the Tx FIFO (a value from 0 to 8,
 *   inclusive).
 *
 ****************************************************************************/

static int spi_performtx(struct imx_spidev_s *priv)
{
  uint32 regval;
  int ntxd = 0;  /* Number of words written to Tx FIFO */

  /* Check if the Tx FIFO is empty */

  if ((spi_getreg(priv, CSPI_INTCS_OFFSET) & CSPI_INTCS_TE) != 0)
    {
      /* Check if all of the Tx words have been sent */

      if (priv->ntxwords > 0)
        {
          /* No.. Transfer more words until either the TxFIFO is full or
           * until all of the user provided data has been sent.
           */

          for (; ntxd < priv->ntxwords && ntxd < IMX_TXFIFO_WORDS; ntxd++)
            {
               priv->txword(priv);
            }

          /* Update the count of words to to transferred */

          priv->ntxwords -= ntxd;
        }
      else
        {
          /* Yes.. The transfer is complete, disable Tx FIFO empty interrupt */

          regval = spi_getreg(priv, CSPI_INTCS_OFFSET);
          regval &= ~CSPI_INTCS_TEEN;
          spi_putreg(priv, CSPI_INTCS_OFFSET, regval);
        }
    }
  return ntxd;
}

/****************************************************************************
 * Name: spi_performrx
 *
 * Description:
 *   Transfer as many bytes as possible from the Rx FIFO to the user Rx
 *   buffer (if one was provided).
 *
 * Input Parameters:
 *   priv   - Device-specific state data
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

static inline void spi_performrx(struct imx_spidev_s *priv)
{
  /* Loop while data is available in the Rx FIFO */

  while ((spi_getreg(priv, CSPI_INTCS_OFFSET) & CSPI_INTCS_RR) != 0)
    {
      /* Have all of the requested words been transferred from the Rx FIFO? */

      if (priv->nrxwords < priv->nwords)
        {
          /* No.. Read more data from Rx FIFO */

          priv->rxword(priv);
          priv->nrxwords++;
        }
    }
}

/****************************************************************************
 * Name: spi_startxfr
 *
 * Description:
 *   If data was added to the Tx FIFO, then start the exchange
 *
 * Input Parameters:
 *   priv  - Device-specific state data
 *   ntxd  - The number of bytes added to the Tx FIFO by spi_performtx.
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

static void spi_startxfr(struct imx_spidev_s *priv, int ntxd)
{
  uint32 regval;

  /* The XCH bit initiates an exchange in master mode.  It remains set
   * remains set while the exchange is in progress but is automatically
   * clear when all data in the Tx FIFO and shift register are shifted out.
   * So if we have added data to the Tx FIFO on this interrupt, we must
   * set the XCH bit to resume the exchange.
   */

  if (ntxd > 0)
   {
      regval = spi_getreg(priv, CSPI_CTRL_OFFSET);
      regval |= CSPI_CTRL_XCH;
      spi_putreg(priv, CSPI_CTRL_OFFSET, regval);
   }
}

/****************************************************************************
 * Name: spi_transfer
 *
 * Description:
 *   Exchange a block data with the SPI device
 *
 * Input Parameters:
 *   priv   - Device-specific state data
 *   txbuffer - The buffer of data to send to the device (may be NULL).
 *   rxbuffer - The buffer to receive data from the device (may be NULL).
 *   nwords   - The total number of words to be exchanged.  If the interface
 *              uses <= 8 bits per word, then this is the number of ubytes;
 *              if the interface uses >8 bits per word, then this is the
 *              number of uint16's
 *
 * Returned Value:
 *   0: success, <0:Negated error number on failure
 *
 ****************************************************************************/

static int spi_transfer(struct imx_spidev_s *priv, const void *txbuffer,
                        void *rxbuffer, unsigned int nwords)
{
#ifndef CONFIG_SPI_POLLWAIT
  irqstate_t flags;
#endif
  uint32 regval;
  int ntxd;
  int ret;

  /* Set up to perform the transfer */

  priv->txbuffer     = (ubyte*)txbuffer; /* Source buffer */
  priv->rxbuffer     = (ubyte*)rxbuffer; /* Destination buffer */
  priv->ntxwords     = nwords;           /* Number of words left to send */
  priv->nrxwords     = 0;                /* Number of words received */
  priv->nwords       = nwords;           /* Total number of exchanges */

  /* Set up the low-level data transfer function pointers */

  if (priv->nbits > 8)
    {
      priv->txword = spi_txuint16;
      priv->rxword = spi_rxuint16;
    }
  else
    {
      priv->txword = spi_txubyte;
      priv->rxword = spi_rxubyte;
    }

  if (!txbuffer)
    {
      priv->txword = spi_txnull;
    }

  if (!rxbuffer)
    {
      priv->rxword = spi_rxnull;
    }

  /* Prime the Tx FIFO to start the sequence (saves one interrupt) */

#ifndef CONFIG_SPI_POLLWAIT
  flags = irqsave();
  ntxd  = spi_performtx(priv);
  spi_startxfr(priv, ntxd);

  /* Enable transmit empty interrupt */

  regval = spi_getreg(priv, CSPI_INTCS_OFFSET);
  regval |= CSPI_INTCS_TEEN;
  spi_putreg(priv, CSPI_INTCS_OFFSET, regval);
  irqrestore(flags);

  /* Wait for the transfer to complete.  Since there is no handshake
   * with SPI, the following should complete even if there are problems
   * with the transfer, so it should be safe with no timeout.
   */

  do
    {
      /* Wait to be signaled from the interrupt handler */

      ret = sem_wait(&priv->sem);
    }
  while (ret < 0 && errno == EINTR);
#else
  /* Perform the transfer using polling logic.  This will totally
   * dominate the CPU until the transfer is complete.  Only recommended
   * if (1) your SPI is very fast, and (2) if you only use very short
   * transfers.
   */

  do
    {
      /* Handle outgoing Tx FIFO transfers */

      ntxd = spi_performtx(priv);

      /* Handle incoming Rx FIFO transfers */

      spi_performrx(priv);

      /* Resume the transfer */

      spi_startxfr(priv, ntxd);

      /* If there are other threads at this same priority level,
       * the following may help:
       */

      sched_yield();
    }
  while (priv->nrxwords < priv->nwords);
#endif
  return OK;
}

/****************************************************************************
 * Name: spi_mapirq
 *
 * Description:
 *   Map an IRQ number into the appropriate SPI device
 *
 * Input Parameters:
 *   irq   - The IRQ number to be mapped
 *
 * Returned Value:
 *   On success, a reference to the private data structgure for this IRQ.
 *   NULL on failrue.
 *
 ****************************************************************************/

#ifndef CONFIG_SPI_POLLWAIT
static inline struct imx_spidev_s *spi_mapirq(int irq)
{
  switch (irq)
    {
#ifndef CONFIG_SPI1_DISABLE
      case IMX_IRQ_CSPI1:
        return &g_spidev[SPI1_NDX];
#endif
#ifndef CONFIG_SPI2_DISABLE
      case IMX_IRQ_CSPI2:
        return &g_spidev[SPI2_NDX];
#endif
      default:
        return NULL;
    }
}
#endif

/****************************************************************************
 * Name: spi_interrupt
 *
 * Description:
 *   Exchange a block data with the SPI device
 *
 * Input Parameters:
 *   priv   - Device-specific state data
 *   txbuffer - The buffer of data to send to the device (may be NULL).
 *   rxbuffer - The buffer to receive data from the device (may be NULL).
 *   nwords   - The total number of words to be exchanged.  If the interface
 *              uses <= 8 bits per word, then this is the number of ubytes;
 *              if the interface uses >8 bits per word, then this is the
 *              number of uint16's
 *
 * Returned Value:
 *   0: success, <0:Negated error number on failure
 *
 ****************************************************************************/

#ifndef CONFIG_SPI_POLLWAIT
static int spi_interrupt(int irq, void *context)
{
  struct imx_spidev_s *priv = spi_mapirq(irq);
  int ntxd;

  DEBUGASSERT(priv != NULL);

  /* Handle outgoing Tx FIFO transfers */

  ntxd = spi_performtx(priv);

  /* Handle incoming Rx FIFO transfers */

  spi_performrx(priv);

  /* Resume the transfer */

  spi_startxfr(priv, ntxd);

  /* Check if the transfer is complete */

  if (priv->nrxwords >= priv->nwords)
    {
      /* Yes, wake up the waiting thread */

      sem_post(&priv->sem);
    }
  return OK;
}
#endif

/****************************************************************************
 * Name: spi_setfrequency
 *
 * Description:
 *   Set the SPI frequency.
 *
 * Input Parameters:
 *   dev -       Device-specific state data
 *   frequency - The SPI frequency requested
 *
 * Returned Value:
 *   Returns the actual frequency selected
 *
 ****************************************************************************/

static uint32 spi_setfrequency(FAR struct spi_dev_s *dev, uint32 frequency)
{
  struct imx_spidev_s *priv = (struct imx_spidev_s *)dev;
  uint32 actual = priv->actual;

  if (priv && frequency != priv->frequency)
    {
      uint32 freqbits;
      uint32 regval;

      if (frequency >= IMX_PERCLK2_FREQ / 4)
        {
          freqbits = CSPI_CTRL_DIV4;
          actual   = IMX_PERCLK2_FREQ / 4;
        }
      else if (frequency >= IMX_PERCLK2_FREQ / 8)
        {
          freqbits = CSPI_CTRL_DIV8;
          actual   = IMX_PERCLK2_FREQ / 8;
        }
      else if (frequency >= IMX_PERCLK2_FREQ / 16)
        {
          freqbits = CSPI_CTRL_DIV16;
          actual   = IMX_PERCLK2_FREQ / 16;
        }
      else if (frequency >= IMX_PERCLK2_FREQ / 32)
        {
          freqbits = CSPI_CTRL_DIV32;
          actual   = IMX_PERCLK2_FREQ / 32;
        }
      else if (frequency >= IMX_PERCLK2_FREQ / 64)
        {
          freqbits = CSPI_CTRL_DIV64;
          actual   = IMX_PERCLK2_FREQ / 64;
        }
      else if (frequency >= IMX_PERCLK2_FREQ / 128)
        {
          freqbits = CSPI_CTRL_DIV128;
          actual   = IMX_PERCLK2_FREQ / 128;
        }
      else if (frequency >= IMX_PERCLK2_FREQ / 256)
        {
          freqbits = CSPI_CTRL_DIV256;
          actual   = IMX_PERCLK2_FREQ / 256;
        }
      else /*if (frequency >= IMX_PERCLK2_FREQ / 512) */
        {
          freqbits = CSPI_CTRL_DIV512;
          actual   = IMX_PERCLK2_FREQ / 512;
        }

      /* Then set the selected frequency */

      regval = spi_getreg(priv, CSPI_CTRL_OFFSET);
      regval &= ~(CSPI_CTRL_DATARATE_MASK);
      regval |= freqbits;
      spi_putreg(priv, CSPI_CTRL_OFFSET, regval);

      priv->frequency = frequency;
      priv->actual    = actual;
    }

  return actual;
}

/****************************************************************************
 * Name: spi_setmode
 *
 * Description:
 *   Set the SPI mode. Optional.  See enum spi_mode_e for mode definitions
 *
 * Input Parameters:
 *   dev -  Device-specific state data
 *   mode - The SPI mode requested
 *
 * Returned Value:
 *   none
 *
 ****************************************************************************/

static void spi_setmode(FAR struct spi_dev_s *dev, enum spi_mode_e mode)
{
  struct imx_spidev_s *priv = (struct imx_spidev_s *)dev;
  if (priv && mode != priv->mode)
    {
      uint32 modebits;
      uint32 regval;

      /* Select the CTL register bits based on the selected mode */

      switch (mode)
        {
        case SPIDEV_MODE0: /* CPOL=0 CHPHA=0 */
          modebits = 0;
          break;

        case SPIDEV_MODE1: /* CPOL=0 CHPHA=1 */
          modebits = CSPI_CTRL_PHA;
          break;

        case SPIDEV_MODE2: /* CPOL=1 CHPHA=0 */
          modebits = CSPI_CTRL_POL;
         break;

        case SPIDEV_MODE3: /* CPOL=1 CHPHA=1 */
          modebits = CSPI_CTRL_PHA|CSPI_CTRL_POL;
          break;

        default:
          return;
        }

      /* Then set the selected mode */

      regval = spi_getreg(priv, CSPI_CTRL_OFFSET);
      regval &= ~(CSPI_CTRL_PHA|CSPI_CTRL_POL);
      regval |= modebits;
      spi_putreg(priv, CSPI_CTRL_OFFSET, regval);
    }
}

/****************************************************************************
 * Name: spi_setbits
 *
 * Description:
 *   Set the number of bits per word.
 *
 * Input Parameters:
 *   dev -  Device-specific state data
 *   nbits - The number of bits requests
 *
 * Returned Value:
 *   none
 *
 ****************************************************************************/

static void spi_setbits(FAR struct spi_dev_s *dev, int nbits)
{
  struct imx_spidev_s *priv = (struct imx_spidev_s *)dev;
  if (priv && nbits != priv->nbits && nbits > 0 && nbits <= 16)
    {
      uint32 regval = spi_getreg(priv, CSPI_CTRL_OFFSET);
      regval       &= ~CSPI_CTRL_BITCOUNT_MASK;
      regval       |= ((nbits - 1) << CSPI_CTRL_BITCOUNT_SHIFT);
      spi_putreg(priv, CSPI_CTRL_OFFSET, regval);
      priv->nbits   = nbits;
    }
}

/****************************************************************************
 * Name: spi_send
 *
 * Description:
 *   Exchange one word on SPI
 *
 * Input Parameters:
 *   dev - Device-specific state data
 *   wd  - The word to send.  the size of the data is determined by the
 *         number of bits selected for the SPI interface.
 *
 * Returned Value:
 *   response
 *
 ****************************************************************************/

static uint16 spi_send(FAR struct spi_dev_s *dev, uint16 wd)
{
  struct imx_spidev_s *priv = (struct imx_spidev_s*)dev;
  uint16 response = 0;

  (void)spi_transfer(priv, &wd, &response, 1);
  return response;
}

/****************************************************************************
 * Name: SPI_EXCHANGE
 *
 * Description:
 *   Exahange a block of data from SPI. Required.
 *
 * Input Parameters:
 *   dev      - Device-specific state data
 *   buffer   - A pointer to the buffer of data to be sent
 *   rxbuffer - A pointer to the buffer in which to recieve data
 *   nwords   - the length of data that to be exchanged in units of words.
 *              The wordsize is determined by the number of bits-per-word
 *              selected for the SPI interface.  If nbits <= 8, the data is
 *              packed into ubytes; if nbits >8, the data is packed into uint16's
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

#ifdef CONFIG_SPI_EXCHANGE
static void spi_exchange(FAR struct spi_dev_s *dev, FAR const void *txbuffer,
                         FAR void *rxbuffer, size_t nwords)
{
  struct imx_spidev_s *priv = (struct imx_spidev_s *)dev;
  (void)spi_transfer(priv, txbuffer, rxbuffer, nwords);
}
#endif

/*************************************************************************
 * Name: spi_sndblock
 *
 * Description:
 *   Send a block of data on SPI
 *
 * Input Parameters:
 *   dev -    Device-specific state data
 *   buffer - A pointer to the buffer of data to be sent
 *   nwords - the length of data to send from the buffer in number of words.
 *            The wordsize is determined by the number of bits-per-word
 *            selected for the SPI interface.  If nbits <= 8, the data is
 *            packed into ubytes; if nbits >8, the data is packed into uint16's
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

#ifndef CONFIG_SPI_EXCHANGE
static void spi_sndblock(FAR struct spi_dev_s *dev, FAR const void *buffer, size_t nwords)
{
  struct imx_spidev_s *priv = (struct imx_spidev_s *)dev;
  (void)spi_transfer(priv, buffer, NULL, nwords);
}
#endif

/****************************************************************************
 * Name: spi_recvblock
 *
 * Description:
 *   Revice a block of data from SPI
 *
 * Input Parameters:
 *   dev -    Device-specific state data
 *   buffer - A pointer to the buffer in which to recieve data
 *   nwords - the length of data that can be received in the buffer in number
 *            of words.  The wordsize is determined by the number of bits-per-word
 *            selected for the SPI interface.  If nbits <= 8, the data is
 *            packed into ubytes; if nbits >8, the data is packed into uint16's
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

#ifndef CONFIG_SPI_EXCHANGE
static void spi_recvblock(FAR struct spi_dev_s *dev, FAR void *buffer, size_t nwords)
{
  struct imx_spidev_s *priv = (struct imx_spidev_s *)dev;
  (void)spi_transfer(priv, NULL, buffer, nwords);
}
#endif

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: up_spiinitialize
 *
 * Description:
 *   Initialize common parts the selected SPI port.  Initialization of
 *   chip select GPIOs must have been performed by board specific logic
 *   prior to calling this function.  Specifically:  GPIOs should have
 *   been configured for output, and all chip selects disabled.
 *
 *   One GPIO, SS (PB2 on the eZ8F091) is reserved as a chip select.  However,
 *   If multiple devices on on the bus, then multiple chip selects will be
 *   required.  Theregore, all GPIO chip management is deferred to board-
 *   specific logic.
 *
 * Input Parameter:
 *   Port number (for hardware that has mutiple SPI interfaces)
 *
 * Returned Value:
 *   Valid SPI device structre reference on succcess; a NULL on failure
 *
 ****************************************************************************/

FAR struct spi_dev_s *up_spiinitialize(int port)
{
  struct imx_spidev_s *priv;
  ubyte regval;

  /* Only the SPI1 interface is supported */

  switch (port)
    {
#ifndef CONFIG_SPI1_DISABLE
    case 1:
      /* Select SPI1 */

      priv = &g_spidev[SPI1_NDX];

      /* Configure SPI1 GPIOs (NOTE that SS is not initialized here, the
       * logic in this file makes no assumptions about chip select)
       */

      imxgpio_configpfinput(GPIOC, 13);  /* Port C, pin 13: RDY */
      imxgpio_configpfoutput(GPIOC, 14); /* Port C, pin 14: SCLK */
      imxgpio_configpfinput(GPIOC, 16);  /* Port C, pin 16: MISO */
      imxgpio_configpfoutput(GPIOC, 17); /* Port C, pin 17: MOSI */
      break;
#endif /* CONFIG_SPI1_DISABLE */

#ifndef CONFIG_SPI2_DISABLE
    case 2:
      /* Select SPI2 */

      priv = &g_spidev[SPI2_NDX];

      /* Configure SPI2 GPIOs */
      /* SCLK: AIN of Port A, pin 0 -OR- AIN of Port D, pin 7 */

#if 1
      imxgpio_configoutput(GPIOA, 0); /* Set GIUS=1 OCR=0 DIR=OUT */
#else
      imxgpio_configoutput(GPIOD, 7); /* Set GIUS=1 OCR=0 DIR=OUT */
#endif

      /* SS: AIN of Port A, pin 17 -OR- AIN of Port D, pin 8.(NOTE that SS
       * is not initialized here, the logic in this file makes no assumptions
       * about chip select)
       */

      /* RXD: AOUT of Port A, pin 1 -OR- AOUT of Port D, pin 9 */

#if 1
      imxgpio_configinput(GPIOA, 1); /* Set GIUS=1 OCR=0 DIR=IN */

      /* Select input from SPI2_RXD_0 pin (AOUT Port A, pin 1) */

      regval = getreg32(IMX_SC_FMCR);
      regval &= ~FMCR_SPI2_RXDSEL;
      putreg32(regval, IMX_SC_FMCR);
#else
      imxgpio_configinput(GPIOD, 9); /* Set GIUS=1 OCR=0 DIR=IN */

      /* Select input from SPI2_RXD_1 pin (AOUT Port D, pin 9) */

      regval = getreg32(IMX_SC_FMCR);
      regval |= FMCR_SPI2_RXDSEL;
      putreg32(regval, IMX_SC_FMCR);
#endif

      /* TXD: BIN of Port D, pin 31 -OR- AIN of Port D, pin 10 */

#if 1
      imxgpio_configinput(GPIOD, 31);
      imxgpio_ocrbin(GPIOD, 31);
      imxgpio_dirout(GPIOD, 31);
#else 
      imxgpio_configoutput(GPIOD, 10);
#endif
      break;
#endif /* CONFIG_SPI2_DISABLE */

    default:
      return NULL;
    }

  /* Initialize the state structure */

#ifndef CONFIG_SPI_POLLWAIT
   sem_init(&priv->sem, 0, 0);
#endif

  /* Initialize control register: min frequency, ignore ready, master mode, mode=0, 8-bit */

  spi_putreg(priv, CSPI_CTRL_OFFSET, 
             CSPI_CTRL_DIV512 |                /* Lowest frequency */
             CSPI_CTRL_DRCTL_IGNRDY |          /* Ignore ready */
             CSPI_CTRL_MODE |                  /* Master mode */
             (7 << CSPI_CTRL_BITCOUNT_SHIFT)); /* 8-bit data */

  /* Make sure state agrees with data */

  priv->mode  = SPIDEV_MODE0;
  priv->nbits = 8;

  /* Set the initial clock frequency for identification mode < 400kHz */

  spi_setfrequency((FAR struct spi_dev_s *)priv, 400000);

  /* Enable interrupts on data ready (and certain error conditions */

#ifndef CONFIG_SPI_POLLWAIT
  spi_putreg(priv, CSPI_INTCS_OFFSET,
             CSPI_INTCS_RREN |                 /* RXFIFO Data Ready Interrupt Enable */
             CSPI_INTCS_ROEN |                 /* RXFIFO Overflow Interrupt Enable */
             CSPI_INTCS_BOEN);                 /* Bit Count Overflow Interrupt Enable */
#else
  spi_putreg(priv, CSPI_INTCS_OFFSET, 0);      /* No interrupts */
#endif

  /* Set the clock source=bit clock and number of clocks inserted between
   * transactions = 2.
   */

  spi_putreg(priv, CSPI_SPCR_OFFSET, 2);

  /* No DMA */

  spi_putreg(priv, CSPI_DMA_OFFSET, 0);

  /* Attach the interrupt */

#ifndef CONFIG_SPI_POLLWAIT
  irq_attach(priv->irq, (xcpt_t)spi_interrupt);
#endif

  /* Enable SPI */

  regval = spi_getreg(priv, CSPI_CTRL_OFFSET);
  regval |= CSPI_CTRL_SPIEN;
  spi_putreg(priv, CSPI_CTRL_OFFSET, regval);

  /* Enable SPI interrupts */

#ifndef CONFIG_SPI_POLLWAIT
  up_enable_irq(priv->irq);
#endif
  return (FAR struct spi_dev_s *)priv;
}

#endif /* NSPIS > 0 */