summaryrefslogtreecommitdiff
path: root/drivers/sensors/brcm/bbdpl2/bcm_gps_spi.c
blob: 8434aa157e11ca5bf51263385feb7ab0791d6fb8 (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
/******************************************************************************
 * Copyright (C) 2015 Broadcom Corporation
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation version 2.
 *
 * This program is distributed "as is" WITHOUT ANY WARRANTY of any
 * kind, whether express or implied; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 ******************************************************************************/

#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/sysrq.h>
#include <linux/console.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <linux/spi/spidev.h>
#include <linux/kthread.h>
#include <linux/circ_buf.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/poll.h>
#include <linux/uaccess.h>
#include <linux/wakelock.h>
#include <linux/suspend.h>
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/ssp_platformdata.h>
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#include <linux/miscdevice.h>
#include <linux/time.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <linux/kernel_stat.h>
#include <linux/pm_runtime.h>

#include "bbd.h"

#define WORD_BURST_SIZE			4
#define CONFIG_SPI_DMA_BYTES_PER_WORD	4
#define CONFIG_SPI_DMA_BITS_PER_WORD	32

#define SSI_MODE_STREAM		0x00
#define SSI_MODE_DEBUG		0x80

#define SSI_MODE_HALF_DUPLEX	0x00
#define SSI_MODE_FULL_DUPLEX	0x40

#define SSI_WRITE_TRANS		0x00
#define SSI_READ_TRANS		0x20

#define SSI_WRITE_HD (SSI_WRITE_TRANS | SSI_MODE_HALF_DUPLEX)
#define SSI_READ_HD  (SSI_READ_TRANS  | SSI_MODE_HALF_DUPLEX)

#define DEBUG_TIME_STAT

#ifdef CONFIG_SENSORS_SSP_BBD
extern void bbd_parse_asic_data(unsigned char *pucData, unsigned short usLen, void (*to_gpsd)(unsigned char *packet, unsigned short len, void* priv), void* priv);
#endif

bool ssi_dbg;

//--------------------------------------------------------------
//
//               Structs
//
//--------------------------------------------------------------

#define BCM_SPI_READ_BUF_SIZE	(4*PAGE_SIZE)
#define BCM_SPI_WRITE_BUF_SIZE	(4*PAGE_SIZE)


#define MAX_SPI_FRAME_LEN 254
struct bcm_ssi_tx_frame
{
	unsigned char cmd;
	unsigned char data[MAX_SPI_FRAME_LEN-1];
} __attribute__((__packed__));

struct bcm_ssi_rx_frame
{
	unsigned char status;
	unsigned char len;
	unsigned char data[MAX_SPI_FRAME_LEN-2];
} __attribute__((__packed__));


struct bcm_spi_priv
{
	struct spi_device *spi;

	/* Char device stuff */
	struct miscdevice misc;
	bool busy;
	struct circ_buf read_buf;
	struct circ_buf write_buf;
	struct mutex rlock;			/* Lock for read_buf */
	struct mutex wlock;			/* Lock for write_buf */
	char _read_buf[BCM_SPI_READ_BUF_SIZE];
	char _write_buf[BCM_SPI_WRITE_BUF_SIZE];
	wait_queue_head_t poll_wait;		/* for poll */

	/* GPIO pins */
	int host_req;
	int mcu_req;
	int mcu_resp;

	/* IRQ and its control */
	atomic_t irq_enabled;
	spinlock_t irq_lock;

	/* Work */
	struct work_struct rxtx_work;
	struct workqueue_struct *serial_wq;
	atomic_t suspending;

	/* SPI tx/rx buf */
	struct bcm_ssi_tx_frame *tx_buf;
	struct bcm_ssi_rx_frame *rx_buf;

	struct wake_lock bcm_wake_lock;

	struct clk *clk;
};

static struct bcm_spi_priv *g_bcm_gps;

//--------------------------------------------------------------
//
//               File Operations
//
//--------------------------------------------------------------
static int bcm_spi_open(struct inode *inode, struct file *filp)
{
	/* Initially, file->private_data points device itself and we can get our priv structs from it. */
	struct bcm_spi_priv *priv = container_of(filp->private_data, struct bcm_spi_priv, misc);
	unsigned long int flags;

	if (priv->busy)
		return -EBUSY;

	priv->busy = true;

	/* Reset circ buffer */
	priv->read_buf.head = priv->read_buf.tail = 0;
	priv->write_buf.head = priv->write_buf.tail = 0;


	/* Enable irq */
	spin_lock_irqsave( &priv->irq_lock, flags);
	if (!atomic_xchg(&priv->irq_enabled, 1))
		enable_irq(priv->spi->irq);

	spin_unlock_irqrestore( &priv->irq_lock, flags);

	enable_irq_wake(priv->spi->irq);

	filp->private_data = priv;
#ifdef DEBUG_1HZ_STAT
	bbd_enable_stat();
#endif
	return 0;
}

static int bcm_spi_release(struct inode *inode, struct file *filp)
{
	struct bcm_spi_priv *priv = filp->private_data;
	unsigned long int flags;

	priv->busy = false;

#ifdef DEBUG_1HZ_STAT
	bbd_disable_stat();
#endif
	/* Disable irq */
	spin_lock_irqsave( &priv->irq_lock, flags);
	if (atomic_xchg(&priv->irq_enabled, 0))
		disable_irq_nosync(priv->spi->irq);

	spin_unlock_irqrestore( &priv->irq_lock, flags);

	disable_irq_wake(priv->spi->irq);

	return 0;
}

static ssize_t bcm_spi_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
	struct bcm_spi_priv *priv = filp->private_data;
	struct circ_buf *circ = &priv->read_buf;
	size_t rd_size=0;

	/* Copy from circ buffer to user
	 * We may require 2 copies from [tail..end] and [end..head]
	 */
	do {
		size_t cnt_to_end = CIRC_CNT_TO_END(circ->head, circ->tail, BCM_SPI_READ_BUF_SIZE);
		size_t copied = min(cnt_to_end, size);

		WARN_ON(copy_to_user(buf + rd_size, (void*) circ->buf + circ->tail, copied));
		size -= copied;
		rd_size += copied;
		circ->tail = (circ->tail + copied) & (BCM_SPI_READ_BUF_SIZE-1);

	} while (size>0 && CIRC_CNT(circ->head, circ->tail, BCM_SPI_READ_BUF_SIZE));

#ifdef DEBUG_1HZ_STAT
	bbd_update_stat(STAT_RX_LHD, rd_size);
#endif

	return rd_size;
}

