f925e8a615624b6384cdbb81ebacacba5456811d
[linux-3.10.git] / drivers / iio / proximity / nvs_iqs2x3.c
1 /* Copyright (c) 2015, NVIDIA CORPORATION.  All rights reserved.
2  *
3  * This software is licensed under the terms of the GNU General Public
4  * License version 2, as published by the Free Software Foundation, and
5  * may be copied, distributed, and modified under those terms.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  */
12
13 /* The NVS = NVidia Sensor framework */
14 /* See nvs_iio.c and nvs.h for documentation */
15 /* See nvs_proximity.c and nvs_proximity.h for documentation */
16
17 /* !!!!!!!!!!!!!TODO: add IQS253 support */
18
19 #include <linux/i2c.h>
20 #include <linux/module.h>
21 #include <linux/slab.h>
22 #include <linux/err.h>
23 #include <linux/delay.h>
24 #include <linux/regulator/consumer.h>
25 #include <linux/workqueue.h>
26 #include <linux/interrupt.h>
27 #include <linux/gpio.h>
28 #include <linux/of.h>
29 #include <linux/of_gpio.h>
30 #include <linux/string.h>
31 #include <linux/ctype.h>
32 #include <linux/nvs.h>
33 #include <linux/nvs_proximity.h>
34 #include <linux/nvs_iqs2x3.h>
35 #include <asm/atomic.h>
36
37
38 #define IQS_DRIVER_VERSION              (19)
39 #define IQS_VENDOR                      "Azoteq"
40 #define IQS_NAME                        "iqs2x3"
41 #define IQS_NAME_IQS253                 "iqs253"
42 #define IQS_NAME_IQS263                 "iqs263"
43 #define IQS_NAME_SAR_PROXIMITY          "SAR_proximity"
44 #define IQS_NAME_SAR_TOUCH              "SAR_touch"
45 #define IQS_NAME_SAR_DELTA              "SAR_delta"
46 #define IQS_NAME_SAR_DELTA_CH0          "SAR_delta_ch0"
47 #define IQS_NAME_SAR_DELTA_CH1          "SAR_delta_ch1"
48 #define IQS_NAME_SAR_DELTA_CH2          "SAR_delta_ch2"
49 #define IQS_NAME_SAR_DELTA_CH3          "SAR_delta_ch3"
50 #define IQS_GPIO_SAR_DBG_I2C_STR        "debug_i2c"
51 #define IQS_DEVID_IQS253                (0x29)
52 #define IQS_DEVID_IQS263                (0x3C)
53 #define IQS_PART_253                    (0)
54 #define IQS_PART_263                    (1)
55 #define IQS_PART_N                      (2)
56 #define IQS_HW_DELAY_MS                 (10)
57 #define IQS_START_DELAY_MS              (100)
58 #define IQS_PROX_MILLIAMP_MICRO         (180000)
59 #define IQS_PROX_THRESHOLD              (10)
60 #define IQS_MULTI_THRESHOLD             (5)
61 /* configuration */
62 #define IQS_POLL_DLY_MS_MIN             (1000)
63 #define IQS_POLL_DLY_MS_MAX             (1000)
64 #define IQS_POLL_DLY_MS_WATCHDOG        (30000)
65 #define IQS_I2C_STOP_DLY_NS             (1000000) /* must be >= 1ms */
66 #define IQS_I2C_RETRY_N                 (10)
67 #define IQS_RDY_RETRY_N                 (25)
68 /* proximity defines */
69 #define IQS_PROX_VERSION                (1)
70 /* binary proximity when max_range and resolution are 1.0 */
71 #define IQS_PROX_MAX_RANGE_IVAL         (1)
72 #define IQS_PROX_MAX_RANGE_MICRO        (0)
73 #define IQS_PROX_RESOLUTION_IVAL        (1)
74 #define IQS_PROX_RESOLUTION_MICRO       (0)
75 #define IQS_PROX_MILLIAMP_IVAL          (0)
76 /* devices */
77 #define IQS_DEV_PROX                    (0)
78 #define IQS_DEV_TOUCH                   (1)
79 #define IQS_DEV_HW_N                    (2)
80 #define IQS_DEV_DELTA                   (2)
81 #define IQS_DEV_DELTA0                  (3)
82 #define IQS_DEV_DELTA1                  (4)
83 #define IQS_DEV_DELTA2                  (5)
84 #define IQS_DEV_DELTA3                  (6)
85 #define IQS_DEV_N                       (7)
86 #define IQS_CH_N                        (4)
87 /* to allow code style rules */
88 #define IQS_FS_NANO                     NVS_FLOAT_SIGNIFICANCE_NANO
89 #define IQS_FS_MICRO                    NVS_FLOAT_SIGNIFICANCE_MICRO
90 /* delta test conditions */
91 #define IQS_DELTA_TEST0_N               (3)
92 #define IQS_DELTA_TEST1_N               (4)
93 /* debug message spew flags */
94 #define IQS_STS_GPIO_SAR                (1 << NVS_STS_EXT_N)
95 #define IQS_STS_EXT_STATE               (1 << (NVS_STS_EXT_N + 1))
96
97 /* regulator names in order of powering on */
98 static char *iqs_vregs[] = {
99         "vddhi",
100 };
101
102 static unsigned short iqs_i2c_addrs[] = {
103         0x44,
104         0x45,
105         0x46,
106         0x47,
107 };
108
109 static const struct i2c_device_id iqs_i2c_device_id[] = {
110         { IQS_NAME_IQS253, 0 },
111         { IQS_NAME_IQS263, 0 },
112         { IQS_NAME, 0 },
113         {}
114 };
115
116 static char * const iqs_snsr_names[] = {
117         IQS_NAME_SAR_PROXIMITY,
118         IQS_NAME_SAR_TOUCH,
119         IQS_NAME_SAR_DELTA,
120         IQS_NAME_SAR_DELTA_CH0,
121         IQS_NAME_SAR_DELTA_CH1,
122         IQS_NAME_SAR_DELTA_CH2,
123         IQS_NAME_SAR_DELTA_CH3,
124         IQS_GPIO_SAR_DBG_I2C_STR,
125 };
126
127 enum IQS_GPIO_SAR_DBG {
128         IQS_GPIO_SAR_DBG_I2C = IQS_DEV_N, /* IQS_GPIO_SAR_DBG_I2C_STR align */
129         /* Additional debug uses for the SAR GPIO can be added here.  Be sure
130          * to add the gpio_sar_dev_asrt enable string to iqs_snsr_names.
131          */
132         IQS_GPIO_SAR_DBG_N,
133 };
134
135 enum IQS_OS {
136         IQS_OS_NONE = 0,
137         IQS_OS_VISIBLE,                 /* OS sees sensors */
138         IQS_OS_CONTROL,                 /* OS has control of sensors */
139 };
140
141 enum IQS_INFO {
142         IQS_INFO_STS = 0,
143         IQS_INFO_EXT_STATE_SPEW = 14,
144         IQS_INFO_GPIO_SAR_SPEW,
145         IQS_INFO_GPIO_RDY_INPUT,
146         IQS_INFO_GPIO_RDY_OUTPUT,
147         IQS_INFO_GPIO_SAR_OUTPUT,
148         IQS_INFO_REG_WR,
149         IQS_INFO_DBG,
150 };
151
152 enum IQS_DB_CMD {
153         IQS_DB_CMD_INIT = 1,
154         IQS_DB_CMD_EN,
155         IQS_DB_CMD_DIS,
156         IQS_DB_CMD_EVNT,
157         IQS_DB_CMD_SUSPND,
158         IQS_DB_CMD_DELTA,
159         IQS_DB_CMD_N,
160 };
161
162 enum IQS_STREAM {
163         IQS_STREAM_OFF = 0,
164         IQS_STREAM_ALWAYS,
165         IQS_STREAM_AUTO,
166         IQS_STREAM_N,
167 };
168
169 struct iqs_delta_tst {
170         int ch;
171         int lt;
172         int gt;
173 };
174
175 static const char * const iqs_delta_tst_dt[] = {
176         "SAR_delta_test",
177         "SAR_delta_test_true",
178         "SAR_delta_test_false",
179 };
180
181 static unsigned char iqs263_wr_stream[] = {
182         2, 0x09, 0x00, 0x00, /* data */
183                  0x18, 0x40, /* mask */
184         0 /* end - done - exit */
185 };
186
187 static unsigned char iqs253_wr_stream[] = {
188         16, 0xC4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, /* data */
189                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, /* mask */
190         0, /* end - done - exit */
191 };
192
193 static unsigned char iqs263_wr_events[] = {
194         2, 0x09, 0x00, 0x40, /* data */
195                  0x18, 0x40, /* mask */
196         0 /* end - done - exit */
197 };
198
199 static unsigned char iqs253_wr_events[] = {
200         16, 0xC4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, /* data */
201                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, /* mask */
202         0 /* end - done - exit */
203 };
204
205 static unsigned char iqs263_wr_ati_redo[] = {
206         1, 0x09, 0x10, /* data */
207                  0x18, /* mask */
208         0 /* end - done - exit */
209 };
210
211 static unsigned char iqs253_wr_ati_redo[] = {
212         14, 0xC4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10, /* data */
213                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x18, /* mask */
214         0 /* end - done - exit */
215 };
216
217 static unsigned char iqs263_wr_reseed[] = {
218         1, 0x09, 0x08, /* data */
219                  0x18, /* mask */
220         0 /* end - done - exit */
221 };
222
223 static unsigned char iqs253_wr_reseed[] = {
224         14, 0xC4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x08, /* data */
225                   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x18, /* mask */
226         0 /* end - done - exit */
227 };
228
229 static unsigned char iqs263_wr_disable[] = {
230         3, 0x09, 0x00, 0x00, 0xC0, /* data */
231                  0xFF, 0xFF, 0xFF, /* mask */
232         0 /* end - done - exit */
233 };
234
235 static unsigned char iqs253_wr_disable[] = {
236         /* TODO */
237         0 /* end - done - exit */
238 };
239
240 struct iqs_hal {
241         u8 reg;
242         u16 len;
243         u8 ndx;
244         bool wr;
245 };
246
247 /* RI = Register Init */
248 /* RL = Register Length */
249 /* BI = Buffer Index */
250 #define IQS_BI_DEVINF                   (0)
251 #define IQS_RL_DEVINF                   (2)
252 /* IQS263 */
253 #define IQS263_BI_SYSFLAGS              (IQS_BI_DEVINF + \
254                                          IQS_RL_DEVINF + 1)
255 #define IQS263_RL_SYSFLAGS              (2)
256 #define IQS263_BI_COORDINATES           (IQS263_BI_SYSFLAGS + \
257                                          IQS263_RL_SYSFLAGS + 1)
258 #define IQS263_RL_COORDINATES           (3)
259 #define IQS263_BI_TOUCH                 (IQS263_BI_COORDINATES + \
260                                          IQS263_RL_COORDINATES + 1)
261 #define IQS263_RL_TOUCH                 (2)
262 #define IQS263_BI_COUNTS                (IQS263_BI_TOUCH + \
263                                          IQS263_RL_TOUCH + 1)
264 #define IQS263_RL_COUNTS                (10)
265 #define IQS263_BI_LTA                   (IQS263_BI_COUNTS + \
266                                          IQS263_RL_COUNTS + 1)
267 #define IQS263_RL_LTA                   (10)
268 #define IQS263_BI_DELTAS                (IQS263_BI_LTA + \
269                                          IQS263_RL_LTA + 1)
270 #define IQS263_RL_DELTAS                (8)
271 #define IQS263_BI_MULTIPLIERS           (IQS263_BI_DELTAS + \
272                                          IQS263_RL_DELTAS + 1)
273 #define IQS263_RL_MULTIPLIERS           (5)
274 #define IQS263_BI_COMPENSATION          (IQS263_BI_MULTIPLIERS + \
275                                          IQS263_RL_MULTIPLIERS + 1)
276 #define IQS263_RL_COMPENSATION          (4)
277 #define IQS263_BI_PROXSETTINGS          (IQS263_BI_COMPENSATION + \
278                                          IQS263_RL_COMPENSATION + 1)
279 #define IQS263_RL_PROXSETTINGS          (5)
280 #define IQS263_BI_THRESHOLDS            (IQS263_BI_PROXSETTINGS + \
281                                          IQS263_RL_PROXSETTINGS + 1)
282 #define IQS263_RL_THRESHOLDS            (8)
283 #define IQS263_BI_TIMINGS               (IQS263_BI_THRESHOLDS + \
284                                          IQS263_RL_THRESHOLDS + 1)
285 #define IQS263_RL_TIMINGS               (3)
286 #define IQS263_BI_GESTURE_TIMERS        (IQS263_BI_TIMINGS + \
287                                          IQS263_RL_TIMINGS + 1)
288 #define IQS263_RL_GESTURE_TIMERS        (3)
289 #define IQS263_BI_ACTIVE_CH             (IQS263_BI_GESTURE_TIMERS + \
290                                          IQS263_RL_GESTURE_TIMERS + 1)
291 #define IQS263_RL_ACTIVE_CH             (1)
292 #define IQS263_BI_N                     (IQS263_BI_ACTIVE_CH + \
293                                          IQS263_RL_ACTIVE_CH + 1)
294 /* IQS253 */
295 #define IQS253_BI_SYSFLAGS              (IQS_BI_DEVINF + \
296                                          IQS_RL_DEVINF + 1)
297 #define IQS253_RL_SYSFLAGS              (1)
298 #define IQS253_BI_PROXSTS               (IQS253_BI_SYSFLAGS + \
299                                          IQS253_RL_SYSFLAGS + 1)
300 #define IQS253_RL_PROXSTS               (1)
301 #define IQS253_BI_TOUCHSTS              (IQS253_BI_PROXSTS + \
302                                          IQS253_RL_PROXSTS + 1)
303 #define IQS253_RL_TOUCHSTS              (3)
304 #define IQS253_BI_HALT                  (IQS253_BI_TOUCHSTS + \
305                                          IQS253_RL_TOUCHSTS + 1)
306 #define IQS253_RL_HALT                  (1)
307 #define IQS253_BI_ACTIVE_CH             (IQS253_BI_HALT + \
308                                          IQS253_RL_HALT + 1)
309 #define IQS253_RL_ACTIVE_CH             (1)
310 #define IQS253_BI_COUNTS                (IQS253_BI_ACTIVE_CH + \
311                                          IQS253_RL_ACTIVE_CH + 1)
312 #define IQS253_RL_COUNTS                (2)
313 #define IQS253_BI_LTA                   (IQS253_BI_COUNTS + \
314                                          IQS253_RL_COUNTS + 1)
315 #define IQS253_RL_LTA                   (2)
316 #define IQS253_BI_SETTINGS              (IQS253_BI_LTA + \
317                                          IQS253_RL_LTA + 1)
318 #define IQS253_RL_SETTINGS              (26)
319 #define IQS253_BI_N                     (IQS253_BI_SETTINGS + \
320                                          IQS253_RL_SETTINGS + 1)
321
322 #if IQS263_BI_N < IQS253_BI_N
323 #define IQS_BI_N                        (IQS253_BI_N)
324 #else
325 #define IQS_BI_N                        (IQS263_BI_N)
326 #endif /* IQS263_BI_N < IQS253_BI_N */
327
328 static const struct iqs_hal const iqs263_hal_tbl[] = {
329         { 0x00, IQS_RL_DEVINF, IQS_BI_DEVINF, false, },
330         { 0x01, IQS263_RL_SYSFLAGS, IQS263_BI_SYSFLAGS, true, },
331         { 0x02, IQS263_RL_COORDINATES, IQS263_BI_COORDINATES, false, },
332         { 0x03, IQS263_RL_TOUCH, IQS263_BI_TOUCH, false, },
333         { 0x04, IQS263_RL_COUNTS, IQS263_BI_COUNTS, false, },
334         { 0x05, IQS263_RL_LTA, IQS263_BI_LTA, false, },
335         { 0x06, IQS263_RL_DELTAS, IQS263_BI_DELTAS, false, },
336         { 0x07, IQS263_RL_MULTIPLIERS, IQS263_BI_MULTIPLIERS, true, },
337         { 0x08, IQS263_RL_COMPENSATION, IQS263_BI_COMPENSATION, true, },
338         { 0x09, IQS263_RL_PROXSETTINGS, IQS263_BI_PROXSETTINGS, true, },
339         { 0x0A, IQS263_RL_THRESHOLDS, IQS263_BI_THRESHOLDS, true, },
340         { 0x0B, IQS263_RL_TIMINGS, IQS263_BI_TIMINGS, true, },
341         { 0x0C, IQS263_RL_GESTURE_TIMERS, IQS263_BI_GESTURE_TIMERS, true, },
342         { 0x0D, IQS263_RL_ACTIVE_CH, IQS263_BI_ACTIVE_CH, true, },
343 };
344
345 static const struct iqs_hal const iqs253_hal_tbl[] = {
346         { 0x00, IQS_RL_DEVINF, IQS_BI_DEVINF, false, },
347         { 0x10, IQS253_RL_SYSFLAGS, IQS253_BI_SYSFLAGS, false, },
348         { 0x31, IQS253_RL_PROXSTS, IQS253_BI_PROXSTS, false, },
349         { 0x35, IQS253_RL_TOUCHSTS, IQS253_BI_TOUCHSTS, false, },
350         { 0x39, IQS253_RL_HALT, IQS253_BI_HALT, false, },
351         { 0x3D, IQS253_RL_ACTIVE_CH, IQS253_BI_ACTIVE_CH, false, },
352         { 0x42, IQS253_RL_COUNTS, IQS253_BI_COUNTS, false, },
353         { 0x83, IQS253_RL_LTA, IQS253_BI_LTA, true, },
354         { 0xC4, IQS253_RL_SETTINGS, IQS253_BI_SETTINGS, true, },
355 };
356
357 #define IQS_DT_INIT_N                   (96) /* max DT init bytes */
358 #define IQS_DT_ABLE_N                   (32) /* max DT en/dis-able bytes */
359 #define IQS_DT_EVNT_N                   (32) /* max DT en/dis-able bytes */
360 #define IQS_DT_SUSPND_N                 (64) /* max DT suspend bytes */
361 #define IQS263_MSG_N                    (14)
362 #define IQS253_MSG_N                    (9)
363
364 #if IQS263_MSG_N < IQS253_MSG_N
365 #define IQS_MSG_N                       (IQS253_MSG_N * 2)
366 #else
367 #define IQS_MSG_N                       (IQS263_MSG_N * 2)
368 #endif /* IQS263_MSG_N < IQS253_MSG_N */
369
370 struct iqs_hal_iom {
371         u8 hal_i;
372         u8 offset;
373         u8 mask;
374 };
375
376 struct iqs_hal_bit {
377         struct iqs_hal_iom devinf_id;
378         struct iqs_hal_iom sysflag_reset;
379         struct iqs_hal_iom ati_err;
380         struct iqs_hal_iom ati_busy;
381         struct iqs_hal_iom event_mode;
382         struct iqs_hal_iom ati_partial;
383         struct iqs_hal_iom active_ch;
384         struct iqs_hal_iom lta;
385         struct iqs_hal_iom delta;
386         struct iqs_hal_iom multi_comp;
387         struct iqs_hal_iom multi_sens;
388         struct iqs_hal_iom touch_prx;
389         struct iqs_hal_iom touch_tch;
390         struct iqs_hal_iom count_prx;
391         struct iqs_hal_iom count_tch;
392         struct iqs_hal_iom thresh_prx;
393         struct iqs_hal_iom thresh_tch;
394 };
395
396 static const struct iqs_hal_bit iqs263_hal_bit = {
397         .devinf_id                      = {
398                 .hal_i                  = 0,
399                 .offset                 = 0,
400                 .mask                   = 0xFF,
401         },
402         .sysflag_reset                  = {
403                 .hal_i                  = 1,
404                 .offset                 = 0,
405                 .mask                   = 0x80,
406         },
407         .ati_err                        = {
408                 .hal_i                  = 1,
409                 .offset                 = 0,
410                 .mask                   = 0x20,
411         },
412         .ati_busy                       = {
413                 .hal_i                  = 1,
414                 .offset                 = 0,
415                 .mask                   = 0x04,
416         },
417         .event_mode                     = {
418                 .hal_i                  = 9,
419                 .offset                 = 1,
420                 .mask                   = 0x40,
421         },
422         .ati_partial                    = {
423                 .hal_i                  = 9,
424                 .offset                 = 0,
425                 .mask                   = 0x40,
426         },
427         .active_ch                      = {
428                 .hal_i                  = 0x0D,
429                 .offset                 = 0,
430                 .mask                   = 0x0F,
431         },
432         .lta                            = {
433                 .hal_i                  = 5,
434                 .offset                 = 0,
435                 .mask                   = 0xFF,
436         },
437         .delta                          = {
438                 .hal_i                  = 6,
439                 .offset                 = 0,
440                 .mask                   = 0xFF,
441         },
442         .multi_comp                     = {
443                 .hal_i                  = 7,
444                 .offset                 = 0,
445                 .mask                   = 0x0F,
446         },
447         .multi_sens                     = {
448                 .hal_i                  = 7,
449                 .offset                 = 0,
450                 .mask                   = 0x30,
451         },
452         .touch_prx                      = {
453                 .hal_i                  = 3,
454                 .offset                 = 0,
455                 .mask                   = 0x01,
456         },
457         .touch_tch                      = {
458                 .hal_i                  = 3,
459                 .offset                 = 0,
460                 .mask                   = 0x0E,
461         },
462         .count_prx                      = {
463                 .hal_i                  = 4,
464                 .offset                 = 0,
465                 .mask                   = 1,
466         },
467         .count_tch                      = {
468                 .hal_i                  = 4,
469                 .offset                 = 4,
470                 .mask                   = 3,
471         },
472         .thresh_prx                     = {
473                 .hal_i                  = 10,
474                 .offset                 = 0,
475                 .mask                   = 1,
476         },
477         .thresh_tch                     = {
478                 .hal_i                  = 10,
479                 .offset                 = 1,
480                 .mask                   = 3,
481         },
482 };
483
484 static const struct iqs_hal_bit iqs253_hal_bit = {
485         .devinf_id                      = {
486                 .hal_i                  = 0,
487                 .offset                 = 0,
488                 .mask                   = 0xFF,
489         },
490         .sysflag_reset                  = {
491                 .hal_i                  = 1,
492                 .offset                 = 0,
493                 .mask                   = 0x20,
494         },
495         .thresh_prx                     = {
496                 .hal_i                  = 10,
497                 .offset                 = 0,
498                 .mask                   = 1,
499         },
500         .thresh_tch                     = {
501                 .hal_i                  = 10,
502                 .offset                 = 1,
503                 .mask                   = 3,
504         },
505         .count_prx                      = {
506                 .hal_i                  = 4,
507                 .offset                 = 0,
508                 .mask                   = 1,
509         },
510         .count_tch                      = {
511                 .hal_i                  = 4,
512                 .offset                 = 4,
513                 .mask                   = 3,
514         },
515 };
516
517 struct iqs_state {
518         struct i2c_client *i2c;
519         struct nvs_fn_if *nvs;
520         struct sensor_cfg cfg[IQS_DEV_N];
521         struct delayed_work dw;
522         struct regulator_bulk_data vreg[ARRAY_SIZE(iqs_vregs)];
523         struct nvs_proximity prox[IQS_DEV_N];
524         unsigned int sts;               /* status flags */
525         unsigned int errs;              /* error count */
526         unsigned int enabled;           /* enable status */
527         unsigned int susrsm_en;         /* suspend/resume enable status */
528         unsigned int dfr_rsm_ms;        /* ms to wait before resuming */
529         u16 i2c_addr;                   /* I2C address */
530         u8 dev_id;                      /* device ID */
531         bool irq_dis;                   /* interrupt disable flag */
532         bool irq_set_irq_wake;          /* if irq_set_irq_wake is enabled */
533         bool irq_trigger_edge;          /* if irq set for edge trigger */
534         bool suspend_dis;               /* active during suspend */
535         bool susrsm;                    /* suspend/resume - exit I2C early */
536         bool resume;                    /* resume action needed */
537         int op_i;                       /* operational index */
538         int op_read_n;                  /* operational register read count */
539         int op_read_reg[IQS_DEV_N + 2]; /* operational registers to read */
540         unsigned int part_i;            /* part index */
541         unsigned int dbg;               /* nvs debug interface */
542         unsigned int os;                /* OS options */
543         unsigned int stream;            /* configured for stream mode only */
544         unsigned int delta_ch_msk;      /* delta sensors enable channel mask */
545         unsigned int delta_avg_n;       /* delta sensors moving average cnt */
546         unsigned int dbnc_lo[IQS_DEV_HW_N]; /* binary low debounce */
547         unsigned int dbnc_hi[IQS_DEV_HW_N]; /* binary high debounce */
548         unsigned int dbnc_lo_n[IQS_DEV_HW_N]; /* binary low debounce count */
549         unsigned int dbnc_hi_n[IQS_DEV_HW_N]; /* binary high debounce count */
550         unsigned int ati_redo_n;        /* ATI redo count */
551         unsigned int wd_to_ms;          /* watchdog timeout ms */
552         unsigned int gpio_rdy_retry;    /* GPIO RDY assert loop limit */
553         unsigned int i2c_retry;         /* I2C transaction loop limit */
554         s64 i2c_ss_war_ns;              /* I2C stop/start delay WAR */
555         s64 i2c_stop_ts;                /* see IQS_I2C_STOP_DLY_NS */
556         int gpio_rdy;                   /* GPIO */
557         int gpio_sar;                   /* GPIO */
558         int gpio_sar_val;               /* current GPIO state */
559         int gpio_sar_sus_asrt;          /* GPIO assertion when suspending */
560         unsigned int gpio_sar_asrt_pol; /* GPIO SAR assert polarity */
561         unsigned int gpio_sar_dev_asrt; /* device that asserts SAR GPIO */
562         unsigned int gpio_sar_dev_dasrt; /* device that deasserts SAR GPIO */
563         unsigned int msg_n;             /* I2C transaction count */
564         struct i2c_msg msg[IQS_MSG_N];  /* max possible I2C transactions */
565         const struct iqs_hal *hal_tbl;  /* HAL register table */
566         unsigned int hal_tbl_n;         /* HAL register table count */
567         const struct iqs_hal_bit *hal_bit; /* HAL for specific bits */
568         unsigned char *wr_disable;      /* byte stream to disable device */
569         unsigned char *wr_stream;       /* byte stream for stream mode */
570         unsigned char *wr_events;       /* byte stream for event mode */
571         unsigned char *wr_ati_redo;     /* byte stream to do ATI redo */
572         unsigned char *wr_reseed;       /* byte stream to do reseed */
573         unsigned char dt_init[IQS_PART_N][IQS_DT_INIT_N]; /* DT byte stream */
574         unsigned char dt_en[IQS_PART_N][IQS_DEV_HW_N][IQS_DT_ABLE_N]; /* " */
575         unsigned char dt_dis[IQS_PART_N][IQS_DEV_HW_N][IQS_DT_ABLE_N]; /* " */
576         unsigned char dt_evnt[IQS_PART_N][IQS_DT_EVNT_N]; /* DT byte stream */
577         unsigned char dt_suspnd[IQS_PART_N][IQS_DT_SUSPND_N]; /* " */
578         u8 rc[IQS_BI_N];                /* register cache */
579         u16 *delta_avg[IQS_CH_N];       /* delta moving average data */
580         struct iqs_delta_tst delta_tst[IQS_DELTA_TEST0_N][IQS_DELTA_TEST1_N];
581 };
582
583
584 static int iqs_ext_sts;
585 static atomic_t iqs_ext_sts_chg = ATOMIC_INIT(0);
586
587
588 static void iqs_err(struct iqs_state *st)
589 {
590         st->errs++;
591         if (!st->errs)
592                 st->errs--;
593 }
594
595 static void iqs_mutex_lock(struct iqs_state *st)
596 {
597         unsigned int i;
598
599         if (st->nvs) {
600                 for (i = 0; i < IQS_DEV_N; i++) {
601                         if (st->prox[i].nvs_st)
602                                 st->nvs->nvs_mutex_lock(st->prox[i].nvs_st);
603                 }
604         }
605 }
606
607 static void iqs_mutex_unlock(struct iqs_state *st)
608 {
609         unsigned int i;
610
611         if (st->nvs) {
612                 for (i = 0; i < IQS_DEV_N; i++) {
613                         if (st->prox[i].nvs_st)
614                                 st->nvs->nvs_mutex_unlock(st->prox[i].nvs_st);
615                 }
616         }
617 }
618
619 static unsigned int iqs_i2c_stop_ms(struct iqs_state *st)
620 {
621         s64 i2c_stop_t;
622         unsigned int ms = 0;
623
624         i2c_stop_t = nvs_timestamp() - st->i2c_stop_ts;
625         if (i2c_stop_t < st->i2c_ss_war_ns) {
626                 i2c_stop_t = st->i2c_ss_war_ns - i2c_stop_t;
627                 do_div(i2c_stop_t, 1000000); /* ns => ms */
628                 ms = i2c_stop_t;
629                 if (!ms)
630                         ms = 1;
631         }
632         return ms;
633 }
634
635 static void iqs_enable_irq(struct iqs_state *st)
636 {
637         unsigned int ms;
638         unsigned int i;
639
640         if (st->irq_dis && st->i2c->irq) {
641                 /* ensure IRQ is high after I2C STOP when enabling */
642                 ms = iqs_i2c_stop_ms(st);
643                 if (ms) {
644                         ms <<= 1; /* *2 */
645                         for (i = 0; i < ms; i++) {
646                                 if (gpio_get_value_cansleep(st->gpio_rdy))
647                                         break;
648
649                                 usleep_range(500, 1000);
650                         }
651                 }
652
653                 enable_irq(st->i2c->irq);
654                 st->irq_dis = false;
655                 if (st->sts & NVS_STS_SPEW_IRQ)
656                         dev_info(&st->i2c->dev, "%s delay=%ums\n",
657                                  __func__, ms >> 1);
658         }
659 }
660
661 static void iqs_irq_restore(struct iqs_state *st, bool disable)
662 {
663         if (!disable)
664                 iqs_enable_irq(st);
665 }
666
667 static void iqs_disable_irq(struct iqs_state *st)
668 {
669         if ((!st->irq_dis) && st->i2c->irq) {
670                 disable_irq_nosync(st->i2c->irq);
671                 st->irq_dis = true;
672                 if (st->sts & NVS_STS_SPEW_IRQ)
673                         dev_info(&st->i2c->dev, "%s\n", __func__);
674         }
675 }
676
677 static int iqs_gpio_sar(struct iqs_state *st, int assert)
678 {
679         int gpio_sar_val;
680         int ret = 0;
681
682         if (st->gpio_sar >= 0) {
683                 /* polarity   assertion   GPIO
684                  *     0          0        1
685                  *     0          1        0
686                  *     1          0        0
687                  *     1          1        1
688                  */
689                 assert = !!assert;
690                 gpio_sar_val = !(st->gpio_sar_asrt_pol ^ assert);
691                 if (st->gpio_sar_val != gpio_sar_val) {
692                         ret = gpio_direction_output(st->gpio_sar,
693                                                     gpio_sar_val);
694                         if (ret) {
695                                 dev_err(&st->i2c->dev,
696                                         "%s assert=%d gpio_sar %d=%d err=%d\n",
697                                         __func__, assert, st->gpio_sar,
698                                         gpio_sar_val, ret);
699                         } else {
700                                 st->gpio_sar_val = gpio_sar_val;
701                                 if (st->sts & (NVS_STS_SPEW_MSG |
702                                                IQS_STS_GPIO_SAR))
703                                         dev_info(&st->i2c->dev,
704                                                "%s assert=%d gpio_sar %d=%d\n",
705                                                  __func__, assert,
706                                                  st->gpio_sar, gpio_sar_val);
707                         }
708                 }
709         } else {
710                 ret = -EINVAL;
711         }
712         return ret;
713 }
714
715 static int iqs_gpio_rdy_poll(struct iqs_state *st)
716 {
717         unsigned int i;
718         int ret;
719
720         for (i = 0; i < 2000; i++) {
721                 ret = gpio_get_value_cansleep(st->gpio_rdy);
722                 if (st->susrsm || !ret)
723                         break;
724
725                 usleep_range(500, 1000);
726         }
727         return ret;
728 }
729
730 static int iqs_gpio_rdy(struct iqs_state *st, bool poll)
731 {
732         bool force = false;
733         unsigned int i = 0;
734         int ret;
735
736         if (poll)
737                 ret = iqs_gpio_rdy_poll(st);
738         else
739                 ret = gpio_get_value_cansleep(st->gpio_rdy);
740         if (ret && !st->susrsm) {
741                 force = true;
742                 iqs_disable_irq(st);
743                 for (; i < st->gpio_rdy_retry; i++) {
744                         gpio_direction_output(st->gpio_rdy, 0);
745                         usleep_range(10000, 12000);
746                         /* put to tristate */
747                         gpio_direction_input(st->gpio_rdy);
748                         ret = iqs_gpio_rdy_poll(st);
749                         if (st->susrsm || !ret)
750                                 break;
751                 }
752         }
753         if (st->sts & NVS_STS_SPEW_MSG)
754                 dev_info(&st->i2c->dev,
755                          "%s gpio_rdy=%d poll=%x force=%x retry=%u exit=%x\n",
756                          __func__, ret, poll, force, i, st->susrsm);
757         return ret;
758 }
759
760 static unsigned int iqs_rc_i(struct iqs_state *st,
761                              const struct iqs_hal_iom *iom)
762 {
763         unsigned int rc_i;
764
765         rc_i = st->hal_tbl[iom->hal_i].ndx + 1;
766         rc_i += iom->offset;
767         return rc_i;
768 }
769
770 static unsigned int iqs_bits_rd(struct iqs_state *st,
771                                 const struct iqs_hal_iom *iom,
772                                 unsigned int additional_offset)
773 {
774         return st->rc[iqs_rc_i(st, iom) + additional_offset] & iom->mask;
775 }
776
777 static int iqs_i2c(struct iqs_state *st, bool poll)
778 {
779         ssize_t t;
780         char spew[128];
781         unsigned int i;
782         unsigned int ms;
783         unsigned int n = 0;
784         int ret = -ENODEV;
785
786         if (st->i2c_addr && st->msg_n) {
787 #ifdef IQS_I2C_M_NO_RD_ACK
788                 /* This IQS device mangles the I2C protocol for read restarts.
789                  * In order to do I2C message stacking to avoid an I2C STOP
790                  * that would end the communication window, the last read
791                  * byte must not be acknowledged, and instead the restart done.
792                  * Probably no normal I2C HW supports this thus requiring the
793                  * I2C bus to be bit-banged.
794                  * I2C_M_NO_RD_ACK probably wouldn't work (if supported)
795                  * because it's just the last read byte that requires this,
796                  * not all of them.
797                  */
798                 for (i = 0; i < st->msg_n - 1; i++) {
799                         if (st->msg[i].flags & I2C_M_RD)
800                                 st->msg[i].flags |= I2C_M_NO_RD_ACK;
801                 }
802 #endif /* IQS_I2C_M_NO_RD_ACK */
803                 for (i = 0; i < st->i2c_retry; i++) {
804                         /* I2C transactions must be separated by a delay after
805                          * the STOP is issued.  Here we just ensure that the
806                          * delay time has passed before issueing another
807                          * transaction.
808                          */
809                         ms = iqs_i2c_stop_ms(st);
810                         if (ms)
811                                 msleep(ms);
812                         if (iqs_gpio_rdy(st, poll)) {
813                                 ret = -EIO;
814                                 break;
815                         }
816
817                         /* Since this device has so many I2C issues, a debug
818                          * feature is to use the SAR GPIO as a signal for when
819                          * I2C transactions are actually done.
820                          */
821                         if (st->gpio_sar_dev_asrt == IQS_GPIO_SAR_DBG_I2C)
822                                 iqs_gpio_sar(st, 1);
823                         ret = i2c_transfer(st->i2c->adapter,
824                                            &st->msg[n], st->msg_n);
825                         if (st->gpio_sar_dev_asrt == IQS_GPIO_SAR_DBG_I2C)
826                                 iqs_gpio_sar(st, 0);
827                         st->i2c_stop_ts = nvs_timestamp();
828                         if (ret == st->msg_n) {
829                                 ret = 0;
830                                 break;
831                         } else {
832                                 if (ret < 0)
833                                         continue;
834
835                                 /* skip the successful messages */
836                                 n = ret;
837                                 while (n && st->msg[n].flags & I2C_M_RD)
838                                         n--;
839                                 st->msg_n -= n;
840                                 ret = -EIO;
841                         }
842                 }
843                 if (ret && !st->susrsm)
844                         iqs_err(st);
845                 if (st->sts & NVS_STS_SPEW_MSG) {
846                         st->msg_n += n;
847                         if (i || ret)
848                                 dev_info(&st->i2c->dev,
849                                         "%s retry=%u poll=%x err=%d exit=%x\n",
850                                          __func__, i, poll, ret, st->susrsm);
851                         for (i = 0; i < st->msg_n; i++) {
852                                 n = 0;
853                                 if (st->msg[i].flags & I2C_M_RD) {
854                                         t = sprintf(spew, "read=");
855                                 } else {
856                                         if (st->msg[i].len == 1) {
857                                                 /* part of read transaction */
858                                                 t = sprintf(spew, "read %#2x=",
859                                                             st->msg[i].buf[0]);
860                                                 i++;
861                                         } else {
862                                                 t = sprintf(spew,
863                                                             "write %#2x=",
864                                                             st->msg[i].buf[0]);
865                                                 n = 1;
866                                         }
867                                 }
868                                 for (; n < st->msg[i].len; n++)
869                                         t += sprintf(spew + t, "%#2x ",
870                                                      st->msg[i].buf[n]);
871                                 dev_info(&st->i2c->dev, "%s %s\n",
872                                          __func__, spew);
873                         }
874                 }
875         } else {
876                 if (st->sts & NVS_STS_SPEW_MSG)
877                         dev_info(&st->i2c->dev,
878                                  "%s NO OP: i2c_addr=%hx  msg_n=%u\n",
879                                  __func__, st->i2c_addr, st->msg_n);
880         }
881         st->msg_n = 0;
882         return ret;
883 }
884
885 static int iqs_i2c_rd(struct iqs_state *st, int hal_i, u16 len)
886 {
887         if (st->msg_n + 1 < ARRAY_SIZE(st->msg)) {
888                 st->msg[st->msg_n].flags = 0;
889                 st->msg[st->msg_n].len = 1;
890                 st->msg[st->msg_n].buf = &st->rc[st->hal_tbl[hal_i].ndx];
891                 st->msg_n++;
892                 st->msg[st->msg_n].flags = I2C_M_RD;
893                 if (len)
894                         st->msg[st->msg_n].len = len;
895                 else
896                         st->msg[st->msg_n].len = st->hal_tbl[hal_i].len;
897                 st->msg[st->msg_n].buf = &st->rc[st->hal_tbl[hal_i].ndx + 1];
898                 st->msg_n++;
899                 return 0;
900         }
901
902         return -EINVAL;
903 };
904
905 static int iqs_i2c_read(struct iqs_state *st, int hal_i, u16 len, bool poll)
906 {
907         iqs_i2c_rd(st, hal_i, len);
908         return iqs_i2c(st, poll);
909 };
910
911 static int iqs_i2c_wr(struct iqs_state *st, int hal_i, u16 len)
912 {
913         if (st->msg_n < ARRAY_SIZE(st->msg)) {
914                 st->msg[st->msg_n].flags = 0;
915                 if (len)
916                         st->msg[st->msg_n].len = len + 1;
917                 else
918                         st->msg[st->msg_n].len = st->hal_tbl[hal_i].len + 1;
919                 st->msg[st->msg_n].buf = &st->rc[st->hal_tbl[hal_i].ndx];
920                 st->msg_n++;
921                 return 0;
922         }
923
924         return -EINVAL;
925 };
926
927 static int iqs_i2c_write(struct iqs_state *st, int hal_i, u16 len,
928                          bool poll, bool irq_restore)
929 {
930         bool irq_dis = st->irq_dis;
931         int ret;
932
933         iqs_i2c_wr(st, hal_i, len);
934         ret = iqs_i2c(st, poll);
935         if (irq_restore)
936                 iqs_irq_restore(st, irq_dis);
937         return ret;
938 };
939
940 static int iqs_wr(struct iqs_state *st, unsigned char *wr)
941 {
942         u8 ndx = 0;
943         unsigned int msg_n = st->msg_n;
944         bool irq_dis;
945         unsigned int i;
946         unsigned int j;
947         unsigned int k;
948         unsigned char len;
949         unsigned char reg;
950         int hal_i;
951         int ret = 0;
952
953         if (!st->hal_tbl_n)
954                 /* exit if HAL not initialized */
955                 return -EINVAL;
956
957         i = 0;
958         while (wr[i] != 0) { /* while a length */
959                 len = wr[i];
960                 i++;
961                 if (len == 0xFF) {
962                         /* if length == FF then do an I2C write now */
963                         if (st->msg_n) {
964                                 irq_dis = st->irq_dis;
965                                 ret |= iqs_i2c(st, false);
966                                 iqs_irq_restore(st, irq_dis);
967                         }
968                         if (wr[i])
969                                 msleep(wr[i]);
970                         i++;
971                         continue;
972                 }
973
974                 /* get the register */
975                 reg = wr[i];
976                 i++;
977                 /* find the register and reg cache index in the hal table */
978                 for (hal_i = st->hal_tbl_n - 1; hal_i > 0; hal_i--) {
979                         if (st->hal_tbl[hal_i].reg == reg) {
980                                 if (st->hal_tbl[hal_i].len >= len) {
981                                         ndx = st->hal_tbl[hal_i].ndx + 1;
982                                         break;
983                                 } else {
984                                         dev_err(&st->i2c->dev,
985                                                 "%s reg=%hhx ERR: len=%hhu\n",
986                                                 __func__, reg, len);
987                                         /* length too long and need to exit */
988                                         return -EFAULT;
989                                 }
990                         }
991                 }
992                 if (hal_i) {
993                         /* if register and index found, mask data to cache */
994                         for (j = 0; j < len; j++) {
995                                 k = ndx + j;
996                                 st->rc[k] &= ~wr[i + len];
997                                 st->rc[k] |= wr[i];
998                                 i++;
999                         }
1000                         ret |= iqs_i2c_wr(st, hal_i, len);
1001                         i += len;
1002                 } else {
1003                         /* if register not found we're lost and need to exit */
1004                         dev_err(&st->i2c->dev,
1005                                 "%s ERR: reg=%hhx not found.  FYI: len=%hhu\n",
1006                                 __func__, reg, len);
1007                         st->msg_n = msg_n;
1008                         return -EFAULT;
1009                 }
1010         }
1011
1012         return ret;
1013 };
1014
1015 static int iqs_write(struct iqs_state *st, unsigned char *wr,
1016                      bool poll, bool irq_restore)
1017 {
1018         bool irq_dis = st->irq_dis;
1019         int ret;
1020
1021         ret = iqs_wr(st, wr);
1022         if (st->msg_n) {
1023                 ret |= iqs_i2c(st, poll);
1024                 if (irq_restore)
1025                         iqs_irq_restore(st, irq_dis);
1026         }
1027         return ret;
1028 }
1029
1030 static void iqs_op_rd(struct iqs_state *st)
1031 {
1032         bool prox_binary = false;
1033         bool prox_full = false;
1034         unsigned int i;
1035
1036         st->op_read_n = 0;
1037         /* add multi_comp if ATI partial is enabled */
1038         if (iqs_bits_rd(st, &st->hal_bit->ati_partial, 0)) {
1039                 st->op_read_reg[st->op_read_n] = st->hal_bit->multi_comp.hal_i;
1040                 st->op_read_n++;
1041         }
1042         /* always test for device reset */
1043         st->op_read_reg[st->op_read_n] = st->hal_bit->sysflag_reset.hal_i;
1044         st->op_read_n++;
1045         /* read either binary data or full counts */
1046         for (i = 0; i < IQS_DEV_HW_N; i++) {
1047                 if (st->enabled & (1 << i)) {
1048                         if (st->prox[i].proximity_binary_hw) {
1049                                 if (!prox_binary) {
1050                                         st->op_read_reg[st->op_read_n] =
1051                                                  st->hal_bit->touch_prx.hal_i;
1052                                         prox_binary = true;
1053                                         st->op_read_n++;
1054                                 }
1055                         } else if (!prox_full) {
1056                                 st->op_read_reg[st->op_read_n] =
1057                                                  st->hal_bit->count_prx.hal_i;
1058                                 prox_full = true;
1059                                 st->op_read_n++;
1060                         }
1061                 }
1062         }
1063         if (st->enabled & (st->delta_ch_msk << IQS_DEV_DELTA0)) {
1064                 st->op_read_reg[st->op_read_n] = st->hal_bit->lta.hal_i;
1065                 st->op_read_n++;
1066                 st->op_read_reg[st->op_read_n] = st->hal_bit->delta.hal_i;
1067                 st->op_read_n++;
1068         }
1069
1070         st->op_i = st->op_read_n; /* force new read cycle */
1071 }
1072
1073 static int iqs_stream(struct iqs_state *st, bool stream)
1074 {
1075         unsigned int event_mode = iqs_bits_rd(st, &st->hal_bit->event_mode, 0);
1076         int ret = 0;
1077
1078         if (stream && event_mode)
1079                 ret = iqs_wr(st, st->wr_stream);
1080         else if ((!stream) && (!event_mode))
1081                 ret = iqs_wr(st, st->wr_events);
1082         else
1083                 ret = 1; /* no op */
1084         return ret;
1085 }
1086
1087 static int iqs_init(struct iqs_state *st)
1088 {
1089         bool stream = (st->stream == IQS_STREAM_ALWAYS) ? true : false;
1090         int ret = 0;
1091
1092         if (st->hal_tbl_n) {
1093                 /* only if HAL initialized */
1094                 ret = iqs_wr(st, st->dt_init[st->part_i]);
1095                 ret |= iqs_stream(st, stream);
1096                 if (ret < 0) {
1097                         /* if an error then write separately */
1098                         ret = iqs_write(st, st->dt_init[st->part_i],
1099                                         false, false);
1100                         if (!ret) {
1101                                 ret = iqs_stream(st, stream);
1102                                 if (!ret)
1103                                         ret = iqs_i2c(st, false);
1104                         }
1105                 } else {
1106                         ret = iqs_i2c(st, false);
1107                 }
1108         }
1109         return ret;
1110 }
1111
1112 static int iqs_en(struct iqs_state *st, int snsr_id)
1113 {
1114         int ret = 0;
1115
1116         if (snsr_id >= IQS_DEV_N)
1117                 return -EINVAL;
1118
1119         if (snsr_id < IQS_DEV_HW_N) {
1120                 st->dbnc_lo_n[snsr_id] = st->dbnc_lo[snsr_id];
1121                 st->dbnc_hi_n[snsr_id] = 0;
1122                 ret = iqs_write(st, st->dt_en[st->part_i][snsr_id],
1123                                 false, false);
1124         }
1125         if (!ret)
1126                 ret = nvs_proximity_enable(&st->prox[snsr_id]);
1127         return ret;
1128 }
1129
1130 static int iqs_dis(struct iqs_state *st, int snsr_id)
1131 {
1132         unsigned char *wr = NULL;
1133         int ret = 0;
1134
1135         if (snsr_id >= IQS_DEV_N)
1136                 return -EINVAL;
1137
1138         if (snsr_id < 0)
1139                 wr = st->wr_disable;
1140         else if (snsr_id < IQS_DEV_HW_N)
1141                 wr = st->dt_dis[st->part_i][snsr_id];
1142         if (st->hal_tbl_n && wr)
1143                 /* only if HAL initialized */
1144                 ret = iqs_write(st, wr, false, true);
1145         return ret;
1146 }
1147
1148 static int iqs_reenable(struct iqs_state *st)
1149 {
1150         unsigned int i;
1151         int ret;
1152
1153         ret = iqs_init(st);
1154         for (i = 0; i < IQS_DEV_N; i++) {
1155                 if (st->enabled & (1 << i))
1156                         ret |= iqs_en(st, i);
1157         }
1158         iqs_op_rd(st);
1159         return ret;
1160 }
1161
1162 static int iqs_reenable_err(struct iqs_state *st)
1163 {
1164         iqs_err(st);
1165         iqs_reenable(st);
1166         return RET_POLL_NEXT;
1167 }
1168
1169 static int iqs_pm(struct iqs_state *st, bool enable)
1170 {
1171         int ret = 0;
1172
1173         if (enable) {
1174                 ret = nvs_vregs_enable(&st->i2c->dev, st->vreg,
1175                                        ARRAY_SIZE(iqs_vregs));
1176                 if (ret > 0)
1177                         mdelay(IQS_HW_DELAY_MS);
1178         } else {
1179                 ret = nvs_vregs_sts(st->vreg, ARRAY_SIZE(iqs_vregs));
1180                 if ((ret < 0) || (ret == ARRAY_SIZE(iqs_vregs))) {
1181                         ret = iqs_dis(st, -1);
1182                 } else if (ret > 0) {
1183                         nvs_vregs_enable(&st->i2c->dev, st->vreg,
1184                                          ARRAY_SIZE(iqs_vregs));
1185                         mdelay(IQS_HW_DELAY_MS);
1186                         ret = iqs_dis(st, -1);
1187                 }
1188                 ret |= nvs_vregs_disable(&st->i2c->dev, st->vreg,
1189                                          ARRAY_SIZE(iqs_vregs));
1190         }
1191         if (ret > 0)
1192                 ret = 0;
1193         if (ret) {
1194                 dev_err(&st->i2c->dev, "%s pwr=%x ERR=%d\n",
1195                         __func__, enable, ret);
1196         } else {
1197                 if (st->sts & NVS_STS_SPEW_MSG)
1198                         dev_info(&st->i2c->dev, "%s pwr=%x\n",
1199                                  __func__, enable);
1200         }
1201         return ret;
1202 }
1203
1204 static void iqs_pm_exit(struct iqs_state *st)
1205 {
1206         iqs_pm(st, false);
1207         nvs_vregs_exit(&st->i2c->dev, st->vreg, ARRAY_SIZE(iqs_vregs));
1208 }
1209
1210 static int iqs_pm_init(struct iqs_state *st)
1211 {
1212         int ret;
1213
1214         st->enabled = 0;
1215         nvs_vregs_init(&st->i2c->dev,
1216                        st->vreg, ARRAY_SIZE(iqs_vregs), iqs_vregs);
1217         ret = iqs_pm(st, true);
1218         return ret;
1219 }
1220
1221 static int iqs_delta_tst(struct iqs_state *st, int ch, int lt, int gt)
1222 {
1223         if (lt < 0 && gt < 0)
1224                 return -1;
1225
1226         ch += IQS_DEV_DELTA0;
1227         if (lt >= 0 && gt >= 0) {
1228                 if (lt > gt) {
1229                         if (st->prox[ch].proximity < lt &&
1230                                                    st->prox[ch].proximity > gt)
1231                                 return 1;
1232                         else
1233                                 return 0;
1234                 } else {
1235                         if (st->prox[ch].proximity < lt ||
1236                                                    st->prox[ch].proximity > gt)
1237                                 return 1;
1238                         else
1239                                 return 0;
1240                 }
1241         }
1242
1243         if (lt >= 0) {
1244                 if (st->prox[ch].proximity < lt)
1245                         return 1;
1246         }
1247
1248         if (gt >= 0) {
1249                 if (st->prox[ch].proximity > gt)
1250                         return 1;
1251         }
1252
1253         return 0;
1254 }
1255
1256 static int iqs_rd_delta(struct iqs_state *st, s64 ts)
1257 {
1258         u16 hw;
1259         u64 calc_i;
1260         u64 calc_f;
1261         s64 calc;
1262         unsigned int ch;
1263         unsigned int i;
1264         unsigned int j;
1265         int ret;
1266
1267         for (ch = 0; ch < IQS_CH_N; ch++) {
1268                 if (st->enabled & ((1 << ch) << IQS_DEV_DELTA0)) {
1269                         i = iqs_rc_i(st, &st->hal_bit->delta) + (ch << 1);
1270                         hw = (u16)st->rc[i];
1271                         st->prox[i].hw = hw;
1272                         if (st->delta_avg_n) {
1273                                 memcpy(&st->delta_avg[ch][0],
1274                                        &st->delta_avg[ch][1],
1275                                        st->delta_avg_n - 1);
1276                                 st->delta_avg[ch][st->delta_avg_n - 1] = hw;
1277                                 calc_i = 0;
1278                                 for (i = 0; i < st->delta_avg_n; i++)
1279                                         calc_i += st->delta_avg[ch][i];
1280                                 do_div(calc_i, st->delta_avg_n);
1281                                 hw = (u16)calc_i;
1282                         }
1283
1284                         calc_i = hw;
1285                         calc_f = 0;
1286                         if (st->cfg[i].scale.fval) {
1287                                 i = IQS_DEV_DELTA0 + ch;
1288                                 if (st->cfg[i].resolution.fval) {
1289                                         calc_f = (u64)(hw *
1290                                                    st->cfg[i].resolution.fval);
1291                                         do_div(calc_f, st->cfg[i].scale.fval);
1292                                 }
1293                                 if (st->cfg[i].resolution.ival) {
1294                                         if (st->cfg[i].float_significance)
1295                                                 calc_i = IQS_FS_NANO;
1296                                         else
1297                                                 calc_i = IQS_FS_MICRO;
1298                                         do_div(calc_i, st->cfg[i].scale.fval);
1299                                         calc_i *= (u64)(hw *
1300                                                    st->cfg[i].resolution.ival);
1301                                 }
1302                         }
1303                         calc = (s64)(calc_i + calc_f);
1304                         if (st->sts & NVS_STS_SPEW_DATA)
1305                                 dev_info(&st->i2c->dev,
1306                                          "%s ch%u=%lld avg=%u hw=%hu  %lld\n",
1307                                          __func__, ch, calc, hw,
1308                                          st->prox[i].hw, ts);
1309
1310                         st->prox[i].timestamp = ts;
1311                         st->prox[i].proximity = (u32)calc;
1312                         st->nvs->handler(st->prox[i].nvs_st,
1313                                          &st->prox[i].proximity,
1314                                          st->prox[i].timestamp);
1315                 }
1316         }
1317
1318         for (i = 0; i < IQS_DELTA_TEST0_N; i++) {
1319                 hw = 0;
1320                 for (j = 0; j < IQS_DELTA_TEST1_N; j++) {
1321                         if (st->delta_tst[i][j].ch < 0) {
1322                                 break;
1323                         } else if (st->delta_tst[i][j].ch >= IQS_CH_N) {
1324                                 break;
1325                         } else {
1326                                 ret = iqs_delta_tst(st, st->delta_tst[i][j].ch,
1327                                                     st->delta_tst[i][j].lt,
1328                                                     st->delta_tst[i][j].gt);
1329                                 if (ret < 0)
1330                                         break;
1331
1332                                 hw = ret;
1333                                 if (!ret)
1334                                         break;
1335                         }
1336                 }
1337                 if (!hw)
1338                         i++;
1339         }
1340
1341         st->prox[IQS_DEV_DELTA].timestamp = ts;
1342         st->prox[IQS_DEV_DELTA].hw = hw;
1343         st->prox[IQS_DEV_DELTA].proximity = (u32)hw;
1344         st->nvs->handler(st->prox[IQS_DEV_DELTA].nvs_st,
1345                          &st->prox[IQS_DEV_DELTA].proximity,
1346                          st->prox[IQS_DEV_DELTA].timestamp);
1347         return 0;
1348 }
1349
1350 static int iqs_rd_snsr(struct iqs_state *st, s64 ts, int dev,
1351                        const struct iqs_hal_iom *tch,
1352                        const struct iqs_hal_iom *cnt)
1353 {
1354         u16 hw;
1355         u16 rp;                         /* reported proximity */
1356         int ret;
1357
1358         if (st->prox[dev].proximity_binary_hw) {
1359                 hw = (iqs_bits_rd(st, tch, 0));
1360                 rp = hw;
1361                 if (rp) {
1362                         st->dbnc_lo_n[dev] = 0;
1363                         if (st->dbnc_hi[dev]) {
1364                                 if (st->dbnc_hi_n[dev] < st->dbnc_hi[dev]) {
1365                                         st->dbnc_hi_n[dev]++;
1366                                         rp = 0;
1367                                 }
1368                         }
1369                 } else {
1370                         st->dbnc_hi_n[dev] = 0;
1371                         if (st->dbnc_lo[dev]) {
1372                                 if (st->dbnc_lo_n[dev] < st->dbnc_lo[dev]) {
1373                                         st->dbnc_lo_n[dev]++;
1374                                         rp = 1;
1375                                 }
1376                         }
1377                 }
1378                 /* reverse polarity for Android (0=close 1=far) */
1379                 rp = !rp;
1380         } else {
1381                 hw = (u16)st->rc[iqs_rc_i(st, cnt)];
1382                 rp = hw;
1383         }
1384         st->prox[dev].hw = rp;
1385         st->prox[dev].timestamp = ts;
1386         ret = nvs_proximity_read(&st->prox[dev]);
1387         if (st->sts & NVS_STS_SPEW_DATA)
1388                 dev_info(&st->i2c->dev,
1389                          "%s: hw=%hu rp=%hu %lld  lo_n=%u hi_n=%u  %lldns\n",
1390                          iqs_snsr_names[dev], hw, rp, ts,
1391                          st->dbnc_lo_n[dev], st->dbnc_hi_n[dev],
1392                          ts - st->prox[IQS_DEV_PROX].timestamp);
1393         return ret;
1394 }
1395
1396 static int iqs_ati_redo(struct iqs_state *st)
1397 {
1398         iqs_wr(st, st->wr_ati_redo);
1399         st->ati_redo_n++;
1400         if (!st->ati_redo_n)
1401                 st->ati_redo_n--;
1402         /* restart read cycle to get status */
1403         st->op_i = st->op_read_n;
1404         return RET_NO_CHANGE;
1405 }
1406
1407 static int iqs_rd(struct iqs_state *st, bool poll)
1408 {
1409         s64 ts;
1410         unsigned int i;
1411         unsigned int k;
1412         unsigned int ch;
1413         int mc;
1414         int ret = 0;
1415
1416 #ifdef IQS_I2C_M_NO_RD_ACK
1417         /* I2C message stacking */
1418         for (i = 0; i < st->op_read_n; i++)
1419                 iqs_i2c_rd(st, st->op_read_reg[i], 0);
1420         ret = iqs_i2c(st, true);
1421 #else /* IQS_I2C_M_NO_RD_ACK */
1422         if (atomic_xchg(&iqs_ext_sts_chg, 0))
1423                 iqs_ati_redo(st);
1424         st->op_i++;
1425         if (st->op_i >= st->op_read_n) {
1426                 st->op_i = 0; /* restart read cycle */
1427                 /* when slider is enabled then device automatically goes into
1428                  * and stays in stream mode during the slider event.  The DT
1429                  * stream_mode should be set to (IQS_STREAM_AUTO) for this.
1430                  */
1431                 if ((st->stream == IQS_STREAM_OFF) || !poll) {
1432                         /* enter stream mode on first I2C transaction if DT
1433                          * stream_mode IQS_STREAM_OFF OR not polling
1434                          */
1435                         ret = iqs_stream(st, true);
1436                         if (!ret)
1437                                 /* was in event mode */
1438                                 poll = false; /* need to force mode switch */
1439                 }
1440         } else if (st->op_i == 1) {
1441                 iqs_wr(st, st->dt_evnt[st->part_i]); /* DT additional action */
1442         }
1443         if (st->op_i == st->op_read_n - 1) {
1444                 /* at the end of read cycle */
1445                 if (st->stream != IQS_STREAM_ALWAYS)
1446                         iqs_stream(st, false); /* event mode at end of reads */
1447         }
1448         iqs_i2c_rd(st, st->op_read_reg[st->op_i], 0);
1449         ret = iqs_i2c(st, poll);
1450 #endif /* IQS_I2C_M_NO_RD_ACK */
1451         if (ret) {
1452 #if 0
1453                 /* device needs to be power cycled */
1454                 iqs_pm(st, false);
1455                 iqs_pm(st, true);
1456                 return iqs_reenable_err(st);
1457 #endif /* 0 */
1458         } else {
1459                 /* test for device reset */
1460                 if (st->op_read_reg[st->op_i] ==
1461                                             st->hal_bit->sysflag_reset.hal_i) {
1462                         if (iqs_bits_rd(st, &st->hal_bit->sysflag_reset, 0))
1463                                 /* an error occurred so reinitialization */
1464                                 return iqs_reenable_err(st);
1465
1466                         if (iqs_bits_rd(st, &st->hal_bit->ati_busy, 0)) {
1467                                 /* restart read cycle to get status */
1468                                 st->op_i = st->op_read_n;
1469                                 return RET_NO_CHANGE;
1470                         }
1471
1472                         if (iqs_bits_rd(st, &st->hal_bit->ati_err, 0))
1473                                 /* ATI redo on next I2C access */
1474                                 return iqs_ati_redo(st);
1475                 }
1476
1477                 /* test for partial ATI */
1478                 if (st->op_read_reg[st->op_i] ==
1479                                                st->hal_bit->multi_comp.hal_i) {
1480                         /* check if reseed needed */
1481                         ch = iqs_bits_rd(st, &st->hal_bit->active_ch, 0);
1482                         for (i = 0; i < IQS_CH_N; i++) {
1483                                 if (ch & (1 << i)) {
1484                                         mc = iqs_bits_rd(st,
1485                                                   &st->hal_bit->multi_comp, i);
1486                                         if (i)
1487                                                 k = IQS_DEV_TOUCH;
1488                                         else
1489                                                 k = IQS_DEV_PROX;
1490                                         if (mc > st->cfg[k].thresh_hi) {
1491                                                 /* reseed on next I2C access */
1492                                                 iqs_wr(st, st->wr_reseed);
1493                                                 /* restart cycle for status */
1494                                                 st->op_i = st->op_read_n;
1495                                                 break;
1496                                         }
1497                                 }
1498                         }
1499                 }
1500                 /* read data */
1501                 ts = nvs_timestamp();
1502                 if (st->enabled & (1 << IQS_DEV_PROX))
1503                         ret |= iqs_rd_snsr(st, ts, IQS_DEV_PROX,
1504                                            &st->hal_bit->touch_prx,
1505                                            &st->hal_bit->count_prx);
1506                 if (st->enabled & (1 << IQS_DEV_TOUCH))
1507                         ret |= iqs_rd_snsr(st, ts, IQS_DEV_TOUCH,
1508                                            &st->hal_bit->touch_tch,
1509                                            &st->hal_bit->count_tch);
1510                 if (st->enabled & (st->delta_ch_msk << IQS_DEV_DELTA0))
1511                         ret |= iqs_rd_delta(st, ts);
1512                 /* TODO: Expect the PO pin used for proximity_binary_hw.
1513                  *       Use a proximity threshold for SAR GPIO so that
1514                  *       proximity doesn't have to be in HW binary mode.
1515                  */
1516                 if (st->gpio_sar_dev_asrt < IQS_DEV_N) {
1517                         /* SAR GPIO assert and deassert can be controlled by
1518                          * separate sources.
1519                          * GPIO  polarity | XOR  asserted
1520                          *  0        0    |  0      1
1521                          *  0        1    |  1      0
1522                          *  1        0    |  1      0
1523                          *  1        1    |  0      1
1524                          */
1525                         if (st->gpio_sar_val ^ st->gpio_sar_asrt_pol)
1526                                 /* currently deasserted */
1527                                 iqs_gpio_sar(st, !st->prox[st->
1528                                              gpio_sar_dev_asrt].proximity);
1529                         else
1530                                 /* currently asserted */
1531                                 iqs_gpio_sar(st, !st->prox[st->
1532                                              gpio_sar_dev_dasrt].proximity);
1533                 }
1534         }
1535         if (st->stream == IQS_STREAM_ALWAYS) {
1536                 /* with stream always on we want to control the IRQ rate */
1537                 if (ret != RET_NO_CHANGE) {
1538                         /* keep IRQ enabled if anything but no change */
1539                         ret = RET_HW_UPDATE;
1540                 } else if (st->op_i == st->op_read_n - 1) {
1541                         /* throttle IRQ at end of read cycle */
1542                         iqs_disable_irq(st);
1543                         ret = RET_POLL_NEXT;
1544                 }
1545         }
1546         return ret;
1547 }
1548
1549 static int iqs_disable(struct iqs_state *st, int snsr_id)
1550 {
1551         bool disable = true;
1552         unsigned int i;
1553         int ret = 0;
1554
1555         if (snsr_id >= 0) {
1556                 ret = iqs_dis(st, snsr_id);
1557                 if (!ret)
1558                         st->enabled &= ~(1 << snsr_id);
1559                 if (st->enabled)
1560                         disable = false;
1561         } else {
1562                 for (i = 0; i < IQS_DEV_N; i++) {
1563                         if (st->enabled & (1 << i))
1564                                 iqs_dis(st, i);
1565                 }
1566         }
1567         if (disable) {
1568                 iqs_disable_irq(st);
1569                 if (st->dw.work.func)
1570                         cancel_delayed_work(&st->dw);
1571                 ret = iqs_pm(st, false);
1572                 if (!ret)
1573                         st->enabled = 0;
1574         }
1575         return ret;
1576 }
1577
1578 static int iqs_enable(struct iqs_state *st, int snsr_id, int enable)
1579 {
1580         int ret;
1581
1582         if (enable) {
1583                 enable = st->enabled | (1 << snsr_id);
1584                 ret = iqs_pm(st, true);
1585                 if (!ret) {
1586                         if (!st->enabled)
1587                                 ret = iqs_init(st);
1588                         ret |= iqs_en(st, snsr_id);
1589                         if (ret < 0) {
1590                                 iqs_disable(st, snsr_id);
1591                         } else {
1592                                 st->enabled = enable;
1593                                 iqs_op_rd(st);
1594                                 mod_delayed_work(system_freezable_wq, &st->dw,
1595                                          msecs_to_jiffies(IQS_START_DELAY_MS));
1596                         }
1597                 }
1598         } else {
1599                 ret = iqs_disable(st, snsr_id);
1600         }
1601         return ret;
1602 }
1603
1604 static int iqs_enables(struct iqs_state *st, unsigned int en_mask)
1605 {
1606         unsigned int i;
1607         int ret = 0;
1608
1609         for (i = 0; i < IQS_DEV_N; i++) {
1610                 if (en_mask & (1 << i))
1611                         ret |= iqs_enable(st, i, 1);
1612         }
1613         return ret;
1614 }
1615
1616 static unsigned int iqs_polldelay(struct iqs_state *st)
1617 {
1618         unsigned int poll_delay_ms = IQS_POLL_DLY_MS_MAX;
1619         unsigned int i;
1620
1621         for (i = 0; i < IQS_DEV_HW_N; i++) {
1622                 if (st->enabled & (1 << i)) {
1623                         if (poll_delay_ms > st->prox[i].poll_delay_ms)
1624                                 poll_delay_ms = st->prox[i].poll_delay_ms;
1625                 }
1626         }
1627         return poll_delay_ms;
1628 }
1629
1630 static void iqs_read(struct iqs_state *st, bool poll)
1631 {
1632         unsigned int ms = st->wd_to_ms;
1633         int ret;
1634
1635         iqs_mutex_lock(st);
1636         if (st->resume) {
1637                 if (st->suspend_dis) {
1638                         ret = iqs_reenable(st);
1639                 } else {
1640                         ret = iqs_enables(st, st->susrsm_en);
1641                         st->susrsm_en &= ~st->enabled;
1642                 }
1643                 if (ret) {
1644                         if (st->sts & NVS_STS_SPEW_MSG)
1645                                 dev_err(&st->i2c->dev,
1646                                         "%s resume ERR=%d Try again in %ums\n",
1647                                         __func__, ret, ms);
1648                 } else {
1649                         st->resume = false;
1650                         st->susrsm_en = 0;
1651                         iqs_enable_irq(st);
1652                         if (st->sts & NVS_STS_SPEW_MSG)
1653                                 dev_info(&st->i2c->dev, "%s resume complete\n",
1654                                          __func__);
1655                 }
1656                 mod_delayed_work(system_freezable_wq, &st->dw,
1657                                  msecs_to_jiffies(ms));
1658         } else if (st->enabled) {
1659 #ifdef IQS_I2C_M_NO_RD_ACK
1660                 ret = iqs_rd(st, poll);
1661                 if (ret > RET_POLL_NEXT)
1662                         iqs_enable_irq(st);
1663                 else
1664                         ms = iqs_polldelay(st);
1665 #else /* IQS_I2C_M_NO_RD_ACK */
1666                 if (st->irq_dis) {
1667                         /* if IRQ disabled then in irq throttle mode */
1668                         iqs_enable_irq(st); /* IRQ driven mode */
1669                 } else {
1670                         ret = iqs_rd(st, poll);
1671                         if (ret > RET_POLL_NEXT)
1672                                 iqs_enable_irq(st);
1673                         else
1674                                 ms = iqs_polldelay(st);
1675                 }
1676 #endif /* IQS_I2C_M_NO_RD_ACK */
1677                 /* always start a delayed work thread as a watchdog */
1678                 mod_delayed_work(system_freezable_wq, &st->dw,
1679                                  msecs_to_jiffies(ms));
1680                 if (st->sts & NVS_STS_SPEW_MSG)
1681                         dev_info(&st->i2c->dev, "%s work delay=%ums\n",
1682                                  __func__, ms);
1683         }
1684         iqs_mutex_unlock(st);
1685 }
1686
1687 static void iqs_work(struct work_struct *ws)
1688 {
1689         struct iqs_state *st = container_of((struct delayed_work *)ws,
1690                                             struct iqs_state, dw);
1691
1692         iqs_read(st, false);
1693 }
1694
1695 static irqreturn_t iqs_irq_thread(int irq, void *dev_id)
1696 {
1697         struct iqs_state *st = (struct iqs_state *)dev_id;
1698
1699         iqs_read(st, true);
1700         return IRQ_HANDLED;
1701 }
1702
1703 static irqreturn_t iqs_irq_handler(int irq, void *dev_id)
1704 {
1705         struct iqs_state *st = (struct iqs_state *)dev_id;
1706
1707         if (st->sts & NVS_STS_SPEW_IRQ)
1708                 dev_info(&st->i2c->dev, "%s\n", __func__);
1709         return IRQ_WAKE_THREAD;
1710 }
1711
1712 static int iqs_enable_os(void *client, int snsr_id, int enable)
1713 {
1714         struct iqs_state *st = (struct iqs_state *)client;
1715
1716         if (enable < 0)
1717                 return st->enabled & (1 << snsr_id);
1718
1719         if (st->os == IQS_OS_CONTROL || st->sts & (NVS_STS_SHUTDOWN |
1720                                                    NVS_STS_SUSPEND))
1721                 return iqs_enable(st, snsr_id, enable);
1722
1723         if (enable)
1724                 st->prox[snsr_id].report = st->cfg[snsr_id].report_n;
1725         return 0;
1726 }
1727
1728 static int iqs_batch(void *client, int snsr_id, int flags,
1729                     unsigned int period_us, unsigned int timeout_us)
1730 {
1731         struct iqs_state *st = (struct iqs_state *)client;
1732
1733         if (timeout_us)
1734                 /* timeout not supported (no HW FIFO) */
1735                 return -EINVAL;
1736
1737         st->prox[snsr_id].delay_us = period_us;
1738         return 0;
1739 }
1740
1741 static int iqs_thresh_lo(void *client, int snsr_id, int thresh)
1742 {
1743         struct iqs_state *st = (struct iqs_state *)client;
1744         unsigned int hal_i;
1745         unsigned int i;
1746         unsigned int n;
1747         int ret;
1748
1749         if (snsr_id >= IQS_DEV_DELTA && snsr_id <= IQS_DEV_DELTA3) {
1750                 st->cfg[snsr_id].thresh_lo = thresh;
1751                 return 0;
1752         }
1753
1754         if (snsr_id == IQS_DEV_TOUCH) {
1755                 hal_i = st->hal_bit->thresh_tch.hal_i;
1756                 i = st->hal_bit->thresh_tch.offset + 1;
1757                 n = i + st->hal_bit->thresh_tch.mask;
1758         } else {
1759                 hal_i = st->hal_bit->thresh_prx.hal_i;
1760                 i = st->hal_bit->thresh_prx.offset + 1;
1761                 n = i + st->hal_bit->thresh_prx.mask;
1762         }
1763         for (; i < n; i++) {
1764                 st->rc[st->hal_tbl[hal_i].ndx + i] = thresh & 0xFF;
1765                 thresh >>= 8;
1766         }
1767         ret = iqs_i2c_write(st, hal_i, 0, false, true);
1768         if (!ret)
1769                 st->cfg[snsr_id].thresh_lo = thresh;
1770         return ret;
1771 }
1772
1773 static int iqs_regs(void *client, int snsr_id, char *buf)
1774 {
1775         struct iqs_state *st = (struct iqs_state *)client;
1776         ssize_t t;
1777         bool irq_dis;
1778         unsigned int i;
1779         unsigned int j;
1780         unsigned int n;
1781         int ret = 0;
1782
1783         iqs_mutex_lock(st);
1784         irq_dis = st->irq_dis;
1785 #ifdef IQS_I2C_M_NO_RD_ACK
1786         /* I2C message stacking */
1787         for (i = 0; i < st->hal_tbl_n; i++)
1788                 iqs_i2c_rd(st, i, 0);
1789         ret = iqs_i2c(st, false);
1790         t = sprintf(buf, "registers: (ERR=%d)\n", ret);
1791         for (i = 0; i < st->hal_tbl_n; i++) {
1792                 n = st->hal_tbl[i].ndx;
1793                 t += sprintf(buf + t, "0x%hhx=", st->rc[n]);
1794                 n = st->hal_tbl[i].ndx + st->hal_tbl[i].len;
1795                 for (j = st->hal_tbl[i].ndx + 1; j <= n; j++)
1796                         t += sprintf(buf + t, "0x%hhx ", st->rc[j]);
1797                 t += sprintf(buf + t, "\n");
1798         }
1799 #else /* IQS_I2C_M_NO_RD_ACK */
1800         t = sprintf(buf, "registers:\n");
1801         for (i = 0; i < st->hal_tbl_n; i++) {
1802                 ret = iqs_i2c_read(st, i, 0, false);
1803                 n = st->hal_tbl[i].ndx;
1804                 if (ret) {
1805                         t += sprintf(buf + t, "0x%hhx=ERR %d",
1806                                      st->rc[n], ret);
1807                 } else {
1808                         t += sprintf(buf + t, "0x%hhx=", st->rc[n]);
1809                         n = st->hal_tbl[i].ndx + st->hal_tbl[i].len;
1810                         for (j = st->hal_tbl[i].ndx + 1; j <= n; j++)
1811                                 t += sprintf(buf + t, "0x%hhx ", st->rc[j]);
1812                         t += sprintf(buf + t, "\n");
1813                 }
1814         }
1815 #endif /* IQS_I2C_M_NO_RD_ACK */
1816         iqs_irq_restore(st, irq_dis);
1817         iqs_mutex_unlock(st);
1818         return t;
1819 }
1820
1821 static int iqs_nvs_write(void *client, int snsr_id, unsigned int nvs)
1822 {
1823         struct iqs_state *st = (struct iqs_state *)client;
1824         u8 val = (nvs >> 8) & 0xFF;
1825         unsigned int offset;
1826         unsigned int reg;
1827         unsigned int i;
1828         int ret = -EINVAL;
1829
1830         switch (nvs & 0xFF) {
1831         case IQS_INFO_STS:
1832         case IQS_INFO_DBG:
1833                 st->dbg = nvs;
1834                 return 0;
1835
1836         case IQS_INFO_EXT_STATE_SPEW:
1837                 st->sts ^= IQS_STS_EXT_STATE;
1838                 dev_info(&st->i2c->dev, "%s EXT_STATE_SPEW=%x\n",
1839                          __func__, !!(st->sts & IQS_STS_EXT_STATE));
1840                 return 0;
1841
1842         case IQS_INFO_GPIO_SAR_SPEW:
1843                 st->sts ^= IQS_STS_GPIO_SAR;
1844                 dev_info(&st->i2c->dev, "%s GPIO_SAR_SPEW=%x\n",
1845                          __func__, !!(st->sts & IQS_STS_GPIO_SAR));
1846                 return 0;
1847
1848         case IQS_INFO_GPIO_RDY_INPUT:
1849                 ret = gpio_direction_input(st->gpio_rdy);
1850                 dev_info(&st->i2c->dev,
1851                          "%s gpio_direction_input(gpio_rdy(%d))=%d\n",
1852                          __func__, st->gpio_rdy, ret);
1853                 return ret;
1854
1855         case IQS_INFO_GPIO_RDY_OUTPUT:
1856                 val = !!val;
1857                 ret = gpio_direction_output(st->gpio_rdy, val);
1858                 dev_info(&st->i2c->dev,
1859                          "%s gpio_direction_output(gpio_rdy(%d), %hhx)=%d\n",
1860                          __func__, st->gpio_rdy, val, ret);
1861                 return ret;
1862
1863         case IQS_INFO_GPIO_SAR_OUTPUT:
1864                 val = !!val;
1865                 if (st->gpio_sar >= 0) {
1866                         ret = gpio_direction_output(st->gpio_sar, val);
1867                         if (!ret)
1868                                 st->gpio_sar_val = val;
1869                 }
1870                 dev_info(&st->i2c->dev,
1871                          "%s gpio_direction_output(gpio_sar(%d), %hhx)=%d\n",
1872                          __func__, st->gpio_sar, val, ret);
1873                 return ret;
1874
1875         case IQS_INFO_REG_WR:
1876                 offset = ((nvs >> 16) & 0xFF) + 1;
1877                 reg = (nvs >> 24) & 0xFF;
1878                 for (i = 0; i < st->hal_tbl_n; i++) {
1879                         if (st->hal_tbl[i].reg == reg) {
1880                                 if (offset > st->hal_tbl[i].len)
1881                                         break;
1882
1883                                 iqs_mutex_lock(st);
1884                                 st->rc[st->hal_tbl[i].ndx + offset] = val;
1885                                 ret = iqs_i2c_write(st, i, 0, false, true);
1886                                 iqs_mutex_unlock(st);
1887                                 dev_info(&st->i2c->dev,
1888                                          "%s %x => %x + %u err=%d\n",
1889                                          __func__, val, reg, offset - 1, ret);
1890                                 return ret;
1891                         }
1892                 }
1893                 return ret;
1894
1895         default:
1896                 ret = 0;
1897                 break;
1898         }
1899
1900         return ret;
1901 }
1902
1903 static ssize_t iqs_nvs_dbg_db(struct iqs_state *st, char *buf, ssize_t t,
1904                               unsigned char *db)
1905 {
1906         unsigned int i;
1907         unsigned int j;
1908         unsigned int n;
1909
1910         i = 0;
1911         while (db[i]) {
1912                 n = db[i];
1913                 i++;
1914                 if (n == 0xFF) {
1915                         t += sprintf(buf + t, "flush write and mdelay=%hhu\n",
1916                                      db[i]);
1917                         i++;
1918                         continue;
1919                 }
1920
1921                 t += sprintf(buf + t, "len=%x reg=%x data/mask=", n, db[i]);
1922                 i++;
1923                 for (j = 0; j < n; j++)
1924                         t += sprintf(buf + t, "%x/%x ",
1925                                      db[i + j], db[i + j + n]);
1926                 t += sprintf(buf + t, "\n");
1927                 i += (n << 1);
1928         }
1929         if (i == 0)
1930                 t += sprintf(buf + t, "<empty>\n");
1931         return t;
1932 }
1933
1934 static ssize_t iqs_nvs_dbg_tst(struct iqs_state *st, char *buf, ssize_t t,
1935                                struct iqs_delta_tst *tst)
1936 {
1937         if (tst->lt >= 0 && tst->gt >= 0) {
1938                 if (tst->lt > tst->gt)
1939                         t += sprintf(buf + t, "if (ch%d > %d && ch%d < %d)\n",
1940                                      tst->ch, tst->gt, tst->ch, tst->lt);
1941                 else
1942                         t += sprintf(buf + t, "if (ch%d < %d || ch%d > %d)\n",
1943                                      tst->ch, tst->lt, tst->ch, tst->gt);
1944                 return t;
1945         }
1946
1947         if (tst->lt >= 0) {
1948                 t += sprintf(buf + t, "if (ch%d < %d)\n", tst->ch, tst->lt);
1949                 return t;
1950         }
1951
1952         if (tst->gt >= 0) {
1953                 t += sprintf(buf + t, "if (ch%d > %d)\n", tst->ch, tst->gt);
1954                 return t;
1955         }
1956
1957         t += sprintf(buf + t, "exit conditions\n");
1958         return t;
1959 }
1960
1961 static int iqs_nvs_read(void *client, int snsr_id, char *buf)
1962 {
1963         struct iqs_state *st = (struct iqs_state *)client;
1964         u8 prt = (st->dbg >> 24) & 0xFF;
1965         u8 cmd = (st->dbg >> 16) & 0xFF;
1966         u8 dev = (st->dbg >> 8) & 0xFF;
1967         ssize_t t = 0;
1968         int i;
1969         int j;
1970         int n;
1971
1972         switch (st->dbg & 0xFF) {
1973         case IQS_INFO_DBG:
1974                 if (cmd >= IQS_DB_CMD_N) {
1975                         t = sprintf(buf, "ERR: UNKNOWN COMMAND\n");
1976                         break;
1977                 }
1978
1979                 if (cmd == IQS_DB_CMD_DELTA) {
1980                         t = sprintf(buf, "DELTA conditions:\n");
1981                         for (i = 0; i < IQS_DELTA_TEST0_N; i++) {
1982                                 if (i)
1983                                         t += sprintf(buf + t, "if %s:\n",
1984                                                      iqs_delta_tst_dt[i]);
1985                                 else
1986                                         t += sprintf(buf + t, "%s:\n",
1987                                                      iqs_delta_tst_dt[i]);
1988                                 for (j = 0; j < IQS_DELTA_TEST1_N; j++) {
1989                                         if (st->delta_tst[i][j].ch < 0)
1990                                                 break;
1991                                         else if (st->delta_tst[i][j].ch >=
1992                                                                       IQS_CH_N)
1993                                                 break;
1994                                         else
1995                                                 t += iqs_nvs_dbg_tst(st,
1996                                                                      buf, t,
1997                                                          &st->delta_tst[i][j]);
1998                                 }
1999                         }
2000                         return t;
2001                 }
2002
2003                 if (!prt) {
2004                         i = st->part_i;
2005                 } else if (prt == IQS_DEVID_IQS253) {
2006                         i = IQS_PART_253;
2007                 } else if (prt == IQS_DEVID_IQS263) {
2008                         i = IQS_PART_263;
2009                 } else {
2010                         t = sprintf(buf, "ERR: UNKNOWN PART\n");
2011                         break;
2012                 }
2013
2014                 if (dev > IQS_DEV_HW_N) {
2015                         t = sprintf(buf, "ERR: UNKNOWN DEVICE\n");
2016                         break;
2017                 } else if (dev) {
2018                         n = dev;
2019                         dev--;
2020                 } else {
2021                         n = IQS_DEV_HW_N;
2022                 }
2023
2024                 if (cmd == IQS_DB_CMD_INIT || !cmd) {
2025                         t += sprintf(buf + t, "%s initialization:\n",
2026                                      iqs_i2c_device_id[i].name);
2027                         t += iqs_nvs_dbg_db(st, buf, t, st->dt_init[i]);
2028                 }
2029                 if (cmd == IQS_DB_CMD_EN || !cmd) {
2030                         for (j = dev; j < n; j++) {
2031                                 t += sprintf(buf + t, "%s %s enable:\n",
2032                                              iqs_i2c_device_id[i].name,
2033                                              iqs_snsr_names[j]);
2034                                 t += iqs_nvs_dbg_db(st, buf, t,
2035                                                     st->dt_en[i][j]);
2036                         }
2037                 }
2038                 if (cmd == IQS_DB_CMD_DIS || !cmd) {
2039                         for (j = dev; j < n; j++) {
2040                                 t += sprintf(buf + t, "%s %s disable:\n",
2041                                              iqs_i2c_device_id[i].name,
2042                                              iqs_snsr_names[j]);
2043                                 t += iqs_nvs_dbg_db(st, buf, t,
2044                                                     st->dt_dis[i][j]);
2045                         }
2046                 }
2047                 if (cmd == IQS_DB_CMD_EVNT || !cmd) {
2048                         t += sprintf(buf + t, "%s event:\n",
2049                                      iqs_i2c_device_id[i].name);
2050                         t += iqs_nvs_dbg_db(st, buf, t, st->dt_evnt[i]);
2051                 }
2052                 if (cmd == IQS_DB_CMD_SUSPND || !cmd) {
2053                         t += sprintf(buf + t, "%s suspend:\n",
2054                                      iqs_i2c_device_id[i].name);
2055                         t += iqs_nvs_dbg_db(st, buf, t, st->dt_suspnd[i]);
2056                 }
2057                 break;
2058
2059         default:
2060                 t = sprintf(buf, "IQS driver v. %u\n", IQS_DRIVER_VERSION);
2061                 t += sprintf(buf + t, "ATI redo count=%u\n", st->ati_redo_n);
2062                 st->ati_redo_n = 0;
2063                 t += sprintf(buf + t, "os_options=%x\n", st->os);
2064                 t += sprintf(buf + t, "stream_mode=%x\n", st->stream);
2065                 t += sprintf(buf + t, "watchdog_timeout_ms=%u\n",
2066                              st->wd_to_ms);
2067                 t += sprintf(buf + t, "i2c_ss_delay_ns=%lld\n",
2068                              st->i2c_ss_war_ns);
2069                 t += sprintf(buf + t, "i2c_retry=%u\n", st->i2c_retry);
2070                 t += sprintf(buf + t, "gpio_rdy_retry=%u\n",
2071                              st->gpio_rdy_retry);
2072                 if (st->gpio_rdy < 0)
2073                         t += sprintf(buf + t, "NO gpio_rdy\n");
2074                 else
2075                         t += sprintf(buf + t, "gpio_rdy %d=%d\n", st->gpio_rdy,
2076                                      gpio_get_value_cansleep(st->gpio_rdy));
2077                 if (st->gpio_sar < 0)
2078                         t += sprintf(buf + t, "NO gpio_sar\n");
2079                 else
2080                         t += sprintf(buf + t, "gpio_sar %d=%d\n", st->gpio_sar,
2081                                      gpio_get_value_cansleep(st->gpio_sar));
2082                 t += sprintf(buf + t, "gpio_sar_assert_polarity=%d\n",
2083                              st->gpio_sar_asrt_pol);
2084                 t += sprintf(buf + t, "gpio_sar_dev_assert=%s\n",
2085                              iqs_snsr_names[st->gpio_sar_dev_asrt]);
2086                 t += sprintf(buf + t, "gpio_sar_dev_deassert=%s\n",
2087                              iqs_snsr_names[st->gpio_sar_dev_dasrt]);
2088                 t += sprintf(buf + t, "gpio_sar_suspend_assert=%d\n",
2089                              st->gpio_sar_sus_asrt);
2090                 t += sprintf(buf + t, "deferred_resume_ms=%u\n",
2091                              st->dfr_rsm_ms);
2092                 t += sprintf(buf + t, "resume=%x\n", st->resume);
2093                 for (i = 0; i < IQS_DEV_HW_N; i++) {
2094                         if (st->dbnc_lo[i])
2095                                 t += sprintf(buf + t, "%s_debounce_lo=%u\n",
2096                                              iqs_snsr_names[i],
2097                                              st->dbnc_lo[i]);
2098                         if (st->dbnc_hi[i])
2099                                 t += sprintf(buf + t, "%s_debounce_hi=%u\n",
2100                                              iqs_snsr_names[i],
2101                                              st->dbnc_hi[i]);
2102                 }
2103                 t += sprintf(buf + t, "SAR_delta_channel_mask=%u\n",
2104                              st->delta_ch_msk);
2105                 if (st->delta_ch_msk)
2106                         t += sprintf(buf + t, "SAR_delta_average_count=%u\n",
2107                                      st->delta_avg_n);
2108                 t += sprintf(buf + t, "irq=%d\n", st->i2c->irq);
2109                 t += sprintf(buf + t, "irq_disable=%x\n", st->irq_dis);
2110                 t += sprintf(buf + t, "irq_trigger_edge=%x\n",
2111                              st->irq_trigger_edge);
2112                 for (i = 0; i < IQS_DEV_HW_N; i++)
2113                         t += sprintf(buf + t, "%s_binary_hw=%x\n",
2114                                      iqs_snsr_names[i],
2115                                      st->prox[i].proximity_binary_hw);
2116         }
2117
2118         st->dbg = IQS_INFO_STS;
2119         return t;
2120 }
2121
2122 static struct nvs_fn_dev iqs_fn_dev = {
2123         .enable                         = iqs_enable_os,
2124         .batch                          = iqs_batch,
2125         .thresh_lo                      = iqs_thresh_lo,
2126         .regs                           = iqs_regs,
2127         .nvs_write                      = iqs_nvs_write,
2128         .nvs_read                       = iqs_nvs_read,
2129 };
2130
2131
2132 int sar_external_status(int status)
2133 {
2134         iqs_ext_sts = status;
2135         atomic_set(&iqs_ext_sts_chg, 1);
2136         if (iqs_fn_dev.sts) {
2137                 if (*iqs_fn_dev.sts & (NVS_STS_SPEW_MSG | IQS_STS_EXT_STATE))
2138                         pr_info("%s status=%d\n", __func__, status);
2139         }
2140         return 0;
2141 }
2142 EXPORT_SYMBOL(sar_external_status);
2143
2144
2145 static int iqs_suspend(struct device *dev)
2146 {
2147         struct i2c_client *client = to_i2c_client(dev);
2148         struct iqs_state *st = i2c_get_clientdata(client);
2149         unsigned int i;
2150         int ret = 0;
2151         s64 ts = 0; /* = 0 to fix compile */
2152
2153         if (st->sts & NVS_STS_SPEW_MSG)
2154                 ts = nvs_timestamp();
2155         /* Due to the device's horrendous communication protocol that causes
2156          * unacceptable delays, suspend flag is used to exit pending actions.
2157          */
2158         st->susrsm = true;
2159         iqs_mutex_lock(st);
2160         st->susrsm = false;
2161         st->sts |= NVS_STS_SUSPEND;
2162         st->susrsm_en |= st->enabled;
2163         /* determine if we'll be operational during suspend */
2164         for (i = 0; i < IQS_DEV_HW_N; i++) {
2165                 if ((st->enabled & (1 << i)) && (st->cfg[i].flags &
2166                                                  SENSOR_FLAG_WAKE_UP))
2167                         break;
2168         }
2169         if (i < IQS_DEV_HW_N) {
2170                 st->suspend_dis = true; /* stay active during suspend */
2171                 /* DT additional action for suspend */
2172                 ret = iqs_write(st, st->dt_suspnd[st->part_i], false, false);
2173                 iqs_enable_irq(st);
2174                 irq_set_irq_wake(st->i2c->irq, 1);
2175                 st->irq_set_irq_wake = true;
2176         } else {
2177                 st->suspend_dis = false;
2178                 iqs_disable(st, -1);
2179                 if (st->gpio_sar_sus_asrt >= 0)
2180                         iqs_gpio_sar(st, st->gpio_sar_sus_asrt);
2181         }
2182         if (st->dw.work.func)
2183                 /* turn off watchdog during suspend */
2184                 cancel_delayed_work(&st->dw);
2185         iqs_mutex_unlock(st);
2186         if (st->sts & NVS_STS_SPEW_MSG)
2187                 dev_info(&client->dev, "%s elapsed t=%lldns  err=%d\n",
2188                          __func__, nvs_timestamp() - ts, ret);
2189         return 0;
2190 }
2191
2192 static int iqs_resume(struct device *dev)
2193 {
2194         struct i2c_client *client = to_i2c_client(dev);
2195         struct iqs_state *st = i2c_get_clientdata(client);
2196         s64 ts = 0; /* = 0 to fix compile */
2197         int ret = 0;
2198
2199         if (st->sts & NVS_STS_SPEW_MSG)
2200                 ts = nvs_timestamp();
2201         st->susrsm = true;
2202         iqs_mutex_lock(st);
2203         st->susrsm = false;
2204         if (st->irq_set_irq_wake) {
2205                 irq_set_irq_wake(st->i2c->irq, 0);
2206                 st->irq_set_irq_wake = false;
2207         }
2208         st->sts &= ~NVS_STS_SUSPEND;
2209         if (st->susrsm_en) {
2210                 /* Due to the device's horrendous communication protocol that
2211                  * causes unacceptable delays, resume is deferred.
2212                  */
2213                 st->resume = true;
2214                 mod_delayed_work(system_freezable_wq, &st->dw,
2215                                  msecs_to_jiffies(st->dfr_rsm_ms));
2216         }
2217         iqs_mutex_unlock(st);
2218         if (st->sts & NVS_STS_SPEW_MSG)
2219                 dev_info(&client->dev, "%s elapsed t=%lldns  err=%d\n",
2220                          __func__, nvs_timestamp() - ts, ret);
2221         return 0;
2222 }
2223
2224 static SIMPLE_DEV_PM_OPS(iqs_pm_ops, iqs_suspend, iqs_resume);
2225
2226 static void iqs_shutdown(struct i2c_client *client)
2227 {
2228         struct iqs_state *st = i2c_get_clientdata(client);
2229
2230         iqs_mutex_lock(st);
2231         st->sts |= NVS_STS_SHUTDOWN;
2232         iqs_disable(st, -1);
2233         iqs_mutex_unlock(st);
2234         if (st->sts & NVS_STS_SPEW_MSG)
2235                 dev_info(&client->dev, "%s\n", __func__);
2236 }
2237
2238 static int iqs_remove(struct i2c_client *client)
2239 {
2240         struct iqs_state *st = i2c_get_clientdata(client);
2241         unsigned int i;
2242
2243         if (st != NULL) {
2244                 iqs_shutdown(client);
2245                 if (st->nvs) {
2246                         for (i = 0; i < IQS_DEV_N; i++) {
2247                                 if (st->prox[i].nvs_st)
2248                                         st->nvs->remove(st->prox[i].nvs_st);
2249                         }
2250                 }
2251                 iqs_pm_exit(st);
2252         }
2253         for (i = 0; i < IQS_CH_N; i++)
2254                 kfree(st->delta_avg[i]);
2255         dev_info(&client->dev, "%s\n", __func__);
2256         return 0;
2257 }
2258
2259 static void iqs_id_part(struct iqs_state *st, const char *part)
2260 {
2261         unsigned int i;
2262
2263         for (i = 0; i < IQS_DEV_N; i++)
2264                 st->cfg[i].part = part;
2265 }
2266
2267 static int iqs_id_dev(struct iqs_state *st, const char *name)
2268 {
2269         unsigned int hal_i;
2270         unsigned int i;
2271         int ret = 1;
2272
2273         /* assume for initial dev id read */
2274         st->hal_tbl = iqs263_hal_tbl;
2275         st->hal_tbl_n = ARRAY_SIZE(iqs263_hal_tbl);
2276         st->hal_bit = &iqs263_hal_bit;
2277         for (i = 0; i < ARRAY_SIZE(st->msg); i++)
2278                 st->msg[i].addr = st->i2c_addr;
2279         if (!strcmp(name, IQS_NAME_IQS263))
2280                 st->dev_id = IQS_DEVID_IQS263;
2281         else if (!strcmp(name, IQS_NAME_IQS253))
2282                 st->dev_id = IQS_DEVID_IQS253;
2283         if (!st->dev_id) {
2284                 hal_i = st->hal_bit->devinf_id.hal_i;
2285                 i = st->hal_bit->devinf_id.offset + 1;
2286                 ret = iqs_i2c_read(st, hal_i, i, false);
2287                 if (ret) {
2288                         st->hal_tbl_n = 0; /* disable PM I2C */
2289                         return ret;
2290                 } else {
2291                         i += st->hal_tbl[hal_i].ndx;
2292                         st->dev_id = st->rc[i];
2293                 }
2294         }
2295
2296         switch (st->dev_id) {
2297         case IQS_DEVID_IQS263:
2298                 BUG_ON(IQS263_MSG_N != ARRAY_SIZE(iqs263_hal_tbl));
2299                 iqs_id_part(st, IQS_NAME_IQS263);
2300                 st->part_i = IQS_PART_263;
2301                 st->wr_disable = iqs263_wr_disable;
2302                 st->wr_stream = iqs263_wr_stream;
2303                 st->wr_events = iqs263_wr_events;
2304                 st->wr_ati_redo = iqs263_wr_ati_redo;
2305                 st->wr_reseed = iqs263_wr_reseed;
2306                 break;
2307
2308         case IQS_DEVID_IQS253:
2309                 BUG_ON(IQS253_MSG_N != ARRAY_SIZE(iqs253_hal_tbl));
2310                 iqs_id_part(st, IQS_NAME_IQS253);
2311                 st->part_i = IQS_PART_253;
2312                 st->hal_tbl = iqs253_hal_tbl;
2313                 st->hal_tbl_n = ARRAY_SIZE(iqs253_hal_tbl);
2314                 st->hal_bit = &iqs253_hal_bit;
2315                 st->wr_disable = iqs253_wr_disable;
2316                 st->wr_stream = iqs253_wr_stream;
2317                 st->wr_events = iqs253_wr_events;
2318                 st->wr_ati_redo = iqs253_wr_ati_redo;
2319                 st->wr_reseed = iqs253_wr_reseed;
2320                 break;
2321
2322         default:
2323                 return -ENODEV;
2324         }
2325
2326         for (i = 0; i < st->hal_tbl_n; i++)
2327                 /* fill in register addresses for I2C writes */
2328                 st->rc[st->hal_tbl[i].ndx] = st->hal_tbl[i].reg;
2329         if (!ret)
2330                 dev_info(&st->i2c->dev, "%s found %s\n",
2331                          __func__, st->cfg[0].part);
2332         return 0;
2333 }
2334
2335 static int iqs_id_i2c(struct iqs_state *st, const char *name)
2336 {
2337         int i;
2338         int ret;
2339
2340         for (i = 0; i < ARRAY_SIZE(iqs_i2c_addrs); i++) {
2341                 if (st->i2c->addr == iqs_i2c_addrs[i])
2342                         break;
2343         }
2344
2345         if (i < ARRAY_SIZE(iqs_i2c_addrs)) {
2346                 st->i2c_addr = st->i2c->addr;
2347                 ret = iqs_id_dev(st, name);
2348         } else {
2349                 name = IQS_NAME;
2350                 for (i = 0; i < ARRAY_SIZE(iqs_i2c_addrs); i++) {
2351                         st->i2c_addr = iqs_i2c_addrs[i];
2352                         ret = iqs_id_dev(st, name);
2353                         if (!ret)
2354                                 break;
2355                 }
2356         }
2357         if (ret)
2358                 st->i2c_addr = 0;
2359         return ret;
2360 }
2361
2362 static const struct sensor_cfg iqs_cfg_dflt = {
2363         .snsr_id                        = SENSOR_TYPE_PROXIMITY,
2364         .ch_n                           = 1,
2365         .ch_sz                          = 4,
2366         .part                           = IQS_NAME,
2367         .vendor                         = IQS_VENDOR,
2368         .version                        = IQS_PROX_VERSION,
2369         .max_range                      = {
2370                 .ival                   = IQS_PROX_MAX_RANGE_IVAL,
2371                 .fval                   = IQS_PROX_MAX_RANGE_MICRO,
2372         },
2373         .resolution                     = {
2374                 .ival                   = IQS_PROX_RESOLUTION_IVAL,
2375                 .fval                   = IQS_PROX_RESOLUTION_MICRO,
2376         },
2377         .milliamp                       = {
2378                 .ival                   = IQS_PROX_MILLIAMP_IVAL,
2379                 .fval                   = IQS_PROX_MILLIAMP_MICRO,
2380         },
2381         .delay_us_min                   = IQS_POLL_DLY_MS_MIN * 1000,
2382         .delay_us_max                   = IQS_POLL_DLY_MS_MAX * 1000,
2383         .flags                          = SENSOR_FLAG_ON_CHANGE_MODE |
2384                                           SENSOR_FLAG_WAKE_UP,
2385         .thresh_lo                      = IQS_PROX_THRESHOLD,
2386         .thresh_hi                      = IQS_MULTI_THRESHOLD,
2387 };
2388
2389 static int iqs_of_dt_db(struct iqs_state *st, struct device_node *dn,
2390                         char *name, unsigned char *dt_db, int db_n)
2391 {
2392         char str[16];
2393         const char *charp;
2394         unsigned int limit = IQS_MSG_N;
2395         unsigned int i;
2396         int n;
2397         int lenp;
2398         int ret;
2399
2400         n = 0;
2401         for (i = 0; i < limit; i++) {
2402                 ret = sprintf(str, "%s_%u", name, i);
2403                 if (ret <= 0) {
2404                         dev_err(&st->i2c->dev, "%s sprintf(%s_%u)\n",
2405                                 __func__, name, i);
2406                         return -ENODEV;
2407                 }
2408
2409                 charp = of_get_property(dn, str, &lenp);
2410                 if (charp) {
2411                         if (lenp < (db_n - n)) {
2412                                 memcpy(&dt_db[n], charp, lenp);
2413                                 if (dt_db[n] == 0xFF)
2414                                         /* flush is done so limit extended */
2415                                         limit = i + IQS_MSG_N;
2416                                 n += lenp;
2417                         } else {
2418                                 dev_err(&st->i2c->dev, "%s ERR: NOMEM @ %s\n",
2419                                         __func__, str);
2420                                 return -ENOMEM;
2421                         }
2422                 } else {
2423                         dt_db[n] = 0; /* terminate byte stream */
2424                         break;
2425                 }
2426         }
2427
2428         return 0;
2429 }
2430
2431 static int iqs_of_dt(struct iqs_state *st, struct device_node *dn)
2432 {
2433         char str[64];
2434         char const *pchar;
2435         const char *dev;
2436         unsigned int part;
2437         unsigned int i;
2438         unsigned int j;
2439         int ret;
2440
2441         /* just test if global disable */
2442         ret = nvs_of_dt(dn, NULL, NULL);
2443         if (ret == -ENODEV)
2444                 return -ENODEV;
2445
2446         /* default device specific parameters */
2447         for (i = 0; i < IQS_DEV_N; i++) {
2448                 memcpy(&st->cfg[i], &iqs_cfg_dflt, sizeof(st->cfg[0]));
2449                 st->cfg[i].name = iqs_snsr_names[i];
2450                 st->prox[i].cfg = &st->cfg[i];
2451                 st->prox[i].hw_mask = 0xFFFF;
2452                 st->prox[i].proximity_binary_hw = true;
2453                 nvs_proximity_of_dt(&st->prox[i], dn, st->cfg[i].name);
2454         }
2455         for (i = 0; i <= IQS_CH_N; i++)
2456                 /* delta sensors default disable */
2457                 st->cfg[IQS_DEV_DELTA + i].snsr_id = -1;
2458         st->wd_to_ms = IQS_POLL_DLY_MS_WATCHDOG;
2459         st->dfr_rsm_ms = IQS_START_DELAY_MS;
2460         st->i2c_ss_war_ns = IQS_I2C_STOP_DLY_NS;
2461         st->i2c_retry = IQS_I2C_RETRY_N;
2462         st->gpio_rdy_retry = IQS_RDY_RETRY_N;
2463         st->gpio_rdy = -1;
2464         st->gpio_sar = -1;
2465         st->gpio_sar_sus_asrt = -1;
2466         for (i = 0; i < IQS_DELTA_TEST0_N; i++) {
2467                 for (j = 0; j < IQS_DELTA_TEST1_N; j++) {
2468                         st->delta_tst[i][j].ch = -1;
2469                         st->delta_tst[i][j].lt = -1;
2470                         st->delta_tst[i][j].gt = -1;
2471                 }
2472         }
2473         /* device tree parameters */
2474         if (dn) {
2475                 /* device specific parameters */
2476                 for (i = 0; i < IQS_DEV_HW_N; i++) {
2477                         sprintf(str, "%s_debounce_lo", iqs_snsr_names[i]);
2478                         of_property_read_u32(dn, str, &st->dbnc_lo[i]);
2479                         sprintf(str, "%s_debounce_hi", iqs_snsr_names[i]);
2480                         of_property_read_u32(dn, str, &st->dbnc_hi[i]);
2481                 }
2482                 of_property_read_u32(dn, "SAR_delta_average_count",
2483                                      &st->delta_avg_n);
2484                 if (st->delta_avg_n < 2)
2485                         st->delta_avg_n = 0;
2486                 if (!of_property_read_u32(dn, "SAR_delta_channel_mask",
2487                                           &st->delta_ch_msk)) {
2488                         st->delta_ch_msk &= ((1 << IQS_CH_N) - 1);
2489                         if (st->delta_ch_msk) {
2490                                 /* enable delta sensor(s) */
2491                                 st->cfg[IQS_DEV_DELTA].snsr_id =
2492                                                          SENSOR_TYPE_PROXIMITY;
2493                                 for (i = 0; i < IQS_CH_N; i++) {
2494                                         if (st->delta_ch_msk & (1 << i)) {
2495                                                 j = IQS_DEV_DELTA0 + i;
2496                                                 st->cfg[j].snsr_id =
2497                                                          SENSOR_TYPE_PROXIMITY;
2498                                         }
2499                                 }
2500                         }
2501                 }
2502                 of_property_read_u32(dn, "os_options", &st->os);
2503                 of_property_read_u32(dn, "stream_mode", &st->stream);
2504                 if (st->stream >= IQS_STREAM_N) {
2505                         dev_err(&st->i2c->dev,
2506                                 "%s ERR: stream_mode %u > %u limit\n",
2507                                 __func__, st->stream, IQS_STREAM_N - 1);
2508                         st->stream = IQS_STREAM_OFF;
2509                 }
2510                 of_property_read_u32(dn, "deferred_resume_ms",
2511                                      &st->dfr_rsm_ms);
2512                 i = 0;
2513                 of_property_read_u32(dn, "irq_trigger_edge", &i);
2514                 if (i)
2515                         st->irq_trigger_edge = true;
2516                 of_property_read_u32(dn, "watchdog_timeout_ms", &st->wd_to_ms);
2517                 of_property_read_u32(dn, "i2c_ss_delay_ns",
2518                                      (u32 *)&st->i2c_ss_war_ns);
2519                 of_property_read_u32(dn, "i2c_retry", &st->i2c_retry);
2520                 of_property_read_u32(dn, "gpio_rdy_retry",
2521                                      &st->gpio_rdy_retry);
2522                 if (!of_property_read_u32(dn, "gpio_sar_assert_polarity",
2523                                           &st->gpio_sar_asrt_pol))
2524                         st->gpio_sar_asrt_pol = !!st->gpio_sar_asrt_pol;
2525                 if (!of_property_read_s32(dn, "gpio_sar_suspend_assert",
2526                                           &st->gpio_sar_sus_asrt))
2527                         st->gpio_sar_sus_asrt = !!st->gpio_sar_sus_asrt;
2528                 st->gpio_rdy = of_get_named_gpio(dn, "gpio_rdy", 0);
2529                 st->gpio_sar = of_get_named_gpio(dn, "gpio_sar", 0);
2530                 if (!of_property_read_string(dn, "gpio_sar_dev_assert",
2531                                              &pchar)) {
2532                         for (i = 0; i < ARRAY_SIZE(iqs_snsr_names); i++) {
2533                                 if (!strcasecmp(pchar, iqs_snsr_names[i])) {
2534                                         st->gpio_sar_dev_asrt = i;
2535                                         break;
2536                                 }
2537                         }
2538                 }
2539
2540                 if (!of_property_read_string(dn, "gpio_sar_dev_deassert",
2541                                              &pchar)) {
2542                         for (i = 0; i < ARRAY_SIZE(iqs_snsr_names); i++) {
2543                                 if (!strcasecmp(pchar, iqs_snsr_names[i])) {
2544                                         st->gpio_sar_dev_dasrt = i;
2545                                         break;
2546                                 }
2547                         }
2548                 }
2549
2550                 ret = 0;
2551                 for (i = 0; i < IQS_PART_N; i++) {
2552                         if (i == 0)
2553                                 part = 253;
2554                         else
2555                                 part = 263;
2556                         sprintf(str, "%uinit", part);
2557                         ret |= iqs_of_dt_db(st, dn, str, st->dt_init[i],
2558                                             IQS_DT_INIT_N);
2559                         sprintf(str, "%uevent", part);
2560                         ret |= iqs_of_dt_db(st, dn, str, st->dt_evnt[i],
2561                                             IQS_DT_EVNT_N);
2562                         sprintf(str, "%ususpend", part);
2563                         ret |= iqs_of_dt_db(st, dn, str, st->dt_suspnd[i],
2564                                             IQS_DT_SUSPND_N);
2565                         for (j = 0; j < IQS_DEV_HW_N; j++) {
2566                                 if (j == 0)
2567                                         dev = "prox";
2568                                 else
2569                                         dev = "touch";
2570                                 sprintf(str, "%uen_%s", part, dev);
2571                                 ret |= iqs_of_dt_db(st, dn, str,
2572                                                     st->dt_en[i][j],
2573                                                     IQS_DT_ABLE_N);
2574                                 sprintf(str, "%udis_%s", part, dev);
2575                                 ret |= iqs_of_dt_db(st, dn, str,
2576                                                     st->dt_dis[i][j],
2577                                                     IQS_DT_ABLE_N);
2578                         }
2579                 }
2580                 if (ret)
2581                         return ret;
2582
2583                 for (i = 0; i < IQS_DELTA_TEST0_N; i++) {
2584                         for (j = 0; j < IQS_DELTA_TEST1_N; j++) {
2585                                 sprintf(str, "%s_%u_ch",
2586                                         iqs_delta_tst_dt[i], j);
2587                                 of_property_read_s32(dn, str,
2588                                                      &st->delta_tst[i][j].ch);
2589                                 sprintf(str, "%s_%u_lt",
2590                                         iqs_delta_tst_dt[i], j);
2591                                 of_property_read_s32(dn, str,
2592                                                      &st->delta_tst[i][j].lt);
2593                                 sprintf(str, "%s_%u_gt",
2594                                         iqs_delta_tst_dt[i], j);
2595                                 of_property_read_s32(dn, str,
2596                                                      &st->delta_tst[i][j].gt);
2597                         }
2598                 }
2599         }
2600
2601         for (i = 0; i < IQS_DEV_N; i++) {
2602                 for (j = 0; j < 3; j++) {
2603                         if (st->os)
2604                                 /* change 'SAR' to 'sar' for OS visibility */
2605                                 iqs_snsr_names[i][j] = tolower((unsigned char)
2606                                                          iqs_snsr_names[i][j]);
2607                         else
2608                                 /* change 'sar' to 'SAR' */
2609                                 iqs_snsr_names[i][j] = toupper((unsigned char)
2610                                                          iqs_snsr_names[i][j]);
2611                 }
2612         }
2613
2614         if (gpio_is_valid(st->gpio_rdy)) {
2615                 ret = gpio_request(st->gpio_rdy, IQS_NAME);
2616                 if (ret) {
2617                         dev_err(&st->i2c->dev,
2618                                 "%s gpio_request(%d %s) ERR:%d\n",
2619                                 __func__, st->gpio_rdy, IQS_NAME, ret);
2620                         /* can't communicate with device without this GPIO */
2621                         return -EPROBE_DEFER;
2622                 } else {
2623                         ret = gpio_direction_input(st->gpio_rdy);
2624                         if (ret < 0) {
2625                                 dev_err(&st->i2c->dev,
2626                                         "%s gpio_direction_input(%d) ERR:%d\n",
2627                                         __func__, st->gpio_rdy, ret);
2628                                 return -ENODEV;
2629                         }
2630                 }
2631         } else {
2632                 /* can't communicate with device without this GPIO */
2633                 return -EPROBE_DEFER;
2634         }
2635
2636         if (gpio_is_valid(st->gpio_sar)) {
2637                 ret = gpio_request(st->gpio_sar, IQS_NAME);
2638                 if (ret) {
2639                         dev_err(&st->i2c->dev,
2640                                 "%s gpio_request(%d %s) ERR:%d\n",
2641                                 __func__, st->gpio_sar, IQS_NAME, ret);
2642                 } else {
2643                         /* start with SAR GPIO asserted */
2644                         st->gpio_sar_val = -1;
2645                         iqs_gpio_sar(st, 1);
2646                 }
2647         }
2648         return 0;
2649 }
2650
2651 static int iqs_probe(struct i2c_client *client, const struct i2c_device_id *id)
2652 {
2653         struct iqs_state *st;
2654         unsigned long irqflags;
2655         unsigned int en;
2656         unsigned int i;
2657         int ret;
2658
2659         dev_info(&client->dev, "%s\n", __func__);
2660         st = devm_kzalloc(&client->dev, sizeof(*st), GFP_KERNEL);
2661         if (st == NULL) {
2662                 dev_err(&client->dev, "%s devm_kzalloc ERR\n", __func__);
2663                 return -ENOMEM;
2664         }
2665
2666         i2c_set_clientdata(client, st);
2667         st->i2c = client;
2668         ret = iqs_of_dt(st, client->dev.of_node);
2669         if (ret) {
2670                 if (ret == -ENODEV) {
2671                         dev_info(&client->dev, "%s DT disabled\n", __func__);
2672                 } else {
2673                         dev_err(&client->dev, "%s _of_dt ERR\n", __func__);
2674                         ret = -ENODEV;
2675                 }
2676                 goto iqs_probe_exit;
2677         }
2678
2679         iqs_pm_init(st);
2680         ret = iqs_id_i2c(st, id->name);
2681         if (ret) {
2682                 dev_err(&client->dev, "%s _id_i2c ERR\n", __func__);
2683                 ret = -ENODEV;
2684                 goto iqs_probe_exit;
2685         }
2686
2687         iqs_pm(st, false);
2688         iqs_fn_dev.sts = &st->sts;
2689         iqs_fn_dev.errs = &st->errs;
2690         st->nvs = nvs_iio();
2691         if (st->nvs == NULL) {
2692                 ret = -ENODEV;
2693                 goto iqs_probe_exit;
2694         }
2695
2696         en = 0;
2697         for (i = 0; i < IQS_DEV_N; i++) {
2698                 nvs_of_dt(client->dev.of_node, &st->cfg[i], NULL);
2699                 ret = st->nvs->probe(&st->prox[i].nvs_st, st, &client->dev,
2700                                      &iqs_fn_dev, &st->cfg[i]);
2701                 st->cfg[i].snsr_id = i;
2702                 if (!ret) {
2703                         st->prox[i].handler = st->nvs->handler;
2704                         en |= 1 << i;
2705                 }
2706         }
2707         if (!en) {
2708                 dev_err(&client->dev, "%s nvs_probe ERR\n", __func__);
2709                 ret = -ENODEV;
2710                 goto iqs_probe_exit;
2711         }
2712
2713         INIT_DELAYED_WORK(&st->dw, iqs_work);
2714         if (st->gpio_rdy > 0)
2715                 st->i2c->irq = gpio_to_irq(st->gpio_rdy);
2716         if (client->irq) {
2717                 irqflags = IRQF_ONESHOT | IRQF_NO_THREAD;
2718                 if (st->irq_trigger_edge)
2719                         irqflags |= IRQF_TRIGGER_FALLING;
2720                 else
2721                         irqflags |= IRQF_TRIGGER_LOW;
2722                 for (i = 0; i < IQS_DEV_HW_N; i++) {
2723                         if (st->cfg[i].snsr_id >= 0) {
2724                                 if (st->cfg[i].flags & SENSOR_FLAG_WAKE_UP)
2725                                         irqflags |= IRQF_NO_SUSPEND;
2726                         }
2727                 }
2728                 ret = request_threaded_irq(client->irq,
2729                                            iqs_irq_handler, iqs_irq_thread,
2730                                            irqflags, IQS_NAME, st);
2731                 if (ret) {
2732                         dev_err(&client->dev, "%s req_threaded_irq ERR %d\n",
2733                                 __func__, ret);
2734                         ret = -ENOMEM;
2735                         goto iqs_probe_exit;
2736                 }
2737         }
2738
2739         if (st->delta_ch_msk && st->delta_avg_n) {
2740                 /* allocate data buffers for delta sensors moving average */
2741                 for (i = 0; i < IQS_CH_N; i++) {
2742                         st->delta_avg[i] = kzalloc(sizeof(*st->delta_avg[i] *
2743                                                           st->delta_avg_n),
2744                                                    GFP_KERNEL);
2745                         if (st->delta_avg[i] == NULL) {
2746                                 dev_err(&client->dev,
2747                                         "%s kzalloc delta_avg[%u] sz=%u ERR\n",
2748                                         __func__, i, st->delta_avg_n << 1);
2749                                 ret = -ENOMEM;
2750                                 goto iqs_probe_exit;
2751                         }
2752                 }
2753         }
2754
2755         iqs_mutex_lock(st);
2756         if (st->os == IQS_OS_CONTROL) {
2757                 iqs_disable(st, -1);
2758         } else {
2759                 ret = iqs_enables(st, en);
2760                 if (ret) {
2761                         dev_err(&client->dev, "%s auto enable ERR=%d\n",
2762                                 __func__, ret);
2763                         /* use the resume execution to keep trying */
2764                         iqs_pm(st, true);
2765                         st->enabled = en;
2766                         st->susrsm_en = en;
2767                         st->resume = true;
2768                         mod_delayed_work(system_freezable_wq, &st->dw,
2769                                          msecs_to_jiffies(IQS_START_DELAY_MS));
2770                 }
2771         }
2772         iqs_mutex_unlock(st);
2773         dev_info(&client->dev, "%s done\n", __func__);
2774         return 0;
2775
2776 iqs_probe_exit:
2777         iqs_remove(client);
2778         return ret;
2779 }
2780
2781 MODULE_DEVICE_TABLE(i2c, iqs_i2c_device_id);
2782
2783 static const struct of_device_id iqs_of_match[] = {
2784         { .compatible = "azoteq,iqs2x3", },
2785         { .compatible = "azoteq,iqs253", },
2786         { .compatible = "azoteq,iqs263", },
2787         {},
2788 };
2789
2790 MODULE_DEVICE_TABLE(of, iqs_of_match);
2791
2792 static struct i2c_driver iqs_driver = {
2793         .class          = I2C_CLASS_HWMON,
2794         .probe          = iqs_probe,
2795         .remove         = iqs_remove,
2796         .shutdown       = iqs_shutdown,
2797         .driver = {
2798                 .name           = IQS_NAME,
2799                 .owner          = THIS_MODULE,
2800                 .of_match_table = of_match_ptr(iqs_of_match),
2801                 .pm             = &iqs_pm_ops,
2802         },
2803         .id_table       = iqs_i2c_device_id,
2804 };
2805 module_i2c_driver(iqs_driver);
2806
2807 MODULE_LICENSE("GPL");
2808 MODULE_DESCRIPTION("IQS2X3 driver");
2809 MODULE_AUTHOR("NVIDIA Corporation");
2810