summaryrefslogtreecommitdiffstats
path: root/drivers/i2c/busses/i2c-stu300.c
blob: 182e711318bacf6793307b6641ab2ab6910158b8 (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
/*
 * Copyright (C) 2007-2009 ST-Ericsson AB
 * License terms: GNU General Public License (GPL) version 2
 * ST DDC I2C master mode driver, used in e.g. U300 series platforms.
 * Author: Linus Walleij <linus.walleij@stericsson.com>
 * Author: Jonas Aaberg <jonas.aberg@stericsson.com>
 */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/clk.h>
#include <linux/io.h>

/* the name of this kernel module */
#define NAME "stu300"

/* CR (Control Register) 8bit (R/W) */
#define I2C_CR					(0x00000000)
#define I2C_CR_RESET_VALUE			(0x00)
#define I2C_CR_RESET_UMASK			(0x00)
#define I2C_CR_DDC1_ENABLE			(0x80)
#define I2C_CR_TRANS_ENABLE			(0x40)
#define I2C_CR_PERIPHERAL_ENABLE		(0x20)
#define I2C_CR_DDC2B_ENABLE			(0x10)
#define I2C_CR_START_ENABLE			(0x08)
#define I2C_CR_ACK_ENABLE			(0x04)
#define I2C_CR_STOP_ENABLE			(0x02)
#define I2C_CR_INTERRUPT_ENABLE			(0x01)
/* SR1 (Status Register 1) 8bit (R/-) */
#define I2C_SR1					(0x00000004)
#define I2C_SR1_RESET_VALUE			(0x00)
#define I2C_SR1_RESET_UMASK			(0x00)
#define I2C_SR1_EVF_IND				(0x80)
#define I2C_SR1_ADD10_IND			(0x40)
#define I2C_SR1_TRA_IND				(0x20)
#define I2C_SR1_BUSY_IND			(0x10)
#define I2C_SR1_BTF_IND				(0x08)
#define I2C_SR1_ADSL_IND			(0x04)
#define I2C_SR1_MSL_IND				(0x02)
#define I2C_SR1_SB_IND				(0x01)
/* SR2 (Status Register 2) 8bit (R/-) */
#define I2C_SR2					(0x00000008)
#define I2C_SR2_RESET_VALUE			(0x00)
#define I2C_SR2_RESET_UMASK			(0x40)
#define I2C_SR2_MASK				(0xBF)
#define I2C_SR2_SCLFAL_IND			(0x80)
#define I2C_SR2_ENDAD_IND			(0x20)
#define I2C_SR2_AF_IND				(0x10)
#define I2C_SR2_STOPF_IND			(0x08)
#define I2C_SR2_ARLO_IND			(0x04)
#define I2C_SR2_BERR_IND			(0x02)
#define I2C_SR2_DDC2BF_IND			(0x01)
/* CCR (Clock Control Register) 8bit (R/W) */
#define I2C_CCR					(0x0000000C)
#define I2C_CCR_RESET_VALUE			(0x00)
#define I2C_CCR_RESET_UMASK			(0x00)
#define I2C_CCR_MASK				(0xFF)
#define I2C_CCR_FMSM				(0x80)
#define I2C_CCR_CC_MASK				(0x7F)
/* OAR1 (Own Address Register 1) 8bit (R/W) */
#define I2C_OAR1				(0x00000010)
#define I2C_OAR1_RESET_VALUE			(0x00)
#define I2C_OAR1_RESET_UMASK			(0x00)
#define I2C_OAR1_ADD_MASK			(0xFF)
/* OAR2 (Own Address Register 2) 8bit (R/W) */
#define I2C_OAR2				(0x00000014)
#define I2C_OAR2_RESET_VALUE			(0x40)
#define I2C_OAR2_RESET_UMASK			(0x19)
#define I2C_OAR2_MASK				(0xE6)
#define I2C_OAR2_FR_25_10MHZ			(0x00)
#define I2C_OAR2_FR_10_1667MHZ			(0x20)
#define I2C_OAR2_FR_1667_2667MHZ		(0x40)
#define I2C_OAR2_FR_2667_40MHZ			(0x60)
#define I2C_OAR2_FR_40_5333MHZ			(0x80)
#define I2C_OAR2_FR_5333_66MHZ			(0xA0)
#define I2C_OAR2_FR_66_80MHZ			(0xC0)
#define I2C_OAR2_FR_80_100MHZ			(0xE0)
#define I2C_OAR2_FR_MASK			(0xE0)
#define I2C_OAR2_ADD_MASK			(0x06)
/* DR (Data Register) 8bit (R/W) */
#define I2C_DR					(0x00000018)
#define I2C_DR_RESET_VALUE			(0x00)
#define I2C_DR_RESET_UMASK			(0xFF)
#define I2C_DR_D_MASK				(0xFF)
/* ECCR (Extended Clock Control Register) 8bit (R/W) */
#define I2C_ECCR				(0x0000001C)
#define I2C_ECCR_RESET_VALUE			(0x00)
#define I2C_ECCR_RESET_UMASK			(0xE0)
#define I2C_ECCR_MASK				(0x1F)
#define I2C_ECCR_CC_MASK			(0x1F)

/*
 * These events are more or less responses to commands
 * sent into the hardware, presumably reflecting the state
 * of an internal state machine.
 */
enum stu300_event {
	STU300_EVENT_NONE = 0,
	STU300_EVENT_1,
	STU300_EVENT_2,
	STU300_EVENT_3,
	STU300_EVENT_4,
	STU300_EVENT_5,
	STU300_EVENT_6,
	STU300_EVENT_7,
	STU300_EVENT_8,
	STU300_EVENT_9
};

enum stu300_error {
	STU300_ERROR_NONE = 0,
	STU300_ERROR_ACKNOWLEDGE_FAILURE,
	STU300_ERROR_BUS_ERROR,
	STU300_ERROR_ARBITRATION_LOST
};

/* timeout waiting for the controller to respond */
#define STU300_TIMEOUT (msecs_to_jiffies(1000))

/*
 * The number of address send athemps tried before giving up.
 * If the first one failes it seems like 5 to 8 attempts are required.
 */
#define NUM_ADDR_RESEND_ATTEMPTS 10

/* I2C clock speed, in Hz 0-400kHz*/
static unsigned int scl_frequency = 100000;
module_param(scl_frequency, uint,  0644);

/**
 * struct stu300_dev - the stu300 driver state holder
 * @pdev: parent platform device
 * @adapter: corresponding I2C adapter
 * @phybase: location of I/O area in memory
 * @physize: size of I/O area in memory
 * @clk: hardware block clock
 * @irq: assigned interrupt line
 * @cmd_issue_lock: this locks the following cmd_ variables
 * @cmd_complete: acknowledge completion for an I2C command
 * @cmd_event: expected event coming in as a response to a command
 * @cmd_err: error code as response to a command
 * @speed: current bus speed in Hz
 * @msg_index: index of current message
 * @msg_len: length of current message
 */
struct stu300_dev {
	struct platform_device	*pdev;
	struct i2c_adapter	adapter;
	resource_size_t		phybase;
	resource_size_t		physize;
	void __iomem		*virtbase;
	struct clk		*clk;
	int			irq;
	spinlock_t		cmd_issue_lock;
	struct completion	cmd_complete;
	enum stu300_event	cmd_event;
	enum stu300_error	cmd_err;
	unsigned int		speed;
	int			msg_index;
	int			msg_len;
};

/* Local forward function declarations */
static int stu300_init_hw(struct stu300_dev *dev);

/*
 * The block needs writes in both MSW and LSW in order
 * for all data lines to reach their destination.
 */
static inline void stu300_wr8(u32 value, void __iomem *address)
{
	writel((value << 16) | value, address);
}

/*
 * This merely masks off the duplicates which appear
 * in bytes 1-3. You _MUST_ use 32-bit bus access on this
 * device, else it will not work.
 */
static inline u32 stu300_r8(void __iomem *address)
{
	return readl(address) & 0x000000FFU;
}

/*
 * Tells whether a certain event or events occurred in
 * response to a command. The events represent states in
 * the internal state machine of the hardware. The events
 * are not very well described in the hardware
 * documentation and can only be treated as abstract state
 * machine states.
 *
 * @ret 0 = event has not occurred, any other value means
 * the event occurred.
 */
static int stu300_event_occurred(struct stu300_dev *dev,
				   enum stu300_event mr_event) {
	u32 status1;
	u32 status2;

	/* What event happened? */
	status1 = stu300_r8(dev->virtbase + I2C_SR1);
	if (!(status1 & I2C_SR1_EVF_IND))
		/* No event at all */
		return 0;
	status2 = stu300_r8(dev->virtbase + I2C_SR2);

	switch (mr_event) {
	case STU300_EVENT_1:
		if (status1 & I2C_SR1_ADSL_IND)
			return 1;
		break;
	case STU300_EVENT_2:
	case STU300_EVENT_3:
	case STU300_EVENT_7:
	case STU300_EVENT_8:
		if (status1 & I2C_SR1_BTF_IND) {
			if (status2 & I2C_SR2_AF_IND)
				dev->cmd_err = STU300_ERROR_ACKNOWLEDGE_FAILURE;
			else if (status2 & I2C_SR2_BERR_IND)
				dev->cmd_err = STU300_ERROR_BUS_ERROR;
			return 1;
		}
		break;
	case STU300_EVENT_4:
		if (status2 & I2C_SR2_STOPF_IND)
			return 1;
		break;
	case STU300_EVENT_5:
		if (status1 & I2C_SR1_SB_IND)
			/* Clear start bit */
			return 1;
		break;
	case STU300_EVENT_6:
		if (status2 & I2C_SR2_ENDAD_IND) {
			/* First check for any errors */
			if (status2 & I2C_SR2_AF_IND)
				dev->cmd_err = STU300_ERROR_ACKNOWLEDGE_FAILURE;
			return 1;
		}
		break;
	case STU300_EVENT_9:
		if (status1 & I2C_SR1_ADD10_IND)
			return 1;
		break;
	default:
		break;
	}
	if (status2 & I2C_SR2_ARLO_IND)
		dev->cmd_err = STU300_ERROR_ARBITRATION_LOST;
	return 0;
}

static irqreturn_t stu300_irh(int irq, void *data)
{
	struct stu300_dev *dev = data;
	int res;

	/* See if this was what we were waiting for */
	spin_lock(&dev->cmd_issue_lock);
	if (dev->cmd_event != STU300_EVENT_NONE) {
		res = stu300_event_occurred(dev, dev->cmd_event);
		if (res || dev->cmd_err != STU300_ERROR_NONE) {
			u32 val;

			complete(&dev->cmd_complete);
			/* Block any multiple interrupts */
			val = stu300_r8(dev->virtbase + I2C_CR);
			val &= ~I2C_CR_INTERRUPT_ENABLE;
			stu300_wr8(val, dev->virtbase + I2C_CR);
		}
	}
	spin_unlock(&dev->cmd_issue_lock);
	return IRQ_HANDLED;
}

/*
 * Sends a command and then waits for the bits masked by *flagmask*
 * to go high or low by IRQ awaiting.
 */
static int stu300_start_and_await_event(struct stu300_dev *dev,
					  u8 cr_value,
					  enum stu300_event mr_event)
{
	int ret;

	if (unlikely(irqs_disabled())) {
		/* TODO: implement polling for this case if need be. */
		WARN(1, "irqs are disabled, cannot poll for event\n");
		return -EIO;
	}

	/* Lock command issue, fill in an event we wait for */
	spin_lock_irq(&dev->cmd_issue_lock);
	init_completion(&dev->cmd_complete);
	dev->cmd_err = STU300_ERROR_NONE;
	dev->cmd_event = mr_event;
	spin_unlock_irq(&dev->cmd_issue_lock);

	/* Turn on interrupt, send command and wait. */
	cr_value |= I2C_CR_INTERRUPT_ENABLE;
	stu300_wr8(cr_value, dev->virtbase + I2C_CR);
	ret = wait_for_completion_interruptible_timeout(&dev->cmd_complete,
							STU300_TIMEOUT);

	if (ret < 0) {
		dev_err(&dev->pdev->dev,
		       "wait_for_completion_interruptible_timeout() "
		       "returned %d waiting for event %04x\n", ret, mr_event);
		return ret;
	}

	if (ret == 0) {
		dev_err(&dev->pdev->dev, "controller timed out "
		       "waiting for event %d, reinit hardware\n", mr_event);
		(void) stu300_init_hw(dev);
		return -ETIMEDOUT;
	}

	if (dev->cmd_err != STU300_ERROR_NONE) {
		dev_err(&dev->pdev->dev, "controller (start) "
		       "error %d waiting for event %d, reinit hardware\n",
		       dev->cmd_err, mr_event);
		(void) stu300_init_hw(dev);
		return -EIO;
	}

	return 0;
}

/*
 * This waits for a flag to be set, if it is not set on entry, an interrupt is
 * configured to wait for the flag using a completion.
 */
static int stu300_await_event(struct stu300_dev *dev,
				enum stu300_event mr_event)
{
	int ret;
	u32 val;

	if (unlikely(irqs_disabled())) {
		/* TODO: implement polling for this case if need be. */
		dev_err(&dev->pdev->dev, "irqs are disabled on this "
			"system!\n");
		return -EIO;
	}

	/* Is it already here? */
	spin_lock_irq(&dev->cmd_issue_lock);
	dev->cmd_err = STU300_ERROR_NONE;
	if (stu300_event_occurred(dev, mr_event)) {
		spin_unlock_irq(&dev->cmd_issue_lock);
		goto exit_await_check_err;
	}
	init_completion(&dev->cmd_complete);
	dev->cmd_err = STU300_ERROR_NONE;
	dev->cmd_event = mr_event;

	/* Turn on the I2C interrupt for current operation */
	val = stu300_r8(dev->virtbase + I2C_CR);
	val |= I2C_CR_INTERRUPT_ENABLE;
	stu300_wr8(val, dev->virtbase + I2C_CR);

	/* Twice paranoia (possible HW glitch) */
	stu300_wr8(val, dev->virtbase + I2C_CR);

	/* Check again: is it already here? */
	if (unlikely(stu300_event_occurred(dev, mr_event))) {
		/* Disable IRQ again. */
		val &= ~I2C_CR_INTERRUPT_ENABLE;
		stu300_wr8(val, dev->virtbase + I2C_CR);
		spin_unlock_irq(&dev->cmd_issue_lock);
		goto exit_await_check_err;
	}

	/* Unlock the command block and wait for the event to occur */
	spin_unlock_irq(&dev->cmd_issue_lock);
	ret = wait_for_completion_interruptible_timeout(&dev->cmd_complete,
							STU300_TIMEOUT);

	if (ret < 0) {
		dev_err(&dev->pdev->dev,
		       "wait_for_completion_interruptible_timeout()"
		       "returned %d waiting for event %04x\n", ret, mr_event);
		return ret;
	}

	if (ret == 0) {
		if (mr_event != STU300_EVENT_6) {
			dev_err(&dev->pdev->dev, "controller "
				"timed out waiting for event %d, reinit "
				"hardware\n", mr_event);
			(void) stu300_init_hw(dev);
		}
		return -ETIMEDOUT;
	}

 exit_await_check_err:
	if (dev->cmd_err != STU300_ERROR_NONE) {
		if (mr_event != STU300_EVENT_6) {
			dev_err(&dev->pdev->dev, "controller "
				"error (await_event) %d waiting for event %d, "
			       "reinit hardware\n", dev->cmd_err, mr_event);
			(void) stu300_init_hw(dev);
		}
		return -EIO;
	}

	return 0;
}

/*
 * Waits for the busy bit to go low by repeated polling.
 */
#define BUSY_RELEASE_ATTEMPTS 10
static int stu300_wait_while_busy(struct stu300_dev *dev)
{
	unsigned long timeout;
	int i;

	for (i = 0; i < BUSY_RELEASE_ATTEMPTS; i++) {
		timeout = jiffies + STU300_TIMEOUT;

		while (!time_after(jiffies, timeout)) {
			/* Is not busy? */
			if ((stu300_r8(dev->virtbase + I2C_SR1) &
			     I2C_SR1_BUSY_IND) == 0)
				return 0;
			msleep(1);
		}

		dev_err(&dev->pdev->dev, "transaction timed out "
			"waiting for device to be free (not busy). "
		       "Attempt: %d\n", i+1);

		dev_err(&dev->pdev->dev, "base address = "
			"0x%08x, reinit hardware\n", (u32) dev->virtbase);

		(void) stu300_init_hw(dev);
	}

	dev_err(&dev->pdev->dev, "giving up after %d attempts "
		"to reset the bus.\n",  BUSY_RELEASE_ATTEMPTS);

	return -ETIMEDOUT;
}

struct stu300_clkset {
	unsigned long rate;
	u32 setting;
};

static const struct stu300_clkset stu300_clktable[] = {
	{ 0, 0xFFU },
	{ 2500000, I2C_OAR2_FR_25_10MHZ },
	{ 10000000, I2C_OAR2_FR_10_1667MHZ },
	{ 16670000, I2C_OAR2_FR_1667_2667MHZ },
	{ 26670000, I2C_OAR2_FR_2667_40MHZ },
	{ 40000000, I2C_OAR2_FR_40_5333MHZ },
	{ 53330000, I2C_OAR2_FR_5333_66MHZ },
	{ 66000000, I2C_OAR2_FR_66_80MHZ },
	{ 80000000, I2C_OAR2_FR_80_100MHZ },
	{ 100000000, 0xFFU },
};

static int stu300_set_clk(struct stu300_dev *dev, unsigned long clkrate)
{

	u32 val;
	int i = 0;

	/* Locate the apropriate clock setting */
	while (i < ARRAY_SIZE(stu300_clktable) &&
	       stu300_clktable[i].rate < clkrate)
		i++;

	if (stu300_clktable[i].setting == 0xFFU) {
		dev_err(&dev->pdev->dev, "too %s clock rate requested "
			"(%lu Hz).\n", i ? "high" : "low", clkrate);
		return -EINVAL;
	}

	stu300_wr8(stu300_clktable[i].setting,
		   dev->virtbase + I2C_OAR2);

	dev_dbg(&dev->pdev->dev, "Clock rate %lu Hz, I2C bus speed %d Hz "
		"virtbase %p\n", clkrate, dev->speed, dev->virtbase);

	if (dev->speed > 100000)
		/* Fast Mode I2C */
		val = ((clkrate/dev->speed)-9)/3;
	else
		/* Standard Mode I2C */
		val = ((clkrate/dev->speed)-7)/2;

	/* According to spec the divider must be > 2 */
	if (val < 0x002) {
		dev_err(&dev->pdev->dev, "too low clock rate (%lu Hz).\n",
			clkrate);
		return -EINVAL;
	}

	/* We have 12 bits clock divider only! */
	if (val & 0xFFFFF000U) {
		dev_err(&dev->pdev->dev, "too high clock rate (%lu Hz).\n",
			clkrate);
		return -EINVAL;
	}

	if (dev->speed > 100000) {
		/* CC6..CC0 */
		stu300_wr8((val & I2C_CCR_CC_MASK) | I2C_CCR_FMSM,
			   dev->virtbase + I2C_CCR);
		dev_dbg(&dev->pdev->dev, "set clock divider to 0x%08x, "
			"Fast Mode I2C\n", val);
	} else {
		/* CC6..CC0 */
		stu300_wr8((val & I2C_CCR_CC_MASK),
			   dev->virtbase + I2C_CCR);
		dev_dbg(&dev->pdev->dev, "set clock divider to "
			"0x%08x, Standard Mode I2C\n", val);
	}

	/* CC11..CC7 */
	stu300_wr8(((val >> 7) & 0x1F),
		   dev->virtbase + I2C_ECCR);

	return 0;
}


static int stu300_init_hw(struct stu300_dev *dev)
{
	u32 dummy;
	unsigned long clkrate;
	int ret;

	/* Disable controller */
	stu300_wr8(0x00, dev->virtbase + I2C_CR);
	/*
	 * Set own address to some default value (0x00).
	 * We do not support slave mode anyway.
	 */
	stu300_wr8(0x00, dev->virtbase + I2C_OAR1);
	/*
	 * The I2C controller only operates properly in 26 MHz but we
	 * program this driver as if we didn't know. This will also set the two
	 * high bits of the own address to zero as well.
	 * There is no known hardware issue with running in 13 MHz
	 * However, speeds over 200 kHz are not used.
	 */
	clkrate = clk_get_rate(dev->clk);
	ret = stu300_set_clk(dev, clkrate);
	if (ret)
		return ret;
	/*
	 * Enable block, do it TWICE (hardware glitch)
	 * Setting bit 7 can enable DDC mode. (Not used currently.)
	 */
	stu300_wr8(I2C_CR_PERIPHERAL_ENABLE,
				  dev->virtbase + I2C_CR);
	stu300_wr8(I2C_CR_PERIPHERAL_ENABLE,
				  dev->virtbase + I2C_CR);
	/* Make a dummy read of the status register SR1 & SR2 */
	dummy = stu300_r8(dev->virtbase + I2C_SR2);
	dummy = stu300_r8(dev->virtbase + I2C_SR1);

	return 0;
}



/* Send slave address. */
static int stu300_send_address(struct stu300_dev *dev,
				 struct i2c_msg *msg, int resend)
{
	u32 val;
	int ret;

	if (msg->flags & I2C_M_TEN)
		/* This is probably how 10 bit addresses look */
		val = (0xf0 | (((u32) msg->addr & 0x300) >> 7)) &
			I2C_DR_D_MASK;
	else
		val = ((msg->addr << 1) & I2C_DR_D_MASK);

	if (msg->flags & I2C_M_RD) {
		/* This is the direction bit */
		val |= 0x01;
		if (resend)
			dev_dbg(&dev->pdev->dev, "read resend\n");
	} else if (resend)
		dev_dbg(&dev->pdev->dev, "write resend\n");
	stu300_wr8(val, dev->virtbase + I2C_DR);

	/* For 10bit addressing, await 10bit request (EVENT 9) */
	if (msg->flags & I2C_M_TEN) {
		ret = stu300_await_event(dev, STU300_EVENT_9);
		/*
		 * The slave device wants a 10bit address, send the rest
		 * of the bits (the LSBits)
		 */
		val = msg->addr & I2C_DR_D_MASK;
		/* This clears "event 9" */
		stu300_wr8(val, dev->virtbase + I2C_DR);
		if (ret != 0)
			return ret;
	}
	/* FIXME: Why no else here? two events for 10bit?
	 * Await event 6 (normal) or event 9 (10bit)
	 */

	if (resend)
		dev_dbg(&dev->pdev->dev, "await event 6\n");
	ret = stu300_await_event(dev, STU300_EVENT_6);

	/*
	 * Clear any pending EVENT 6 no matter what happend during
	 * await_event.
	 */
	val = stu300_r8(dev->virtbase + I2C_CR);
	val |= I2C_CR_PERIPHERAL_ENABLE;
	stu300_wr8(val, dev->virtbase + I2C_CR);

	return ret;
}

static int stu300_xfer_msg(struct i2c_adapter *adap,
			     struct i2c_msg *msg, int stop)
{
	u32 cr;
	u32 val;
	u32 i;
	int ret;
	int attempts = 0;
	struct stu300_dev *dev = i2c_get_adapdata(adap);


	clk_enable(dev->clk);

	/* Remove this if (0) to trace each and every message. */
	if (0) {
		dev_dbg(&dev->pdev->dev, "I2C message to: 0x%04x, len: %d, "
			"flags: 0x%04x, stop: %d\n",
			msg->addr, msg->len, msg->flags, stop);
	}

	/* Zero-length messages are not supported by this hardware */
	if (msg->len == 0) {
		ret = -EINVAL;
		goto exit_disable;
	}

	/*
	 * For some reason, sending the address sometimes fails when running
	 * on  the 13 MHz clock. No interrupt arrives. This is a work around,
	 * which tries to restart and send the address up to 10 times before
	 * really giving up. Usually 5 to 8 attempts are enough.
	 */
	do {
		if (attempts)
			dev_dbg(&dev->pdev->dev, "wait while busy\n");
		/* Check that the bus is free, or wait until some timeout */
		ret = stu300_wait_while_busy(dev);
		if (ret != 0)
			goto exit_disable;

		if (attempts)
			dev_dbg(&dev->pdev->dev, "re-int hw\n");
		/*
		 * According to ST, there is no problem if the clock is
		 * changed between 13 and 26 MHz during a transfer.
		 */
		ret = stu300_init_hw(dev);
		if (ret)
			goto exit_disable;

		/* Send a start condition */
		cr = I2C_CR_PERIPHERAL_ENABLE;
		/* Setting the START bit puts the block in master mode */
		if (!(msg->flags & I2C_M_NOSTART))
			cr |= I2C_CR_START_ENABLE;
		if ((msg->flags & I2C_M_RD) && (msg->len > 1))
			/* On read more than 1 byte, we need ack. */
			cr |= I2C_CR_ACK_ENABLE;
		/* Check that it gets through */
		if (!(msg->flags & I2C_M_NOSTART)) {
			if (attempts)
				dev_dbg(&dev->pdev->dev, "send start event\n");
			ret = stu300_start_and_await_event(dev, cr,
							     STU300_EVENT_5);
		}

		if (attempts)
			dev_dbg(&dev->pdev->dev, "send address\n");

		if (ret == 0)
			/* Send address */
			ret = stu300_send_address(dev, msg, attempts != 0);

		if (ret != 0) {
			attempts++;
			dev_dbg(&dev->pdev->dev, "failed sending address, "
				"retrying. Attempt: %d msg_index: %d/%d\n",
			       attempts, dev->msg_index, dev->msg_len);
		}

	} while (ret != 0 && attempts < NUM_ADDR_RESEND_ATTEMPTS);

	if (attempts < NUM_ADDR_RESEND_ATTEMPTS && attempts > 0) {
		dev_dbg(&dev->pdev->dev, "managed to get address "
		       "through after %d attempts\n", attempts);
	} else if (attempts == NUM_ADDR_RESEND_ATTEMPTS) {
		dev_dbg(&dev->pdev->dev, "I give up, tried %d times "
		       "to resend address.\n",
		       NUM_ADDR_RESEND_ATTEMPTS);
		goto exit_disable;
	}

	if (msg->flags & I2C_M_RD) {
		/* READ: we read the actual bytes one at a time */
		for (i = 0; i < msg->len; i++) {
			if (i == msg->len-1) {
				/*
				 * Disable ACK and set STOP condition before
				 * reading last byte
				 */
				val = I2C_CR_PERIPHERAL_ENABLE;

				if (stop)
					val |= I2C_CR_STOP_ENABLE;

				stu300_wr8(val,
					   dev->virtbase + I2C_CR);
			}
			/* Wait for this byte... */
			ret = stu300_await_event(dev, STU300_EVENT_7);
			if (ret != 0)
				goto exit_disable;
			/* This clears event 7 */
			msg->buf[i] = (u8) stu300_r8(dev->virtbase + I2C_DR);
		}
	} else {
		/* WRITE: we send the actual bytes one at a time */
		for (i = 0; i < msg->len; i++) {
			/* Write the byte */
			stu300_wr8(msg->buf[i],
				   dev->virtbase + I2C_DR);
			/* Check status */
			ret = stu300_await_event(dev, STU300_EVENT_8);
			/* Next write to DR will clear event 8 */
			if (ret != 0) {
				dev_err(&dev->pdev->dev, "error awaiting "
				       "event 8 (%d)\n", ret);
				goto exit_disable;
			}
		}
		/* Check NAK */
		if (!(msg->flags & I2C_M_IGNORE_NAK)) {
			if (stu300_r8(dev->virtbase + I2C_SR2) &
			    I2C_SR2_AF_IND) {
				dev_err(&dev->pdev->dev, "I2C payload "
				       "send returned NAK!\n");
				ret = -EIO;
				goto exit_disable;
			}
		}
		if (stop) {
			/* Send stop condition */
			val = I2C_CR_PERIPHERAL_ENABLE;
			val |= I2C_CR_STOP_ENABLE;
			stu300_wr8(val, dev->virtbase + I2C_CR);
		}
	}

	/* Check that the bus is free, or wait until some timeout occurs */
	ret = stu300_wait_while_busy(dev);
	if (ret != 0) {
		dev_err(&dev->pdev->dev, "timout waiting for transfer "
		       "to commence.\n");
		goto exit_disable;
	}

	/* Dummy read status registers */
	val = stu300_r8(dev->virtbase + I2C_SR2);
	val = stu300_r8(dev->virtbase + I2C_SR1);
	ret = 0;

 exit_disable:
	/* Disable controller */
	stu300_wr8(0x00, dev->virtbase + I2C_CR);
	clk_disable(dev->clk);
	return ret;
}

static int stu300_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
			 int num)
{
	int ret = -1;
	int i;
	struct stu300_dev *dev = i2c_get_adapdata(adap);
	dev->msg_len = num;
	for (i = 0; i < num; i++) {
		/*
		 * Another driver appears to send stop for each message,
		 * here we only do that for the last message. Possibly some
		 * peripherals require this behaviour, then their drivers
		 * have to send single messages in order to get "stop" for
		 * each message.
		 */
		dev->msg_index = i;

		ret = stu300_xfer_msg(adap, &msgs[i], (i == (num - 1)));
		if (ret != 0) {
			num = ret;
			break;
		}
	}

	return num;
}