static ssize_t bcm_spi_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)
{
	struct bcm_spi_priv *priv = filp->private_data;
	struct circ_buf *circ = &priv->write_buf;
	size_t wr_size=0;

	/* Copy from user into circ buffer
	 * We may require 2 copies from [tail..end] and [end..head]
	 */
	do {
		size_t space_to_end = CIRC_SPACE_TO_END(circ->head, circ->tail, BCM_SPI_WRITE_BUF_SIZE);
		size_t copied = min(space_to_end, size);


		WARN_ON(copy_from_user((void*) circ->buf + circ->head, buf + wr_size, copied));
		size -= copied;
		wr_size += copied;
		circ->head = (circ->head + copied) & (BCM_SPI_WRITE_BUF_SIZE-1);
	} while (size>0 && CIRC_SPACE(circ->head, circ->tail, BCM_SPI_WRITE_BUF_SIZE));

	/* kick start rxtx thread */
	/* we don't want to queue work in suspending and shutdown */
	if (!atomic_read(&priv->suspending))
		queue_work(priv->serial_wq, &(priv->rxtx_work) );

#ifdef DEBUG_1HZ_STAT
	bbd_update_stat(STAT_TX_LHD, wr_size);
#endif
	return wr_size;
}

static unsigned int bcm_spi_poll(struct file *filp, poll_table *wait)
{
	struct bcm_spi_priv *priv = filp->private_data;
	struct circ_buf *rd_circ = &priv->read_buf;
	struct circ_buf *wr_circ = &priv->write_buf;
	unsigned int mask = 0;

	poll_wait(filp, &priv->poll_wait, wait);

	if (CIRC_CNT(rd_circ->head, rd_circ->tail, BCM_SPI_READ_BUF_SIZE))
		mask |= POLLIN;

	if (CIRC_SPACE(wr_circ->head, wr_circ->tail, BCM_SPI_WRITE_BUF_SIZE))
		mask |= POLLOUT;

	return mask;
}


