xref: /linux/drivers/iio/flow/slf3s.c (revision 67f8bc848ee31831336bd478e57d2f993551902e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Sensirion SLF3S liquid flow sensor driver.
4  *
5  * Supports the SLF3S-0600F, SLF3S-1300F and SLF3S-4000B liquid-flow
6  * sensors over I2C.  Each measurement frame returns a 16-bit signed
7  * flow value, a 16-bit signed temperature value and a status word,
8  * each protected by a CRC-8 byte.
9  *
10  * The active calibration medium (water or isopropyl alcohol) is
11  * runtime-switchable via the in_volumeflow_medium sysfs attribute and
12  * defaults to water.
13  *
14  * Datasheet: https://sensirion.com/products/catalog/SLF3S-0600F/
15  *
16  * Copyright (C) 2026 CMBlu Energy GmbH
17  * Author: Wadim Mueller <wafgo01@gmail.com>
18  */
19 
20 #include <linux/array_size.h>
21 #include <linux/bitops.h>
22 #include <linux/cleanup.h>
23 #include <linux/crc8.h>
24 #include <linux/delay.h>
25 #include <linux/dev_printk.h>
26 #include <linux/device.h>
27 #include <linux/err.h>
28 #include <linux/errno.h>
29 #include <linux/i2c.h>
30 #include <linux/math.h>
31 #include <linux/math64.h>
32 #include <linux/module.h>
33 #include <linux/mutex.h>
34 #include <linux/pm.h>
35 #include <linux/regulator/consumer.h>
36 #include <linux/types.h>
37 #include <linux/unaligned.h>
38 #include <linux/units.h>
39 
40 #include <linux/iio/iio.h>
41 
42 #define SLF3S_CRC8_POLY			0x31
43 #define SLF3S_CRC8_INIT			0xff
44 
45 #define SLF3S_PRODUCT_ID_LEN		18
46 #define SLF3S_PRODUCT_FAMILY_BYTE	1
47 #define SLF3S_PRODUCT_SUBTYPE_BYTE	3
48 #define SLF3S_PRODUCT_FAMILY_ID		0x03
49 
50 /* Datasheet section 2.2: tPU = 25 ms max from power-on to first cmd. */
51 #define SLF3S_POWER_UP_DELAY_US		(25 * USEC_PER_MSEC)
52 /* Datasheet section 2.2: tw = 60 ms typical until first valid sample. */
53 #define SLF3S_MEAS_START_DELAY_US	(60 * USEC_PER_MSEC)
54 
55 static const u8 slf3s_cmd_prep_pid[]	= { 0x36, 0x7c };
56 static const u8 slf3s_cmd_read_pid[]	= { 0xe1, 0x02 };
57 static const u8 slf3s_cmd_start_water[]	= { 0x36, 0x08 };
58 static const u8 slf3s_cmd_start_ipa[]	= { 0x36, 0x15 };
59 static const u8 slf3s_cmd_stop_meas[]	= { 0x3f, 0xf9 };
60 
61 enum slf3s_medium {
62 	SLF3S_MEDIUM_WATER,
63 	SLF3S_MEDIUM_IPA,
64 };
65 
66 static const char * const slf3s_medium_modes[] = {
67 	[SLF3S_MEDIUM_WATER]	= "water",
68 	[SLF3S_MEDIUM_IPA]	= "ipa",
69 };
70 
71 enum slf3s_variant_id {
72 	SLF3S_0600F,
73 	SLF3S_1300F,
74 	SLF3S_4000B,
75 };
76 
77 /**
78  * struct slf3s_variant - per-variant calibration constants
79  * @sub_type:	product-info sub-type byte returned by the sensor
80  * @name:	name reported via @iio_dev.name
81  * @scale:	flow scale in l/s per LSB
82  */
83 struct slf3s_variant {
84 	u8 sub_type;
85 	const char *name;
86 	struct s32_fract scale;
87 };
88 
89 static const struct slf3s_variant slf3s_variants[] = {
90 	[SLF3S_0600F] = {
91 		.sub_type	= 0x03,
92 		.name		= "slf3s-0600f",
93 		.scale		= { .numerator = 1, .denominator = 600 * MICRO },
94 	},
95 	[SLF3S_1300F] = {
96 		.sub_type	= 0x02,
97 		.name		= "slf3s-1300f",
98 		.scale		= { .numerator = 1, .denominator = 30 * MICRO },
99 	},
100 	[SLF3S_4000B] = {
101 		.sub_type	= 0x05,
102 		.name		= "slf3s-4000b",
103 		.scale		= { .numerator = 1, .denominator = 1920 * MILLI },
104 	},
105 };
106 
107 /**
108  * struct slf3s_data - per-device state
109  * @client:	I2C client this instance is bound to
110  * @vdd:	supply regulator, disabled while suspended
111  * @variant:	pointer into @slf3s_variants for the detected device
112  * @medium:	currently active calibration medium
113  * @lock:	serialises the multi-step command/response exchanges
114  * @crc_table:	pre-computed CRC-8 lookup table for SLF3S_CRC8_POLY
115  */
116 struct slf3s_data {
117 	struct i2c_client *client;
118 	struct regulator *vdd;
119 	const struct slf3s_variant *variant;
120 	enum slf3s_medium medium;
121 	struct mutex lock;
122 	u8 crc_table[CRC8_TABLE_SIZE];
123 };
124 
125 static int slf3s_send_cmd(struct i2c_client *client, const u8 *cmd)
126 {
127 	int ret;
128 
129 	ret = i2c_master_send(client, cmd, 2);
130 	if (ret < 0)
131 		return ret;
132 	if (ret != 2)
133 		return -EIO;
134 
135 	return 0;
136 }
137 
138 /* Start continuous measurement and wait until the first sample is valid. */
139 static int slf3s_start_meas(struct slf3s_data *sf, enum slf3s_medium medium)
140 {
141 	const u8 *cmd = (medium == SLF3S_MEDIUM_IPA) ? slf3s_cmd_start_ipa
142 						     : slf3s_cmd_start_water;
143 	int ret;
144 
145 	ret = slf3s_send_cmd(sf->client, cmd);
146 	if (ret)
147 		return ret;
148 
149 	fsleep(SLF3S_MEAS_START_DELAY_US);
150 
151 	return 0;
152 }
153 
154 static bool slf3s_crc_valid(const struct slf3s_data *sf, const u8 *block)
155 {
156 	return crc8(sf->crc_table, block, 2, SLF3S_CRC8_INIT) == block[2];
157 }
158 
159 /*
160  * Read the product-info block and pick the matching variant.  The
161  * sub-type byte returned by the sensor is the source of truth; a
162  * DT-supplied compatible only seeds an initial guess and is overridden
163  * on mismatch (with an informational message so misconfigured device
164  * trees are easy to spot).
165  *
166  * Bus / CRC failures are real errors and fail probe.  An unknown
167  * sub-type byte falls back to the variant named in the device tree /
168  * I2C table, so a drop-in replacement part that lists one of the known
169  * compatibles keeps working on an older kernel that does not know its
170  * sub-type yet.  Without any match data probe fails since no
171  * meaningful scale can be published.
172  */
173 static int slf3s_detect_variant(struct slf3s_data *sf)
174 {
175 	struct i2c_client *client = sf->client;
176 	u8 buf[SLF3S_PRODUCT_ID_LEN];
177 	int ret;
178 
179 	ret = slf3s_send_cmd(client, slf3s_cmd_prep_pid);
180 	if (ret)
181 		return ret;
182 
183 	ret = slf3s_send_cmd(client, slf3s_cmd_read_pid);
184 	if (ret)
185 		return ret;
186 
187 	ret = i2c_master_recv(client, buf, sizeof(buf));
188 	if (ret < 0)
189 		return ret;
190 	if (ret != sizeof(buf))
191 		return -EIO;
192 
193 	for (unsigned int i = 0; i < SLF3S_PRODUCT_ID_LEN; i += 3) {
194 		if (!slf3s_crc_valid(sf, &buf[i]))
195 			return -EIO;
196 	}
197 
198 	if (buf[SLF3S_PRODUCT_FAMILY_BYTE] != SLF3S_PRODUCT_FAMILY_ID)
199 		dev_info(&client->dev,
200 			 "unexpected family byte 0x%02x (expected 0x%02x)\n",
201 			 buf[SLF3S_PRODUCT_FAMILY_BYTE],
202 			 SLF3S_PRODUCT_FAMILY_ID);
203 
204 	for (unsigned int i = 0; i < ARRAY_SIZE(slf3s_variants); i++) {
205 		if (buf[SLF3S_PRODUCT_SUBTYPE_BYTE] !=
206 		    slf3s_variants[i].sub_type)
207 			continue;
208 
209 		if (sf->variant && sf->variant != &slf3s_variants[i])
210 			dev_info(&client->dev,
211 				 "DT compatible says %s but sensor reports %s; using the latter\n",
212 				 sf->variant->name,
213 				 slf3s_variants[i].name);
214 
215 		sf->variant = &slf3s_variants[i];
216 
217 		return 0;
218 	}
219 
220 	if (sf->variant) {
221 		dev_warn(&client->dev,
222 			 "unknown SLF3S sub-type 0x%02x, assuming %s\n",
223 			 buf[SLF3S_PRODUCT_SUBTYPE_BYTE], sf->variant->name);
224 		return 0;
225 	}
226 
227 	dev_err(&client->dev, "unknown SLF3S sub-type 0x%02x\n",
228 		buf[SLF3S_PRODUCT_SUBTYPE_BYTE]);
229 
230 	return -ENODEV;
231 }
232 
233 static int slf3s_read_sample(struct slf3s_data *sf, int *flow, int *temp)
234 {
235 	/*
236 	 * A measurement frame is flow, temperature and a signaling-flags
237 	 * word, each followed by a CRC byte.  Only flow and temperature are
238 	 * used, so the read is stopped after their two words (6 bytes).
239 	 */
240 	u8 buf[6];
241 	int ret;
242 
243 	ret = i2c_master_recv(sf->client, buf, sizeof(buf));
244 	if (ret < 0)
245 		return ret;
246 	if (ret != sizeof(buf))
247 		return -EIO;
248 
249 	for (unsigned int i = 0; i < sizeof(buf); i += 3) {
250 		if (!slf3s_crc_valid(sf, &buf[i]))
251 			return -EIO;
252 	}
253 
254 	*flow = sign_extend32(get_unaligned_be16(&buf[0]), 15);
255 	*temp = sign_extend32(get_unaligned_be16(&buf[3]), 15);
256 
257 	return 0;
258 }
259 
260 static int slf3s_get_medium(struct iio_dev *indio_dev,
261 			    const struct iio_chan_spec *chan)
262 {
263 	struct slf3s_data *sf = iio_priv(indio_dev);
264 
265 	return sf->medium;
266 }
267 
268 static int slf3s_set_medium(struct iio_dev *indio_dev,
269 			    const struct iio_chan_spec *chan, unsigned int mode)
270 {
271 	struct slf3s_data *sf = iio_priv(indio_dev);
272 	int ret;
273 
274 	guard(mutex)(&sf->lock);
275 
276 	ret = slf3s_send_cmd(sf->client, slf3s_cmd_stop_meas);
277 	if (ret)
278 		return ret;
279 
280 	ret = slf3s_start_meas(sf, mode);
281 	if (ret) {
282 		/*
283 		 * Try to restart with the previous medium so the sensor is
284 		 * not left idle, which would fail all subsequent reads.
285 		 */
286 		if (slf3s_start_meas(sf, sf->medium))
287 			dev_warn(&sf->client->dev,
288 				 "failed to restart measurement, reads will fail until a medium is set\n");
289 		return ret;
290 	}
291 
292 	sf->medium = mode;
293 
294 	return 0;
295 }
296 
297 static const struct iio_enum slf3s_medium_enum = {
298 	.items		= slf3s_medium_modes,
299 	.num_items	= ARRAY_SIZE(slf3s_medium_modes),
300 	.get		= slf3s_get_medium,
301 	.set		= slf3s_set_medium,
302 };
303 
304 static const struct iio_chan_spec_ext_info slf3s_ext_info[] = {
305 	IIO_ENUM("medium", IIO_SHARED_BY_TYPE, &slf3s_medium_enum),
306 	IIO_ENUM_AVAILABLE("medium", IIO_SHARED_BY_TYPE, &slf3s_medium_enum),
307 	{ }
308 };
309 
310 static const struct iio_chan_spec slf3s_channels[] = {
311 	{
312 		.type = IIO_VOLUMEFLOW,
313 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
314 				      BIT(IIO_CHAN_INFO_SCALE),
315 		.ext_info = slf3s_ext_info,
316 	},
317 	{
318 		.type = IIO_TEMP,
319 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
320 				      BIT(IIO_CHAN_INFO_SCALE),
321 	},
322 };
323 
324 static int slf3s_read_raw(struct iio_dev *indio_dev,
325 			  struct iio_chan_spec const *chan, int *val,
326 			  int *val2, long mask)
327 {
328 	struct slf3s_data *sf = iio_priv(indio_dev);
329 	int flow, temp, ret;
330 
331 	switch (mask) {
332 	case IIO_CHAN_INFO_RAW:
333 		scoped_guard(mutex, &sf->lock)
334 			ret = slf3s_read_sample(sf, &flow, &temp);
335 		if (ret)
336 			return ret;
337 
338 		*val = (chan->type == IIO_VOLUMEFLOW) ? flow : temp;
339 
340 		return IIO_VAL_INT;
341 	case IIO_CHAN_INFO_SCALE:
342 		if (chan->type == IIO_VOLUMEFLOW) {
343 			/*
344 			 * The variant scale is the flow per LSB in l/s, but
345 			 * IIO reports volume flow in m^3/s (1 l = 1e-3 m^3).
346 			 * These values are tiny (~1.67e-12 m^3/s for the
347 			 * SLF3S-0600F), so emit a 64-bit fixed-point value with
348 			 * femto (1e-15) resolution to preserve precision.
349 			 * Converting l/s to m^3/s (/ MILLI) and scaling to femto
350 			 * (* FEMTO) leaves a net * (FEMTO / MILLI) factor.
351 			 */
352 			const struct slf3s_variant *v = sf->variant;
353 			s64 num = (s64)v->scale.numerator * (FEMTO / MILLI);
354 			s64 scale = DIV_S64_ROUND_CLOSEST(num,
355 							  v->scale.denominator);
356 
357 			iio_val_s64_decompose(scale, val, val2);
358 
359 			return IIO_VAL_DECIMAL64_FEMTO;
360 		}
361 		/* Temperature LSB = 1/200 degC; IIO_TEMP wants milli-degC. */
362 		*val = MILLIDEGREE_PER_DEGREE / 200;
363 
364 		return IIO_VAL_INT;
365 	default:
366 		return -EINVAL;
367 	}
368 }
369 
370 static const struct iio_info slf3s_info = {
371 	.read_raw = slf3s_read_raw,
372 };
373 
374 static void slf3s_stop_meas(void *data)
375 {
376 	struct slf3s_data *sf = data;
377 
378 	slf3s_send_cmd(sf->client, slf3s_cmd_stop_meas);
379 }
380 
381 static void slf3s_disable_vdd(void *data)
382 {
383 	struct slf3s_data *sf = data;
384 
385 	regulator_disable(sf->vdd);
386 }
387 
388 static int slf3s_probe(struct i2c_client *client)
389 {
390 	struct device *dev = &client->dev;
391 	struct iio_dev *indio_dev;
392 	struct slf3s_data *sf;
393 	int ret;
394 
395 	indio_dev = devm_iio_device_alloc(dev, sizeof(*sf));
396 	if (!indio_dev)
397 		return -ENOMEM;
398 
399 	sf = iio_priv(indio_dev);
400 	sf->client = client;
401 	i2c_set_clientdata(client, indio_dev);
402 	sf->variant = i2c_get_match_data(client);
403 	sf->medium = SLF3S_MEDIUM_WATER;
404 	crc8_populate_msb(sf->crc_table, SLF3S_CRC8_POLY);
405 
406 	ret = devm_mutex_init(dev, &sf->lock);
407 	if (ret)
408 		return ret;
409 
410 	sf->vdd = devm_regulator_get(dev, "vdd");
411 	if (IS_ERR(sf->vdd))
412 		return dev_err_probe(dev, PTR_ERR(sf->vdd),
413 				     "failed to get vdd supply\n");
414 
415 	ret = regulator_enable(sf->vdd);
416 	if (ret)
417 		return dev_err_probe(dev, ret, "failed to enable vdd supply\n");
418 
419 	ret = devm_add_action_or_reset(dev, slf3s_disable_vdd, sf);
420 	if (ret)
421 		return ret;
422 
423 	fsleep(SLF3S_POWER_UP_DELAY_US);
424 
425 	/*
426 	 * The sensor may still be in continuous measurement mode from a
427 	 * previous boot (warm reboot / kexec); in that case it would NACK
428 	 * the product-id command below.  Stop it first and ignore the error
429 	 * if it was already idle.
430 	 */
431 	slf3s_send_cmd(client, slf3s_cmd_stop_meas);
432 
433 	ret = slf3s_detect_variant(sf);
434 	if (ret)
435 		return dev_err_probe(dev, ret, "product info read failed\n");
436 
437 	ret = slf3s_start_meas(sf, sf->medium);
438 	if (ret)
439 		return dev_err_probe(dev, ret,
440 				     "failed to start measurement\n");
441 
442 	ret = devm_add_action_or_reset(dev, slf3s_stop_meas, sf);
443 	if (ret)
444 		return ret;
445 
446 	indio_dev->name = sf->variant->name;
447 	indio_dev->channels = slf3s_channels;
448 	indio_dev->num_channels = ARRAY_SIZE(slf3s_channels);
449 	indio_dev->info = &slf3s_info;
450 	indio_dev->modes = INDIO_DIRECT_MODE;
451 
452 	return devm_iio_device_register(dev, indio_dev);
453 }
454 
455 /*
456  * The sensor has no low-power state of its own, so stop the measurement
457  * and cut the supply while suspended.  Resume powers it back up, waits
458  * out the power-up time and restarts with the medium that was active
459  * before.
460  */
461 static int slf3s_suspend(struct device *dev)
462 {
463 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
464 	struct slf3s_data *sf = iio_priv(indio_dev);
465 	int ret;
466 
467 	guard(mutex)(&sf->lock);
468 
469 	ret = slf3s_send_cmd(sf->client, slf3s_cmd_stop_meas);
470 	if (ret)
471 		return ret;
472 
473 	return regulator_disable(sf->vdd);
474 }
475 
476 static int slf3s_resume(struct device *dev)
477 {
478 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
479 	struct slf3s_data *sf = iio_priv(indio_dev);
480 	int ret;
481 
482 	guard(mutex)(&sf->lock);
483 
484 	ret = regulator_enable(sf->vdd);
485 	if (ret)
486 		return ret;
487 
488 	fsleep(SLF3S_POWER_UP_DELAY_US);
489 
490 	return slf3s_start_meas(sf, sf->medium);
491 }
492 
493 static DEFINE_SIMPLE_DEV_PM_OPS(slf3s_pm_ops, slf3s_suspend, slf3s_resume);
494 
495 static const struct i2c_device_id slf3s_id[] = {
496 	{
497 		.name = "slf3s-0600f",
498 		.driver_data = (kernel_ulong_t)&slf3s_variants[SLF3S_0600F],
499 	},
500 	{
501 		.name = "slf3s-1300f",
502 		.driver_data = (kernel_ulong_t)&slf3s_variants[SLF3S_1300F],
503 	},
504 	{
505 		.name = "slf3s-4000b",
506 		.driver_data = (kernel_ulong_t)&slf3s_variants[SLF3S_4000B],
507 	},
508 	{ }
509 };
510 MODULE_DEVICE_TABLE(i2c, slf3s_id);
511 
512 static const struct of_device_id slf3s_of_match[] = {
513 	{
514 		.compatible = "sensirion,slf3s-0600f",
515 		.data = &slf3s_variants[SLF3S_0600F],
516 	},
517 	{
518 		.compatible = "sensirion,slf3s-1300f",
519 		.data = &slf3s_variants[SLF3S_1300F],
520 	},
521 	{
522 		.compatible = "sensirion,slf3s-4000b",
523 		.data = &slf3s_variants[SLF3S_4000B],
524 	},
525 	{ }
526 };
527 MODULE_DEVICE_TABLE(of, slf3s_of_match);
528 
529 static struct i2c_driver slf3s_driver = {
530 	.driver = {
531 		.name		= "slf3s",
532 		.of_match_table	= slf3s_of_match,
533 		.pm		= pm_sleep_ptr(&slf3s_pm_ops),
534 	},
535 	.probe		= slf3s_probe,
536 	.id_table	= slf3s_id,
537 };
538 module_i2c_driver(slf3s_driver);
539 
540 MODULE_AUTHOR("Wadim Mueller <wafgo01@gmail.com>");
541 MODULE_DESCRIPTION("Sensirion SLF3S liquid flow sensor driver");
542 MODULE_LICENSE("GPL");
543