static u32 stu300_func(struct i2c_adapter *adap)
{
	/* This is the simplest thing you can think of... */
	return I2C_FUNC_I2C | I2C_FUNC_10BIT_ADDR;
}

static const struct i2c_algorithm stu300_algo = {
	.master_xfer	= stu300_xfer,
	.functionality	= stu300_func,
};

static int __init
stu300_probe(struct platform_device *pdev)
{
	struct stu300_dev *dev;
	struct i2c_adapter *adap;
	struct resource *res;
	int bus_nr;
	int ret = 0;

	dev = kzalloc(sizeof(struct stu300_dev), GFP_KERNEL);
	if (!dev) {
		dev_err(&pdev->dev, "could not allocate device struct\n");
		ret = -ENOMEM;
		goto err_no_devmem;
	}

	bus_nr = pdev->id;
	dev->clk = clk_get(&pdev->dev, NULL);
	if (IS_ERR(dev->clk)) {
		ret = PTR_ERR(dev->clk);
		dev_err(&pdev->dev, "could not retrieve i2c bus clock\n");
		goto err_no_clk;
	}

	dev->pdev = pdev;
	platform_set_drvdata(pdev, dev);

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (!res) {
		ret = -ENOENT;
		goto err_no_resource;
	}

	dev->phybase = res->start;
	dev->physize = resource_size(res);

	if (request_mem_region(dev->phybase, dev->physize,
			       NAME " I/O Area") == NULL) {
		ret = -EBUSY;
		goto err_no_ioregion;
	}

	dev->virtbase = ioremap(dev->phybase, dev->physize);
	dev_dbg(&pdev->dev, "initialize bus device I2C%d on virtual "
		"base %p\n", bus_nr, dev->virtbase);
	if (!dev->virtbase) {
		ret = -ENOMEM;
		goto err_no_ioremap;
	}

	dev->irq = platform_get_irq(pdev, 0);
	if (request_irq(dev->irq, stu300_irh, IRQF_DISABLED,
			NAME, dev)) {
		ret = -EIO;
		goto err_no_irq;
	}

	dev->speed = scl_frequency;

	clk_enable(dev->clk);
	ret = stu300_init_hw(dev);
	clk_disable(dev->clk);

	if (ret != 0) {
		dev_err(&dev->pdev->dev, "error initializing hardware.\n");
		goto err_init_hw;
	}

	/* IRQ event handling initialization */
	spin_lock_init(&dev->cmd_issue_lock);
	dev->cmd_event = STU300_EVENT_NONE;
	dev->cmd_err = STU300_ERROR_NONE;

	adap = &dev->adapter;
	adap->owner = THIS_MODULE;
	/* DDC class but actually often used for more generic I2C */
	adap->class = I2C_CLASS_DDC;
	strncpy(adap->name, "ST Microelectronics DDC I2C adapter",
		sizeof(adap->name));
	adap->nr = bus_nr;
	adap->algo = &stu300_algo;
	adap->dev.parent = &pdev->dev;
	i2c_set_adapdata(adap, dev);

	/* i2c device drivers may be active on return from add_adapter() */
	ret = i2c_add_numbered_adapter(adap);
	if (ret) {
		dev_err(&dev->pdev->dev, "failure adding ST Micro DDC "
		       "I2C adapter\n");
		goto err_add_adapter;
	}
	return 0;

 err_add_adapter:
 err_init_hw:
	free_irq(dev->irq, dev);
 err_no_irq:
	iounmap(dev->virtbase);
 err_no_ioremap:
	release_mem_region(dev->phybase, dev->physize);
 err_no_ioregion:
	platform_set_drvdata(pdev, NULL);
 err_no_resource:
	clk_put(dev->clk);
 err_no_clk:
	kfree(dev);
 err_no_devmem:
	dev_err(&pdev->dev, "failed to add " NAME " adapter: %d\n",
		pdev->id);
	return ret;
}