static const struct file_operations bcm_spi_fops = {
	.owner          =  THIS_MODULE,
	.open           =  bcm_spi_open,
	.release        =  bcm_spi_release,
	.read           =  bcm_spi_read,
	.write          =  bcm_spi_write,
	.poll           =  bcm_spi_poll,
};



//--------------------------------------------------------------
//
//               Misc. functions
//
//--------------------------------------------------------------

/*
 * bcm4773_hello - wakeup chip by toggling mcu_req while monitoring mcu_resp to check if awake
 *
 */
static bool bcm4773_hello(struct bcm_spi_priv *priv)
{
	int count=0, retries=0;

	gpio_set_value(priv->mcu_req, 1);
	while (!gpio_get_value(priv->mcu_resp)) {
		if (count++ > 100) {
			gpio_set_value(priv->mcu_req, 0);
			printk("[SSPBBD] MCU_REQ_RESP timeout. MCU_RESP(gpio%d) not responding to MCU_REQ(gpio%d)\n", 
					priv->mcu_resp, priv->mcu_req);
			return false;
		}

		mdelay(1);

		/*if awake, done */
		if (gpio_get_value(priv->mcu_resp)) break;

		if (count%20==0 && retries++ < 3) {
			gpio_set_value(priv->mcu_req, 0);
			mdelay(1);
			gpio_set_value(priv->mcu_req, 1);
			mdelay(1);
		}
	}
	return true;
}

/*
 * bcm4773_bye - set mcu_req low to let chip go to sleep
 *
 */
static void bcm4773_bye(struct bcm_spi_priv *priv)
{
	gpio_set_value(priv->mcu_req, 0);
}


static unsigned long init_time = 0;
static unsigned long clock_get_ms(void)
{
	struct timeval t;
	unsigned long now;

	do_gettimeofday(&t);
	now = t.tv_usec / 1000 + t.tv_sec * 1000;
	if ( init_time == 0 )
		init_time = now;

	return now - init_time;
}


static void pk_log(char* dir, unsigned char* data, int len)
{
	char acB[960];
	char *p = acB;
	int  the_trans = len;
	int i,j,n;

	char ic = 'D';
	char xc = dir[0] == 'r' || dir[0] == 'w' ? 'x':'X';

	if (likely(!ssi_dbg))
		return;

	n = len;
	p += snprintf(acB,sizeof(acB),"#%06ld%c %2s,      %5d: ",
			clock_get_ms() % 1000000,ic, dir, n);

	for (i=0, n=32; i<len; i=j, n=32)
	{
		for(j = i; j < (i + n) && j < len && the_trans != 0; j++,the_trans--) {
			p += snprintf(p,sizeof(acB) - (p - acB), "%02X ", data[j]);
		}
		pr_info("%s\n",acB);
		if(j < len) {
			p = acB;
			if ( the_trans == 0 )  { dir[0] = xc; the_trans--; }
			p += snprintf(acB,sizeof(acB),"         %2s              ",dir);
		}
	}

	if (i==0)
		pr_info("%s\n",acB);
}



//--------------------------------------------------------------
//
//               SSI tx/rx functions
//
//--------------------------------------------------------------
static int bcm_spi_sync(struct bcm_spi_priv *priv, void *tx_buf, void *rx_buf, int len, int bits_per_word)
{
	struct spi_message msg;
	struct spi_transfer xfer;
	int ret;

	/* Init */
	spi_message_init(&msg);
	memset(&xfer, 0, sizeof(xfer));
	spi_message_add_tail(&xfer, &msg);

	/* Setup */
	msg.spi = priv->spi;
	xfer.len = len; 
	xfer.tx_buf = tx_buf;
	xfer.rx_buf = rx_buf;

	/* Sync */
	pk_log("w", (unsigned char *)xfer.tx_buf, len);
	ret = spi_sync(msg.spi, &msg);
	pk_log("r", (unsigned char *)xfer.rx_buf, len);

	if (ret)
		pr_err("[SSPBBD} spi_sync error, return=%d\n", ret);

	return ret;
}


