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