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