static int bcm_ssi_tx(struct bcm_spi_priv *priv, int length)
{
	struct bcm_ssi_tx_frame *tx = priv->tx_buf;
	struct bcm_ssi_rx_frame *rx = priv->rx_buf;
	int bits_per_word = (length >= 255) ? CONFIG_SPI_DMA_BITS_PER_WORD : 8;
	int ret;

	tx->cmd = SSI_WRITE_HD;
	ret = bcm_spi_sync(priv, tx, rx, length+1, bits_per_word); /*1 for tx cmd */

	return ret;
}

static int bcm_ssi_rx( struct bcm_spi_priv *priv, size_t *length)
{
	struct bcm_ssi_tx_frame *tx = priv->tx_buf;
	struct bcm_ssi_rx_frame *rx = priv->rx_buf;

	memset(tx, 0, MAX_SPI_FRAME_LEN);
	tx->cmd = SSI_READ_HD;
	rx->status = 0;

	if (bcm_spi_sync(priv, tx, rx, 2, 8))  /* 2 for rx status + len */
		return -1;

	/* Check Sanity */
	if (rx->status) {
		pr_err("[SSPBBD] spi_sync error, status = 0x%02X\n", rx->status);
		return -1;
	}

	if (rx->len == 0)
	{
		rx->len = MAX_SPI_FRAME_LEN;
		pr_err("[SSPBBD] rx->len is still read to 0. set MAX_SPI_FRAME_LEN\n");
	}

	/* limit max payload to 254 because of exynos3 bug */
	*length = min((unsigned char)(MAX_SPI_FRAME_LEN-2), rx->len);
	if (bcm_spi_sync(priv, tx, rx, *length+2, 8)) /* 2 for rx status + len */
		return -1;

	/* Check Sanity */
	if (rx->status) {
		pr_err("[SSPBBD] spi_sync error, status = 0x%02X\n", rx->status);
		return -1;
	}

	if (rx->len < *length) {
		*length = rx->len; /* workaround */
	}

#ifdef DEBUG_1HZ_STAT
	bbd_update_stat(STAT_RX_SSI, *length);
#endif
	return 0;
}

void bcm_on_packet_recieved(void *_priv, unsigned char *data, unsigned int size)
{
	struct bcm_spi_priv *priv = (struct bcm_spi_priv *)_priv;
	struct circ_buf *rd_circ = &priv->read_buf;
	size_t written=0, avail = size;

	/* Copy into circ buffer */
	mutex_lock(&priv->rlock);
	do {
		size_t space_to_end = CIRC_SPACE_TO_END(rd_circ->head, rd_circ->tail, BCM_SPI_READ_BUF_SIZE);
		size_t copied = min(space_to_end, avail);

		memcpy((void*) rd_circ->buf + rd_circ->head, data + written, copied);
		avail -= copied;
		written += copied;
		rd_circ->head = (rd_circ->head + copied) & (BCM_SPI_READ_BUF_SIZE-1);

	} while (avail>0 && CIRC_SPACE(rd_circ->head, rd_circ->tail, BCM_SPI_READ_BUF_SIZE));
	mutex_unlock(&priv->rlock);
	wake_up(&priv->poll_wait);

	if (avail>0)
		pr_err("[SSPBBD]: input overrun error by %zd bytes!\n", avail);
}

