Merge tag 'spi-v4.8' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/spi
[sfrench/cifs-2.6.git] / drivers / i2c / busses / i2c-rk3x.c
1 /*
2  * Driver for I2C adapter in Rockchip RK3xxx SoC
3  *
4  * Max Schwarz <max.schwarz@online.de>
5  * based on the patches by Rockchip Inc.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/i2c.h>
15 #include <linux/interrupt.h>
16 #include <linux/errno.h>
17 #include <linux/err.h>
18 #include <linux/platform_device.h>
19 #include <linux/io.h>
20 #include <linux/of_address.h>
21 #include <linux/of_irq.h>
22 #include <linux/spinlock.h>
23 #include <linux/clk.h>
24 #include <linux/wait.h>
25 #include <linux/mfd/syscon.h>
26 #include <linux/regmap.h>
27 #include <linux/math64.h>
28
29
30 /* Register Map */
31 #define REG_CON        0x00 /* control register */
32 #define REG_CLKDIV     0x04 /* clock divisor register */
33 #define REG_MRXADDR    0x08 /* slave address for REGISTER_TX */
34 #define REG_MRXRADDR   0x0c /* slave register address for REGISTER_TX */
35 #define REG_MTXCNT     0x10 /* number of bytes to be transmitted */
36 #define REG_MRXCNT     0x14 /* number of bytes to be received */
37 #define REG_IEN        0x18 /* interrupt enable */
38 #define REG_IPD        0x1c /* interrupt pending */
39 #define REG_FCNT       0x20 /* finished count */
40
41 /* Data buffer offsets */
42 #define TXBUFFER_BASE 0x100
43 #define RXBUFFER_BASE 0x200
44
45 /* REG_CON bits */
46 #define REG_CON_EN        BIT(0)
47 enum {
48         REG_CON_MOD_TX = 0,      /* transmit data */
49         REG_CON_MOD_REGISTER_TX, /* select register and restart */
50         REG_CON_MOD_RX,          /* receive data */
51         REG_CON_MOD_REGISTER_RX, /* broken: transmits read addr AND writes
52                                   * register addr */
53 };
54 #define REG_CON_MOD(mod)  ((mod) << 1)
55 #define REG_CON_MOD_MASK  (BIT(1) | BIT(2))
56 #define REG_CON_START     BIT(3)
57 #define REG_CON_STOP      BIT(4)
58 #define REG_CON_LASTACK   BIT(5) /* 1: send NACK after last received byte */
59 #define REG_CON_ACTACK    BIT(6) /* 1: stop if NACK is received */
60
61 /* REG_MRXADDR bits */
62 #define REG_MRXADDR_VALID(x) BIT(24 + (x)) /* [x*8+7:x*8] of MRX[R]ADDR valid */
63
64 /* REG_IEN/REG_IPD bits */
65 #define REG_INT_BTF       BIT(0) /* a byte was transmitted */
66 #define REG_INT_BRF       BIT(1) /* a byte was received */
67 #define REG_INT_MBTF      BIT(2) /* master data transmit finished */
68 #define REG_INT_MBRF      BIT(3) /* master data receive finished */
69 #define REG_INT_START     BIT(4) /* START condition generated */
70 #define REG_INT_STOP      BIT(5) /* STOP condition generated */
71 #define REG_INT_NAKRCV    BIT(6) /* NACK received */
72 #define REG_INT_ALL       0x7f
73
74 /* Constants */
75 #define WAIT_TIMEOUT      1000 /* ms */
76 #define DEFAULT_SCL_RATE  (100 * 1000) /* Hz */
77
78 enum rk3x_i2c_state {
79         STATE_IDLE,
80         STATE_START,
81         STATE_READ,
82         STATE_WRITE,
83         STATE_STOP
84 };
85
86 /**
87  * @grf_offset: offset inside the grf regmap for setting the i2c type
88  */
89 struct rk3x_i2c_soc_data {
90         int grf_offset;
91 };
92
93 struct rk3x_i2c {
94         struct i2c_adapter adap;
95         struct device *dev;
96         struct rk3x_i2c_soc_data *soc_data;
97
98         /* Hardware resources */
99         void __iomem *regs;
100         struct clk *clk;
101         struct notifier_block clk_rate_nb;
102
103         /* Settings */
104         struct i2c_timings t;
105
106         /* Synchronization & notification */
107         spinlock_t lock;
108         wait_queue_head_t wait;
109         bool busy;
110
111         /* Current message */
112         struct i2c_msg *msg;
113         u8 addr;
114         unsigned int mode;
115         bool is_last_msg;
116
117         /* I2C state machine */
118         enum rk3x_i2c_state state;
119         unsigned int processed; /* sent/received bytes */
120         int error;
121 };
122
123 static inline void i2c_writel(struct rk3x_i2c *i2c, u32 value,
124                               unsigned int offset)
125 {
126         writel(value, i2c->regs + offset);
127 }
128
129 static inline u32 i2c_readl(struct rk3x_i2c *i2c, unsigned int offset)
130 {
131         return readl(i2c->regs + offset);
132 }
133
134 /* Reset all interrupt pending bits */
135 static inline void rk3x_i2c_clean_ipd(struct rk3x_i2c *i2c)
136 {
137         i2c_writel(i2c, REG_INT_ALL, REG_IPD);
138 }
139
140 /**
141  * Generate a START condition, which triggers a REG_INT_START interrupt.
142  */
143 static void rk3x_i2c_start(struct rk3x_i2c *i2c)
144 {
145         u32 val;
146
147         rk3x_i2c_clean_ipd(i2c);
148         i2c_writel(i2c, REG_INT_START, REG_IEN);
149
150         /* enable adapter with correct mode, send START condition */
151         val = REG_CON_EN | REG_CON_MOD(i2c->mode) | REG_CON_START;
152
153         /* if we want to react to NACK, set ACTACK bit */
154         if (!(i2c->msg->flags & I2C_M_IGNORE_NAK))
155                 val |= REG_CON_ACTACK;
156
157         i2c_writel(i2c, val, REG_CON);
158 }
159
160 /**
161  * Generate a STOP condition, which triggers a REG_INT_STOP interrupt.
162  *
163  * @error: Error code to return in rk3x_i2c_xfer
164  */
165 static void rk3x_i2c_stop(struct rk3x_i2c *i2c, int error)
166 {
167         unsigned int ctrl;
168
169         i2c->processed = 0;
170         i2c->msg = NULL;
171         i2c->error = error;
172
173         if (i2c->is_last_msg) {
174                 /* Enable stop interrupt */
175                 i2c_writel(i2c, REG_INT_STOP, REG_IEN);
176
177                 i2c->state = STATE_STOP;
178
179                 ctrl = i2c_readl(i2c, REG_CON);
180                 ctrl |= REG_CON_STOP;
181                 i2c_writel(i2c, ctrl, REG_CON);
182         } else {
183                 /* Signal rk3x_i2c_xfer to start the next message. */
184                 i2c->busy = false;
185                 i2c->state = STATE_IDLE;
186
187                 /*
188                  * The HW is actually not capable of REPEATED START. But we can
189                  * get the intended effect by resetting its internal state
190                  * and issuing an ordinary START.
191                  */
192                 i2c_writel(i2c, 0, REG_CON);
193
194                 /* signal that we are finished with the current msg */
195                 wake_up(&i2c->wait);
196         }
197 }
198
199 /**
200  * Setup a read according to i2c->msg
201  */
202 static void rk3x_i2c_prepare_read(struct rk3x_i2c *i2c)
203 {
204         unsigned int len = i2c->msg->len - i2c->processed;
205         u32 con;
206
207         con = i2c_readl(i2c, REG_CON);
208
209         /*
210          * The hw can read up to 32 bytes at a time. If we need more than one
211          * chunk, send an ACK after the last byte of the current chunk.
212          */
213         if (len > 32) {
214                 len = 32;
215                 con &= ~REG_CON_LASTACK;
216         } else {
217                 con |= REG_CON_LASTACK;
218         }
219
220         /* make sure we are in plain RX mode if we read a second chunk */
221         if (i2c->processed != 0) {
222                 con &= ~REG_CON_MOD_MASK;
223                 con |= REG_CON_MOD(REG_CON_MOD_RX);
224         }
225
226         i2c_writel(i2c, con, REG_CON);
227         i2c_writel(i2c, len, REG_MRXCNT);
228 }
229
230 /**
231  * Fill the transmit buffer with data from i2c->msg
232  */
233 static void rk3x_i2c_fill_transmit_buf(struct rk3x_i2c *i2c)
234 {
235         unsigned int i, j;
236         u32 cnt = 0;
237         u32 val;
238         u8 byte;
239
240         for (i = 0; i < 8; ++i) {
241                 val = 0;
242                 for (j = 0; j < 4; ++j) {
243                         if ((i2c->processed == i2c->msg->len) && (cnt != 0))
244                                 break;
245
246                         if (i2c->processed == 0 && cnt == 0)
247                                 byte = (i2c->addr & 0x7f) << 1;
248                         else
249                                 byte = i2c->msg->buf[i2c->processed++];
250
251                         val |= byte << (j * 8);
252                         cnt++;
253                 }
254
255                 i2c_writel(i2c, val, TXBUFFER_BASE + 4 * i);
256
257                 if (i2c->processed == i2c->msg->len)
258                         break;
259         }
260
261         i2c_writel(i2c, cnt, REG_MTXCNT);
262 }
263
264
265 /* IRQ handlers for individual states */
266
267 static void rk3x_i2c_handle_start(struct rk3x_i2c *i2c, unsigned int ipd)
268 {
269         if (!(ipd & REG_INT_START)) {
270                 rk3x_i2c_stop(i2c, -EIO);
271                 dev_warn(i2c->dev, "unexpected irq in START: 0x%x\n", ipd);
272                 rk3x_i2c_clean_ipd(i2c);
273                 return;
274         }
275
276         /* ack interrupt */
277         i2c_writel(i2c, REG_INT_START, REG_IPD);
278
279         /* disable start bit */
280         i2c_writel(i2c, i2c_readl(i2c, REG_CON) & ~REG_CON_START, REG_CON);
281
282         /* enable appropriate interrupts and transition */
283         if (i2c->mode == REG_CON_MOD_TX) {
284                 i2c_writel(i2c, REG_INT_MBTF | REG_INT_NAKRCV, REG_IEN);
285                 i2c->state = STATE_WRITE;
286                 rk3x_i2c_fill_transmit_buf(i2c);
287         } else {
288                 /* in any other case, we are going to be reading. */
289                 i2c_writel(i2c, REG_INT_MBRF | REG_INT_NAKRCV, REG_IEN);
290                 i2c->state = STATE_READ;
291                 rk3x_i2c_prepare_read(i2c);
292         }
293 }
294
295 static void rk3x_i2c_handle_write(struct rk3x_i2c *i2c, unsigned int ipd)
296 {
297         if (!(ipd & REG_INT_MBTF)) {
298                 rk3x_i2c_stop(i2c, -EIO);
299                 dev_err(i2c->dev, "unexpected irq in WRITE: 0x%x\n", ipd);
300                 rk3x_i2c_clean_ipd(i2c);
301                 return;
302         }
303
304         /* ack interrupt */
305         i2c_writel(i2c, REG_INT_MBTF, REG_IPD);
306
307         /* are we finished? */
308         if (i2c->processed == i2c->msg->len)
309                 rk3x_i2c_stop(i2c, i2c->error);
310         else
311                 rk3x_i2c_fill_transmit_buf(i2c);
312 }
313
314 static void rk3x_i2c_handle_read(struct rk3x_i2c *i2c, unsigned int ipd)
315 {
316         unsigned int i;
317         unsigned int len = i2c->msg->len - i2c->processed;
318         u32 uninitialized_var(val);
319         u8 byte;
320
321         /* we only care for MBRF here. */
322         if (!(ipd & REG_INT_MBRF))
323                 return;
324
325         /* ack interrupt */
326         i2c_writel(i2c, REG_INT_MBRF, REG_IPD);
327
328         /* Can only handle a maximum of 32 bytes at a time */
329         if (len > 32)
330                 len = 32;
331
332         /* read the data from receive buffer */
333         for (i = 0; i < len; ++i) {
334                 if (i % 4 == 0)
335                         val = i2c_readl(i2c, RXBUFFER_BASE + (i / 4) * 4);
336
337                 byte = (val >> ((i % 4) * 8)) & 0xff;
338                 i2c->msg->buf[i2c->processed++] = byte;
339         }
340
341         /* are we finished? */
342         if (i2c->processed == i2c->msg->len)
343                 rk3x_i2c_stop(i2c, i2c->error);
344         else
345                 rk3x_i2c_prepare_read(i2c);
346 }
347
348 static void rk3x_i2c_handle_stop(struct rk3x_i2c *i2c, unsigned int ipd)
349 {
350         unsigned int con;
351
352         if (!(ipd & REG_INT_STOP)) {
353                 rk3x_i2c_stop(i2c, -EIO);
354                 dev_err(i2c->dev, "unexpected irq in STOP: 0x%x\n", ipd);
355                 rk3x_i2c_clean_ipd(i2c);
356                 return;
357         }
358
359         /* ack interrupt */
360         i2c_writel(i2c, REG_INT_STOP, REG_IPD);
361
362         /* disable STOP bit */
363         con = i2c_readl(i2c, REG_CON);
364         con &= ~REG_CON_STOP;
365         i2c_writel(i2c, con, REG_CON);
366
367         i2c->busy = false;
368         i2c->state = STATE_IDLE;
369
370         /* signal rk3x_i2c_xfer that we are finished */
371         wake_up(&i2c->wait);
372 }
373
374 static irqreturn_t rk3x_i2c_irq(int irqno, void *dev_id)
375 {
376         struct rk3x_i2c *i2c = dev_id;
377         unsigned int ipd;
378
379         spin_lock(&i2c->lock);
380
381         ipd = i2c_readl(i2c, REG_IPD);
382         if (i2c->state == STATE_IDLE) {
383                 dev_warn(i2c->dev, "irq in STATE_IDLE, ipd = 0x%x\n", ipd);
384                 rk3x_i2c_clean_ipd(i2c);
385                 goto out;
386         }
387
388         dev_dbg(i2c->dev, "IRQ: state %d, ipd: %x\n", i2c->state, ipd);
389
390         /* Clean interrupt bits we don't care about */
391         ipd &= ~(REG_INT_BRF | REG_INT_BTF);
392
393         if (ipd & REG_INT_NAKRCV) {
394                 /*
395                  * We got a NACK in the last operation. Depending on whether
396                  * IGNORE_NAK is set, we have to stop the operation and report
397                  * an error.
398                  */
399                 i2c_writel(i2c, REG_INT_NAKRCV, REG_IPD);
400
401                 ipd &= ~REG_INT_NAKRCV;
402
403                 if (!(i2c->msg->flags & I2C_M_IGNORE_NAK))
404                         rk3x_i2c_stop(i2c, -ENXIO);
405         }
406
407         /* is there anything left to handle? */
408         if ((ipd & REG_INT_ALL) == 0)
409                 goto out;
410
411         switch (i2c->state) {
412         case STATE_START:
413                 rk3x_i2c_handle_start(i2c, ipd);
414                 break;
415         case STATE_WRITE:
416                 rk3x_i2c_handle_write(i2c, ipd);
417                 break;
418         case STATE_READ:
419                 rk3x_i2c_handle_read(i2c, ipd);
420                 break;
421         case STATE_STOP:
422                 rk3x_i2c_handle_stop(i2c, ipd);
423                 break;
424         case STATE_IDLE:
425                 break;
426         }
427
428 out:
429         spin_unlock(&i2c->lock);
430         return IRQ_HANDLED;
431 }
432
433 /**
434  * Calculate divider values for desired SCL frequency
435  *
436  * @clk_rate: I2C input clock rate
437  * @t: Known I2C timing information.
438  * @div_low: Divider output for low
439  * @div_high: Divider output for high
440  *
441  * Returns: 0 on success, -EINVAL if the goal SCL rate is too slow. In that case
442  * a best-effort divider value is returned in divs. If the target rate is
443  * too high, we silently use the highest possible rate.
444  */
445 static int rk3x_i2c_calc_divs(unsigned long clk_rate,
446                               struct i2c_timings *t,
447                               unsigned long *div_low,
448                               unsigned long *div_high)
449 {
450         unsigned long spec_min_low_ns, spec_min_high_ns;
451         unsigned long spec_setup_start, spec_max_data_hold_ns;
452         unsigned long data_hold_buffer_ns;
453
454         unsigned long min_low_ns, min_high_ns;
455         unsigned long max_low_ns, min_total_ns;
456
457         unsigned long clk_rate_khz, scl_rate_khz;
458
459         unsigned long min_low_div, min_high_div;
460         unsigned long max_low_div;
461
462         unsigned long min_div_for_hold, min_total_div;
463         unsigned long extra_div, extra_low_div, ideal_low_div;
464
465         int ret = 0;
466
467         /* Only support standard-mode and fast-mode */
468         if (WARN_ON(t->bus_freq_hz > 400000))
469                 t->bus_freq_hz = 400000;
470
471         /* prevent scl_rate_khz from becoming 0 */
472         if (WARN_ON(t->bus_freq_hz < 1000))
473                 t->bus_freq_hz = 1000;
474
475         /*
476          * min_low_ns:  The minimum number of ns we need to hold low to
477          *              meet I2C specification, should include fall time.
478          * min_high_ns: The minimum number of ns we need to hold high to
479          *              meet I2C specification, should include rise time.
480          * max_low_ns:  The maximum number of ns we can hold low to meet
481          *              I2C specification.
482          *
483          * Note: max_low_ns should be (maximum data hold time * 2 - buffer)
484          *       This is because the i2c host on Rockchip holds the data line
485          *       for half the low time.
486          */
487         if (t->bus_freq_hz <= 100000) {
488                 /* Standard-mode */
489                 spec_min_low_ns = 4700;
490                 spec_setup_start = 4700;
491                 spec_min_high_ns = 4000;
492                 spec_max_data_hold_ns = 3450;
493                 data_hold_buffer_ns = 50;
494         } else {
495                 /* Fast-mode */
496                 spec_min_low_ns = 1300;
497                 spec_setup_start = 600;
498                 spec_min_high_ns = 600;
499                 spec_max_data_hold_ns = 900;
500                 data_hold_buffer_ns = 50;
501         }
502         min_high_ns = t->scl_rise_ns + spec_min_high_ns;
503
504         /*
505          * Timings for repeated start:
506          * - controller appears to drop SDA at .875x (7/8) programmed clk high.
507          * - controller appears to keep SCL high for 2x programmed clk high.
508          *
509          * We need to account for those rules in picking our "high" time so
510          * we meet tSU;STA and tHD;STA times.
511          */
512         min_high_ns = max(min_high_ns,
513                 DIV_ROUND_UP((t->scl_rise_ns + spec_setup_start) * 1000, 875));
514         min_high_ns = max(min_high_ns,
515                 DIV_ROUND_UP((t->scl_rise_ns + spec_setup_start +
516                               t->sda_fall_ns + spec_min_high_ns), 2));
517
518         min_low_ns = t->scl_fall_ns + spec_min_low_ns;
519         max_low_ns = spec_max_data_hold_ns * 2 - data_hold_buffer_ns;
520         min_total_ns = min_low_ns + min_high_ns;
521
522         /* Adjust to avoid overflow */
523         clk_rate_khz = DIV_ROUND_UP(clk_rate, 1000);
524         scl_rate_khz = t->bus_freq_hz / 1000;
525
526         /*
527          * We need the total div to be >= this number
528          * so we don't clock too fast.
529          */
530         min_total_div = DIV_ROUND_UP(clk_rate_khz, scl_rate_khz * 8);
531
532         /* These are the min dividers needed for min hold times. */
533         min_low_div = DIV_ROUND_UP(clk_rate_khz * min_low_ns, 8 * 1000000);
534         min_high_div = DIV_ROUND_UP(clk_rate_khz * min_high_ns, 8 * 1000000);
535         min_div_for_hold = (min_low_div + min_high_div);
536
537         /*
538          * This is the maximum divider so we don't go over the maximum.
539          * We don't round up here (we round down) since this is a maximum.
540          */
541         max_low_div = clk_rate_khz * max_low_ns / (8 * 1000000);
542
543         if (min_low_div > max_low_div) {
544                 WARN_ONCE(true,
545                           "Conflicting, min_low_div %lu, max_low_div %lu\n",
546                           min_low_div, max_low_div);
547                 max_low_div = min_low_div;
548         }
549
550         if (min_div_for_hold > min_total_div) {
551                 /*
552                  * Time needed to meet hold requirements is important.
553                  * Just use that.
554                  */
555                 *div_low = min_low_div;
556                 *div_high = min_high_div;
557         } else {
558                 /*
559                  * We've got to distribute some time among the low and high
560                  * so we don't run too fast.
561                  */
562                 extra_div = min_total_div - min_div_for_hold;
563
564                 /*
565                  * We'll try to split things up perfectly evenly,
566                  * biasing slightly towards having a higher div
567                  * for low (spend more time low).
568                  */
569                 ideal_low_div = DIV_ROUND_UP(clk_rate_khz * min_low_ns,
570                                              scl_rate_khz * 8 * min_total_ns);
571
572                 /* Don't allow it to go over the maximum */
573                 if (ideal_low_div > max_low_div)
574                         ideal_low_div = max_low_div;
575
576                 /*
577                  * Handle when the ideal low div is going to take up
578                  * more than we have.
579                  */
580                 if (ideal_low_div > min_low_div + extra_div)
581                         ideal_low_div = min_low_div + extra_div;
582
583                 /* Give low the "ideal" and give high whatever extra is left */
584                 extra_low_div = ideal_low_div - min_low_div;
585                 *div_low = ideal_low_div;
586                 *div_high = min_high_div + (extra_div - extra_low_div);
587         }
588
589         /*
590          * Adjust to the fact that the hardware has an implicit "+1".
591          * NOTE: Above calculations always produce div_low > 0 and div_high > 0.
592          */
593         *div_low = *div_low - 1;
594         *div_high = *div_high - 1;
595
596         /* Maximum divider supported by hw is 0xffff */
597         if (*div_low > 0xffff) {
598                 *div_low = 0xffff;
599                 ret = -EINVAL;
600         }
601
602         if (*div_high > 0xffff) {
603                 *div_high = 0xffff;
604                 ret = -EINVAL;
605         }
606
607         return ret;
608 }
609
610 static void rk3x_i2c_adapt_div(struct rk3x_i2c *i2c, unsigned long clk_rate)
611 {
612         struct i2c_timings *t = &i2c->t;
613         unsigned long div_low, div_high;
614         u64 t_low_ns, t_high_ns;
615         int ret;
616
617         ret = rk3x_i2c_calc_divs(clk_rate, t, &div_low, &div_high);
618         WARN_ONCE(ret != 0, "Could not reach SCL freq %u", t->bus_freq_hz);
619
620         clk_enable(i2c->clk);
621         i2c_writel(i2c, (div_high << 16) | (div_low & 0xffff), REG_CLKDIV);
622         clk_disable(i2c->clk);
623
624         t_low_ns = div_u64(((u64)div_low + 1) * 8 * 1000000000, clk_rate);
625         t_high_ns = div_u64(((u64)div_high + 1) * 8 * 1000000000, clk_rate);
626         dev_dbg(i2c->dev,
627                 "CLK %lukhz, Req %uns, Act low %lluns high %lluns\n",
628                 clk_rate / 1000,
629                 1000000000 / t->bus_freq_hz,
630                 t_low_ns, t_high_ns);
631 }
632
633 /**
634  * rk3x_i2c_clk_notifier_cb - Clock rate change callback
635  * @nb:         Pointer to notifier block
636  * @event:      Notification reason
637  * @data:       Pointer to notification data object
638  *
639  * The callback checks whether a valid bus frequency can be generated after the
640  * change. If so, the change is acknowledged, otherwise the change is aborted.
641  * New dividers are written to the HW in the pre- or post change notification
642  * depending on the scaling direction.
643  *
644  * Code adapted from i2c-cadence.c.
645  *
646  * Return:      NOTIFY_STOP if the rate change should be aborted, NOTIFY_OK
647  *              to acknowedge the change, NOTIFY_DONE if the notification is
648  *              considered irrelevant.
649  */
650 static int rk3x_i2c_clk_notifier_cb(struct notifier_block *nb, unsigned long
651                                     event, void *data)
652 {
653         struct clk_notifier_data *ndata = data;
654         struct rk3x_i2c *i2c = container_of(nb, struct rk3x_i2c, clk_rate_nb);
655         unsigned long div_low, div_high;
656
657         switch (event) {
658         case PRE_RATE_CHANGE:
659                 if (rk3x_i2c_calc_divs(ndata->new_rate, &i2c->t,
660                                        &div_low, &div_high) != 0)
661                         return NOTIFY_STOP;
662
663                 /* scale up */
664                 if (ndata->new_rate > ndata->old_rate)
665                         rk3x_i2c_adapt_div(i2c, ndata->new_rate);
666
667                 return NOTIFY_OK;
668         case POST_RATE_CHANGE:
669                 /* scale down */
670                 if (ndata->new_rate < ndata->old_rate)
671                         rk3x_i2c_adapt_div(i2c, ndata->new_rate);
672                 return NOTIFY_OK;
673         case ABORT_RATE_CHANGE:
674                 /* scale up */
675                 if (ndata->new_rate > ndata->old_rate)
676                         rk3x_i2c_adapt_div(i2c, ndata->old_rate);
677                 return NOTIFY_OK;
678         default:
679                 return NOTIFY_DONE;
680         }
681 }
682
683 /**
684  * Setup I2C registers for an I2C operation specified by msgs, num.
685  *
686  * Must be called with i2c->lock held.
687  *
688  * @msgs: I2C msgs to process
689  * @num: Number of msgs
690  *
691  * returns: Number of I2C msgs processed or negative in case of error
692  */
693 static int rk3x_i2c_setup(struct rk3x_i2c *i2c, struct i2c_msg *msgs, int num)
694 {
695         u32 addr = (msgs[0].addr & 0x7f) << 1;
696         int ret = 0;
697
698         /*
699          * The I2C adapter can issue a small (len < 4) write packet before
700          * reading. This speeds up SMBus-style register reads.
701          * The MRXADDR/MRXRADDR hold the slave address and the slave register
702          * address in this case.
703          */
704
705         if (num >= 2 && msgs[0].len < 4 &&
706             !(msgs[0].flags & I2C_M_RD) && (msgs[1].flags & I2C_M_RD)) {
707                 u32 reg_addr = 0;
708                 int i;
709
710                 dev_dbg(i2c->dev, "Combined write/read from addr 0x%x\n",
711                         addr >> 1);
712
713                 /* Fill MRXRADDR with the register address(es) */
714                 for (i = 0; i < msgs[0].len; ++i) {
715                         reg_addr |= msgs[0].buf[i] << (i * 8);
716                         reg_addr |= REG_MRXADDR_VALID(i);
717                 }
718
719                 /* msgs[0] is handled by hw. */
720                 i2c->msg = &msgs[1];
721
722                 i2c->mode = REG_CON_MOD_REGISTER_TX;
723
724                 i2c_writel(i2c, addr | REG_MRXADDR_VALID(0), REG_MRXADDR);
725                 i2c_writel(i2c, reg_addr, REG_MRXRADDR);
726
727                 ret = 2;
728         } else {
729                 /*
730                  * We'll have to do it the boring way and process the msgs
731                  * one-by-one.
732                  */
733
734                 if (msgs[0].flags & I2C_M_RD) {
735                         addr |= 1; /* set read bit */
736
737                         /*
738                          * We have to transmit the slave addr first. Use
739                          * MOD_REGISTER_TX for that purpose.
740                          */
741                         i2c->mode = REG_CON_MOD_REGISTER_TX;
742                         i2c_writel(i2c, addr | REG_MRXADDR_VALID(0),
743                                    REG_MRXADDR);
744                         i2c_writel(i2c, 0, REG_MRXRADDR);
745                 } else {
746                         i2c->mode = REG_CON_MOD_TX;
747                 }
748
749                 i2c->msg = &msgs[0];
750
751                 ret = 1;
752         }
753
754         i2c->addr = msgs[0].addr;
755         i2c->busy = true;
756         i2c->state = STATE_START;
757         i2c->processed = 0;
758         i2c->error = 0;
759
760         rk3x_i2c_clean_ipd(i2c);
761
762         return ret;
763 }
764
765 static int rk3x_i2c_xfer(struct i2c_adapter *adap,
766                          struct i2c_msg *msgs, int num)
767 {
768         struct rk3x_i2c *i2c = (struct rk3x_i2c *)adap->algo_data;
769         unsigned long timeout, flags;
770         int ret = 0;
771         int i;
772
773         spin_lock_irqsave(&i2c->lock, flags);
774
775         clk_enable(i2c->clk);
776
777         i2c->is_last_msg = false;
778
779         /*
780          * Process msgs. We can handle more than one message at once (see
781          * rk3x_i2c_setup()).
782          */
783         for (i = 0; i < num; i += ret) {
784                 ret = rk3x_i2c_setup(i2c, msgs + i, num - i);
785
786                 if (ret < 0) {
787                         dev_err(i2c->dev, "rk3x_i2c_setup() failed\n");
788                         break;
789                 }
790
791                 if (i + ret >= num)
792                         i2c->is_last_msg = true;
793
794                 spin_unlock_irqrestore(&i2c->lock, flags);
795
796                 rk3x_i2c_start(i2c);
797
798                 timeout = wait_event_timeout(i2c->wait, !i2c->busy,
799                                              msecs_to_jiffies(WAIT_TIMEOUT));
800
801                 spin_lock_irqsave(&i2c->lock, flags);
802
803                 if (timeout == 0) {
804                         dev_err(i2c->dev, "timeout, ipd: 0x%02x, state: %d\n",
805                                 i2c_readl(i2c, REG_IPD), i2c->state);
806
807                         /* Force a STOP condition without interrupt */
808                         i2c_writel(i2c, 0, REG_IEN);
809                         i2c_writel(i2c, REG_CON_EN | REG_CON_STOP, REG_CON);
810
811                         i2c->state = STATE_IDLE;
812
813                         ret = -ETIMEDOUT;
814                         break;
815                 }
816
817                 if (i2c->error) {
818                         ret = i2c->error;
819                         break;
820                 }
821         }
822
823         clk_disable(i2c->clk);
824         spin_unlock_irqrestore(&i2c->lock, flags);
825
826         return ret < 0 ? ret : num;
827 }
828
829 static u32 rk3x_i2c_func(struct i2c_adapter *adap)
830 {
831         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL | I2C_FUNC_PROTOCOL_MANGLING;
832 }
833
834 static const struct i2c_algorithm rk3x_i2c_algorithm = {
835         .master_xfer            = rk3x_i2c_xfer,
836         .functionality          = rk3x_i2c_func,
837 };
838
839 static struct rk3x_i2c_soc_data soc_data[3] = {
840         { .grf_offset = 0x154 }, /* rk3066 */
841         { .grf_offset = 0x0a4 }, /* rk3188 */
842         { .grf_offset = -1 },    /* no I2C switching needed */
843 };
844
845 static const struct of_device_id rk3x_i2c_match[] = {
846         { .compatible = "rockchip,rk3066-i2c", .data = (void *)&soc_data[0] },
847         { .compatible = "rockchip,rk3188-i2c", .data = (void *)&soc_data[1] },
848         { .compatible = "rockchip,rk3228-i2c", .data = (void *)&soc_data[2] },
849         { .compatible = "rockchip,rk3288-i2c", .data = (void *)&soc_data[2] },
850         {},
851 };
852 MODULE_DEVICE_TABLE(of, rk3x_i2c_match);
853
854 static int rk3x_i2c_probe(struct platform_device *pdev)
855 {
856         struct device_node *np = pdev->dev.of_node;
857         const struct of_device_id *match;
858         struct rk3x_i2c *i2c;
859         struct resource *mem;
860         int ret = 0;
861         int bus_nr;
862         u32 value;
863         int irq;
864         unsigned long clk_rate;
865
866         i2c = devm_kzalloc(&pdev->dev, sizeof(struct rk3x_i2c), GFP_KERNEL);
867         if (!i2c)
868                 return -ENOMEM;
869
870         match = of_match_node(rk3x_i2c_match, np);
871         i2c->soc_data = (struct rk3x_i2c_soc_data *)match->data;
872
873         /* use common interface to get I2C timing properties */
874         i2c_parse_fw_timings(&pdev->dev, &i2c->t, true);
875
876         strlcpy(i2c->adap.name, "rk3x-i2c", sizeof(i2c->adap.name));
877         i2c->adap.owner = THIS_MODULE;
878         i2c->adap.algo = &rk3x_i2c_algorithm;
879         i2c->adap.retries = 3;
880         i2c->adap.dev.of_node = np;
881         i2c->adap.algo_data = i2c;
882         i2c->adap.dev.parent = &pdev->dev;
883
884         i2c->dev = &pdev->dev;
885
886         spin_lock_init(&i2c->lock);
887         init_waitqueue_head(&i2c->wait);
888
889         i2c->clk = devm_clk_get(&pdev->dev, NULL);
890         if (IS_ERR(i2c->clk)) {
891                 dev_err(&pdev->dev, "cannot get clock\n");
892                 return PTR_ERR(i2c->clk);
893         }
894
895         mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
896         i2c->regs = devm_ioremap_resource(&pdev->dev, mem);
897         if (IS_ERR(i2c->regs))
898                 return PTR_ERR(i2c->regs);
899
900         /* Try to set the I2C adapter number from dt */
901         bus_nr = of_alias_get_id(np, "i2c");
902
903         /*
904          * Switch to new interface if the SoC also offers the old one.
905          * The control bit is located in the GRF register space.
906          */
907         if (i2c->soc_data->grf_offset >= 0) {
908                 struct regmap *grf;
909
910                 grf = syscon_regmap_lookup_by_phandle(np, "rockchip,grf");
911                 if (IS_ERR(grf)) {
912                         dev_err(&pdev->dev,
913                                 "rk3x-i2c needs 'rockchip,grf' property\n");
914                         return PTR_ERR(grf);
915                 }
916
917                 if (bus_nr < 0) {
918                         dev_err(&pdev->dev, "rk3x-i2c needs i2cX alias");
919                         return -EINVAL;
920                 }
921
922                 /* 27+i: write mask, 11+i: value */
923                 value = BIT(27 + bus_nr) | BIT(11 + bus_nr);
924
925                 ret = regmap_write(grf, i2c->soc_data->grf_offset, value);
926                 if (ret != 0) {
927                         dev_err(i2c->dev, "Could not write to GRF: %d\n", ret);
928                         return ret;
929                 }
930         }
931
932         /* IRQ setup */
933         irq = platform_get_irq(pdev, 0);
934         if (irq < 0) {
935                 dev_err(&pdev->dev, "cannot find rk3x IRQ\n");
936                 return irq;
937         }
938
939         ret = devm_request_irq(&pdev->dev, irq, rk3x_i2c_irq,
940                                0, dev_name(&pdev->dev), i2c);
941         if (ret < 0) {
942                 dev_err(&pdev->dev, "cannot request IRQ\n");
943                 return ret;
944         }
945
946         platform_set_drvdata(pdev, i2c);
947
948         ret = clk_prepare(i2c->clk);
949         if (ret < 0) {
950                 dev_err(&pdev->dev, "Could not prepare clock\n");
951                 return ret;
952         }
953
954         i2c->clk_rate_nb.notifier_call = rk3x_i2c_clk_notifier_cb;
955         ret = clk_notifier_register(i2c->clk, &i2c->clk_rate_nb);
956         if (ret != 0) {
957                 dev_err(&pdev->dev, "Unable to register clock notifier\n");
958                 goto err_clk;
959         }
960
961         clk_rate = clk_get_rate(i2c->clk);
962         rk3x_i2c_adapt_div(i2c, clk_rate);
963
964         ret = i2c_add_adapter(&i2c->adap);
965         if (ret < 0) {
966                 dev_err(&pdev->dev, "Could not register adapter\n");
967                 goto err_clk_notifier;
968         }
969
970         dev_info(&pdev->dev, "Initialized RK3xxx I2C bus at %p\n", i2c->regs);
971
972         return 0;
973
974 err_clk_notifier:
975         clk_notifier_unregister(i2c->clk, &i2c->clk_rate_nb);
976 err_clk:
977         clk_unprepare(i2c->clk);
978         return ret;
979 }
980
981 static int rk3x_i2c_remove(struct platform_device *pdev)
982 {
983         struct rk3x_i2c *i2c = platform_get_drvdata(pdev);
984
985         i2c_del_adapter(&i2c->adap);
986
987         clk_notifier_unregister(i2c->clk, &i2c->clk_rate_nb);
988         clk_unprepare(i2c->clk);
989
990         return 0;
991 }
992
993 static struct platform_driver rk3x_i2c_driver = {
994         .probe   = rk3x_i2c_probe,
995         .remove  = rk3x_i2c_remove,
996         .driver  = {
997                 .name  = "rk3x-i2c",
998                 .of_match_table = rk3x_i2c_match,
999         },
1000 };
1001
1002 module_platform_driver(rk3x_i2c_driver);
1003
1004 MODULE_DESCRIPTION("Rockchip RK3xxx I2C Bus driver");
1005 MODULE_AUTHOR("Max Schwarz <max.schwarz@online.de>");
1006 MODULE_LICENSE("GPL v2");