1/*
2 * Copyright (C) 2007-2009 ST-Ericsson AB
3 * License terms: GNU General Public License (GPL) version 2
4 * ST DDC I2C master mode driver, used in e.g. U300 series platforms.
5 * Author: Linus Walleij <linus.walleij@stericsson.com>
6 * Author: Jonas Aaberg <jonas.aberg@stericsson.com>
7 */
8#include <linux/init.h>
9#include <linux/module.h>
10#include <linux/platform_device.h>
11#include <linux/delay.h>
12#include <linux/i2c.h>
13#include <linux/spinlock.h>
14#include <linux/completion.h>
15#include <linux/err.h>
16#include <linux/interrupt.h>
17#include <linux/clk.h>
18#include <linux/io.h>
19#include <linux/slab.h>
20
21/* the name of this kernel module */
22#define NAME "stu300"
23
24/* CR (Control Register) 8bit (R/W) */
25#define I2C_CR					(0x00000000)
26#define I2C_CR_RESET_VALUE			(0x00)
27#define I2C_CR_RESET_UMASK			(0x00)
28#define I2C_CR_DDC1_ENABLE			(0x80)
29#define I2C_CR_TRANS_ENABLE			(0x40)
30#define I2C_CR_PERIPHERAL_ENABLE		(0x20)
31#define I2C_CR_DDC2B_ENABLE			(0x10)
32#define I2C_CR_START_ENABLE			(0x08)
33#define I2C_CR_ACK_ENABLE			(0x04)
34#define I2C_CR_STOP_ENABLE			(0x02)
35#define I2C_CR_INTERRUPT_ENABLE			(0x01)
36/* SR1 (Status Register 1) 8bit (R/-) */
37#define I2C_SR1					(0x00000004)
38#define I2C_SR1_RESET_VALUE			(0x00)
39#define I2C_SR1_RESET_UMASK			(0x00)
40#define I2C_SR1_EVF_IND				(0x80)
41#define I2C_SR1_ADD10_IND			(0x40)
42#define I2C_SR1_TRA_IND				(0x20)
43#define I2C_SR1_BUSY_IND			(0x10)
44#define I2C_SR1_BTF_IND				(0x08)
45#define I2C_SR1_ADSL_IND			(0x04)
46#define I2C_SR1_MSL_IND				(0x02)
47#define I2C_SR1_SB_IND				(0x01)
48/* SR2 (Status Register 2) 8bit (R/-) */
49#define I2C_SR2					(0x00000008)
50#define I2C_SR2_RESET_VALUE			(0x00)
51#define I2C_SR2_RESET_UMASK			(0x40)
52#define I2C_SR2_MASK				(0xBF)
53#define I2C_SR2_SCLFAL_IND			(0x80)
54#define I2C_SR2_ENDAD_IND			(0x20)
55#define I2C_SR2_AF_IND				(0x10)
56#define I2C_SR2_STOPF_IND			(0x08)
57#define I2C_SR2_ARLO_IND			(0x04)
58#define I2C_SR2_BERR_IND			(0x02)
59#define I2C_SR2_DDC2BF_IND			(0x01)
60/* CCR (Clock Control Register) 8bit (R/W) */
61#define I2C_CCR					(0x0000000C)
62#define I2C_CCR_RESET_VALUE			(0x00)
63#define I2C_CCR_RESET_UMASK			(0x00)
64#define I2C_CCR_MASK				(0xFF)
65#define I2C_CCR_FMSM				(0x80)
66#define I2C_CCR_CC_MASK				(0x7F)
67/* OAR1 (Own Address Register 1) 8bit (R/W) */
68#define I2C_OAR1				(0x00000010)
69#define I2C_OAR1_RESET_VALUE			(0x00)
70#define I2C_OAR1_RESET_UMASK			(0x00)
71#define I2C_OAR1_ADD_MASK			(0xFF)
72/* OAR2 (Own Address Register 2) 8bit (R/W) */
73#define I2C_OAR2				(0x00000014)
74#define I2C_OAR2_RESET_VALUE			(0x40)
75#define I2C_OAR2_RESET_UMASK			(0x19)
76#define I2C_OAR2_MASK				(0xE6)
77#define I2C_OAR2_FR_25_10MHZ			(0x00)
78#define I2C_OAR2_FR_10_1667MHZ			(0x20)
79#define I2C_OAR2_FR_1667_2667MHZ		(0x40)
80#define I2C_OAR2_FR_2667_40MHZ			(0x60)
81#define I2C_OAR2_FR_40_5333MHZ			(0x80)
82#define I2C_OAR2_FR_5333_66MHZ			(0xA0)
83#define I2C_OAR2_FR_66_80MHZ			(0xC0)
84#define I2C_OAR2_FR_80_100MHZ			(0xE0)
85#define I2C_OAR2_FR_MASK			(0xE0)
86#define I2C_OAR2_ADD_MASK			(0x06)
87/* DR (Data Register) 8bit (R/W) */
88#define I2C_DR					(0x00000018)
89#define I2C_DR_RESET_VALUE			(0x00)
90#define I2C_DR_RESET_UMASK			(0xFF)
91#define I2C_DR_D_MASK				(0xFF)
92/* ECCR (Extended Clock Control Register) 8bit (R/W) */
93#define I2C_ECCR				(0x0000001C)
94#define I2C_ECCR_RESET_VALUE			(0x00)
95#define I2C_ECCR_RESET_UMASK			(0xE0)
96#define I2C_ECCR_MASK				(0x1F)
97#define I2C_ECCR_CC_MASK			(0x1F)
98
99/*
100 * These events are more or less responses to commands
101 * sent into the hardware, presumably reflecting the state
102 * of an internal state machine.
103 */
104enum stu300_event {
105	STU300_EVENT_NONE = 0,
106	STU300_EVENT_1,
107	STU300_EVENT_2,
108	STU300_EVENT_3,
109	STU300_EVENT_4,
110	STU300_EVENT_5,
111	STU300_EVENT_6,
112	STU300_EVENT_7,
113	STU300_EVENT_8,
114	STU300_EVENT_9
115};
116
117enum stu300_error {
118	STU300_ERROR_NONE = 0,
119	STU300_ERROR_ACKNOWLEDGE_FAILURE,
120	STU300_ERROR_BUS_ERROR,
121	STU300_ERROR_ARBITRATION_LOST,
122	STU300_ERROR_UNKNOWN
123};
124
125/* timeout waiting for the controller to respond */
126#define STU300_TIMEOUT (msecs_to_jiffies(1000))
127
128/*
129 * The number of address send athemps tried before giving up.
130 * If the first one failes it seems like 5 to 8 attempts are required.
131 */
132#define NUM_ADDR_RESEND_ATTEMPTS 12
133
134/* I2C clock speed, in Hz 0-400kHz*/
135static unsigned int scl_frequency = 100000;
136module_param(scl_frequency, uint,  0644);
137
138/**
139 * struct stu300_dev - the stu300 driver state holder
140 * @pdev: parent platform device
141 * @adapter: corresponding I2C adapter
142 * @phybase: location of I/O area in memory
143 * @physize: size of I/O area in memory
144 * @clk: hardware block clock
145 * @irq: assigned interrupt line
146 * @cmd_issue_lock: this locks the following cmd_ variables
147 * @cmd_complete: acknowledge completion for an I2C command
148 * @cmd_event: expected event coming in as a response to a command
149 * @cmd_err: error code as response to a command
150 * @speed: current bus speed in Hz
151 * @msg_index: index of current message
152 * @msg_len: length of current message
153 */
154
155struct stu300_dev {
156	struct platform_device	*pdev;
157	struct i2c_adapter	adapter;
158	resource_size_t		phybase;
159	resource_size_t		physize;
160	void __iomem		*virtbase;
161	struct clk		*clk;
162	int			irq;
163	spinlock_t		cmd_issue_lock;
164	struct completion	cmd_complete;
165	enum stu300_event	cmd_event;
166	enum stu300_error	cmd_err;
167	unsigned int		speed;
168	int			msg_index;
169	int			msg_len;
170};
171
172/* Local forward function declarations */
173static int stu300_init_hw(struct stu300_dev *dev);
174
175/*
176 * The block needs writes in both MSW and LSW in order
177 * for all data lines to reach their destination.
178 */
179static inline void stu300_wr8(u32 value, void __iomem *address)
180{
181	writel((value << 16) | value, address);
182}
183
184/*
185 * This merely masks off the duplicates which appear
186 * in bytes 1-3. You _MUST_ use 32-bit bus access on this
187 * device, else it will not work.
188 */
189static inline u32 stu300_r8(void __iomem *address)
190{
191	return readl(address) & 0x000000FFU;
192}
193
194static void stu300_irq_enable(struct stu300_dev *dev)
195{
196	u32 val;
197	val = stu300_r8(dev->virtbase + I2C_CR);
198	val |= I2C_CR_INTERRUPT_ENABLE;
199	/* Twice paranoia (possible HW glitch) */
200	stu300_wr8(val, dev->virtbase + I2C_CR);
201	stu300_wr8(val, dev->virtbase + I2C_CR);
202}
203
204static void stu300_irq_disable(struct stu300_dev *dev)
205{
206	u32 val;
207	val = stu300_r8(dev->virtbase + I2C_CR);
208	val &= ~I2C_CR_INTERRUPT_ENABLE;
209	/* Twice paranoia (possible HW glitch) */
210	stu300_wr8(val, dev->virtbase + I2C_CR);
211	stu300_wr8(val, dev->virtbase + I2C_CR);
212}
213
214
215/*
216 * Tells whether a certain event or events occurred in
217 * response to a command. The events represent states in
218 * the internal state machine of the hardware. The events
219 * are not very well described in the hardware
220 * documentation and can only be treated as abstract state
221 * machine states.
222 *
223 * @ret 0 = event has not occurred or unknown error, any
224 * other value means the correct event occurred or an error.
225 */
226
227static int stu300_event_occurred(struct stu300_dev *dev,
228				   enum stu300_event mr_event) {
229	u32 status1;
230	u32 status2;
231
232	/* What event happened? */
233	status1 = stu300_r8(dev->virtbase + I2C_SR1);
234
235	if (!(status1 & I2C_SR1_EVF_IND))
236		/* No event at all */
237		return 0;
238
239	status2 = stu300_r8(dev->virtbase + I2C_SR2);
240
241	/* Block any multiple interrupts */
242	stu300_irq_disable(dev);
243
244	/* Check for errors first */
245	if (status2 & I2C_SR2_AF_IND) {
246		dev->cmd_err = STU300_ERROR_ACKNOWLEDGE_FAILURE;
247		return 1;
248	} else if (status2 & I2C_SR2_BERR_IND) {
249		dev->cmd_err = STU300_ERROR_BUS_ERROR;
250		return 1;
251	} else if (status2 & I2C_SR2_ARLO_IND) {
252		dev->cmd_err = STU300_ERROR_ARBITRATION_LOST;
253		return 1;
254	}
255
256	switch (mr_event) {
257	case STU300_EVENT_1:
258		if (status1 & I2C_SR1_ADSL_IND)
259			return 1;
260		break;
261	case STU300_EVENT_2:
262	case STU300_EVENT_3:
263	case STU300_EVENT_7:
264	case STU300_EVENT_8:
265		if (status1 & I2C_SR1_BTF_IND) {
266			return 1;
267		}
268		break;
269	case STU300_EVENT_4:
270		if (status2 & I2C_SR2_STOPF_IND)
271			return 1;
272		break;
273	case STU300_EVENT_5:
274		if (status1 & I2C_SR1_SB_IND)
275			/* Clear start bit */
276			return 1;
277		break;
278	case STU300_EVENT_6:
279		if (status2 & I2C_SR2_ENDAD_IND) {
280			/* First check for any errors */
281			return 1;
282		}
283		break;
284	case STU300_EVENT_9:
285		if (status1 & I2C_SR1_ADD10_IND)
286			return 1;
287		break;
288	default:
289		break;
290	}
291	/* If we get here, we're on thin ice.
292	 * Here we are in a status where we have
293	 * gotten a response that does not match
294	 * what we requested.
295	 */
296	dev->cmd_err = STU300_ERROR_UNKNOWN;
297	dev_err(&dev->pdev->dev,
298		"Unhandled interrupt! %d sr1: 0x%x sr2: 0x%x\n",
299		mr_event, status1, status2);
300	return 0;
301}
302
303static irqreturn_t stu300_irh(int irq, void *data)
304{
305	struct stu300_dev *dev = data;
306	int res;
307
308	/* Just make sure that the block is clocked */
309	clk_enable(dev->clk);
310
311	/* See if this was what we were waiting for */
312	spin_lock(&dev->cmd_issue_lock);
313
314	res = stu300_event_occurred(dev, dev->cmd_event);
315	if (res || dev->cmd_err != STU300_ERROR_NONE)
316		complete(&dev->cmd_complete);
317
318	spin_unlock(&dev->cmd_issue_lock);
319
320	clk_disable(dev->clk);
321
322	return IRQ_HANDLED;
323}
324
325/*
326 * Sends a command and then waits for the bits masked by *flagmask*
327 * to go high or low by IRQ awaiting.
328 */
329static int stu300_start_and_await_event(struct stu300_dev *dev,
330					  u8 cr_value,
331					  enum stu300_event mr_event)
332{
333	int ret;
334
335	if (unlikely(irqs_disabled())) {
336		/* TODO: implement polling for this case if need be. */
337		WARN(1, "irqs are disabled, cannot poll for event\n");
338		return -EIO;
339	}
340
341	/* Lock command issue, fill in an event we wait for */
342	spin_lock_irq(&dev->cmd_issue_lock);
343	init_completion(&dev->cmd_complete);
344	dev->cmd_err = STU300_ERROR_NONE;
345	dev->cmd_event = mr_event;
346	spin_unlock_irq(&dev->cmd_issue_lock);
347
348	/* Turn on interrupt, send command and wait. */
349	cr_value |= I2C_CR_INTERRUPT_ENABLE;
350	stu300_wr8(cr_value, dev->virtbase + I2C_CR);
351	ret = wait_for_completion_interruptible_timeout(&dev->cmd_complete,
352							STU300_TIMEOUT);
353	if (ret < 0) {
354		dev_err(&dev->pdev->dev,
355		       "wait_for_completion_interruptible_timeout() "
356		       "returned %d waiting for event %04x\n", ret, mr_event);
357		return ret;
358	}
359
360	if (ret == 0) {
361		dev_err(&dev->pdev->dev, "controller timed out "
362		       "waiting for event %d, reinit hardware\n", mr_event);
363		(void) stu300_init_hw(dev);
364		return -ETIMEDOUT;
365	}
366
367	if (dev->cmd_err != STU300_ERROR_NONE) {
368		dev_err(&dev->pdev->dev, "controller (start) "
369		       "error %d waiting for event %d, reinit hardware\n",
370		       dev->cmd_err, mr_event);
371		(void) stu300_init_hw(dev);
372		return -EIO;
373	}
374
375	return 0;
376}
377
378/*
379 * This waits for a flag to be set, if it is not set on entry, an interrupt is
380 * configured to wait for the flag using a completion.
381 */
382static int stu300_await_event(struct stu300_dev *dev,
383				enum stu300_event mr_event)
384{
385	int ret;
386
387	if (unlikely(irqs_disabled())) {
388		/* TODO: implement polling for this case if need be. */
389		dev_err(&dev->pdev->dev, "irqs are disabled on this "
390			"system!\n");
391		return -EIO;
392	}
393
394	/* Is it already here? */
395	spin_lock_irq(&dev->cmd_issue_lock);
396	dev->cmd_err = STU300_ERROR_NONE;
397	dev->cmd_event = mr_event;
398
399	init_completion(&dev->cmd_complete);
400
401	/* Turn on the I2C interrupt for current operation */
402	stu300_irq_enable(dev);
403
404	/* Unlock the command block and wait for the event to occur */
405	spin_unlock_irq(&dev->cmd_issue_lock);
406
407	ret = wait_for_completion_interruptible_timeout(&dev->cmd_complete,
408							STU300_TIMEOUT);
409	if (ret < 0) {
410		dev_err(&dev->pdev->dev,
411		       "wait_for_completion_interruptible_timeout()"
412		       "returned %d waiting for event %04x\n", ret, mr_event);
413		return ret;
414	}
415
416	if (ret == 0) {
417		if (mr_event != STU300_EVENT_6) {
418			dev_err(&dev->pdev->dev, "controller "
419				"timed out waiting for event %d, reinit "
420				"hardware\n", mr_event);
421			(void) stu300_init_hw(dev);
422		}
423		return -ETIMEDOUT;
424	}
425
426	if (dev->cmd_err != STU300_ERROR_NONE) {
427		if (mr_event != STU300_EVENT_6) {
428			dev_err(&dev->pdev->dev, "controller "
429				"error (await_event) %d waiting for event %d, "
430			       "reinit hardware\n", dev->cmd_err, mr_event);
431			(void) stu300_init_hw(dev);
432		}
433		return -EIO;
434	}
435
436	return 0;
437}
438
439/*
440 * Waits for the busy bit to go low by repeated polling.
441 */
442#define BUSY_RELEASE_ATTEMPTS 10
443static int stu300_wait_while_busy(struct stu300_dev *dev)
444{
445	unsigned long timeout;
446	int i;
447
448	for (i = 0; i < BUSY_RELEASE_ATTEMPTS; i++) {
449		timeout = jiffies + STU300_TIMEOUT;
450
451		while (!time_after(jiffies, timeout)) {
452			/* Is not busy? */
453			if ((stu300_r8(dev->virtbase + I2C_SR1) &
454			     I2C_SR1_BUSY_IND) == 0)
455				return 0;
456			msleep(1);
457		}
458
459		dev_err(&dev->pdev->dev, "transaction timed out "
460			"waiting for device to be free (not busy). "
461		       "Attempt: %d\n", i+1);
462
463		dev_err(&dev->pdev->dev, "base address = "
464			"0x%08x, reinit hardware\n", (u32) dev->virtbase);
465
466		(void) stu300_init_hw(dev);
467	}
468
469	dev_err(&dev->pdev->dev, "giving up after %d attempts "
470		"to reset the bus.\n",  BUSY_RELEASE_ATTEMPTS);
471
472	return -ETIMEDOUT;
473}
474
475struct stu300_clkset {
476	unsigned long rate;
477	u32 setting;
478};
479
480static const struct stu300_clkset stu300_clktable[] = {
481	{ 0,         0xFFU },
482	{ 2500000,   I2C_OAR2_FR_25_10MHZ },
483	{ 10000000,  I2C_OAR2_FR_10_1667MHZ },
484	{ 16670000,  I2C_OAR2_FR_1667_2667MHZ },
485	{ 26670000,  I2C_OAR2_FR_2667_40MHZ },
486	{ 40000000,  I2C_OAR2_FR_40_5333MHZ },
487	{ 53330000,  I2C_OAR2_FR_5333_66MHZ },
488	{ 66000000,  I2C_OAR2_FR_66_80MHZ },
489	{ 80000000,  I2C_OAR2_FR_80_100MHZ },
490	{ 100000000, 0xFFU },
491};
492
493
494static int stu300_set_clk(struct stu300_dev *dev, unsigned long clkrate)
495{
496
497	u32 val;
498	int i = 0;
499
500	/* Locate the appropriate clock setting */
501	while (i < ARRAY_SIZE(stu300_clktable) - 1 &&
502	       stu300_clktable[i].rate < clkrate)
503		i++;
504
505	if (stu300_clktable[i].setting == 0xFFU) {
506		dev_err(&dev->pdev->dev, "too %s clock rate requested "
507			"(%lu Hz).\n", i ? "high" : "low", clkrate);
508		return -EINVAL;
509	}
510
511	stu300_wr8(stu300_clktable[i].setting,
512		   dev->virtbase + I2C_OAR2);
513
514	dev_dbg(&dev->pdev->dev, "Clock rate %lu Hz, I2C bus speed %d Hz "
515		"virtbase %p\n", clkrate, dev->speed, dev->virtbase);
516
517	if (dev->speed > 100000)
518		/* Fast Mode I2C */
519		val = ((clkrate/dev->speed) - 9)/3 + 1;
520	else
521		/* Standard Mode I2C */
522		val = ((clkrate/dev->speed) - 7)/2 + 1;
523
524	/* According to spec the divider must be > 2 */
525	if (val < 0x002) {
526		dev_err(&dev->pdev->dev, "too low clock rate (%lu Hz).\n",
527			clkrate);
528		return -EINVAL;
529	}
530
531	/* We have 12 bits clock divider only! */
532	if (val & 0xFFFFF000U) {
533		dev_err(&dev->pdev->dev, "too high clock rate (%lu Hz).\n",
534			clkrate);
535		return -EINVAL;
536	}
537
538	if (dev->speed > 100000) {
539		/* CC6..CC0 */
540		stu300_wr8((val & I2C_CCR_CC_MASK) | I2C_CCR_FMSM,
541			   dev->virtbase + I2C_CCR);
542		dev_dbg(&dev->pdev->dev, "set clock divider to 0x%08x, "
543			"Fast Mode I2C\n", val);
544	} else {
545		/* CC6..CC0 */
546		stu300_wr8((val & I2C_CCR_CC_MASK),
547			   dev->virtbase + I2C_CCR);
548		dev_dbg(&dev->pdev->dev, "set clock divider to "
549			"0x%08x, Standard Mode I2C\n", val);
550	}
551
552	/* CC11..CC7 */
553	stu300_wr8(((val >> 7) & 0x1F),
554		   dev->virtbase + I2C_ECCR);
555
556	return 0;
557}
558
559
560static int stu300_init_hw(struct stu300_dev *dev)
561{
562	u32 dummy;
563	unsigned long clkrate;
564	int ret;
565
566	/* Disable controller */
567	stu300_wr8(0x00, dev->virtbase + I2C_CR);
568	/*
569	 * Set own address to some default value (0x00).
570	 * We do not support slave mode anyway.
571	 */
572	stu300_wr8(0x00, dev->virtbase + I2C_OAR1);
573	/*
574	 * The I2C controller only operates properly in 26 MHz but we
575	 * program this driver as if we didn't know. This will also set the two
576	 * high bits of the own address to zero as well.
577	 * There is no known hardware issue with running in 13 MHz
578	 * However, speeds over 200 kHz are not used.
579	 */
580	clkrate = clk_get_rate(dev->clk);
581	ret = stu300_set_clk(dev, clkrate);
582
583	if (ret)
584		return ret;
585	/*
586	 * Enable block, do it TWICE (hardware glitch)
587	 * Setting bit 7 can enable DDC mode. (Not used currently.)
588	 */
589	stu300_wr8(I2C_CR_PERIPHERAL_ENABLE,
590				  dev->virtbase + I2C_CR);
591	stu300_wr8(I2C_CR_PERIPHERAL_ENABLE,
592				  dev->virtbase + I2C_CR);
593	/* Make a dummy read of the status register SR1 & SR2 */
594	dummy = stu300_r8(dev->virtbase + I2C_SR2);
595	dummy = stu300_r8(dev->virtbase + I2C_SR1);
596
597	return 0;
598}
599
600
601
602/* Send slave address. */
603static int stu300_send_address(struct stu300_dev *dev,
604				 struct i2c_msg *msg, int resend)
605{
606	u32 val;
607	int ret;
608
609	if (msg->flags & I2C_M_TEN)
610		/* This is probably how 10 bit addresses look */
611		val = (0xf0 | (((u32) msg->addr & 0x300) >> 7)) &
612			I2C_DR_D_MASK;
613	else
614		val = ((msg->addr << 1) & I2C_DR_D_MASK);
615
616	if (msg->flags & I2C_M_RD) {
617		/* This is the direction bit */
618		val |= 0x01;
619		if (resend)
620			dev_dbg(&dev->pdev->dev, "read resend\n");
621	} else if (resend)
622		dev_dbg(&dev->pdev->dev, "write resend\n");
623	stu300_wr8(val, dev->virtbase + I2C_DR);
624
625	/* For 10bit addressing, await 10bit request (EVENT 9) */
626	if (msg->flags & I2C_M_TEN) {
627		ret = stu300_await_event(dev, STU300_EVENT_9);
628		/*
629		 * The slave device wants a 10bit address, send the rest
630		 * of the bits (the LSBits)
631		 */
632		val = msg->addr & I2C_DR_D_MASK;
633		/* This clears "event 9" */
634		stu300_wr8(val, dev->virtbase + I2C_DR);
635		if (ret != 0)
636			return ret;
637	}
638	/* FIXME: Why no else here? two events for 10bit?
639	 * Await event 6 (normal) or event 9 (10bit)
640	 */
641
642	if (resend)
643		dev_dbg(&dev->pdev->dev, "await event 6\n");
644	ret = stu300_await_event(dev, STU300_EVENT_6);
645
646	/*
647	 * Clear any pending EVENT 6 no matter what happened during
648	 * await_event.
649	 */
650	val = stu300_r8(dev->virtbase + I2C_CR);
651	val |= I2C_CR_PERIPHERAL_ENABLE;
652	stu300_wr8(val, dev->virtbase + I2C_CR);
653
654	return ret;
655}
656
657static int stu300_xfer_msg(struct i2c_adapter *adap,
658			     struct i2c_msg *msg, int stop)
659{
660	u32 cr;
661	u32 val;
662	u32 i;
663	int ret;
664	int attempts = 0;
665	struct stu300_dev *dev = i2c_get_adapdata(adap);
666
667	clk_enable(dev->clk);
668
669	/* Remove this if (0) to trace each and every message. */
670	if (0) {
671		dev_dbg(&dev->pdev->dev, "I2C message to: 0x%04x, len: %d, "
672			"flags: 0x%04x, stop: %d\n",
673			msg->addr, msg->len, msg->flags, stop);
674	}
675
676	/* Zero-length messages are not supported by this hardware */
677	if (msg->len == 0) {
678		ret = -EINVAL;
679		goto exit_disable;
680	}
681
682	/*
683	 * For some reason, sending the address sometimes fails when running
684	 * on  the 13 MHz clock. No interrupt arrives. This is a work around,
685	 * which tries to restart and send the address up to 10 times before
686	 * really giving up. Usually 5 to 8 attempts are enough.
687	 */
688	do {
689		if (attempts)
690			dev_dbg(&dev->pdev->dev, "wait while busy\n");
691		/* Check that the bus is free, or wait until some timeout */
692		ret = stu300_wait_while_busy(dev);
693		if (ret != 0)
694			goto exit_disable;
695
696		if (attempts)
697			dev_dbg(&dev->pdev->dev, "re-int hw\n");
698		/*
699		 * According to ST, there is no problem if the clock is
700		 * changed between 13 and 26 MHz during a transfer.
701		 */
702		ret = stu300_init_hw(dev);
703		if (ret)
704			goto exit_disable;
705
706		/* Send a start condition */
707		cr = I2C_CR_PERIPHERAL_ENABLE;
708		/* Setting the START bit puts the block in master mode */
709		if (!(msg->flags & I2C_M_NOSTART))
710			cr |= I2C_CR_START_ENABLE;
711		if ((msg->flags & I2C_M_RD) && (msg->len > 1))
712			/* On read more than 1 byte, we need ack. */
713			cr |= I2C_CR_ACK_ENABLE;
714		/* Check that it gets through */
715		if (!(msg->flags & I2C_M_NOSTART)) {
716			if (attempts)
717				dev_dbg(&dev->pdev->dev, "send start event\n");
718			ret = stu300_start_and_await_event(dev, cr,
719							     STU300_EVENT_5);
720		}
721
722		if (attempts)
723			dev_dbg(&dev->pdev->dev, "send address\n");
724
725		if (ret == 0)
726			/* Send address */
727			ret = stu300_send_address(dev, msg, attempts != 0);
728
729		if (ret != 0) {
730			attempts++;
731			dev_dbg(&dev->pdev->dev, "failed sending address, "
732				"retrying. Attempt: %d msg_index: %d/%d\n",
733			       attempts, dev->msg_index, dev->msg_len);
734		}
735
736	} while (ret != 0 && attempts < NUM_ADDR_RESEND_ATTEMPTS);
737
738	if (attempts < NUM_ADDR_RESEND_ATTEMPTS && attempts > 0) {
739		dev_dbg(&dev->pdev->dev, "managed to get address "
740			"through after %d attempts\n", attempts);
741	} else if (attempts == NUM_ADDR_RESEND_ATTEMPTS) {
742		dev_dbg(&dev->pdev->dev, "I give up, tried %d times "
743			"to resend address.\n",
744			NUM_ADDR_RESEND_ATTEMPTS);
745		goto exit_disable;
746	}
747
748
749	if (msg->flags & I2C_M_RD) {
750		/* READ: we read the actual bytes one at a time */
751		for (i = 0; i < msg->len; i++) {
752			if (i == msg->len-1) {
753				/*
754				 * Disable ACK and set STOP condition before
755				 * reading last byte
756				 */
757				val = I2C_CR_PERIPHERAL_ENABLE;
758
759				if (stop)
760					val |= I2C_CR_STOP_ENABLE;
761
762				stu300_wr8(val,
763					   dev->virtbase + I2C_CR);
764			}
765			/* Wait for this byte... */
766			ret = stu300_await_event(dev, STU300_EVENT_7);
767			if (ret != 0)
768				goto exit_disable;
769			/* This clears event 7 */
770			msg->buf[i] = (u8) stu300_r8(dev->virtbase + I2C_DR);
771		}
772	} else {
773		/* WRITE: we send the actual bytes one at a time */
774		for (i = 0; i < msg->len; i++) {
775			/* Write the byte */
776			stu300_wr8(msg->buf[i],
777				   dev->virtbase + I2C_DR);
778			/* Check status */
779			ret = stu300_await_event(dev, STU300_EVENT_8);
780			/* Next write to DR will clear event 8 */
781			if (ret != 0) {
782				dev_err(&dev->pdev->dev, "error awaiting "
783				       "event 8 (%d)\n", ret);
784				goto exit_disable;
785			}
786		}
787		/* Check NAK */
788		if (!(msg->flags & I2C_M_IGNORE_NAK)) {
789			if (stu300_r8(dev->virtbase + I2C_SR2) &
790			    I2C_SR2_AF_IND) {
791				dev_err(&dev->pdev->dev, "I2C payload "
792				       "send returned NAK!\n");
793				ret = -EIO;
794				goto exit_disable;
795			}
796		}
797		if (stop) {
798			/* Send stop condition */
799			val = I2C_CR_PERIPHERAL_ENABLE;
800			val |= I2C_CR_STOP_ENABLE;
801			stu300_wr8(val, dev->virtbase + I2C_CR);
802		}
803	}
804
805	/* Check that the bus is free, or wait until some timeout occurs */
806	ret = stu300_wait_while_busy(dev);
807	if (ret != 0) {
808		dev_err(&dev->pdev->dev, "timout waiting for transfer "
809		       "to commence.\n");
810		goto exit_disable;
811	}
812
813	/* Dummy read status registers */
814	val = stu300_r8(dev->virtbase + I2C_SR2);
815	val = stu300_r8(dev->virtbase + I2C_SR1);
816	ret = 0;
817
818 exit_disable:
819	/* Disable controller */
820	stu300_wr8(0x00, dev->virtbase + I2C_CR);
821	clk_disable(dev->clk);
822	return ret;
823}
824
825static int stu300_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
826			 int num)
827{
828	int ret = -1;
829	int i;
830
831	struct stu300_dev *dev = i2c_get_adapdata(adap);
832	dev->msg_len = num;
833
834	for (i = 0; i < num; i++) {
835		/*
836		 * Another driver appears to send stop for each message,
837		 * here we only do that for the last message. Possibly some
838		 * peripherals require this behaviour, then their drivers
839		 * have to send single messages in order to get "stop" for
840		 * each message.
841		 */
842		dev->msg_index = i;
843
844		ret = stu300_xfer_msg(adap, &msgs[i], (i == (num - 1)));
845
846		if (ret != 0) {
847			num = ret;
848			break;
849		}
850	}
851
852	return num;
853}
854
855static u32 stu300_func(struct i2c_adapter *adap)
856{
857	/* This is the simplest thing you can think of... */
858	return I2C_FUNC_I2C | I2C_FUNC_10BIT_ADDR;
859}
860
861static const struct i2c_algorithm stu300_algo = {
862	.master_xfer	= stu300_xfer,
863	.functionality	= stu300_func,
864};
865
866static int __init
867stu300_probe(struct platform_device *pdev)
868{
869	struct stu300_dev *dev;
870	struct i2c_adapter *adap;
871	struct resource *res;
872	int bus_nr;
873	int ret = 0;
874	char clk_name[] = "I2C0";
875
876	dev = kzalloc(sizeof(struct stu300_dev), GFP_KERNEL);
877	if (!dev) {
878		dev_err(&pdev->dev, "could not allocate device struct\n");
879		ret = -ENOMEM;
880		goto err_no_devmem;
881	}
882
883	bus_nr = pdev->id;
884	clk_name[3] += (char)bus_nr;
885	dev->clk = clk_get(&pdev->dev, clk_name);
886	if (IS_ERR(dev->clk)) {
887		ret = PTR_ERR(dev->clk);
888		dev_err(&pdev->dev, "could not retrieve i2c bus clock\n");
889		goto err_no_clk;
890	}
891
892	dev->pdev = pdev;
893	platform_set_drvdata(pdev, dev);
894
895	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
896	if (!res) {
897		ret = -ENOENT;
898		goto err_no_resource;
899	}
900
901	dev->phybase = res->start;
902	dev->physize = resource_size(res);
903
904	if (request_mem_region(dev->phybase, dev->physize,
905			       NAME " I/O Area") == NULL) {
906		ret = -EBUSY;
907		goto err_no_ioregion;
908	}
909
910	dev->virtbase = ioremap(dev->phybase, dev->physize);
911	dev_dbg(&pdev->dev, "initialize bus device I2C%d on virtual "
912		"base %p\n", bus_nr, dev->virtbase);
913	if (!dev->virtbase) {
914		ret = -ENOMEM;
915		goto err_no_ioremap;
916	}
917
918	dev->irq = platform_get_irq(pdev, 0);
919	if (request_irq(dev->irq, stu300_irh, 0,
920			NAME, dev)) {
921		ret = -EIO;
922		goto err_no_irq;
923	}
924
925	dev->speed = scl_frequency;
926
927	clk_enable(dev->clk);
928	ret = stu300_init_hw(dev);
929	clk_disable(dev->clk);
930
931	if (ret != 0) {
932		dev_err(&dev->pdev->dev, "error initializing hardware.\n");
933		goto err_init_hw;
934	}
935
936	/* IRQ event handling initialization */
937	spin_lock_init(&dev->cmd_issue_lock);
938	dev->cmd_event = STU300_EVENT_NONE;
939	dev->cmd_err = STU300_ERROR_NONE;
940
941	adap = &dev->adapter;
942	adap->owner = THIS_MODULE;
943	/* DDC class but actually often used for more generic I2C */
944	adap->class = I2C_CLASS_DDC;
945	strlcpy(adap->name, "ST Microelectronics DDC I2C adapter",
946		sizeof(adap->name));
947	adap->nr = bus_nr;
948	adap->algo = &stu300_algo;
949	adap->dev.parent = &pdev->dev;
950	i2c_set_adapdata(adap, dev);
951
952	/* i2c device drivers may be active on return from add_adapter() */
953	ret = i2c_add_numbered_adapter(adap);
954	if (ret) {
955		dev_err(&dev->pdev->dev, "failure adding ST Micro DDC "
956		       "I2C adapter\n");
957		goto err_add_adapter;
958	}
959	return 0;
960
961 err_add_adapter:
962 err_init_hw:
963	free_irq(dev->irq, dev);
964 err_no_irq:
965	iounmap(dev->virtbase);
966 err_no_ioremap:
967	release_mem_region(dev->phybase, dev->physize);
968 err_no_ioregion:
969	platform_set_drvdata(pdev, NULL);
970 err_no_resource:
971	clk_put(dev->clk);
972 err_no_clk:
973	kfree(dev);
974 err_no_devmem:
975	dev_err(&pdev->dev, "failed to add " NAME " adapter: %d\n",
976		pdev->id);
977	return ret;
978}
979
980#ifdef CONFIG_PM
981static int stu300_suspend(struct platform_device *pdev, pm_message_t state)
982{
983	struct stu300_dev *dev = platform_get_drvdata(pdev);
984
985	/* Turn off everything */
986	stu300_wr8(0x00, dev->virtbase + I2C_CR);
987	return 0;
988}
989
990static int stu300_resume(struct platform_device *pdev)
991{
992	int ret = 0;
993	struct stu300_dev *dev = platform_get_drvdata(pdev);
994
995	clk_enable(dev->clk);
996	ret = stu300_init_hw(dev);
997	clk_disable(dev->clk);
998
999	if (ret != 0)
1000		dev_err(&pdev->dev, "error re-initializing hardware.\n");
1001	return ret;
1002}
1003#else
1004#define stu300_suspend NULL
1005#define stu300_resume NULL
1006#endif
1007
1008static int __exit
1009stu300_remove(struct platform_device *pdev)
1010{
1011	struct stu300_dev *dev = platform_get_drvdata(pdev);
1012
1013	i2c_del_adapter(&dev->adapter);
1014	/* Turn off everything */
1015	stu300_wr8(0x00, dev->virtbase + I2C_CR);
1016	free_irq(dev->irq, dev);
1017	iounmap(dev->virtbase);
1018	release_mem_region(dev->phybase, dev->physize);
1019	clk_put(dev->clk);
1020	platform_set_drvdata(pdev, NULL);
1021	kfree(dev);
1022	return 0;
1023}
1024
1025static struct platform_driver stu300_i2c_driver = {
1026	.driver = {
1027		.name	= NAME,
1028		.owner	= THIS_MODULE,
1029	},
1030	.remove		= __exit_p(stu300_remove),
1031	.suspend        = stu300_suspend,
1032	.resume         = stu300_resume,
1033
1034};
1035
1036static int __init stu300_init(void)
1037{
1038	return platform_driver_probe(&stu300_i2c_driver, stu300_probe);
1039}
1040
1041static void __exit stu300_exit(void)
1042{
1043	platform_driver_unregister(&stu300_i2c_driver);
1044}
1045
1046/*
1047 * The systems using this bus often have very basic devices such
1048 * as regulators on the I2C bus, so this needs to be loaded early.
1049 * Therefore it is registered in the subsys_initcall().
1050 */
1051subsys_initcall(stu300_init);
1052module_exit(stu300_exit);
1053
1054MODULE_AUTHOR("Linus Walleij <linus.walleij@stericsson.com>");
1055MODULE_DESCRIPTION("ST Micro DDC I2C adapter (" NAME ")");
1056MODULE_LICENSE("GPL");
1057MODULE_ALIAS("platform:" NAME);
1058