static void bcm_rxtx_work( struct work_struct *work )
{
#ifdef DEBUG_1HZ_STAT
	u64 ts_rx_start = 0;
	u64 ts_rx_end = 0;
#endif
	struct bcm_spi_priv *priv = container_of(work, struct bcm_spi_priv, rxtx_work);
	struct circ_buf *wr_circ = &priv->write_buf;

	if (!bcm4773_hello(priv)) {
		pr_err("[SSPBBD]: %s timeout!!\n", __func__);
		return;
	}

	do {
		/* Read first */
		if (gpio_get_value(priv->host_req)) {
			size_t avail;
#ifdef DEBUG_1HZ_STAT
			struct timespec ts;
			if (stat1hz.ts_irq) {
				ts = ktime_to_timespec(ktime_get_boottime());
				ts_rx_start = ts.tv_sec * 1000000000ULL
					+ ts.tv_nsec;
			}
#endif
			/* Receive SSI frame */
			if (bcm_ssi_rx(priv, &avail))
				break;

#ifdef DEBUG_1HZ_STAT
			bbd_update_stat(STAT_RX_SSI, avail);
			if (ts_rx_start && !gpio_get_value(priv->host_req)) {
				ts = ktime_to_timespec(ktime_get_boottime());
				ts_rx_end = ts.tv_sec * 1000000000ULL
					+ ts.tv_nsec;
			}
#endif
			/* Call BBD */
			bbd_parse_asic_data(priv->rx_buf->data, avail, NULL, priv);
		}

		/* Next, write */
		if (CIRC_CNT(wr_circ->head, wr_circ->tail, BCM_SPI_WRITE_BUF_SIZE)) {
			size_t written=0, avail=0;

			avail = CIRC_CNT(wr_circ->head, wr_circ->tail, BCM_SPI_WRITE_BUF_SIZE);
			/* For big packet, we should align xfer size to DMA word size and burst size.
			 * That is, SSI payload + one byte command should be multiple of (DMA word size * burst size)
			 */
			if (avail > MAX_SPI_FRAME_LEN - 1)
				avail = MAX_SPI_FRAME_LEN - 1;

			/* Copy from wr_circ the data */
			do {
				size_t cnt_to_end = CIRC_CNT_TO_END(wr_circ->head, wr_circ->tail, BCM_SPI_WRITE_BUF_SIZE);
				size_t copied = min(cnt_to_end, avail);

				memcpy(priv->tx_buf->data + written, wr_circ->buf + wr_circ->tail, copied);
				avail -= copied;
				written += copied;
				wr_circ->tail = (wr_circ->tail + copied) & (BCM_SPI_WRITE_BUF_SIZE-1);
			} while (avail>0);

			/* Transmit SSI frame */
			if (bcm_ssi_tx(priv, written))
				break;

			wake_up(&priv->poll_wait);
#ifdef DEBUG_1HZ_STAT
			bbd_update_stat(STAT_TX_SSI, written);
#endif
		}

	} while (gpio_get_value(priv->host_req) || CIRC_CNT(wr_circ->head, wr_circ->tail, BCM_SPI_WRITE_BUF_SIZE));

	bcm4773_bye(priv);

	/* Enable irq */
	{
		unsigned long int flags;
		spin_lock_irqsave( &priv->irq_lock, flags);

		/* we dont' want to enable irq when going to suspending */
		if (!atomic_read(&priv->suspending))
			if (!atomic_xchg(&priv->irq_enabled, 1))
				enable_irq(priv->spi->irq);

		spin_unlock_irqrestore( &priv->irq_lock, flags);
	}

#ifdef DEBUG_1HZ_STAT
	if (stat1hz.ts_irq && ts_rx_start && ts_rx_end) {
		u64 lat = ts_rx_start - stat1hz.ts_irq;
		u64 dur = ts_rx_end - ts_rx_start;
		stat1hz.min_rx_lat = (lat < stat1hz.min_rx_lat) ?
			lat : stat1hz.min_rx_lat;
		stat1hz.max_rx_lat = (lat > stat1hz.max_rx_lat) ?
			lat : stat1hz.max_rx_lat;
		stat1hz.min_rx_dur = (dur < stat1hz.min_rx_dur) ?
			dur : stat1hz.min_rx_dur;
		stat1hz.max_rx_dur = (dur > stat1hz.max_rx_dur) ?
			dur : stat1hz.max_rx_dur;
		stat1hz.ts_irq = 0;
	}
#endif
}


