GNU Linux-libre 4.19.295-gnu1
[releases.git] / drivers / iio / magnetometer / ak8975.c
1 /*
2  * A sensor driver for the magnetometer AK8975.
3  *
4  * Magnetic compass sensor driver for monitoring magnetic flux information.
5  *
6  * Copyright (c) 2010, NVIDIA Corporation.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
16  * more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21  */
22
23 #include <linux/module.h>
24 #include <linux/kernel.h>
25 #include <linux/slab.h>
26 #include <linux/i2c.h>
27 #include <linux/interrupt.h>
28 #include <linux/err.h>
29 #include <linux/mutex.h>
30 #include <linux/delay.h>
31 #include <linux/bitops.h>
32 #include <linux/gpio.h>
33 #include <linux/of_gpio.h>
34 #include <linux/acpi.h>
35 #include <linux/regulator/consumer.h>
36 #include <linux/pm_runtime.h>
37
38 #include <linux/iio/iio.h>
39 #include <linux/iio/sysfs.h>
40 #include <linux/iio/buffer.h>
41 #include <linux/iio/trigger.h>
42 #include <linux/iio/trigger_consumer.h>
43 #include <linux/iio/triggered_buffer.h>
44
45 #include <linux/iio/magnetometer/ak8975.h>
46
47 /*
48  * Register definitions, as well as various shifts and masks to get at the
49  * individual fields of the registers.
50  */
51 #define AK8975_REG_WIA                  0x00
52 #define AK8975_DEVICE_ID                0x48
53
54 #define AK8975_REG_INFO                 0x01
55
56 #define AK8975_REG_ST1                  0x02
57 #define AK8975_REG_ST1_DRDY_SHIFT       0
58 #define AK8975_REG_ST1_DRDY_MASK        (1 << AK8975_REG_ST1_DRDY_SHIFT)
59
60 #define AK8975_REG_HXL                  0x03
61 #define AK8975_REG_HXH                  0x04
62 #define AK8975_REG_HYL                  0x05
63 #define AK8975_REG_HYH                  0x06
64 #define AK8975_REG_HZL                  0x07
65 #define AK8975_REG_HZH                  0x08
66 #define AK8975_REG_ST2                  0x09
67 #define AK8975_REG_ST2_DERR_SHIFT       2
68 #define AK8975_REG_ST2_DERR_MASK        (1 << AK8975_REG_ST2_DERR_SHIFT)
69
70 #define AK8975_REG_ST2_HOFL_SHIFT       3
71 #define AK8975_REG_ST2_HOFL_MASK        (1 << AK8975_REG_ST2_HOFL_SHIFT)
72
73 #define AK8975_REG_CNTL                 0x0A
74 #define AK8975_REG_CNTL_MODE_SHIFT      0
75 #define AK8975_REG_CNTL_MODE_MASK       (0xF << AK8975_REG_CNTL_MODE_SHIFT)
76 #define AK8975_REG_CNTL_MODE_POWER_DOWN 0x00
77 #define AK8975_REG_CNTL_MODE_ONCE       0x01
78 #define AK8975_REG_CNTL_MODE_SELF_TEST  0x08
79 #define AK8975_REG_CNTL_MODE_FUSE_ROM   0x0F
80
81 #define AK8975_REG_RSVC                 0x0B
82 #define AK8975_REG_ASTC                 0x0C
83 #define AK8975_REG_TS1                  0x0D
84 #define AK8975_REG_TS2                  0x0E
85 #define AK8975_REG_I2CDIS               0x0F
86 #define AK8975_REG_ASAX                 0x10
87 #define AK8975_REG_ASAY                 0x11
88 #define AK8975_REG_ASAZ                 0x12
89
90 #define AK8975_MAX_REGS                 AK8975_REG_ASAZ
91
92 /*
93  * AK09912 Register definitions
94  */
95 #define AK09912_REG_WIA1                0x00
96 #define AK09912_REG_WIA2                0x01
97 #define AK09912_DEVICE_ID               0x04
98 #define AK09911_DEVICE_ID               0x05
99
100 #define AK09911_REG_INFO1               0x02
101 #define AK09911_REG_INFO2               0x03
102
103 #define AK09912_REG_ST1                 0x10
104
105 #define AK09912_REG_ST1_DRDY_SHIFT      0
106 #define AK09912_REG_ST1_DRDY_MASK       (1 << AK09912_REG_ST1_DRDY_SHIFT)
107
108 #define AK09912_REG_HXL                 0x11
109 #define AK09912_REG_HXH                 0x12
110 #define AK09912_REG_HYL                 0x13
111 #define AK09912_REG_HYH                 0x14
112 #define AK09912_REG_HZL                 0x15
113 #define AK09912_REG_HZH                 0x16
114 #define AK09912_REG_TMPS                0x17
115
116 #define AK09912_REG_ST2                 0x18
117 #define AK09912_REG_ST2_HOFL_SHIFT      3
118 #define AK09912_REG_ST2_HOFL_MASK       (1 << AK09912_REG_ST2_HOFL_SHIFT)
119
120 #define AK09912_REG_CNTL1               0x30
121
122 #define AK09912_REG_CNTL2               0x31
123 #define AK09912_REG_CNTL_MODE_POWER_DOWN        0x00
124 #define AK09912_REG_CNTL_MODE_ONCE      0x01
125 #define AK09912_REG_CNTL_MODE_SELF_TEST 0x10
126 #define AK09912_REG_CNTL_MODE_FUSE_ROM  0x1F
127 #define AK09912_REG_CNTL2_MODE_SHIFT    0
128 #define AK09912_REG_CNTL2_MODE_MASK     (0x1F << AK09912_REG_CNTL2_MODE_SHIFT)
129
130 #define AK09912_REG_CNTL3               0x32
131
132 #define AK09912_REG_TS1                 0x33
133 #define AK09912_REG_TS2                 0x34
134 #define AK09912_REG_TS3                 0x35
135 #define AK09912_REG_I2CDIS              0x36
136 #define AK09912_REG_TS4                 0x37
137
138 #define AK09912_REG_ASAX                0x60
139 #define AK09912_REG_ASAY                0x61
140 #define AK09912_REG_ASAZ                0x62
141
142 #define AK09912_MAX_REGS                AK09912_REG_ASAZ
143
144 /*
145  * Miscellaneous values.
146  */
147 #define AK8975_MAX_CONVERSION_TIMEOUT   500
148 #define AK8975_CONVERSION_DONE_POLL_TIME 10
149 #define AK8975_DATA_READY_TIMEOUT       ((100*HZ)/1000)
150
151 /*
152  * Precalculate scale factor (in Gauss units) for each axis and
153  * store in the device data.
154  *
155  * This scale factor is axis-dependent, and is derived from 3 calibration
156  * factors ASA(x), ASA(y), and ASA(z).
157  *
158  * These ASA values are read from the sensor device at start of day, and
159  * cached in the device context struct.
160  *
161  * Adjusting the flux value with the sensitivity adjustment value should be
162  * done via the following formula:
163  *
164  * Hadj = H * ( ( ( (ASA-128)*0.5 ) / 128 ) + 1 )
165  * where H is the raw value, ASA is the sensitivity adjustment, and Hadj
166  * is the resultant adjusted value.
167  *
168  * We reduce the formula to:
169  *
170  * Hadj = H * (ASA + 128) / 256
171  *
172  * H is in the range of -4096 to 4095.  The magnetometer has a range of
173  * +-1229uT.  To go from the raw value to uT is:
174  *
175  * HuT = H * 1229/4096, or roughly, 3/10.
176  *
177  * Since 1uT = 0.01 gauss, our final scale factor becomes:
178  *
179  * Hadj = H * ((ASA + 128) / 256) * 3/10 * 1/100
180  * Hadj = H * ((ASA + 128) * 0.003) / 256
181  *
182  * Since ASA doesn't change, we cache the resultant scale factor into the
183  * device context in ak8975_setup().
184  *
185  * Given we use IIO_VAL_INT_PLUS_MICRO bit when displaying the scale, we
186  * multiply the stored scale value by 1e6.
187  */
188 static long ak8975_raw_to_gauss(u16 data)
189 {
190         return (((long)data + 128) * 3000) / 256;
191 }
192
193 /*
194  * For AK8963 and AK09911, same calculation, but the device is less sensitive:
195  *
196  * H is in the range of +-8190.  The magnetometer has a range of
197  * +-4912uT.  To go from the raw value to uT is:
198  *
199  * HuT = H * 4912/8190, or roughly, 6/10, instead of 3/10.
200  */
201
202 static long ak8963_09911_raw_to_gauss(u16 data)
203 {
204         return (((long)data + 128) * 6000) / 256;
205 }
206
207 /*
208  * For AK09912, same calculation, except the device is more sensitive:
209  *
210  * H is in the range of -32752 to 32752.  The magnetometer has a range of
211  * +-4912uT.  To go from the raw value to uT is:
212  *
213  * HuT = H * 4912/32752, or roughly, 3/20, instead of 3/10.
214  */
215 static long ak09912_raw_to_gauss(u16 data)
216 {
217         return (((long)data + 128) * 1500) / 256;
218 }
219
220 /* Compatible Asahi Kasei Compass parts */
221 enum asahi_compass_chipset {
222         AK8975,
223         AK8963,
224         AK09911,
225         AK09912,
226         AK_MAX_TYPE
227 };
228
229 enum ak_ctrl_reg_addr {
230         ST1,
231         ST2,
232         CNTL,
233         ASA_BASE,
234         MAX_REGS,
235         REGS_END,
236 };
237
238 enum ak_ctrl_reg_mask {
239         ST1_DRDY,
240         ST2_HOFL,
241         ST2_DERR,
242         CNTL_MODE,
243         MASK_END,
244 };
245
246 enum ak_ctrl_mode {
247         POWER_DOWN,
248         MODE_ONCE,
249         SELF_TEST,
250         FUSE_ROM,
251         MODE_END,
252 };
253
254 struct ak_def {
255         enum asahi_compass_chipset type;
256         long (*raw_to_gauss)(u16 data);
257         u16 range;
258         u8 ctrl_regs[REGS_END];
259         u8 ctrl_masks[MASK_END];
260         u8 ctrl_modes[MODE_END];
261         u8 data_regs[3];
262 };
263
264 static const struct ak_def ak_def_array[AK_MAX_TYPE] = {
265         {
266                 .type = AK8975,
267                 .raw_to_gauss = ak8975_raw_to_gauss,
268                 .range = 4096,
269                 .ctrl_regs = {
270                         AK8975_REG_ST1,
271                         AK8975_REG_ST2,
272                         AK8975_REG_CNTL,
273                         AK8975_REG_ASAX,
274                         AK8975_MAX_REGS},
275                 .ctrl_masks = {
276                         AK8975_REG_ST1_DRDY_MASK,
277                         AK8975_REG_ST2_HOFL_MASK,
278                         AK8975_REG_ST2_DERR_MASK,
279                         AK8975_REG_CNTL_MODE_MASK},
280                 .ctrl_modes = {
281                         AK8975_REG_CNTL_MODE_POWER_DOWN,
282                         AK8975_REG_CNTL_MODE_ONCE,
283                         AK8975_REG_CNTL_MODE_SELF_TEST,
284                         AK8975_REG_CNTL_MODE_FUSE_ROM},
285                 .data_regs = {
286                         AK8975_REG_HXL,
287                         AK8975_REG_HYL,
288                         AK8975_REG_HZL},
289         },
290         {
291                 .type = AK8963,
292                 .raw_to_gauss = ak8963_09911_raw_to_gauss,
293                 .range = 8190,
294                 .ctrl_regs = {
295                         AK8975_REG_ST1,
296                         AK8975_REG_ST2,
297                         AK8975_REG_CNTL,
298                         AK8975_REG_ASAX,
299                         AK8975_MAX_REGS},
300                 .ctrl_masks = {
301                         AK8975_REG_ST1_DRDY_MASK,
302                         AK8975_REG_ST2_HOFL_MASK,
303                         0,
304                         AK8975_REG_CNTL_MODE_MASK},
305                 .ctrl_modes = {
306                         AK8975_REG_CNTL_MODE_POWER_DOWN,
307                         AK8975_REG_CNTL_MODE_ONCE,
308                         AK8975_REG_CNTL_MODE_SELF_TEST,
309                         AK8975_REG_CNTL_MODE_FUSE_ROM},
310                 .data_regs = {
311                         AK8975_REG_HXL,
312                         AK8975_REG_HYL,
313                         AK8975_REG_HZL},
314         },
315         {
316                 .type = AK09911,
317                 .raw_to_gauss = ak8963_09911_raw_to_gauss,
318                 .range = 8192,
319                 .ctrl_regs = {
320                         AK09912_REG_ST1,
321                         AK09912_REG_ST2,
322                         AK09912_REG_CNTL2,
323                         AK09912_REG_ASAX,
324                         AK09912_MAX_REGS},
325                 .ctrl_masks = {
326                         AK09912_REG_ST1_DRDY_MASK,
327                         AK09912_REG_ST2_HOFL_MASK,
328                         0,
329                         AK09912_REG_CNTL2_MODE_MASK},
330                 .ctrl_modes = {
331                         AK09912_REG_CNTL_MODE_POWER_DOWN,
332                         AK09912_REG_CNTL_MODE_ONCE,
333                         AK09912_REG_CNTL_MODE_SELF_TEST,
334                         AK09912_REG_CNTL_MODE_FUSE_ROM},
335                 .data_regs = {
336                         AK09912_REG_HXL,
337                         AK09912_REG_HYL,
338                         AK09912_REG_HZL},
339         },
340         {
341                 .type = AK09912,
342                 .raw_to_gauss = ak09912_raw_to_gauss,
343                 .range = 32752,
344                 .ctrl_regs = {
345                         AK09912_REG_ST1,
346                         AK09912_REG_ST2,
347                         AK09912_REG_CNTL2,
348                         AK09912_REG_ASAX,
349                         AK09912_MAX_REGS},
350                 .ctrl_masks = {
351                         AK09912_REG_ST1_DRDY_MASK,
352                         AK09912_REG_ST2_HOFL_MASK,
353                         0,
354                         AK09912_REG_CNTL2_MODE_MASK},
355                 .ctrl_modes = {
356                         AK09912_REG_CNTL_MODE_POWER_DOWN,
357                         AK09912_REG_CNTL_MODE_ONCE,
358                         AK09912_REG_CNTL_MODE_SELF_TEST,
359                         AK09912_REG_CNTL_MODE_FUSE_ROM},
360                 .data_regs = {
361                         AK09912_REG_HXL,
362                         AK09912_REG_HYL,
363                         AK09912_REG_HZL},
364         }
365 };
366
367 /*
368  * Per-instance context data for the device.
369  */
370 struct ak8975_data {
371         struct i2c_client       *client;
372         const struct ak_def     *def;
373         struct mutex            lock;
374         u8                      asa[3];
375         long                    raw_to_gauss[3];
376         int                     eoc_gpio;
377         int                     eoc_irq;
378         wait_queue_head_t       data_ready_queue;
379         unsigned long           flags;
380         u8                      cntl_cache;
381         struct iio_mount_matrix orientation;
382         struct regulator        *vdd;
383         struct regulator        *vid;
384
385         /* Ensure natural alignment of timestamp */
386         struct {
387                 s16 channels[3];
388                 s64 ts __aligned(8);
389         } scan;
390 };
391
392 /* Enable attached power regulator if any. */
393 static int ak8975_power_on(const struct ak8975_data *data)
394 {
395         int ret;
396
397         ret = regulator_enable(data->vdd);
398         if (ret) {
399                 dev_warn(&data->client->dev,
400                          "Failed to enable specified Vdd supply\n");
401                 return ret;
402         }
403         ret = regulator_enable(data->vid);
404         if (ret) {
405                 dev_warn(&data->client->dev,
406                          "Failed to enable specified Vid supply\n");
407                 regulator_disable(data->vdd);
408                 return ret;
409         }
410         /*
411          * According to the datasheet the power supply rise time i 200us
412          * and the minimum wait time before mode setting is 100us, in
413          * total 300 us. Add some margin and say minimum 500us here.
414          */
415         usleep_range(500, 1000);
416         return 0;
417 }
418
419 /* Disable attached power regulator if any. */
420 static void ak8975_power_off(const struct ak8975_data *data)
421 {
422         regulator_disable(data->vid);
423         regulator_disable(data->vdd);
424 }
425
426 /*
427  * Return 0 if the i2c device is the one we expect.
428  * return a negative error number otherwise
429  */
430 static int ak8975_who_i_am(struct i2c_client *client,
431                            enum asahi_compass_chipset type)
432 {
433         u8 wia_val[2];
434         int ret;
435
436         /*
437          * Signature for each device:
438          * Device   |  WIA1      |  WIA2
439          * AK09912  |  DEVICE_ID |  AK09912_DEVICE_ID
440          * AK09911  |  DEVICE_ID |  AK09911_DEVICE_ID
441          * AK8975   |  DEVICE_ID |  NA
442          * AK8963   |  DEVICE_ID |  NA
443          */
444         ret = i2c_smbus_read_i2c_block_data_or_emulated(
445                         client, AK09912_REG_WIA1, 2, wia_val);
446         if (ret < 0) {
447                 dev_err(&client->dev, "Error reading WIA\n");
448                 return ret;
449         }
450
451         if (wia_val[0] != AK8975_DEVICE_ID)
452                 return -ENODEV;
453
454         switch (type) {
455         case AK8975:
456         case AK8963:
457                 return 0;
458         case AK09911:
459                 if (wia_val[1] == AK09911_DEVICE_ID)
460                         return 0;
461                 break;
462         case AK09912:
463                 if (wia_val[1] == AK09912_DEVICE_ID)
464                         return 0;
465                 break;
466         default:
467                 dev_err(&client->dev, "Type %d unknown\n", type);
468         }
469         return -ENODEV;
470 }
471
472 /*
473  * Helper function to write to CNTL register.
474  */
475 static int ak8975_set_mode(struct ak8975_data *data, enum ak_ctrl_mode mode)
476 {
477         u8 regval;
478         int ret;
479
480         regval = (data->cntl_cache & ~data->def->ctrl_masks[CNTL_MODE]) |
481                  data->def->ctrl_modes[mode];
482         ret = i2c_smbus_write_byte_data(data->client,
483                                         data->def->ctrl_regs[CNTL], regval);
484         if (ret < 0) {
485                 return ret;
486         }
487         data->cntl_cache = regval;
488         /* After mode change wait atleast 100us */
489         usleep_range(100, 500);
490
491         return 0;
492 }
493
494 /*
495  * Handle data ready irq
496  */
497 static irqreturn_t ak8975_irq_handler(int irq, void *data)
498 {
499         struct ak8975_data *ak8975 = data;
500
501         set_bit(0, &ak8975->flags);
502         wake_up(&ak8975->data_ready_queue);
503
504         return IRQ_HANDLED;
505 }
506
507 /*
508  * Install data ready interrupt handler
509  */
510 static int ak8975_setup_irq(struct ak8975_data *data)
511 {
512         struct i2c_client *client = data->client;
513         int rc;
514         int irq;
515
516         init_waitqueue_head(&data->data_ready_queue);
517         clear_bit(0, &data->flags);
518         if (client->irq)
519                 irq = client->irq;
520         else
521                 irq = gpio_to_irq(data->eoc_gpio);
522
523         rc = devm_request_irq(&client->dev, irq, ak8975_irq_handler,
524                               IRQF_TRIGGER_RISING | IRQF_ONESHOT,
525                               dev_name(&client->dev), data);
526         if (rc < 0) {
527                 dev_err(&client->dev,
528                         "irq %d request failed, (gpio %d): %d\n",
529                         irq, data->eoc_gpio, rc);
530                 return rc;
531         }
532
533         data->eoc_irq = irq;
534
535         return rc;
536 }
537
538
539 /*
540  * Perform some start-of-day setup, including reading the asa calibration
541  * values and caching them.
542  */
543 static int ak8975_setup(struct i2c_client *client)
544 {
545         struct iio_dev *indio_dev = i2c_get_clientdata(client);
546         struct ak8975_data *data = iio_priv(indio_dev);
547         int ret;
548
549         /* Write the fused rom access mode. */
550         ret = ak8975_set_mode(data, FUSE_ROM);
551         if (ret < 0) {
552                 dev_err(&client->dev, "Error in setting fuse access mode\n");
553                 return ret;
554         }
555
556         /* Get asa data and store in the device data. */
557         ret = i2c_smbus_read_i2c_block_data_or_emulated(
558                         client, data->def->ctrl_regs[ASA_BASE],
559                         3, data->asa);
560         if (ret < 0) {
561                 dev_err(&client->dev, "Not able to read asa data\n");
562                 return ret;
563         }
564
565         /* After reading fuse ROM data set power-down mode */
566         ret = ak8975_set_mode(data, POWER_DOWN);
567         if (ret < 0) {
568                 dev_err(&client->dev, "Error in setting power-down mode\n");
569                 return ret;
570         }
571
572         if (data->eoc_gpio > 0 || client->irq > 0) {
573                 ret = ak8975_setup_irq(data);
574                 if (ret < 0) {
575                         dev_err(&client->dev,
576                                 "Error setting data ready interrupt\n");
577                         return ret;
578                 }
579         }
580
581         data->raw_to_gauss[0] = data->def->raw_to_gauss(data->asa[0]);
582         data->raw_to_gauss[1] = data->def->raw_to_gauss(data->asa[1]);
583         data->raw_to_gauss[2] = data->def->raw_to_gauss(data->asa[2]);
584
585         return 0;
586 }
587
588 static int wait_conversion_complete_gpio(struct ak8975_data *data)
589 {
590         struct i2c_client *client = data->client;
591         u32 timeout_ms = AK8975_MAX_CONVERSION_TIMEOUT;
592         int ret;
593
594         /* Wait for the conversion to complete. */
595         while (timeout_ms) {
596                 msleep(AK8975_CONVERSION_DONE_POLL_TIME);
597                 if (gpio_get_value(data->eoc_gpio))
598                         break;
599                 timeout_ms -= AK8975_CONVERSION_DONE_POLL_TIME;
600         }
601         if (!timeout_ms) {
602                 dev_err(&client->dev, "Conversion timeout happened\n");
603                 return -EINVAL;
604         }
605
606         ret = i2c_smbus_read_byte_data(client, data->def->ctrl_regs[ST1]);
607         if (ret < 0)
608                 dev_err(&client->dev, "Error in reading ST1\n");
609
610         return ret;
611 }
612
613 static int wait_conversion_complete_polled(struct ak8975_data *data)
614 {
615         struct i2c_client *client = data->client;
616         u8 read_status;
617         u32 timeout_ms = AK8975_MAX_CONVERSION_TIMEOUT;
618         int ret;
619
620         /* Wait for the conversion to complete. */
621         while (timeout_ms) {
622                 msleep(AK8975_CONVERSION_DONE_POLL_TIME);
623                 ret = i2c_smbus_read_byte_data(client,
624                                                data->def->ctrl_regs[ST1]);
625                 if (ret < 0) {
626                         dev_err(&client->dev, "Error in reading ST1\n");
627                         return ret;
628                 }
629                 read_status = ret;
630                 if (read_status)
631                         break;
632                 timeout_ms -= AK8975_CONVERSION_DONE_POLL_TIME;
633         }
634         if (!timeout_ms) {
635                 dev_err(&client->dev, "Conversion timeout happened\n");
636                 return -EINVAL;
637         }
638
639         return read_status;
640 }
641
642 /* Returns 0 if the end of conversion interrupt occured or -ETIME otherwise */
643 static int wait_conversion_complete_interrupt(struct ak8975_data *data)
644 {
645         int ret;
646
647         ret = wait_event_timeout(data->data_ready_queue,
648                                  test_bit(0, &data->flags),
649                                  AK8975_DATA_READY_TIMEOUT);
650         clear_bit(0, &data->flags);
651
652         return ret > 0 ? 0 : -ETIME;
653 }
654
655 static int ak8975_start_read_axis(struct ak8975_data *data,
656                                   const struct i2c_client *client)
657 {
658         /* Set up the device for taking a sample. */
659         int ret = ak8975_set_mode(data, MODE_ONCE);
660
661         if (ret < 0) {
662                 dev_err(&client->dev, "Error in setting operating mode\n");
663                 return ret;
664         }
665
666         /* Wait for the conversion to complete. */
667         if (data->eoc_irq)
668                 ret = wait_conversion_complete_interrupt(data);
669         else if (gpio_is_valid(data->eoc_gpio))
670                 ret = wait_conversion_complete_gpio(data);
671         else
672                 ret = wait_conversion_complete_polled(data);
673         if (ret < 0)
674                 return ret;
675
676         /* This will be executed only for non-interrupt based waiting case */
677         if (ret & data->def->ctrl_masks[ST1_DRDY]) {
678                 ret = i2c_smbus_read_byte_data(client,
679                                                data->def->ctrl_regs[ST2]);
680                 if (ret < 0) {
681                         dev_err(&client->dev, "Error in reading ST2\n");
682                         return ret;
683                 }
684                 if (ret & (data->def->ctrl_masks[ST2_DERR] |
685                            data->def->ctrl_masks[ST2_HOFL])) {
686                         dev_err(&client->dev, "ST2 status error 0x%x\n", ret);
687                         return -EINVAL;
688                 }
689         }
690
691         return 0;
692 }
693
694 /* Retrieve raw flux value for one of the x, y, or z axis.  */
695 static int ak8975_read_axis(struct iio_dev *indio_dev, int index, int *val)
696 {
697         struct ak8975_data *data = iio_priv(indio_dev);
698         const struct i2c_client *client = data->client;
699         const struct ak_def *def = data->def;
700         __le16 rval;
701         u16 buff;
702         int ret;
703
704         pm_runtime_get_sync(&data->client->dev);
705
706         mutex_lock(&data->lock);
707
708         ret = ak8975_start_read_axis(data, client);
709         if (ret)
710                 goto exit;
711
712         ret = i2c_smbus_read_i2c_block_data_or_emulated(
713                         client, def->data_regs[index],
714                         sizeof(rval), (u8*)&rval);
715         if (ret < 0)
716                 goto exit;
717
718         mutex_unlock(&data->lock);
719
720         pm_runtime_mark_last_busy(&data->client->dev);
721         pm_runtime_put_autosuspend(&data->client->dev);
722
723         /* Swap bytes and convert to valid range. */
724         buff = le16_to_cpu(rval);
725         *val = clamp_t(s16, buff, -def->range, def->range);
726         return IIO_VAL_INT;
727
728 exit:
729         mutex_unlock(&data->lock);
730         dev_err(&client->dev, "Error in reading axis\n");
731         return ret;
732 }
733
734 static int ak8975_read_raw(struct iio_dev *indio_dev,
735                            struct iio_chan_spec const *chan,
736                            int *val, int *val2,
737                            long mask)
738 {
739         struct ak8975_data *data = iio_priv(indio_dev);
740
741         switch (mask) {
742         case IIO_CHAN_INFO_RAW:
743                 return ak8975_read_axis(indio_dev, chan->address, val);
744         case IIO_CHAN_INFO_SCALE:
745                 *val = 0;
746                 *val2 = data->raw_to_gauss[chan->address];
747                 return IIO_VAL_INT_PLUS_MICRO;
748         }
749         return -EINVAL;
750 }
751
752 static const struct iio_mount_matrix *
753 ak8975_get_mount_matrix(const struct iio_dev *indio_dev,
754                         const struct iio_chan_spec *chan)
755 {
756         return &((struct ak8975_data *)iio_priv(indio_dev))->orientation;
757 }
758
759 static const struct iio_chan_spec_ext_info ak8975_ext_info[] = {
760         IIO_MOUNT_MATRIX(IIO_SHARED_BY_DIR, ak8975_get_mount_matrix),
761         { },
762 };
763
764 #define AK8975_CHANNEL(axis, index)                                     \
765         {                                                               \
766                 .type = IIO_MAGN,                                       \
767                 .modified = 1,                                          \
768                 .channel2 = IIO_MOD_##axis,                             \
769                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |          \
770                              BIT(IIO_CHAN_INFO_SCALE),                  \
771                 .address = index,                                       \
772                 .scan_index = index,                                    \
773                 .scan_type = {                                          \
774                         .sign = 's',                                    \
775                         .realbits = 16,                                 \
776                         .storagebits = 16,                              \
777                         .endianness = IIO_CPU                           \
778                 },                                                      \
779                 .ext_info = ak8975_ext_info,                            \
780         }
781
782 static const struct iio_chan_spec ak8975_channels[] = {
783         AK8975_CHANNEL(X, 0), AK8975_CHANNEL(Y, 1), AK8975_CHANNEL(Z, 2),
784         IIO_CHAN_SOFT_TIMESTAMP(3),
785 };
786
787 static const unsigned long ak8975_scan_masks[] = { 0x7, 0 };
788
789 static const struct iio_info ak8975_info = {
790         .read_raw = &ak8975_read_raw,
791 };
792
793 #ifdef CONFIG_ACPI
794 static const struct acpi_device_id ak_acpi_match[] = {
795         {"AK8975", AK8975},
796         {"AK8963", AK8963},
797         {"INVN6500", AK8963},
798         {"AK009911", AK09911},
799         {"AK09911", AK09911},
800         {"AK09912", AK09912},
801         { },
802 };
803 MODULE_DEVICE_TABLE(acpi, ak_acpi_match);
804 #endif
805
806 static const char *ak8975_match_acpi_device(struct device *dev,
807                                             enum asahi_compass_chipset *chipset)
808 {
809         const struct acpi_device_id *id;
810
811         id = acpi_match_device(dev->driver->acpi_match_table, dev);
812         if (!id)
813                 return NULL;
814         *chipset = (int)id->driver_data;
815
816         return dev_name(dev);
817 }
818
819 static void ak8975_fill_buffer(struct iio_dev *indio_dev)
820 {
821         struct ak8975_data *data = iio_priv(indio_dev);
822         const struct i2c_client *client = data->client;
823         const struct ak_def *def = data->def;
824         int ret;
825         __le16 fval[3];
826
827         mutex_lock(&data->lock);
828
829         ret = ak8975_start_read_axis(data, client);
830         if (ret)
831                 goto unlock;
832
833         /*
834          * For each axis, read the flux value from the appropriate register
835          * (the register is specified in the iio device attributes).
836          */
837         ret = i2c_smbus_read_i2c_block_data_or_emulated(client,
838                                                         def->data_regs[0],
839                                                         3 * sizeof(fval[0]),
840                                                         (u8 *)fval);
841         if (ret < 0)
842                 goto unlock;
843
844         mutex_unlock(&data->lock);
845
846         /* Clamp to valid range. */
847         data->scan.channels[0] = clamp_t(s16, le16_to_cpu(fval[0]), -def->range, def->range);
848         data->scan.channels[1] = clamp_t(s16, le16_to_cpu(fval[1]), -def->range, def->range);
849         data->scan.channels[2] = clamp_t(s16, le16_to_cpu(fval[2]), -def->range, def->range);
850
851         iio_push_to_buffers_with_timestamp(indio_dev, &data->scan,
852                                            iio_get_time_ns(indio_dev));
853
854         return;
855
856 unlock:
857         mutex_unlock(&data->lock);
858         dev_err(&client->dev, "Error in reading axes block\n");
859 }
860
861 static irqreturn_t ak8975_handle_trigger(int irq, void *p)
862 {
863         const struct iio_poll_func *pf = p;
864         struct iio_dev *indio_dev = pf->indio_dev;
865
866         ak8975_fill_buffer(indio_dev);
867         iio_trigger_notify_done(indio_dev->trig);
868         return IRQ_HANDLED;
869 }
870
871 static int ak8975_probe(struct i2c_client *client,
872                         const struct i2c_device_id *id)
873 {
874         struct ak8975_data *data;
875         struct iio_dev *indio_dev;
876         int eoc_gpio;
877         int err;
878         const char *name = NULL;
879         enum asahi_compass_chipset chipset = AK_MAX_TYPE;
880         const struct ak8975_platform_data *pdata =
881                 dev_get_platdata(&client->dev);
882
883         /* Grab and set up the supplied GPIO. */
884         if (pdata)
885                 eoc_gpio = pdata->eoc_gpio;
886         else if (client->dev.of_node)
887                 eoc_gpio = of_get_gpio(client->dev.of_node, 0);
888         else
889                 eoc_gpio = -1;
890
891         if (eoc_gpio == -EPROBE_DEFER)
892                 return -EPROBE_DEFER;
893
894         /* We may not have a GPIO based IRQ to scan, that is fine, we will
895            poll if so */
896         if (gpio_is_valid(eoc_gpio)) {
897                 err = devm_gpio_request_one(&client->dev, eoc_gpio,
898                                                         GPIOF_IN, "ak_8975");
899                 if (err < 0) {
900                         dev_err(&client->dev,
901                                 "failed to request GPIO %d, error %d\n",
902                                                         eoc_gpio, err);
903                         return err;
904                 }
905         }
906
907         /* Register with IIO */
908         indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
909         if (indio_dev == NULL)
910                 return -ENOMEM;
911
912         data = iio_priv(indio_dev);
913         i2c_set_clientdata(client, indio_dev);
914
915         data->client = client;
916         data->eoc_gpio = eoc_gpio;
917         data->eoc_irq = 0;
918
919         if (!pdata) {
920                 err = of_iio_read_mount_matrix(&client->dev,
921                                                "mount-matrix",
922                                                &data->orientation);
923                 if (err)
924                         return err;
925         } else
926                 data->orientation = pdata->orientation;
927
928         /* id will be NULL when enumerated via ACPI */
929         if (id) {
930                 chipset = (enum asahi_compass_chipset)(id->driver_data);
931                 name = id->name;
932         } else if (ACPI_HANDLE(&client->dev)) {
933                 name = ak8975_match_acpi_device(&client->dev, &chipset);
934                 if (!name)
935                         return -ENODEV;
936         } else
937                 return -ENOSYS;
938
939         if (chipset >= AK_MAX_TYPE) {
940                 dev_err(&client->dev, "AKM device type unsupported: %d\n",
941                         chipset);
942                 return -ENODEV;
943         }
944
945         data->def = &ak_def_array[chipset];
946
947         /* Fetch the regulators */
948         data->vdd = devm_regulator_get(&client->dev, "vdd");
949         if (IS_ERR(data->vdd))
950                 return PTR_ERR(data->vdd);
951         data->vid = devm_regulator_get(&client->dev, "vid");
952         if (IS_ERR(data->vid))
953                 return PTR_ERR(data->vid);
954
955         err = ak8975_power_on(data);
956         if (err)
957                 return err;
958
959         err = ak8975_who_i_am(client, data->def->type);
960         if (err < 0) {
961                 dev_err(&client->dev, "Unexpected device\n");
962                 goto power_off;
963         }
964         dev_dbg(&client->dev, "Asahi compass chip %s\n", name);
965
966         /* Perform some basic start-of-day setup of the device. */
967         err = ak8975_setup(client);
968         if (err < 0) {
969                 dev_err(&client->dev, "%s initialization fails\n", name);
970                 goto power_off;
971         }
972
973         mutex_init(&data->lock);
974         indio_dev->dev.parent = &client->dev;
975         indio_dev->channels = ak8975_channels;
976         indio_dev->num_channels = ARRAY_SIZE(ak8975_channels);
977         indio_dev->info = &ak8975_info;
978         indio_dev->available_scan_masks = ak8975_scan_masks;
979         indio_dev->modes = INDIO_DIRECT_MODE;
980         indio_dev->name = name;
981
982         err = iio_triggered_buffer_setup(indio_dev, NULL, ak8975_handle_trigger,
983                                          NULL);
984         if (err) {
985                 dev_err(&client->dev, "triggered buffer setup failed\n");
986                 goto power_off;
987         }
988
989         err = iio_device_register(indio_dev);
990         if (err) {
991                 dev_err(&client->dev, "device register failed\n");
992                 goto cleanup_buffer;
993         }
994
995         /* Enable runtime PM */
996         pm_runtime_get_noresume(&client->dev);
997         pm_runtime_set_active(&client->dev);
998         pm_runtime_enable(&client->dev);
999         /*
1000          * The device comes online in 500us, so add two orders of magnitude
1001          * of delay before autosuspending: 50 ms.
1002          */
1003         pm_runtime_set_autosuspend_delay(&client->dev, 50);
1004         pm_runtime_use_autosuspend(&client->dev);
1005         pm_runtime_put(&client->dev);
1006
1007         return 0;
1008
1009 cleanup_buffer:
1010         iio_triggered_buffer_cleanup(indio_dev);
1011 power_off:
1012         ak8975_power_off(data);
1013         return err;
1014 }
1015
1016 static int ak8975_remove(struct i2c_client *client)
1017 {
1018         struct iio_dev *indio_dev = i2c_get_clientdata(client);
1019         struct ak8975_data *data = iio_priv(indio_dev);
1020
1021         pm_runtime_get_sync(&client->dev);
1022         pm_runtime_put_noidle(&client->dev);
1023         pm_runtime_disable(&client->dev);
1024         iio_device_unregister(indio_dev);
1025         iio_triggered_buffer_cleanup(indio_dev);
1026         ak8975_set_mode(data, POWER_DOWN);
1027         ak8975_power_off(data);
1028
1029         return 0;
1030 }
1031
1032 #ifdef CONFIG_PM
1033 static int ak8975_runtime_suspend(struct device *dev)
1034 {
1035         struct i2c_client *client = to_i2c_client(dev);
1036         struct iio_dev *indio_dev = i2c_get_clientdata(client);
1037         struct ak8975_data *data = iio_priv(indio_dev);
1038         int ret;
1039
1040         /* Set the device in power down if it wasn't already */
1041         ret = ak8975_set_mode(data, POWER_DOWN);
1042         if (ret < 0) {
1043                 dev_err(&client->dev, "Error in setting power-down mode\n");
1044                 return ret;
1045         }
1046         /* Next cut the regulators */
1047         ak8975_power_off(data);
1048
1049         return 0;
1050 }
1051
1052 static int ak8975_runtime_resume(struct device *dev)
1053 {
1054         struct i2c_client *client = to_i2c_client(dev);
1055         struct iio_dev *indio_dev = i2c_get_clientdata(client);
1056         struct ak8975_data *data = iio_priv(indio_dev);
1057         int ret;
1058
1059         /* Take up the regulators */
1060         ak8975_power_on(data);
1061         /*
1062          * We come up in powered down mode, the reading routines will
1063          * put us in the mode to read values later.
1064          */
1065         ret = ak8975_set_mode(data, POWER_DOWN);
1066         if (ret < 0) {
1067                 dev_err(&client->dev, "Error in setting power-down mode\n");
1068                 return ret;
1069         }
1070
1071         return 0;
1072 }
1073 #endif /* CONFIG_PM */
1074
1075 static const struct dev_pm_ops ak8975_dev_pm_ops = {
1076         SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
1077                                 pm_runtime_force_resume)
1078         SET_RUNTIME_PM_OPS(ak8975_runtime_suspend,
1079                            ak8975_runtime_resume, NULL)
1080 };
1081
1082 static const struct i2c_device_id ak8975_id[] = {
1083         {"ak8975", AK8975},
1084         {"ak8963", AK8963},
1085         {"AK8963", AK8963},
1086         {"ak09911", AK09911},
1087         {"ak09912", AK09912},
1088         {}
1089 };
1090
1091 MODULE_DEVICE_TABLE(i2c, ak8975_id);
1092
1093 static const struct of_device_id ak8975_of_match[] = {
1094         { .compatible = "asahi-kasei,ak8975", },
1095         { .compatible = "ak8975", },
1096         { .compatible = "asahi-kasei,ak8963", },
1097         { .compatible = "ak8963", },
1098         { .compatible = "asahi-kasei,ak09911", },
1099         { .compatible = "ak09911", },
1100         { .compatible = "asahi-kasei,ak09912", },
1101         { .compatible = "ak09912", },
1102         {}
1103 };
1104 MODULE_DEVICE_TABLE(of, ak8975_of_match);
1105
1106 static struct i2c_driver ak8975_driver = {
1107         .driver = {
1108                 .name   = "ak8975",
1109                 .pm = &ak8975_dev_pm_ops,
1110                 .of_match_table = of_match_ptr(ak8975_of_match),
1111                 .acpi_match_table = ACPI_PTR(ak_acpi_match),
1112         },
1113         .probe          = ak8975_probe,
1114         .remove         = ak8975_remove,
1115         .id_table       = ak8975_id,
1116 };
1117 module_i2c_driver(ak8975_driver);
1118
1119 MODULE_AUTHOR("Laxman Dewangan <ldewangan@nvidia.com>");
1120 MODULE_DESCRIPTION("AK8975 magnetometer driver");
1121 MODULE_LICENSE("GPL");