#ifdef CONFIG_PM
static int stu300_suspend(struct platform_device *pdev, pm_message_t state)
{
	struct stu300_dev *dev = platform_get_drvdata(pdev);

	/* Turn off everything */
	stu300_wr8(0x00, dev->virtbase + I2C_CR);
	return 0;
}

static int stu300_resume(struct platform_device *pdev)
{
	int ret = 0;
	struct stu300_dev *dev = platform_get_drvdata(pdev);

	clk_enable(dev->clk);
	ret = stu300_init_hw(dev);
	clk_disable(dev->clk);

	if (ret != 0)
		dev_err(&pdev->dev, "error re-initializing hardware.\n");
	return ret;
}
#else
#define stu300_suspend NULL
#define stu300_resume NULL
#endif

static int __exit
stu300_remove(struct platform_device *pdev)
{
	struct stu300_dev *dev = platform_get_drvdata(pdev);

	i2c_del_adapter(&dev->adapter);
	/* Turn off everything */
	stu300_wr8(0x00, dev->virtbase + I2C_CR);
	free_irq(dev->irq, dev);
	iounmap(dev->virtbase);
	release_mem_region(dev->phybase, dev->physize);
	clk_put(dev->clk);
	platform_set_drvdata(pdev, NULL);
	kfree(dev);
	return 0;
}

static struct platform_driver stu300_i2c_driver = {
	.driver = {
		.name	= NAME,
		.owner	= THIS_MODULE,
	},
	.remove		= __exit_p(stu300_remove),
	.suspend        = stu300_suspend,
	.resume         = stu300_resume,

};

static int __init stu300_init(void)
{
	return platform_driver_probe(&stu300_i2c_driver, stu300_probe);
}

static void __exit stu300_exit(void)
{
	platform_driver_unregister(&stu300_i2c_driver);
}

/*
 * The systems using this bus often have very basic devices such
 * as regulators on the I2C bus, so this needs to be loaded early.
 * Therefore it is registered in the subsys_initcall().
 */
subsys_initcall(stu300_init);
module_exit(stu300_exit);

MODULE_AUTHOR("Linus Walleij <linus.walleij@stericsson.com>");
MODULE_DESCRIPTION("ST Micro DDC I2C adapter (" NAME ")");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" NAME);