//--------------------------------------------------------------
//
//               IRQ Handler
//
//--------------------------------------------------------------
static irqreturn_t bcm_irq_handler(int irq, void *pdata)
{
	struct bcm_spi_priv *priv = (struct bcm_spi_priv *) pdata;

	if (!gpio_get_value(priv->host_req))
		return IRQ_HANDLED;
#ifdef DEBUG_1HZ_STAT
	{
		struct timespec ts;
		ts = ktime_to_timespec(ktime_get_boottime());
		stat1hz.ts_irq = ts.tv_sec * 1000000000ULL + ts.tv_nsec;
	}
#endif
	/* Disable irq */
	spin_lock(&priv->irq_lock);
	if (atomic_xchg(&priv->irq_enabled, 0))
		disable_irq_nosync(priv->spi->irq);

	spin_unlock(&priv->irq_lock);

	/* we don't want to queue work in suspending and shutdown */
	if (!atomic_read(&priv->suspending))
		queue_work(priv->serial_wq, &priv->rxtx_work);

	wake_lock_timeout(&priv->bcm_wake_lock, HZ/2);
	return IRQ_HANDLED;
}


//--------------------------------------------------------------
//
//               SPI driver operations
//
//--------------------------------------------------------------

static void bcm_spi_shutdown(struct spi_device *spi)
{
	struct bcm_spi_priv *priv = (struct bcm_spi_priv*) spi_get_drvdata(spi);
	unsigned long int flags;

	printk("[SSPBBD]: %s ++ \n", __func__);

	atomic_set(&priv->suspending, 1);

	/* Disable irq */
	spin_lock_irqsave( &priv->irq_lock, flags);
	if (atomic_xchg(&priv->irq_enabled, 0))
		disable_irq_nosync(spi->irq);

	spin_unlock_irqrestore( &priv->irq_lock, flags);

	printk("[SSPBBD]: %s ** \n", __func__);

	flush_workqueue(priv->serial_wq );
	destroy_workqueue( priv->serial_wq );

	printk("[SSPBBD]: %s -- \n", __func__);
}

