summaryrefslogtreecommitdiff
path: root/drivers/sensors/brcm/bbdpl2/bbd.c
blob: d21244c45455e44870afc24518caa015dec4d42a (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
/*
 * Copyright 2014 Broadcom Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2, as
 * published by the Free Software Foundation (the "GPL").
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * A copy of the GPL is available at
 * http://www.broadcom.com/licenses/GPLv2.php, or by writing to the Free
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * The BBD (Broadcom Bridge Driver)
 */

#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/cdev.h>
#include <linux/sched.h>
#include <linux/poll.h>
#include <linux/wait.h>
#include <linux/delay.h>
#include <linux/circ_buf.h>
#include <linux/fs.h>
#include <linux/wakelock.h>
#include <linux/suspend.h>
#include <linux/notifier.h>
#include <linux/of.h>
#include "bbd.h"

/* Needs because SSP is tightly coupled with SPI */
#ifdef CONFIG_SENSORS_SSP
#include <linux/spi/spi.h>

extern struct spi_driver *pssp_driver;
extern bool ssp_dbg;
extern bool ssp_pkt_dbg;

static struct spi_device dummy_spi = {
	.dev = {
		.init_name = "dummy",
	},
};
#endif

#ifdef CONFIG_BCM_GPS_SPI_DRIVER
extern bool ssi_dbg;
#endif

void bbd_log_hex(const char*, const unsigned char*, unsigned long);

//--------------------------------------------------------------
//
//               BBD device struct
//
//--------------------------------------------------------------
#define BBD_BUFF_SIZE (PAGE_SIZE*2)
struct bbd_cdev_priv {
	const char* name;
	struct cdev dev;			/* char device */
	bool busy;
	struct circ_buf read_buf;		/* LHD reads from BBD */
	struct mutex lock;			/* Lock for read_buf */
	char _read_buf[BBD_BUFF_SIZE];		/* LHD reads from BBD */
	char write_buf[BBD_BUFF_SIZE];		/* LHD writes into BBD */
	wait_queue_head_t poll_wait;		/* for poll */
};

struct bbd_device {
	struct kobject *kobj;			/* for sysfs register */
	struct class *class;			/* for device_create */

	struct bbd_cdev_priv priv[BBD_DEVICE_INDEX];/* individual structures */
	struct wake_lock bbd_wake_lock;
	bool db;				/* debug flag */

	void *ssp_priv;				/* private data pointer */
	bbd_callbacks *ssp_cb;			/* callbacks for SSP */

};

/*
 * Character device names of BBD
 */
static const char *bbd_dev_name[BBD_DEVICE_INDEX] = {
	"bbd_shmd",
	"bbd_sensor",
	"bbd_control",
	"bbd_patch",
	/* "bbd_ssi_spi_debug" */
};

//--------------------------------------------------------------
//
//               Globals
//
//--------------------------------------------------------------
/*
 * The global BBD device which has all necessary information.
 * It's not beautiful but useful when we debug by Trace32.
 */
static struct bbd_device bbd;
/*
 * Embedded patch file provided as /dev/bbd_patch
 */
static unsigned char bbd_patch[] =
{
#if defined(CONFIG_SENSORHUB_TM2)
#include "../platform/bbd_tm2_patch_file.h"
#elif defined(CONFIG_SENSORHUB_S333)
#include "../platform/bbd_s333_patch_file.h"
#endif
};

/* Function to push read data into any bbd device's read buf */
ssize_t bbd_on_read(unsigned int minor, const unsigned char *buf, size_t size);

#ifdef DEBUG_1HZ_STAT

static const char *bbd_stat_name[STAT_MAX] = {
		"tx@lhd",
		"tx@ssp",
		"tx@rpc",
		"tx@tl",
		"tx@ssi",
		"rx@ssi",
		"rx@tl",
		"rx@rpc",
		"rx@ssp",
		"rx@lhd"
};

struct bbd_stat stat1hz;

//--------------------------------------------------------------
//
//               bbd 1hz statistics Functions
//
//--------------------------------------------------------------
static void bbd_init_stat(void)
{
	memset(&stat1hz, 0, sizeof(stat1hz));

	stat1hz.min_rx_lat = (u64)-1;
	stat1hz.min_rx_dur = (u64)-1;
	stat1hz.workq = create_singlethread_workqueue("BBD_1HZ_TICK");
}

static void bbd_exit_stat(void)
{
	bbd_disable_stat();
	if (stat1hz.workq) {
		flush_workqueue(stat1hz.workq);
		destroy_workqueue(stat1hz.workq);
		stat1hz.workq = 0;
	}
}

static void bbd_report_stat(struct work_struct *work)
{
	char buf[512];
	char *p = buf;
	int i;

	p += sprintf(p, "BBD:");
	for (i = 0; i < STAT_MAX; i++)
		p += sprintf(p, " %s=%llu", bbd_stat_name[i], stat1hz.stat[i]);
	p += sprintf(p, " rxlat_min=%llu rxlat_max=%llu",
		stat1hz.min_rx_lat, stat1hz.max_rx_lat);
	p += sprintf(p, " rxdur_min=%llu rxdur_max=%llu",
		stat1hz.min_rx_dur, stat1hz.max_rx_dur);

	/* report only in case we had SSI traffic */
	if (stat1hz.stat[STAT_TX_SSI] || stat1hz.stat[STAT_RX_SSI])
		bbd_on_read(BBD_MINOR_CONTROL, buf, strlen(buf)+1);

	for (i = 0; i < STAT_MAX; i++)
		stat1hz.stat[i] = 0;

	stat1hz.min_rx_lat = (u64)-1;
	stat1hz.min_rx_dur = (u64)-1;
	stat1hz.max_rx_lat = 0;
	stat1hz.max_rx_dur = 0;
}

static void bbd_stat_timer_func(unsigned long p)
{
	if (stat1hz.workq)
		queue_work(stat1hz.workq, &stat1hz.work);
	mod_timer(&stat1hz.timer, jiffies + HZ);
}

void bbd_update_stat(int idx, unsigned int count)
{
	stat1hz.stat[idx] += count;
}

void bbd_enable_stat(void)
{
	if (stat1hz.enabled) {
		pr_info("%s() 1HZ stat already enable. skipping.\n", __func__);
		return;
	}

	INIT_WORK(&stat1hz.work, bbd_report_stat);
	setup_timer(&stat1hz.timer, bbd_stat_timer_func, 0);
	mod_timer(&stat1hz.timer, jiffies + HZ);
	stat1hz.enabled = true;
}

void bbd_disable_stat(void)
{
	if (!stat1hz.enabled) {
		pr_info("%s() 1HZ stat already disabled. skipping.\n", __func__);
		return;
	}
	del_timer_sync(&stat1hz.timer);
	cancel_work_sync(&stat1hz.work);
	stat1hz.enabled = false;
}
#endif /* DEBUG_1HZ_STAT */
//--------------------------------------------------------------
//
//               SHMD Interface Functions
//
//--------------------------------------------------------------

/**
 * bbd_register - Interface function called from SHMD to register itself to BBD
 *
 * @priv: SHMD's private data provided back to SHMD as callback argument
 * @cb: SHMD's functions to be called
 */
void bbd_register(void *priv, bbd_callbacks *cb)
{
	bbd.ssp_priv = priv;
	bbd.ssp_cb = cb;
}
EXPORT_SYMBOL(bbd_register);

/**
 * bbd_send_packet - Interface function called from SHMD to send sensor packet.
 *
 *     The sensor packet is pushed into /dev/bbd_sensor to be read by gpsd/lhd.
 *     gpsd/lhd wrap the packet into RPC and sends to chip directly.
 *
 * @buf: buffer containing sensor packet
 * @size: size of sensor packet
 * @return: pushed data length = success
 */
struct sensor_pkt {
	unsigned short size;
	unsigned char buf[1022];	/*We assume max SSP packet less than 1KB */
}__attribute__((__packed__)) ss_pkt;

ssize_t bbd_send_packet(unsigned char *buf, size_t size)
{
	memset(&ss_pkt, 0, sizeof(ss_pkt));
	ss_pkt.size = (unsigned short)size;
	memcpy(ss_pkt.buf, buf, size);

#ifdef DEBUG_1HZ_STAT
	bbd_update_stat(STAT_TX_SSP, size);
#endif
	return bbd_on_read(BBD_MINOR_SENSOR, (unsigned char*)&ss_pkt, size+2); /* +2 for pkt.size */
}
EXPORT_SYMBOL(bbd_send_packet);


/**
 * bbd_pull_packet - Interface function called from SHMD to read sensor packet.
 *
 *     Read packet consists of sensor packet from gpsd/lhd and from BBD.
 *
 * @buf: buffer to receive packet
 * @size:
 * @timeout_ms: if specified, this function waits for sensor packet during given time
 *
 * @return: popped data length = success
 */
ssize_t bbd_pull_packet(unsigned char *buf, size_t size, unsigned int timeout_ms)
{
	struct circ_buf *circ = &bbd.priv[BBD_MINOR_SHMD].read_buf;
	size_t rd_size = 0;

	WARN_ON(!buf);
	WARN_ON(!size);

	if (timeout_ms) {
		int ret = wait_event_interruptible_timeout(
					bbd.priv[BBD_MINOR_SHMD].poll_wait,
					circ->head != circ->tail,
					msecs_to_jiffies(timeout_ms));
		if (!ret)
			return -ETIMEDOUT;
	}

	mutex_lock(&bbd.priv[BBD_MINOR_SHMD].lock);

	/* Copy from circ buffer to linear buffer
	 * Because SHMD's buffer is linear, we may require 2 copies
	 * from [tail..end] and [start..head]
	 */
	do {
		size_t cnt_to_end = CIRC_CNT_TO_END(circ->head, circ->tail, BBD_BUFF_SIZE);
		size_t copied = min(cnt_to_end, size);

		memcpy(buf + rd_size, (void*) circ->buf + circ->tail, copied);
		size -= copied;
		rd_size += copied;
		circ->tail = (circ->tail + copied) & (BBD_BUFF_SIZE -1);

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

	mutex_unlock(&bbd.priv[BBD_MINOR_SHMD].lock);

	return rd_size;
}
EXPORT_SYMBOL(bbd_pull_packet);

/**
 * bbd_mcu_reset - Interface function called from SHMD to reset chip
 *
 * BBD pushes reset request into /dev/bbd_control and actual reset is
 * done by gpsd/lhd when it reads the request
 *
 * @return: 0 = success, -1 = failure
 */
int bbd_mcu_reset(void)
{
	pr_info("reset request from sensor hub\n");
	return bbd_on_read(BBD_MINOR_CONTROL, BBD_CTRL_RESET_REQ,
		strlen(BBD_CTRL_RESET_REQ)+1);
}
EXPORT_SYMBOL(bbd_mcu_reset);



//--------------------------------------------------------------
//
//               BBD device struct
//
//--------------------------------------------------------------

/**
 * bbd_control - Handles command string from lhd
 *
 *
 */
ssize_t bbd_control(const char *buf, ssize_t len)
{
	if (strstr(buf, ESW_CTRL_READY)) {

		if (bbd.ssp_cb && bbd.ssp_cb->on_mcu_ready)
			bbd.ssp_cb->on_mcu_ready(bbd.ssp_priv, true);

	} else if (strstr(buf, ESW_CTRL_NOTREADY)) {
		struct circ_buf *circ = &bbd.priv[BBD_MINOR_SENSOR].read_buf;
		circ->head = circ->tail = 0;
		if (bbd.ssp_cb && bbd.ssp_cb->on_mcu_ready)
			bbd.ssp_cb->on_mcu_ready(bbd.ssp_priv, false);
	} else if (strstr(buf, ESW_CTRL_CRASHED)) {
		struct circ_buf *circ = &bbd.priv[BBD_MINOR_SENSOR].read_buf;
		circ->head = circ->tail = 0;

		if (bbd.ssp_cb && bbd.ssp_cb->on_mcu_ready)
			bbd.ssp_cb->on_mcu_ready(bbd.ssp_priv, false);

		if (bbd.ssp_cb && bbd.ssp_cb->on_control)
			bbd.ssp_cb->on_control(bbd.ssp_priv, buf);
	} else if (strstr(buf, BBD_CTRL_DEBUG_OFF)) {
		bbd.db = false;
#ifdef CONFIG_SENSORS_SSP
	} else if (strstr(buf, SSP_DEBUG_ON)) {
		ssp_dbg = true;
		ssp_pkt_dbg = true;
	} else if (strstr(buf, SSP_DEBUG_OFF)) {
		ssp_dbg = false;
		ssp_pkt_dbg = false;
#endif
#ifdef CONFIG_BCM_GPS_SPI_DRIVER
	} else if (strstr(buf, SSI_DEBUG_ON)) {
		ssi_dbg = true;
	} else if (strstr(buf, SSI_DEBUG_OFF)) {
		ssi_dbg = false;
#endif
	} else if (bbd.ssp_cb && bbd.ssp_cb->on_control) {
		/* Tell SHMD about the unknown control string */
		bbd.ssp_cb->on_control(bbd.ssp_priv, buf);
	}

	return len;
}



//--------------------------------------------------------------
//
//               BBD Common File Functions
//
//--------------------------------------------------------------

/**
 * bbd_common_open - Common open function for BBD devices
 *
 */
int bbd_common_open(struct inode *inode, struct file *filp)
{
	unsigned int minor = iminor(inode);
	struct circ_buf *circ = &bbd.priv[minor].read_buf;

	if (minor >= BBD_DEVICE_INDEX)
		return -ENODEV;

	pr_debug("%s", bbd.priv[minor].name);

	if (bbd.priv[minor].busy && minor!=BBD_MINOR_CONTROL)
		return -EBUSY;

	bbd.priv[minor].busy = true;

	/* Reset circ buffer */
	circ->head = circ->tail = 0;

	filp->private_data = &bbd;

	return 0;
}

/**
 * bbd_common_release - Common release function for BBD devices
 */
static int bbd_common_release(struct inode *inode, struct file *filp)
{
	unsigned int minor = iminor(inode);


	BUG_ON(minor >= BBD_DEVICE_INDEX);
	pr_debug("%s", bbd.priv[minor].name);

	bbd.priv[minor].busy = false;

	return 0;
}

/**
 * bbd_common_read - Common read function for BBD devices
 *
 * lhd reads from BBD devices via this function
 *
 */
static ssize_t bbd_common_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
	unsigned int minor = iminor(filp->f_path.dentry->d_inode);
	struct circ_buf *circ = &bbd.priv[minor].read_buf;
	size_t rd_size=0;

	BUG_ON(minor >= BBD_DEVICE_INDEX);

	mutex_lock(&bbd.priv[minor].lock);

	/* Copy from circ buffer to lhd
	 * Because lhd's buffer is linear, 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, BBD_BUFF_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) & (BBD_BUFF_SIZE -1);

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

	mutex_unlock(&bbd.priv[minor].lock);

	bbd_log_hex(bbd_dev_name[minor], buf, rd_size);

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

/**
 * bbd_common_write - Common write function for BBD devices *
 * lhd writes to BBD devices via this function
 */
static ssize_t bbd_common_write(struct file *filp, const char __user *buf,
		size_t size, loff_t *ppos)
{
	unsigned int minor = iminor(filp->f_path.dentry->d_inode);

	BUG_ON(size >= BBD_BUFF_SIZE);

	WARN_ON(copy_from_user(bbd.priv[minor].write_buf, buf, size));

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

/**
 * bbd_common_poll - Common poll function for BBD devices
 *
 */
static unsigned int bbd_common_poll(struct file *filp, poll_table *wait)
{
	unsigned int minor = iminor(filp->f_path.dentry->d_inode);
	struct circ_buf *circ = &bbd.priv[minor].read_buf;
	unsigned int mask = 0;

	BUG_ON(minor >= BBD_DEVICE_INDEX);

	poll_wait(filp, &bbd.priv[minor].poll_wait, wait);

	if (CIRC_CNT(circ->head, circ->tail, BBD_BUFF_SIZE))
		mask |= POLLIN;

	return mask;
}

//--------------------------------------------------------------
//
//               BBD Device Specific File Functions
//
//--------------------------------------------------------------

/**
 * bbd_sensor_write - BBD's RPC calls this function to send sensor packet
 *
 * @buf: contains sensor packet coming from gpsd/lhd
 *
 */
ssize_t bbd_sensor_write(const char *buf, size_t size)
{
	/* Copies into /dev/bbd_shmd. If SHMD was sleeping in poll_wait,
	 * bbd_on_read() wakes it up also
	 */
	bbd_on_read(BBD_MINOR_SHMD, buf, size);

#ifdef DEBUG_1HZ_STAT
	bbd_update_stat(STAT_RX_SSP, size);
#endif
	/* OK. Now call pre-registered SHMD callbacks */
	if (bbd.ssp_cb->on_packet)
		bbd.ssp_cb->on_packet(bbd.ssp_priv, bbd.priv[BBD_MINOR_SHMD].write_buf, size);
	else if (bbd.ssp_cb->on_packet_alarm)
		bbd.ssp_cb->on_packet_alarm(bbd.ssp_priv);
	else
		pr_err("%s no SSP on_packet callback registered. "
				"Dropped %u bytes\n", __func__, (unsigned int)size);

	return size;
}

/**
 * bbd_control_write - Write function for BBD control (/dev/bbd_control)
 *
 *  Receives control string from lhd and handles it
 *
 */
ssize_t bbd_control_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)
{
	unsigned int minor = iminor(filp->f_path.dentry->d_inode);

	/* get command string first */
	ssize_t len = bbd_common_write(filp, buf, size, ppos);
	if (len <= 0)
		return len;

	/* Process received command string */
	return bbd_control(bbd.priv[minor].write_buf, len);
}

ssize_t bbd_patch_read( struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
        ssize_t rd_size = size;
        size_t  offset = filp->f_pos;

	if (offset >= sizeof(bbd_patch)) {       /* signal EOF */
		*ppos = 0;
		return 0;
	}
	if (offset+size > sizeof(bbd_patch))
		rd_size = sizeof(bbd_patch) - offset;
	if (copy_to_user(buf, bbd_patch + offset, rd_size))
		rd_size = -EFAULT;
	else
		*ppos = filp->f_pos + rd_size;

        return rd_size;
}


//--------------------------------------------------------------
//
//               Sysfs
//
//--------------------------------------------------------------
static ssize_t store_sysfs_bbd_control(struct device *dev, struct device_attribute *attr, const char *buf, size_t len)
{
	bbd_control(buf, strlen(buf)+1);
	return len;
}

ssize_t bbd_request_mcu(bool on);
static ssize_t show_sysfs_bbd_pl(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	return 0;
}

static DEVICE_ATTR(bbd,     0220, NULL,                store_sysfs_bbd_control);
static DEVICE_ATTR(pl,      0440, show_sysfs_bbd_pl,       NULL);

static struct attribute *bbd_attributes[] = {
	&dev_attr_bbd.attr,
	&dev_attr_pl.attr,
	NULL
};

static const struct attribute_group bbd_group = {
	.attrs = bbd_attributes,
};


//--------------------------------------------------------------
//
//               Misc Functions
//
//--------------------------------------------------------------
void bbd_log_hex(const char*          pIntroduction,
		const unsigned char* pData,
		unsigned long        ulDataLen)
{
	const unsigned char* pDataEnd = pData + ulDataLen;

	if (likely(!bbd.db))
		return;
	if (!pIntroduction) pIntroduction = "...unknown...";

	while (pData < pDataEnd)
	{
		char buf[128];
		size_t bufsize = sizeof(buf) - 3;
		size_t lineLen = pDataEnd - pData;
		size_t perLineCount = lineLen;
		if (lineLen > 32) {
			lineLen = 32;
			perLineCount = lineLen;
		}

		snprintf(buf, bufsize, "%s [%u] { ", pIntroduction,
				(unsigned int)lineLen);

		for (; perLineCount > 0; ++pData, --perLineCount)
		{
			size_t len = strlen(buf);
			snprintf(buf+len, bufsize - len, "%02X ", *pData);
		}
		printk(KERN_INFO"%s}\n", buf);
	}
}

/**
 *
 * bbd_on_read - Push data into read buffer of specified char device.
 *   if minor is bbd_sensor
 *
 * @buf: linear buffer
 */
ssize_t bbd_on_read(unsigned int minor, const unsigned char *buf, size_t size)
{
	struct circ_buf *circ = &bbd.priv[minor].read_buf;
	size_t wr_size = 0;

	bbd_log_hex(bbd_dev_name[minor], buf, size);

	mutex_lock(&bbd.priv[minor].lock);

	/* If there's not enough speace, drop it but try waking up reader */
	if (CIRC_SPACE(circ->head, circ->tail, BBD_BUFF_SIZE)<size) {
		pr_err("%s read buffer full. Dropping %u bytes\n",
				bbd_dev_name[minor], (unsigned int)size);
		goto skip;
	}

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

		memcpy((void*) circ->buf + circ->head, buf + wr_size, copied);
		size -= copied;
		wr_size += copied;
		circ->head = (circ->head + copied) & (BBD_BUFF_SIZE -1);

	} while (size>0 && CIRC_SPACE(circ->head, circ->tail, BBD_BUFF_SIZE));
skip:
	mutex_unlock(&bbd.priv[minor].lock);

	/* Wake up reader */
	wake_up(&bbd.priv[minor].poll_wait);


	return wr_size;
}

ssize_t bbd_request_mcu(bool on)
{
	pr_info("%s(%s) called\n", __func__, (on)?"On":"Off");
	if (on)
		return bbd_on_read(BBD_MINOR_CONTROL, GPSD_SENSOR_ON, strlen(GPSD_SENSOR_ON)+1);
	else {
		bbd.ssp_cb->on_mcu_ready(bbd.ssp_priv, false);
		return bbd_on_read(BBD_MINOR_CONTROL, GPSD_SENSOR_OFF, strlen(GPSD_SENSOR_OFF)+1);
	}
}
EXPORT_SYMBOL(bbd_request_mcu);

//--------------------------------------------------------------
//
//               PM operation
//
//--------------------------------------------------------------
static int bbd_suspend(pm_message_t state)
{
#ifdef DEBUG_1HZ_STAT
	bbd_disable_stat();
#endif
#ifdef CONFIG_SENSORS_SSP
	/* Call SSP suspend */
	if (pssp_driver->driver.pm && pssp_driver->driver.pm->suspend)
		pssp_driver->driver.pm->suspend(&dummy_spi.dev);
#endif
	msleep(20);

     return 0;
}

static int bbd_resume(void)
{
#ifdef CONFIG_SENSORS_SSP
	/* Call SSP resume */
	if (pssp_driver->driver.pm && pssp_driver->driver.pm->suspend)
		pssp_driver->driver.pm->resume(&dummy_spi.dev);
#endif
#ifdef DEBUG_1HZ_STAT
	bbd_enable_stat();
#endif
	wake_lock_timeout(&bbd.bbd_wake_lock, HZ/2);

	return 0;
}

static int bbd_notifier(struct notifier_block *nb, unsigned long event, void * data)
{
	pm_message_t state = {0};
        switch (event) {
		case PM_SUSPEND_PREPARE:
			pr_info("%s going to sleep\n", __func__);
			state.event = event;
			bbd_suspend(state);
			break;
		case PM_POST_SUSPEND:
			pr_info("%s waking up\n", __func__);
			bbd_resume();
			break;
	}
	return NOTIFY_OK;
}

static struct notifier_block bbd_notifier_block = {
        .notifier_call = bbd_notifier,
};

//--------------------------------------------------------------
//
//               BBD Device Init and Exit
//
//--------------------------------------------------------------


static const struct file_operations bbd_fops[BBD_DEVICE_INDEX] = {
        /* bbd shmd file operations */
	{
                .owner          =  THIS_MODULE,
	},
        /* bbd sensor file operations */
        {
                .owner          =  THIS_MODULE,
                .open           =  bbd_common_open,
                .release        =  bbd_common_release,
                .read           =  bbd_common_read,
                .write          =  NULL,
                .poll           =  bbd_common_poll,
        },
	/* bbd control file operations */
	{
		.owner		=  THIS_MODULE,
		.open		=  bbd_common_open,
		.release	=  bbd_common_release,
		.read		=  bbd_common_read,
		.write		=  bbd_control_write,
		.poll		=  bbd_common_poll,
	},
	/* bbd patch file operations */
	{
		.owner		=  THIS_MODULE,
		.open		=  bbd_common_open,
		.release	=  bbd_common_release,
		.read		=  bbd_patch_read,
		.write		=  NULL, /* /dev/bbd_patch is read-only */
		.poll		=  NULL,
	},
};


int bbd_init(struct device* dev)
{
	int minor, ret = -ENOMEM;
	struct timespec ts1;
	unsigned long start, elapsed;

	ts1 = ktime_to_timespec(ktime_get_boottime());
	start = ts1.tv_sec * 1000000000ULL + ts1.tv_nsec;


	pr_err("BBD start: %s, %d\n", __func__, __LINE__);

	/* Initialize BBD device */
	memset(&bbd, 0, sizeof(bbd));
	wake_lock_init(&bbd.bbd_wake_lock, WAKE_LOCK_SUSPEND, "bbd_wake_lock");

	/* Create class which is required for device_create() */
	bbd.class = class_create(THIS_MODULE, "bbd");
	if (IS_ERR(bbd.class)) {
		WARN("BBD:%s() failed to create class \"bbd\"", __func__);
		goto exit;
	}

	/* Create BBD char devices */
	for (minor=0; minor<BBD_DEVICE_INDEX; minor++) {
		dev_t devno = MKDEV(BBD_DEVICE_MAJOR, minor);
		struct cdev *cdev = &bbd.priv[minor].dev;
		const char *name = bbd_dev_name[minor];
		struct device *dev;

		/* Init buf, waitqueue, mutex, etc. */
		bbd.priv[minor].name = bbd_dev_name[minor];
		bbd.priv[minor].read_buf.buf = bbd.priv[minor]._read_buf;

		init_waitqueue_head(&bbd.priv[minor].poll_wait);
		mutex_init(&bbd.priv[minor].lock);

		/* Don't register /dev/bbd_shmd */
		if (minor==BBD_MINOR_SHMD)
			continue;
		/* Reserve char device number (a.k.a, major, minor) for this BBD device */
		ret = register_chrdev_region(devno, 1, name);
		if (ret) {
			pr_err("BBD:%s() failed to register_chrdev_region() "
					"\"%s\", ret=%d", __func__, name, ret);
			goto free_class;
		}

		/* Register cdev which relates above device number with this BBD device */
		cdev_init(cdev, &bbd_fops[minor]);
		cdev->owner = THIS_MODULE;
		cdev->ops = &bbd_fops[minor];
		ret = cdev_add(cdev, devno, 1);
		if (ret) {
			pr_err("BBD:%s()) failed to cdev_add() \"%s\", ret=%d",
							__func__, name, ret);
			unregister_chrdev_region(devno, 1);
			goto free_class;
		}

		/* Let it show in FS */
		dev = device_create(bbd.class, NULL, devno, NULL, "%s", name);
		if (IS_ERR_OR_NULL(dev)) {
			pr_err("BBD:%s() failed to device_create() "
				"\"%s\", ret=%d", __func__, name, ret);
			unregister_chrdev_region(devno, 1);
			cdev_del(&bbd.priv[minor].dev);
			goto free_class;
		}

		/* Done. Put success log and init BBD specific fields */
		pr_debug("BBD:%s(%d,%d) registered /dev/%s\n",
			      __func__, BBD_DEVICE_MAJOR,minor,name);

	}

	/* Register sysfs entry */
	bbd.kobj = kobject_create_and_add("bbd", NULL);
	BUG_ON(!bbd.kobj);
	ret = sysfs_create_group(bbd.kobj, &bbd_group);
	if (ret < 0) {
		pr_err("%s failed to sysfs_create_group \"bbd\", ret = %d",
							__func__, ret);
		goto free_kobj;
	}


	/* Register PM */
	ret = register_pm_notifier(&bbd_notifier_block);
	BUG_ON(ret);

#ifdef CONFIG_SENSORS_SSP
	/* Now, we can initialize SSP */
	BUG_ON(device_register(&dummy_spi.dev));
	{
		struct spi_device *spi = to_spi_device(dev);
		void *org_priv, *new_priv;

		org_priv = spi_get_drvdata(spi);
		pssp_driver->probe(spi);
		new_priv = spi_get_drvdata(spi);
		spi_set_drvdata(spi, org_priv);
		spi_set_drvdata(&dummy_spi, new_priv);

	}
#endif
	ts1 = ktime_to_timespec(ktime_get_boottime());
	elapsed = (ts1.tv_sec * 1000000000ULL + ts1.tv_nsec) - start;
	pr_debug("BBD:%s %lu nsec elapsed\n", __func__, elapsed);

#ifdef DEBUG_1HZ_STAT
	bbd_init_stat();
#endif
        return 0;

free_kobj:
	kobject_put(bbd.kobj);
free_class:
	while (--minor>BBD_MINOR_SHMD) {
		dev_t devno = MKDEV(BBD_DEVICE_MAJOR, minor);
		struct cdev *cdev = &bbd.priv[minor].dev;

		device_destroy(bbd.class, devno);
		cdev_del(cdev);
		unregister_chrdev_region(devno, 1);
	}
	class_destroy(bbd.class);
exit:
	return ret;
}

static void __exit bbd_exit(void)
{
	int minor;

#ifdef CONFIG_SENSORS_SSP
	/* Shutdown SSP first*/
	pssp_driver->shutdown(&dummy_spi);
#endif

	/* Remove sysfs entry */
	sysfs_remove_group(bbd.kobj, &bbd_group);

	/* Remove BBD char devices */
	for (minor=BBD_MINOR_SENSOR; minor<BBD_DEVICE_INDEX; minor++) {
		dev_t devno = MKDEV(BBD_DEVICE_MAJOR, minor);
		struct cdev *cdev = &bbd.priv[minor].dev;
		const char *name = bbd_dev_name[minor];

		device_destroy(bbd.class, devno);
		cdev_del(cdev);
		unregister_chrdev_region(devno, 1);

		pr_debug("%s(%d,%d) unregistered /dev/%s\n",
				__func__, BBD_DEVICE_MAJOR, minor, name);
	}

#ifdef DEBUG_1HZ_STAT
	bbd_exit_stat();
#endif
	/* Remove class */
	class_destroy(bbd.class);
	/* Done. Put success log */
}

MODULE_AUTHOR("Broadcom");
MODULE_LICENSE("Dual BSD/GPL");