static int bcm_spi_probe(struct spi_device *spi)
{
	int host_req, mcu_req, mcu_resp;
	struct bcm_spi_priv *priv;
	int ret;

	/* Check GPIO# */
#ifndef CONFIG_OF
	pr_err("[SSPBBD]: Check platform_data for bcm device\n");
#else
	if (!spi->dev.of_node) {
		pr_err("[SSPBBD]: Failed to find of_node\n");
		goto err_exit;
	}
#endif

	host_req = of_get_named_gpio(spi->dev.of_node, "ssp-irq", 0);
	mcu_req  = of_get_named_gpio(spi->dev.of_node, "ssp-mcu-req", 0);
	mcu_resp = of_get_named_gpio(spi->dev.of_node, "ssp-mcu-resp", 0);

	pr_info("[SSPBBD] ssp-host-req=%d, ssp-mcu_req=%d, ssp-mcu-resp=%d\n", host_req, mcu_req, mcu_resp);
	if (host_req<0 || mcu_req<0 || mcu_resp<0) {
		pr_err("[SSPBBD]: GPIO value not correct\n");
		goto err_exit;
	}

	/* Check IRQ# */
	spi->irq = gpio_to_irq(host_req);
	if (spi->irq < 0) {
		pr_err("[SSPBBD]: irq=%d for host_req=%d not correct\n", spi->irq, host_req);
		goto err_exit;
	}

	/* Config GPIO */
	ret = gpio_request(mcu_req, "MCU REQ");
	if (ret){
		pr_err("[SSPBBD]: failed to request MCU REQ, ret:%d", ret);
		goto err_exit;
	}
	ret = gpio_direction_output(mcu_req, 0);
	if (ret) {
		pr_err("[SSPBBD]: failed set MCU REQ as input mode, ret:%d", ret);
		goto err_exit;
	}
	ret = gpio_request(mcu_resp, "MCU RESP");
	if (ret){
		pr_err("[SSPBBD]: failed to request MCU RESP, ret:%d", ret);
		goto err_exit;
	}
	ret = gpio_direction_input(mcu_resp);
	if (ret) {
		pr_err("[SSPBBD]: failed set MCU RESP as input mode, ret:%d", ret);
		goto err_exit;
	}

	/* Alloc everything */
	priv = (struct bcm_spi_priv*) kmalloc(sizeof(*priv), GFP_KERNEL);
	if (!priv) {
		pr_err("[SSPBBD]: Failed to allocate memory for the BCM SPI driver\n");
		goto err_exit;
	}

	memset(priv, 0, sizeof(*priv));

	priv->spi = spi;

	priv->tx_buf = kmalloc(sizeof(struct bcm_ssi_tx_frame), GFP_KERNEL);
	priv->rx_buf = kmalloc(sizeof(struct bcm_ssi_rx_frame), GFP_KERNEL);
	if (!priv->tx_buf || !priv->rx_buf) {
		pr_err("[SSPBBD]: Failed to allocate xfer buffer. tx_buf=%p, rx_buf=%p\n",
				priv->tx_buf, priv->rx_buf);
		goto free_mem;
	}

	priv->clk = devm_clk_get(&spi->dev, "xtal");
	if (IS_ERR(priv->clk)) {
		pr_err("[SSPBBD] failed to get clock\n");
		goto free_mem;
	}

	ret = clk_prepare_enable(priv->clk);
	if (ret) {
		goto free_mem;
		pr_err("[SSPBBD] failed to enable clock\n");
	}

	priv->serial_wq = alloc_workqueue("bcm4773_wq", WQ_HIGHPRI|WQ_UNBOUND|WQ_MEM_RECLAIM, 1);
	if (!priv->serial_wq) {
		pr_err("[SSPBBD]: Failed to allocate workqueue\n");
		goto free_mem;
	}

	/* Request IRQ */
	ret = request_irq(spi->irq, bcm_irq_handler, IRQF_TRIGGER_HIGH, "ttyBCM", priv);
	if (ret) {
		pr_err("[SSPBBD]: Failed to register BCM4774 SPI TTY IRQ %d.\n",spi->irq);
		goto free_wq;
	}

	disable_irq(spi->irq);

	pr_notice("[SSPBBD]: Probe OK. ssp-host-req=%d, irq=%d, priv=0x%p\n", host_req, spi->irq, priv);

	/* Register misc device */
	priv->misc.minor = MISC_DYNAMIC_MINOR;
	priv->misc.name = "ttyBCM";
	priv->misc.fops = &bcm_spi_fops;

	ret = misc_register(&priv->misc);
	if (ret) {
		pr_err("[SSPBBD]: Failed to register bcm_gps_spi's misc dev. err=%d\n", ret);
		goto free_irq;
	}

	/* Set driver data */
	spi_set_drvdata(spi, priv);

	/* Init - miscdev stuff */
	init_waitqueue_head(&priv->poll_wait);
	priv->read_buf.buf = priv->_read_buf;
	priv->write_buf.buf = priv->_write_buf;
	mutex_init(&priv->rlock);
	mutex_init(&priv->wlock);
	priv->busy = false;

	/* Init - work */
	INIT_WORK(&priv->rxtx_work, bcm_rxtx_work);

	/* Init - irq stuff */
	spin_lock_init(&priv->irq_lock);
	atomic_set(&priv->irq_enabled, 0);
	atomic_set(&priv->suspending, 0);

	/* Init - gpios */
	priv->host_req = host_req;
	priv->mcu_req  = mcu_req;
	priv->mcu_resp = mcu_resp;

	/* Init - etc */
	wake_lock_init(&priv->bcm_wake_lock, WAKE_LOCK_SUSPEND, "bcm_spi_wake_lock");

	g_bcm_gps = priv;
	/* Init BBD & SSP */
	bbd_init(&spi->dev);

	return 0;

free_irq:
	if (spi->irq)
		free_irq( spi->irq, priv );
free_wq:
	if (priv->serial_wq)
		destroy_workqueue(priv->serial_wq);
free_mem:
	if (priv->tx_buf)
		kfree(priv->tx_buf);
	if (priv->rx_buf)
		kfree(priv->rx_buf);
	if (priv)
		kfree(priv);
err_exit:
	return -ENODEV;
}


static int bcm_spi_remove(struct spi_device *spi)
{
	struct bcm_spi_priv *priv = (struct bcm_spi_priv*) spi_get_drvdata(spi);
	unsigned long int flags;

	pr_notice("[SSPBBD]:  %s : called\n", __func__);

	atomic_set(&priv->suspending, 1);

	/* Disable irq */
	spin_lock_irqsave(&priv->irq_lock, flags);
	if (atomic_xchg(&priv->irq_enabled, 0))
		disable_irq_nosync(spi->irq);

	spin_unlock_irqrestore( &priv->irq_lock, flags);

	/* Flush work */
	flush_workqueue(priv->serial_wq);
	destroy_workqueue(priv->serial_wq);

	/* Free everything */
	free_irq( spi->irq, priv );
	kfree(priv->tx_buf);
	kfree(priv->rx_buf);
	kfree( priv );

	g_bcm_gps = NULL;

	return 0;
}

void bcm4773_debug_info(void)
{
	int pin_ttyBCM, pin_MCU_REQ, pin_MCU_RESP;
	int irq_enabled, irq_count;

	pin_ttyBCM = gpio_get_value(g_bcm_gps->host_req);
	pin_MCU_REQ = gpio_get_value(g_bcm_gps->mcu_req);
	pin_MCU_RESP = gpio_get_value(g_bcm_gps->mcu_resp);

	irq_enabled = atomic_read(&g_bcm_gps->irq_enabled);
	irq_count = kstat_irqs_cpu(g_bcm_gps->spi->irq, 0);

	printk("[SSPBBD]: %s pin_ttyBCM:%d, pin_MCU_REQ:%d, pin_MCU_RESP:%d\n",
			__func__, pin_ttyBCM, pin_MCU_REQ, pin_MCU_RESP);
	printk("[SSPBBD]: %s irq_enabled:%d, irq_count:%d\n",
			__func__, irq_enabled, irq_count);
}


static const struct spi_device_id bcm_spi_id[] = {
	{"ssp", 0},
	{}
};
MODULE_DEVICE_TABLE(spi, bcm_spi_id);

#ifdef CONFIG_OF
static struct of_device_id match_table[] = {
	{ .compatible = "ssp,BCM4773",},
	{ .compatible = "ssp,BCM4774",},
	{},
};
#endif

#ifdef CONFIG_PM_SLEEP
static int bcm_spi_suspend(struct device *dev)
{
	struct spi_device *spi = to_spi_device(dev);
	struct bcm_spi_priv *priv = (struct bcm_spi_priv*) spi_get_drvdata(spi);
	unsigned long int flags;

	printk("[SSPBBD]: %s ++ \n", __func__);

	atomic_set(&priv->suspending, 1);

	/* Disable irq */
	spin_lock_irqsave(&priv->irq_lock, flags);
	if (atomic_xchg(&priv->irq_enabled, 0))
		disable_irq_nosync(spi->irq);

	spin_unlock_irqrestore(&priv->irq_lock, flags);

	flush_workqueue(priv->serial_wq);

	return 0;
}

static int bcm_spi_resume(struct device *dev)
{
	struct spi_device *spi = to_spi_device(dev);
	struct bcm_spi_priv *priv = (struct bcm_spi_priv*) spi_get_drvdata(spi);
	unsigned long int flags;

	pr_info("[SSPBBD]: %s ++ \n", __func__);
	atomic_set(&priv->suspending, 0);

	/* Enable irq */
	spin_lock_irqsave(&priv->irq_lock, flags);
	if (!atomic_xchg(&priv->irq_enabled, 1))
		enable_irq(spi->irq);

	spin_unlock_irqrestore( &priv->irq_lock, flags);

	pr_info("[SSPBBD]: %s -- \n", __func__);
	return 0;
}

static const struct dev_pm_ops bcm_spi_pm = {
	SET_SYSTEM_SLEEP_PM_OPS(bcm_spi_suspend, bcm_spi_resume)
};
#endif /* CONFIG_PM_SLEEP */

static struct spi_driver bcm_spi_driver =
{
	.id_table = bcm_spi_id,
	.probe = bcm_spi_probe,
	.remove = bcm_spi_remove,
	.shutdown = bcm_spi_shutdown,
	.driver = {
		.name = "ssp",
		.owner = THIS_MODULE,
		.pm = &bcm_spi_pm,
#ifdef CONFIG_OF
		.of_match_table = match_table
#endif
	},
};


module_spi_driver(bcm_spi_driver);

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("BCM SPI/SSI Driver");