xref: /openbmc/linux/drivers/hwmon/pmbus/pmbus_core.c (revision b04b076f)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Hardware monitoring driver for PMBus devices
4  *
5  * Copyright (c) 2010, 2011 Ericsson AB.
6  * Copyright (c) 2012 Guenter Roeck
7  */
8 
9 #include <linux/debugfs.h>
10 #include <linux/kernel.h>
11 #include <linux/math64.h>
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/err.h>
15 #include <linux/slab.h>
16 #include <linux/i2c.h>
17 #include <linux/hwmon.h>
18 #include <linux/hwmon-sysfs.h>
19 #include <linux/pmbus.h>
20 #include <linux/regulator/driver.h>
21 #include <linux/regulator/machine.h>
22 #include <linux/of.h>
23 #include <linux/thermal.h>
24 #include "pmbus.h"
25 
26 /*
27  * Number of additional attribute pointers to allocate
28  * with each call to krealloc
29  */
30 #define PMBUS_ATTR_ALLOC_SIZE	32
31 #define PMBUS_NAME_SIZE		24
32 
33 struct pmbus_sensor {
34 	struct pmbus_sensor *next;
35 	char name[PMBUS_NAME_SIZE];	/* sysfs sensor name */
36 	struct device_attribute attribute;
37 	u8 page;		/* page number */
38 	u8 phase;		/* phase number, 0xff for all phases */
39 	u16 reg;		/* register */
40 	enum pmbus_sensor_classes class;	/* sensor class */
41 	bool update;		/* runtime sensor update needed */
42 	bool convert;		/* Whether or not to apply linear/vid/direct */
43 	int data;		/* Sensor data.
44 				   Negative if there was a read error */
45 };
46 #define to_pmbus_sensor(_attr) \
47 	container_of(_attr, struct pmbus_sensor, attribute)
48 
49 struct pmbus_boolean {
50 	char name[PMBUS_NAME_SIZE];	/* sysfs boolean name */
51 	struct sensor_device_attribute attribute;
52 	struct pmbus_sensor *s1;
53 	struct pmbus_sensor *s2;
54 };
55 #define to_pmbus_boolean(_attr) \
56 	container_of(_attr, struct pmbus_boolean, attribute)
57 
58 struct pmbus_label {
59 	char name[PMBUS_NAME_SIZE];	/* sysfs label name */
60 	struct device_attribute attribute;
61 	char label[PMBUS_NAME_SIZE];	/* label */
62 };
63 #define to_pmbus_label(_attr) \
64 	container_of(_attr, struct pmbus_label, attribute)
65 
66 /* Macros for converting between sensor index and register/page/status mask */
67 
68 #define PB_STATUS_MASK	0xffff
69 #define PB_REG_SHIFT	16
70 #define PB_REG_MASK	0x3ff
71 #define PB_PAGE_SHIFT	26
72 #define PB_PAGE_MASK	0x3f
73 
74 #define pb_reg_to_index(page, reg, mask)	(((page) << PB_PAGE_SHIFT) | \
75 						 ((reg) << PB_REG_SHIFT) | (mask))
76 
77 #define pb_index_to_page(index)			(((index) >> PB_PAGE_SHIFT) & PB_PAGE_MASK)
78 #define pb_index_to_reg(index)			(((index) >> PB_REG_SHIFT) & PB_REG_MASK)
79 #define pb_index_to_mask(index)			((index) & PB_STATUS_MASK)
80 
81 struct pmbus_data {
82 	struct device *dev;
83 	struct device *hwmon_dev;
84 	struct regulator_dev **rdevs;
85 
86 	u32 flags;		/* from platform data */
87 
88 	int exponent[PMBUS_PAGES];
89 				/* linear mode: exponent for output voltages */
90 
91 	const struct pmbus_driver_info *info;
92 
93 	int max_attributes;
94 	int num_attributes;
95 	struct attribute_group group;
96 	const struct attribute_group **groups;
97 	struct dentry *debugfs;		/* debugfs device directory */
98 
99 	struct pmbus_sensor *sensors;
100 
101 	struct mutex update_lock;
102 
103 	bool has_status_word;		/* device uses STATUS_WORD register */
104 	int (*read_status)(struct i2c_client *client, int page);
105 
106 	s16 currpage;	/* current page, -1 for unknown/unset */
107 	s16 currphase;	/* current phase, 0xff for all, -1 for unknown/unset */
108 
109 	int vout_low[PMBUS_PAGES];	/* voltage low margin */
110 	int vout_high[PMBUS_PAGES];	/* voltage high margin */
111 };
112 
113 struct pmbus_debugfs_entry {
114 	struct i2c_client *client;
115 	u8 page;
116 	u8 reg;
117 };
118 
119 static const int pmbus_fan_rpm_mask[] = {
120 	PB_FAN_1_RPM,
121 	PB_FAN_2_RPM,
122 	PB_FAN_1_RPM,
123 	PB_FAN_2_RPM,
124 };
125 
126 static const int pmbus_fan_config_registers[] = {
127 	PMBUS_FAN_CONFIG_12,
128 	PMBUS_FAN_CONFIG_12,
129 	PMBUS_FAN_CONFIG_34,
130 	PMBUS_FAN_CONFIG_34
131 };
132 
133 static const int pmbus_fan_command_registers[] = {
134 	PMBUS_FAN_COMMAND_1,
135 	PMBUS_FAN_COMMAND_2,
136 	PMBUS_FAN_COMMAND_3,
137 	PMBUS_FAN_COMMAND_4,
138 };
139 
140 void pmbus_clear_cache(struct i2c_client *client)
141 {
142 	struct pmbus_data *data = i2c_get_clientdata(client);
143 	struct pmbus_sensor *sensor;
144 
145 	for (sensor = data->sensors; sensor; sensor = sensor->next)
146 		sensor->data = -ENODATA;
147 }
148 EXPORT_SYMBOL_NS_GPL(pmbus_clear_cache, PMBUS);
149 
150 void pmbus_set_update(struct i2c_client *client, u8 reg, bool update)
151 {
152 	struct pmbus_data *data = i2c_get_clientdata(client);
153 	struct pmbus_sensor *sensor;
154 
155 	for (sensor = data->sensors; sensor; sensor = sensor->next)
156 		if (sensor->reg == reg)
157 			sensor->update = update;
158 }
159 EXPORT_SYMBOL_NS_GPL(pmbus_set_update, PMBUS);
160 
161 int pmbus_set_page(struct i2c_client *client, int page, int phase)
162 {
163 	struct pmbus_data *data = i2c_get_clientdata(client);
164 	int rv;
165 
166 	if (page < 0)
167 		return 0;
168 
169 	if (!(data->info->func[page] & PMBUS_PAGE_VIRTUAL) &&
170 	    data->info->pages > 1 && page != data->currpage) {
171 		rv = i2c_smbus_write_byte_data(client, PMBUS_PAGE, page);
172 		if (rv < 0)
173 			return rv;
174 
175 		rv = i2c_smbus_read_byte_data(client, PMBUS_PAGE);
176 		if (rv < 0)
177 			return rv;
178 
179 		if (rv != page)
180 			return -EIO;
181 	}
182 	data->currpage = page;
183 
184 	if (data->info->phases[page] && data->currphase != phase &&
185 	    !(data->info->func[page] & PMBUS_PHASE_VIRTUAL)) {
186 		rv = i2c_smbus_write_byte_data(client, PMBUS_PHASE,
187 					       phase);
188 		if (rv)
189 			return rv;
190 	}
191 	data->currphase = phase;
192 
193 	return 0;
194 }
195 EXPORT_SYMBOL_NS_GPL(pmbus_set_page, PMBUS);
196 
197 int pmbus_write_byte(struct i2c_client *client, int page, u8 value)
198 {
199 	int rv;
200 
201 	rv = pmbus_set_page(client, page, 0xff);
202 	if (rv < 0)
203 		return rv;
204 
205 	return i2c_smbus_write_byte(client, value);
206 }
207 EXPORT_SYMBOL_NS_GPL(pmbus_write_byte, PMBUS);
208 
209 /*
210  * _pmbus_write_byte() is similar to pmbus_write_byte(), but checks if
211  * a device specific mapping function exists and calls it if necessary.
212  */
213 static int _pmbus_write_byte(struct i2c_client *client, int page, u8 value)
214 {
215 	struct pmbus_data *data = i2c_get_clientdata(client);
216 	const struct pmbus_driver_info *info = data->info;
217 	int status;
218 
219 	if (info->write_byte) {
220 		status = info->write_byte(client, page, value);
221 		if (status != -ENODATA)
222 			return status;
223 	}
224 	return pmbus_write_byte(client, page, value);
225 }
226 
227 int pmbus_write_word_data(struct i2c_client *client, int page, u8 reg,
228 			  u16 word)
229 {
230 	int rv;
231 
232 	rv = pmbus_set_page(client, page, 0xff);
233 	if (rv < 0)
234 		return rv;
235 
236 	return i2c_smbus_write_word_data(client, reg, word);
237 }
238 EXPORT_SYMBOL_NS_GPL(pmbus_write_word_data, PMBUS);
239 
240 
241 static int pmbus_write_virt_reg(struct i2c_client *client, int page, int reg,
242 				u16 word)
243 {
244 	int bit;
245 	int id;
246 	int rv;
247 
248 	switch (reg) {
249 	case PMBUS_VIRT_FAN_TARGET_1 ... PMBUS_VIRT_FAN_TARGET_4:
250 		id = reg - PMBUS_VIRT_FAN_TARGET_1;
251 		bit = pmbus_fan_rpm_mask[id];
252 		rv = pmbus_update_fan(client, page, id, bit, bit, word);
253 		break;
254 	default:
255 		rv = -ENXIO;
256 		break;
257 	}
258 
259 	return rv;
260 }
261 
262 /*
263  * _pmbus_write_word_data() is similar to pmbus_write_word_data(), but checks if
264  * a device specific mapping function exists and calls it if necessary.
265  */
266 static int _pmbus_write_word_data(struct i2c_client *client, int page, int reg,
267 				  u16 word)
268 {
269 	struct pmbus_data *data = i2c_get_clientdata(client);
270 	const struct pmbus_driver_info *info = data->info;
271 	int status;
272 
273 	if (info->write_word_data) {
274 		status = info->write_word_data(client, page, reg, word);
275 		if (status != -ENODATA)
276 			return status;
277 	}
278 
279 	if (reg >= PMBUS_VIRT_BASE)
280 		return pmbus_write_virt_reg(client, page, reg, word);
281 
282 	return pmbus_write_word_data(client, page, reg, word);
283 }
284 
285 /*
286  * _pmbus_write_byte_data() is similar to pmbus_write_byte_data(), but checks if
287  * a device specific mapping function exists and calls it if necessary.
288  */
289 static int _pmbus_write_byte_data(struct i2c_client *client, int page, int reg, u8 value)
290 {
291 	struct pmbus_data *data = i2c_get_clientdata(client);
292 	const struct pmbus_driver_info *info = data->info;
293 	int status;
294 
295 	if (info->write_byte_data) {
296 		status = info->write_byte_data(client, page, reg, value);
297 		if (status != -ENODATA)
298 			return status;
299 	}
300 	return pmbus_write_byte_data(client, page, reg, value);
301 }
302 
303 /*
304  * _pmbus_read_byte_data() is similar to pmbus_read_byte_data(), but checks if
305  * a device specific mapping function exists and calls it if necessary.
306  */
307 static int _pmbus_read_byte_data(struct i2c_client *client, int page, int reg)
308 {
309 	struct pmbus_data *data = i2c_get_clientdata(client);
310 	const struct pmbus_driver_info *info = data->info;
311 	int status;
312 
313 	if (info->read_byte_data) {
314 		status = info->read_byte_data(client, page, reg);
315 		if (status != -ENODATA)
316 			return status;
317 	}
318 	return pmbus_read_byte_data(client, page, reg);
319 }
320 
321 int pmbus_update_fan(struct i2c_client *client, int page, int id,
322 		     u8 config, u8 mask, u16 command)
323 {
324 	int from;
325 	int rv;
326 	u8 to;
327 
328 	from = _pmbus_read_byte_data(client, page,
329 				    pmbus_fan_config_registers[id]);
330 	if (from < 0)
331 		return from;
332 
333 	to = (from & ~mask) | (config & mask);
334 	if (to != from) {
335 		rv = _pmbus_write_byte_data(client, page,
336 					   pmbus_fan_config_registers[id], to);
337 		if (rv < 0)
338 			return rv;
339 	}
340 
341 	return _pmbus_write_word_data(client, page,
342 				      pmbus_fan_command_registers[id], command);
343 }
344 EXPORT_SYMBOL_NS_GPL(pmbus_update_fan, PMBUS);
345 
346 int pmbus_read_word_data(struct i2c_client *client, int page, int phase, u8 reg)
347 {
348 	int rv;
349 
350 	rv = pmbus_set_page(client, page, phase);
351 	if (rv < 0)
352 		return rv;
353 
354 	return i2c_smbus_read_word_data(client, reg);
355 }
356 EXPORT_SYMBOL_NS_GPL(pmbus_read_word_data, PMBUS);
357 
358 static int pmbus_read_virt_reg(struct i2c_client *client, int page, int reg)
359 {
360 	int rv;
361 	int id;
362 
363 	switch (reg) {
364 	case PMBUS_VIRT_FAN_TARGET_1 ... PMBUS_VIRT_FAN_TARGET_4:
365 		id = reg - PMBUS_VIRT_FAN_TARGET_1;
366 		rv = pmbus_get_fan_rate_device(client, page, id, rpm);
367 		break;
368 	default:
369 		rv = -ENXIO;
370 		break;
371 	}
372 
373 	return rv;
374 }
375 
376 /*
377  * _pmbus_read_word_data() is similar to pmbus_read_word_data(), but checks if
378  * a device specific mapping function exists and calls it if necessary.
379  */
380 static int _pmbus_read_word_data(struct i2c_client *client, int page,
381 				 int phase, int reg)
382 {
383 	struct pmbus_data *data = i2c_get_clientdata(client);
384 	const struct pmbus_driver_info *info = data->info;
385 	int status;
386 
387 	if (info->read_word_data) {
388 		status = info->read_word_data(client, page, phase, reg);
389 		if (status != -ENODATA)
390 			return status;
391 	}
392 
393 	if (reg >= PMBUS_VIRT_BASE)
394 		return pmbus_read_virt_reg(client, page, reg);
395 
396 	return pmbus_read_word_data(client, page, phase, reg);
397 }
398 
399 /* Same as above, but without phase parameter, for use in check functions */
400 static int __pmbus_read_word_data(struct i2c_client *client, int page, int reg)
401 {
402 	return _pmbus_read_word_data(client, page, 0xff, reg);
403 }
404 
405 int pmbus_read_byte_data(struct i2c_client *client, int page, u8 reg)
406 {
407 	int rv;
408 
409 	rv = pmbus_set_page(client, page, 0xff);
410 	if (rv < 0)
411 		return rv;
412 
413 	return i2c_smbus_read_byte_data(client, reg);
414 }
415 EXPORT_SYMBOL_NS_GPL(pmbus_read_byte_data, PMBUS);
416 
417 int pmbus_write_byte_data(struct i2c_client *client, int page, u8 reg, u8 value)
418 {
419 	int rv;
420 
421 	rv = pmbus_set_page(client, page, 0xff);
422 	if (rv < 0)
423 		return rv;
424 
425 	return i2c_smbus_write_byte_data(client, reg, value);
426 }
427 EXPORT_SYMBOL_NS_GPL(pmbus_write_byte_data, PMBUS);
428 
429 int pmbus_update_byte_data(struct i2c_client *client, int page, u8 reg,
430 			   u8 mask, u8 value)
431 {
432 	unsigned int tmp;
433 	int rv;
434 
435 	rv = _pmbus_read_byte_data(client, page, reg);
436 	if (rv < 0)
437 		return rv;
438 
439 	tmp = (rv & ~mask) | (value & mask);
440 
441 	if (tmp != rv)
442 		rv = _pmbus_write_byte_data(client, page, reg, tmp);
443 
444 	return rv;
445 }
446 EXPORT_SYMBOL_NS_GPL(pmbus_update_byte_data, PMBUS);
447 
448 static int pmbus_read_block_data(struct i2c_client *client, int page, u8 reg,
449 				 char *data_buf)
450 {
451 	int rv;
452 
453 	rv = pmbus_set_page(client, page, 0xff);
454 	if (rv < 0)
455 		return rv;
456 
457 	return i2c_smbus_read_block_data(client, reg, data_buf);
458 }
459 
460 static struct pmbus_sensor *pmbus_find_sensor(struct pmbus_data *data, int page,
461 					      int reg)
462 {
463 	struct pmbus_sensor *sensor;
464 
465 	for (sensor = data->sensors; sensor; sensor = sensor->next) {
466 		if (sensor->page == page && sensor->reg == reg)
467 			return sensor;
468 	}
469 
470 	return ERR_PTR(-EINVAL);
471 }
472 
473 static int pmbus_get_fan_rate(struct i2c_client *client, int page, int id,
474 			      enum pmbus_fan_mode mode,
475 			      bool from_cache)
476 {
477 	struct pmbus_data *data = i2c_get_clientdata(client);
478 	bool want_rpm, have_rpm;
479 	struct pmbus_sensor *s;
480 	int config;
481 	int reg;
482 
483 	want_rpm = (mode == rpm);
484 
485 	if (from_cache) {
486 		reg = want_rpm ? PMBUS_VIRT_FAN_TARGET_1 : PMBUS_VIRT_PWM_1;
487 		s = pmbus_find_sensor(data, page, reg + id);
488 		if (IS_ERR(s))
489 			return PTR_ERR(s);
490 
491 		return s->data;
492 	}
493 
494 	config = _pmbus_read_byte_data(client, page,
495 				      pmbus_fan_config_registers[id]);
496 	if (config < 0)
497 		return config;
498 
499 	have_rpm = !!(config & pmbus_fan_rpm_mask[id]);
500 	if (want_rpm == have_rpm)
501 		return pmbus_read_word_data(client, page, 0xff,
502 					    pmbus_fan_command_registers[id]);
503 
504 	/* Can't sensibly map between RPM and PWM, just return zero */
505 	return 0;
506 }
507 
508 int pmbus_get_fan_rate_device(struct i2c_client *client, int page, int id,
509 			      enum pmbus_fan_mode mode)
510 {
511 	return pmbus_get_fan_rate(client, page, id, mode, false);
512 }
513 EXPORT_SYMBOL_NS_GPL(pmbus_get_fan_rate_device, PMBUS);
514 
515 int pmbus_get_fan_rate_cached(struct i2c_client *client, int page, int id,
516 			      enum pmbus_fan_mode mode)
517 {
518 	return pmbus_get_fan_rate(client, page, id, mode, true);
519 }
520 EXPORT_SYMBOL_NS_GPL(pmbus_get_fan_rate_cached, PMBUS);
521 
522 static void pmbus_clear_fault_page(struct i2c_client *client, int page)
523 {
524 	_pmbus_write_byte(client, page, PMBUS_CLEAR_FAULTS);
525 }
526 
527 void pmbus_clear_faults(struct i2c_client *client)
528 {
529 	struct pmbus_data *data = i2c_get_clientdata(client);
530 	int i;
531 
532 	for (i = 0; i < data->info->pages; i++)
533 		pmbus_clear_fault_page(client, i);
534 }
535 EXPORT_SYMBOL_NS_GPL(pmbus_clear_faults, PMBUS);
536 
537 static int pmbus_check_status_cml(struct i2c_client *client)
538 {
539 	struct pmbus_data *data = i2c_get_clientdata(client);
540 	int status, status2;
541 
542 	status = data->read_status(client, -1);
543 	if (status < 0 || (status & PB_STATUS_CML)) {
544 		status2 = _pmbus_read_byte_data(client, -1, PMBUS_STATUS_CML);
545 		if (status2 < 0 || (status2 & PB_CML_FAULT_INVALID_COMMAND))
546 			return -EIO;
547 	}
548 	return 0;
549 }
550 
551 static bool pmbus_check_register(struct i2c_client *client,
552 				 int (*func)(struct i2c_client *client,
553 					     int page, int reg),
554 				 int page, int reg)
555 {
556 	int rv;
557 	struct pmbus_data *data = i2c_get_clientdata(client);
558 
559 	rv = func(client, page, reg);
560 	if (rv >= 0 && !(data->flags & PMBUS_SKIP_STATUS_CHECK))
561 		rv = pmbus_check_status_cml(client);
562 	if (rv < 0 && (data->flags & PMBUS_READ_STATUS_AFTER_FAILED_CHECK))
563 		data->read_status(client, -1);
564 	pmbus_clear_fault_page(client, -1);
565 	return rv >= 0;
566 }
567 
568 static bool pmbus_check_status_register(struct i2c_client *client, int page)
569 {
570 	int status;
571 	struct pmbus_data *data = i2c_get_clientdata(client);
572 
573 	status = data->read_status(client, page);
574 	if (status >= 0 && !(data->flags & PMBUS_SKIP_STATUS_CHECK) &&
575 	    (status & PB_STATUS_CML)) {
576 		status = _pmbus_read_byte_data(client, -1, PMBUS_STATUS_CML);
577 		if (status < 0 || (status & PB_CML_FAULT_INVALID_COMMAND))
578 			status = -EIO;
579 	}
580 
581 	pmbus_clear_fault_page(client, -1);
582 	return status >= 0;
583 }
584 
585 bool pmbus_check_byte_register(struct i2c_client *client, int page, int reg)
586 {
587 	return pmbus_check_register(client, _pmbus_read_byte_data, page, reg);
588 }
589 EXPORT_SYMBOL_NS_GPL(pmbus_check_byte_register, PMBUS);
590 
591 bool pmbus_check_word_register(struct i2c_client *client, int page, int reg)
592 {
593 	return pmbus_check_register(client, __pmbus_read_word_data, page, reg);
594 }
595 EXPORT_SYMBOL_NS_GPL(pmbus_check_word_register, PMBUS);
596 
597 static bool __maybe_unused pmbus_check_block_register(struct i2c_client *client,
598 						      int page, int reg)
599 {
600 	int rv;
601 	struct pmbus_data *data = i2c_get_clientdata(client);
602 	char data_buf[I2C_SMBUS_BLOCK_MAX + 2];
603 
604 	rv = pmbus_read_block_data(client, page, reg, data_buf);
605 	if (rv >= 0 && !(data->flags & PMBUS_SKIP_STATUS_CHECK))
606 		rv = pmbus_check_status_cml(client);
607 	if (rv < 0 && (data->flags & PMBUS_READ_STATUS_AFTER_FAILED_CHECK))
608 		data->read_status(client, -1);
609 	pmbus_clear_fault_page(client, -1);
610 	return rv >= 0;
611 }
612 
613 const struct pmbus_driver_info *pmbus_get_driver_info(struct i2c_client *client)
614 {
615 	struct pmbus_data *data = i2c_get_clientdata(client);
616 
617 	return data->info;
618 }
619 EXPORT_SYMBOL_NS_GPL(pmbus_get_driver_info, PMBUS);
620 
621 static int pmbus_get_status(struct i2c_client *client, int page, int reg)
622 {
623 	struct pmbus_data *data = i2c_get_clientdata(client);
624 	int status;
625 
626 	switch (reg) {
627 	case PMBUS_STATUS_WORD:
628 		status = data->read_status(client, page);
629 		break;
630 	default:
631 		status = _pmbus_read_byte_data(client, page, reg);
632 		break;
633 	}
634 	if (status < 0)
635 		pmbus_clear_faults(client);
636 	return status;
637 }
638 
639 static void pmbus_update_sensor_data(struct i2c_client *client, struct pmbus_sensor *sensor)
640 {
641 	if (sensor->data < 0 || sensor->update)
642 		sensor->data = _pmbus_read_word_data(client, sensor->page,
643 						     sensor->phase, sensor->reg);
644 }
645 
646 /*
647  * Convert ieee754 sensor values to milli- or micro-units
648  * depending on sensor type.
649  *
650  * ieee754 data format:
651  *	bit 15:		sign
652  *	bit 10..14:	exponent
653  *	bit 0..9:	mantissa
654  * exponent=0:
655  *	v=(−1)^signbit * 2^(−14) * 0.significantbits
656  * exponent=1..30:
657  *	v=(−1)^signbit * 2^(exponent - 15) * 1.significantbits
658  * exponent=31:
659  *	v=NaN
660  *
661  * Add the number mantissa bits into the calculations for simplicity.
662  * To do that, add '10' to the exponent. By doing that, we can just add
663  * 0x400 to normal values and get the expected result.
664  */
665 static long pmbus_reg2data_ieee754(struct pmbus_data *data,
666 				   struct pmbus_sensor *sensor)
667 {
668 	int exponent;
669 	bool sign;
670 	long val;
671 
672 	/* only support half precision for now */
673 	sign = sensor->data & 0x8000;
674 	exponent = (sensor->data >> 10) & 0x1f;
675 	val = sensor->data & 0x3ff;
676 
677 	if (exponent == 0) {			/* subnormal */
678 		exponent = -(14 + 10);
679 	} else if (exponent ==  0x1f) {		/* NaN, convert to min/max */
680 		exponent = 0;
681 		val = 65504;
682 	} else {
683 		exponent -= (15 + 10);		/* normal */
684 		val |= 0x400;
685 	}
686 
687 	/* scale result to milli-units for all sensors except fans */
688 	if (sensor->class != PSC_FAN)
689 		val = val * 1000L;
690 
691 	/* scale result to micro-units for power sensors */
692 	if (sensor->class == PSC_POWER)
693 		val = val * 1000L;
694 
695 	if (exponent >= 0)
696 		val <<= exponent;
697 	else
698 		val >>= -exponent;
699 
700 	if (sign)
701 		val = -val;
702 
703 	return val;
704 }
705 
706 /*
707  * Convert linear sensor values to milli- or micro-units
708  * depending on sensor type.
709  */
710 static s64 pmbus_reg2data_linear(struct pmbus_data *data,
711 				 struct pmbus_sensor *sensor)
712 {
713 	s16 exponent;
714 	s32 mantissa;
715 	s64 val;
716 
717 	if (sensor->class == PSC_VOLTAGE_OUT) {	/* LINEAR16 */
718 		exponent = data->exponent[sensor->page];
719 		mantissa = (u16) sensor->data;
720 	} else {				/* LINEAR11 */
721 		exponent = ((s16)sensor->data) >> 11;
722 		mantissa = ((s16)((sensor->data & 0x7ff) << 5)) >> 5;
723 	}
724 
725 	val = mantissa;
726 
727 	/* scale result to milli-units for all sensors except fans */
728 	if (sensor->class != PSC_FAN)
729 		val = val * 1000LL;
730 
731 	/* scale result to micro-units for power sensors */
732 	if (sensor->class == PSC_POWER)
733 		val = val * 1000LL;
734 
735 	if (exponent >= 0)
736 		val <<= exponent;
737 	else
738 		val >>= -exponent;
739 
740 	return val;
741 }
742 
743 /*
744  * Convert direct sensor values to milli- or micro-units
745  * depending on sensor type.
746  */
747 static s64 pmbus_reg2data_direct(struct pmbus_data *data,
748 				 struct pmbus_sensor *sensor)
749 {
750 	s64 b, val = (s16)sensor->data;
751 	s32 m, R;
752 
753 	m = data->info->m[sensor->class];
754 	b = data->info->b[sensor->class];
755 	R = data->info->R[sensor->class];
756 
757 	if (m == 0)
758 		return 0;
759 
760 	/* X = 1/m * (Y * 10^-R - b) */
761 	R = -R;
762 	/* scale result to milli-units for everything but fans */
763 	if (!(sensor->class == PSC_FAN || sensor->class == PSC_PWM)) {
764 		R += 3;
765 		b *= 1000;
766 	}
767 
768 	/* scale result to micro-units for power sensors */
769 	if (sensor->class == PSC_POWER) {
770 		R += 3;
771 		b *= 1000;
772 	}
773 
774 	while (R > 0) {
775 		val *= 10;
776 		R--;
777 	}
778 	while (R < 0) {
779 		val = div_s64(val + 5LL, 10L);  /* round closest */
780 		R++;
781 	}
782 
783 	val = div_s64(val - b, m);
784 	return val;
785 }
786 
787 /*
788  * Convert VID sensor values to milli- or micro-units
789  * depending on sensor type.
790  */
791 static s64 pmbus_reg2data_vid(struct pmbus_data *data,
792 			      struct pmbus_sensor *sensor)
793 {
794 	long val = sensor->data;
795 	long rv = 0;
796 
797 	switch (data->info->vrm_version[sensor->page]) {
798 	case vr11:
799 		if (val >= 0x02 && val <= 0xb2)
800 			rv = DIV_ROUND_CLOSEST(160000 - (val - 2) * 625, 100);
801 		break;
802 	case vr12:
803 		if (val >= 0x01)
804 			rv = 250 + (val - 1) * 5;
805 		break;
806 	case vr13:
807 		if (val >= 0x01)
808 			rv = 500 + (val - 1) * 10;
809 		break;
810 	case imvp9:
811 		if (val >= 0x01)
812 			rv = 200 + (val - 1) * 10;
813 		break;
814 	case amd625mv:
815 		if (val >= 0x0 && val <= 0xd8)
816 			rv = DIV_ROUND_CLOSEST(155000 - val * 625, 100);
817 		break;
818 	}
819 	return rv;
820 }
821 
822 static s64 pmbus_reg2data(struct pmbus_data *data, struct pmbus_sensor *sensor)
823 {
824 	s64 val;
825 
826 	if (!sensor->convert)
827 		return sensor->data;
828 
829 	switch (data->info->format[sensor->class]) {
830 	case direct:
831 		val = pmbus_reg2data_direct(data, sensor);
832 		break;
833 	case vid:
834 		val = pmbus_reg2data_vid(data, sensor);
835 		break;
836 	case ieee754:
837 		val = pmbus_reg2data_ieee754(data, sensor);
838 		break;
839 	case linear:
840 	default:
841 		val = pmbus_reg2data_linear(data, sensor);
842 		break;
843 	}
844 	return val;
845 }
846 
847 #define MAX_IEEE_MANTISSA	(0x7ff * 1000)
848 #define MIN_IEEE_MANTISSA	(0x400 * 1000)
849 
850 static u16 pmbus_data2reg_ieee754(struct pmbus_data *data,
851 				  struct pmbus_sensor *sensor, long val)
852 {
853 	u16 exponent = (15 + 10);
854 	long mantissa;
855 	u16 sign = 0;
856 
857 	/* simple case */
858 	if (val == 0)
859 		return 0;
860 
861 	if (val < 0) {
862 		sign = 0x8000;
863 		val = -val;
864 	}
865 
866 	/* Power is in uW. Convert to mW before converting. */
867 	if (sensor->class == PSC_POWER)
868 		val = DIV_ROUND_CLOSEST(val, 1000L);
869 
870 	/*
871 	 * For simplicity, convert fan data to milli-units
872 	 * before calculating the exponent.
873 	 */
874 	if (sensor->class == PSC_FAN)
875 		val = val * 1000;
876 
877 	/* Reduce large mantissa until it fits into 10 bit */
878 	while (val > MAX_IEEE_MANTISSA && exponent < 30) {
879 		exponent++;
880 		val >>= 1;
881 	}
882 	/*
883 	 * Increase small mantissa to generate valid 'normal'
884 	 * number
885 	 */
886 	while (val < MIN_IEEE_MANTISSA && exponent > 1) {
887 		exponent--;
888 		val <<= 1;
889 	}
890 
891 	/* Convert mantissa from milli-units to units */
892 	mantissa = DIV_ROUND_CLOSEST(val, 1000);
893 
894 	/*
895 	 * Ensure that the resulting number is within range.
896 	 * Valid range is 0x400..0x7ff, where bit 10 reflects
897 	 * the implied high bit in normalized ieee754 numbers.
898 	 * Set the range to 0x400..0x7ff to reflect this.
899 	 * The upper bit is then removed by the mask against
900 	 * 0x3ff in the final assignment.
901 	 */
902 	if (mantissa > 0x7ff)
903 		mantissa = 0x7ff;
904 	else if (mantissa < 0x400)
905 		mantissa = 0x400;
906 
907 	/* Convert to sign, 5 bit exponent, 10 bit mantissa */
908 	return sign | (mantissa & 0x3ff) | ((exponent << 10) & 0x7c00);
909 }
910 
911 #define MAX_LIN_MANTISSA	(1023 * 1000)
912 #define MIN_LIN_MANTISSA	(511 * 1000)
913 
914 static u16 pmbus_data2reg_linear(struct pmbus_data *data,
915 				 struct pmbus_sensor *sensor, s64 val)
916 {
917 	s16 exponent = 0, mantissa;
918 	bool negative = false;
919 
920 	/* simple case */
921 	if (val == 0)
922 		return 0;
923 
924 	if (sensor->class == PSC_VOLTAGE_OUT) {
925 		/* LINEAR16 does not support negative voltages */
926 		if (val < 0)
927 			return 0;
928 
929 		/*
930 		 * For a static exponents, we don't have a choice
931 		 * but to adjust the value to it.
932 		 */
933 		if (data->exponent[sensor->page] < 0)
934 			val <<= -data->exponent[sensor->page];
935 		else
936 			val >>= data->exponent[sensor->page];
937 		val = DIV_ROUND_CLOSEST_ULL(val, 1000);
938 		return clamp_val(val, 0, 0xffff);
939 	}
940 
941 	if (val < 0) {
942 		negative = true;
943 		val = -val;
944 	}
945 
946 	/* Power is in uW. Convert to mW before converting. */
947 	if (sensor->class == PSC_POWER)
948 		val = DIV_ROUND_CLOSEST_ULL(val, 1000);
949 
950 	/*
951 	 * For simplicity, convert fan data to milli-units
952 	 * before calculating the exponent.
953 	 */
954 	if (sensor->class == PSC_FAN)
955 		val = val * 1000LL;
956 
957 	/* Reduce large mantissa until it fits into 10 bit */
958 	while (val >= MAX_LIN_MANTISSA && exponent < 15) {
959 		exponent++;
960 		val >>= 1;
961 	}
962 	/* Increase small mantissa to improve precision */
963 	while (val < MIN_LIN_MANTISSA && exponent > -15) {
964 		exponent--;
965 		val <<= 1;
966 	}
967 
968 	/* Convert mantissa from milli-units to units */
969 	mantissa = clamp_val(DIV_ROUND_CLOSEST_ULL(val, 1000), 0, 0x3ff);
970 
971 	/* restore sign */
972 	if (negative)
973 		mantissa = -mantissa;
974 
975 	/* Convert to 5 bit exponent, 11 bit mantissa */
976 	return (mantissa & 0x7ff) | ((exponent << 11) & 0xf800);
977 }
978 
979 static u16 pmbus_data2reg_direct(struct pmbus_data *data,
980 				 struct pmbus_sensor *sensor, s64 val)
981 {
982 	s64 b;
983 	s32 m, R;
984 
985 	m = data->info->m[sensor->class];
986 	b = data->info->b[sensor->class];
987 	R = data->info->R[sensor->class];
988 
989 	/* Power is in uW. Adjust R and b. */
990 	if (sensor->class == PSC_POWER) {
991 		R -= 3;
992 		b *= 1000;
993 	}
994 
995 	/* Calculate Y = (m * X + b) * 10^R */
996 	if (!(sensor->class == PSC_FAN || sensor->class == PSC_PWM)) {
997 		R -= 3;		/* Adjust R and b for data in milli-units */
998 		b *= 1000;
999 	}
1000 	val = val * m + b;
1001 
1002 	while (R > 0) {
1003 		val *= 10;
1004 		R--;
1005 	}
1006 	while (R < 0) {
1007 		val = div_s64(val + 5LL, 10L);  /* round closest */
1008 		R++;
1009 	}
1010 
1011 	return (u16)clamp_val(val, S16_MIN, S16_MAX);
1012 }
1013 
1014 static u16 pmbus_data2reg_vid(struct pmbus_data *data,
1015 			      struct pmbus_sensor *sensor, s64 val)
1016 {
1017 	val = clamp_val(val, 500, 1600);
1018 
1019 	return 2 + DIV_ROUND_CLOSEST_ULL((1600LL - val) * 100LL, 625);
1020 }
1021 
1022 static u16 pmbus_data2reg(struct pmbus_data *data,
1023 			  struct pmbus_sensor *sensor, s64 val)
1024 {
1025 	u16 regval;
1026 
1027 	if (!sensor->convert)
1028 		return val;
1029 
1030 	switch (data->info->format[sensor->class]) {
1031 	case direct:
1032 		regval = pmbus_data2reg_direct(data, sensor, val);
1033 		break;
1034 	case vid:
1035 		regval = pmbus_data2reg_vid(data, sensor, val);
1036 		break;
1037 	case ieee754:
1038 		regval = pmbus_data2reg_ieee754(data, sensor, val);
1039 		break;
1040 	case linear:
1041 	default:
1042 		regval = pmbus_data2reg_linear(data, sensor, val);
1043 		break;
1044 	}
1045 	return regval;
1046 }
1047 
1048 /*
1049  * Return boolean calculated from converted data.
1050  * <index> defines a status register index and mask.
1051  * The mask is in the lower 8 bits, the register index is in bits 8..23.
1052  *
1053  * The associated pmbus_boolean structure contains optional pointers to two
1054  * sensor attributes. If specified, those attributes are compared against each
1055  * other to determine if a limit has been exceeded.
1056  *
1057  * If the sensor attribute pointers are NULL, the function returns true if
1058  * (status[reg] & mask) is true.
1059  *
1060  * If sensor attribute pointers are provided, a comparison against a specified
1061  * limit has to be performed to determine the boolean result.
1062  * In this case, the function returns true if v1 >= v2 (where v1 and v2 are
1063  * sensor values referenced by sensor attribute pointers s1 and s2).
1064  *
1065  * To determine if an object exceeds upper limits, specify <s1,s2> = <v,limit>.
1066  * To determine if an object exceeds lower limits, specify <s1,s2> = <limit,v>.
1067  *
1068  * If a negative value is stored in any of the referenced registers, this value
1069  * reflects an error code which will be returned.
1070  */
1071 static int pmbus_get_boolean(struct i2c_client *client, struct pmbus_boolean *b,
1072 			     int index)
1073 {
1074 	struct pmbus_data *data = i2c_get_clientdata(client);
1075 	struct pmbus_sensor *s1 = b->s1;
1076 	struct pmbus_sensor *s2 = b->s2;
1077 	u16 mask = pb_index_to_mask(index);
1078 	u8 page = pb_index_to_page(index);
1079 	u16 reg = pb_index_to_reg(index);
1080 	int ret, status;
1081 	u16 regval;
1082 
1083 	mutex_lock(&data->update_lock);
1084 	status = pmbus_get_status(client, page, reg);
1085 	if (status < 0) {
1086 		ret = status;
1087 		goto unlock;
1088 	}
1089 
1090 	if (s1)
1091 		pmbus_update_sensor_data(client, s1);
1092 	if (s2)
1093 		pmbus_update_sensor_data(client, s2);
1094 
1095 	regval = status & mask;
1096 	if (regval) {
1097 		ret = _pmbus_write_byte_data(client, page, reg, regval);
1098 		if (ret)
1099 			goto unlock;
1100 	}
1101 	if (s1 && s2) {
1102 		s64 v1, v2;
1103 
1104 		if (s1->data < 0) {
1105 			ret = s1->data;
1106 			goto unlock;
1107 		}
1108 		if (s2->data < 0) {
1109 			ret = s2->data;
1110 			goto unlock;
1111 		}
1112 
1113 		v1 = pmbus_reg2data(data, s1);
1114 		v2 = pmbus_reg2data(data, s2);
1115 		ret = !!(regval && v1 >= v2);
1116 	} else {
1117 		ret = !!regval;
1118 	}
1119 unlock:
1120 	mutex_unlock(&data->update_lock);
1121 	return ret;
1122 }
1123 
1124 static ssize_t pmbus_show_boolean(struct device *dev,
1125 				  struct device_attribute *da, char *buf)
1126 {
1127 	struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
1128 	struct pmbus_boolean *boolean = to_pmbus_boolean(attr);
1129 	struct i2c_client *client = to_i2c_client(dev->parent);
1130 	int val;
1131 
1132 	val = pmbus_get_boolean(client, boolean, attr->index);
1133 	if (val < 0)
1134 		return val;
1135 	return sysfs_emit(buf, "%d\n", val);
1136 }
1137 
1138 static ssize_t pmbus_show_sensor(struct device *dev,
1139 				 struct device_attribute *devattr, char *buf)
1140 {
1141 	struct i2c_client *client = to_i2c_client(dev->parent);
1142 	struct pmbus_sensor *sensor = to_pmbus_sensor(devattr);
1143 	struct pmbus_data *data = i2c_get_clientdata(client);
1144 	ssize_t ret;
1145 
1146 	mutex_lock(&data->update_lock);
1147 	pmbus_update_sensor_data(client, sensor);
1148 	if (sensor->data < 0)
1149 		ret = sensor->data;
1150 	else
1151 		ret = sysfs_emit(buf, "%lld\n", pmbus_reg2data(data, sensor));
1152 	mutex_unlock(&data->update_lock);
1153 	return ret;
1154 }
1155 
1156 static ssize_t pmbus_set_sensor(struct device *dev,
1157 				struct device_attribute *devattr,
1158 				const char *buf, size_t count)
1159 {
1160 	struct i2c_client *client = to_i2c_client(dev->parent);
1161 	struct pmbus_data *data = i2c_get_clientdata(client);
1162 	struct pmbus_sensor *sensor = to_pmbus_sensor(devattr);
1163 	ssize_t rv = count;
1164 	s64 val;
1165 	int ret;
1166 	u16 regval;
1167 
1168 	if (kstrtos64(buf, 10, &val) < 0)
1169 		return -EINVAL;
1170 
1171 	mutex_lock(&data->update_lock);
1172 	regval = pmbus_data2reg(data, sensor, val);
1173 	ret = _pmbus_write_word_data(client, sensor->page, sensor->reg, regval);
1174 	if (ret < 0)
1175 		rv = ret;
1176 	else
1177 		sensor->data = -ENODATA;
1178 	mutex_unlock(&data->update_lock);
1179 	return rv;
1180 }
1181 
1182 static ssize_t pmbus_show_label(struct device *dev,
1183 				struct device_attribute *da, char *buf)
1184 {
1185 	struct pmbus_label *label = to_pmbus_label(da);
1186 
1187 	return sysfs_emit(buf, "%s\n", label->label);
1188 }
1189 
1190 static int pmbus_add_attribute(struct pmbus_data *data, struct attribute *attr)
1191 {
1192 	if (data->num_attributes >= data->max_attributes - 1) {
1193 		int new_max_attrs = data->max_attributes + PMBUS_ATTR_ALLOC_SIZE;
1194 		void *new_attrs = devm_krealloc(data->dev, data->group.attrs,
1195 						new_max_attrs * sizeof(void *),
1196 						GFP_KERNEL);
1197 		if (!new_attrs)
1198 			return -ENOMEM;
1199 		data->group.attrs = new_attrs;
1200 		data->max_attributes = new_max_attrs;
1201 	}
1202 
1203 	data->group.attrs[data->num_attributes++] = attr;
1204 	data->group.attrs[data->num_attributes] = NULL;
1205 	return 0;
1206 }
1207 
1208 static void pmbus_dev_attr_init(struct device_attribute *dev_attr,
1209 				const char *name,
1210 				umode_t mode,
1211 				ssize_t (*show)(struct device *dev,
1212 						struct device_attribute *attr,
1213 						char *buf),
1214 				ssize_t (*store)(struct device *dev,
1215 						 struct device_attribute *attr,
1216 						 const char *buf, size_t count))
1217 {
1218 	sysfs_attr_init(&dev_attr->attr);
1219 	dev_attr->attr.name = name;
1220 	dev_attr->attr.mode = mode;
1221 	dev_attr->show = show;
1222 	dev_attr->store = store;
1223 }
1224 
1225 static void pmbus_attr_init(struct sensor_device_attribute *a,
1226 			    const char *name,
1227 			    umode_t mode,
1228 			    ssize_t (*show)(struct device *dev,
1229 					    struct device_attribute *attr,
1230 					    char *buf),
1231 			    ssize_t (*store)(struct device *dev,
1232 					     struct device_attribute *attr,
1233 					     const char *buf, size_t count),
1234 			    int idx)
1235 {
1236 	pmbus_dev_attr_init(&a->dev_attr, name, mode, show, store);
1237 	a->index = idx;
1238 }
1239 
1240 static int pmbus_add_boolean(struct pmbus_data *data,
1241 			     const char *name, const char *type, int seq,
1242 			     struct pmbus_sensor *s1,
1243 			     struct pmbus_sensor *s2,
1244 			     u8 page, u16 reg, u16 mask)
1245 {
1246 	struct pmbus_boolean *boolean;
1247 	struct sensor_device_attribute *a;
1248 
1249 	if (WARN((s1 && !s2) || (!s1 && s2), "Bad s1/s2 parameters\n"))
1250 		return -EINVAL;
1251 
1252 	boolean = devm_kzalloc(data->dev, sizeof(*boolean), GFP_KERNEL);
1253 	if (!boolean)
1254 		return -ENOMEM;
1255 
1256 	a = &boolean->attribute;
1257 
1258 	snprintf(boolean->name, sizeof(boolean->name), "%s%d_%s",
1259 		 name, seq, type);
1260 	boolean->s1 = s1;
1261 	boolean->s2 = s2;
1262 	pmbus_attr_init(a, boolean->name, 0444, pmbus_show_boolean, NULL,
1263 			pb_reg_to_index(page, reg, mask));
1264 
1265 	return pmbus_add_attribute(data, &a->dev_attr.attr);
1266 }
1267 
1268 /* of thermal for pmbus temperature sensors */
1269 struct pmbus_thermal_data {
1270 	struct pmbus_data *pmbus_data;
1271 	struct pmbus_sensor *sensor;
1272 };
1273 
1274 static int pmbus_thermal_get_temp(struct thermal_zone_device *tz, int *temp)
1275 {
1276 	struct pmbus_thermal_data *tdata = thermal_zone_device_priv(tz);
1277 	struct pmbus_sensor *sensor = tdata->sensor;
1278 	struct pmbus_data *pmbus_data = tdata->pmbus_data;
1279 	struct i2c_client *client = to_i2c_client(pmbus_data->dev);
1280 	struct device *dev = pmbus_data->hwmon_dev;
1281 	int ret = 0;
1282 
1283 	if (!dev) {
1284 		/* May not even get to hwmon yet */
1285 		*temp = 0;
1286 		return 0;
1287 	}
1288 
1289 	mutex_lock(&pmbus_data->update_lock);
1290 	pmbus_update_sensor_data(client, sensor);
1291 	if (sensor->data < 0)
1292 		ret = sensor->data;
1293 	else
1294 		*temp = (int)pmbus_reg2data(pmbus_data, sensor);
1295 	mutex_unlock(&pmbus_data->update_lock);
1296 
1297 	return ret;
1298 }
1299 
1300 static const struct thermal_zone_device_ops pmbus_thermal_ops = {
1301 	.get_temp = pmbus_thermal_get_temp,
1302 };
1303 
1304 static int pmbus_thermal_add_sensor(struct pmbus_data *pmbus_data,
1305 				    struct pmbus_sensor *sensor, int index)
1306 {
1307 	struct device *dev = pmbus_data->dev;
1308 	struct pmbus_thermal_data *tdata;
1309 	struct thermal_zone_device *tzd;
1310 
1311 	tdata = devm_kzalloc(dev, sizeof(*tdata), GFP_KERNEL);
1312 	if (!tdata)
1313 		return -ENOMEM;
1314 
1315 	tdata->sensor = sensor;
1316 	tdata->pmbus_data = pmbus_data;
1317 
1318 	tzd = devm_thermal_of_zone_register(dev, index, tdata,
1319 					    &pmbus_thermal_ops);
1320 	/*
1321 	 * If CONFIG_THERMAL_OF is disabled, this returns -ENODEV,
1322 	 * so ignore that error but forward any other error.
1323 	 */
1324 	if (IS_ERR(tzd) && (PTR_ERR(tzd) != -ENODEV))
1325 		return PTR_ERR(tzd);
1326 
1327 	return 0;
1328 }
1329 
1330 static struct pmbus_sensor *pmbus_add_sensor(struct pmbus_data *data,
1331 					     const char *name, const char *type,
1332 					     int seq, int page, int phase,
1333 					     int reg,
1334 					     enum pmbus_sensor_classes class,
1335 					     bool update, bool readonly,
1336 					     bool convert)
1337 {
1338 	struct pmbus_sensor *sensor;
1339 	struct device_attribute *a;
1340 
1341 	sensor = devm_kzalloc(data->dev, sizeof(*sensor), GFP_KERNEL);
1342 	if (!sensor)
1343 		return NULL;
1344 	a = &sensor->attribute;
1345 
1346 	if (type)
1347 		snprintf(sensor->name, sizeof(sensor->name), "%s%d_%s",
1348 			 name, seq, type);
1349 	else
1350 		snprintf(sensor->name, sizeof(sensor->name), "%s%d",
1351 			 name, seq);
1352 
1353 	if (data->flags & PMBUS_WRITE_PROTECTED)
1354 		readonly = true;
1355 
1356 	sensor->page = page;
1357 	sensor->phase = phase;
1358 	sensor->reg = reg;
1359 	sensor->class = class;
1360 	sensor->update = update;
1361 	sensor->convert = convert;
1362 	sensor->data = -ENODATA;
1363 	pmbus_dev_attr_init(a, sensor->name,
1364 			    readonly ? 0444 : 0644,
1365 			    pmbus_show_sensor, pmbus_set_sensor);
1366 
1367 	if (pmbus_add_attribute(data, &a->attr))
1368 		return NULL;
1369 
1370 	sensor->next = data->sensors;
1371 	data->sensors = sensor;
1372 
1373 	/* temperature sensors with _input values are registered with thermal */
1374 	if (class == PSC_TEMPERATURE && strcmp(type, "input") == 0)
1375 		pmbus_thermal_add_sensor(data, sensor, seq);
1376 
1377 	return sensor;
1378 }
1379 
1380 static int pmbus_add_label(struct pmbus_data *data,
1381 			   const char *name, int seq,
1382 			   const char *lstring, int index, int phase)
1383 {
1384 	struct pmbus_label *label;
1385 	struct device_attribute *a;
1386 
1387 	label = devm_kzalloc(data->dev, sizeof(*label), GFP_KERNEL);
1388 	if (!label)
1389 		return -ENOMEM;
1390 
1391 	a = &label->attribute;
1392 
1393 	snprintf(label->name, sizeof(label->name), "%s%d_label", name, seq);
1394 	if (!index) {
1395 		if (phase == 0xff)
1396 			strncpy(label->label, lstring,
1397 				sizeof(label->label) - 1);
1398 		else
1399 			snprintf(label->label, sizeof(label->label), "%s.%d",
1400 				 lstring, phase);
1401 	} else {
1402 		if (phase == 0xff)
1403 			snprintf(label->label, sizeof(label->label), "%s%d",
1404 				 lstring, index);
1405 		else
1406 			snprintf(label->label, sizeof(label->label), "%s%d.%d",
1407 				 lstring, index, phase);
1408 	}
1409 
1410 	pmbus_dev_attr_init(a, label->name, 0444, pmbus_show_label, NULL);
1411 	return pmbus_add_attribute(data, &a->attr);
1412 }
1413 
1414 /*
1415  * Search for attributes. Allocate sensors, booleans, and labels as needed.
1416  */
1417 
1418 /*
1419  * The pmbus_limit_attr structure describes a single limit attribute
1420  * and its associated alarm attribute.
1421  */
1422 struct pmbus_limit_attr {
1423 	u16 reg;		/* Limit register */
1424 	u16 sbit;		/* Alarm attribute status bit */
1425 	bool update;		/* True if register needs updates */
1426 	bool low;		/* True if low limit; for limits with compare
1427 				   functions only */
1428 	const char *attr;	/* Attribute name */
1429 	const char *alarm;	/* Alarm attribute name */
1430 };
1431 
1432 /*
1433  * The pmbus_sensor_attr structure describes one sensor attribute. This
1434  * description includes a reference to the associated limit attributes.
1435  */
1436 struct pmbus_sensor_attr {
1437 	u16 reg;			/* sensor register */
1438 	u16 gbit;			/* generic status bit */
1439 	u8 nlimit;			/* # of limit registers */
1440 	enum pmbus_sensor_classes class;/* sensor class */
1441 	const char *label;		/* sensor label */
1442 	bool paged;			/* true if paged sensor */
1443 	bool update;			/* true if update needed */
1444 	bool compare;			/* true if compare function needed */
1445 	u32 func;			/* sensor mask */
1446 	u32 sfunc;			/* sensor status mask */
1447 	int sreg;			/* status register */
1448 	const struct pmbus_limit_attr *limit;/* limit registers */
1449 };
1450 
1451 /*
1452  * Add a set of limit attributes and, if supported, the associated
1453  * alarm attributes.
1454  * returns 0 if no alarm register found, 1 if an alarm register was found,
1455  * < 0 on errors.
1456  */
1457 static int pmbus_add_limit_attrs(struct i2c_client *client,
1458 				 struct pmbus_data *data,
1459 				 const struct pmbus_driver_info *info,
1460 				 const char *name, int index, int page,
1461 				 struct pmbus_sensor *base,
1462 				 const struct pmbus_sensor_attr *attr)
1463 {
1464 	const struct pmbus_limit_attr *l = attr->limit;
1465 	int nlimit = attr->nlimit;
1466 	int have_alarm = 0;
1467 	int i, ret;
1468 	struct pmbus_sensor *curr;
1469 
1470 	for (i = 0; i < nlimit; i++) {
1471 		if (pmbus_check_word_register(client, page, l->reg)) {
1472 			curr = pmbus_add_sensor(data, name, l->attr, index,
1473 						page, 0xff, l->reg, attr->class,
1474 						attr->update || l->update,
1475 						false, true);
1476 			if (!curr)
1477 				return -ENOMEM;
1478 			if (l->sbit && (info->func[page] & attr->sfunc)) {
1479 				ret = pmbus_add_boolean(data, name,
1480 					l->alarm, index,
1481 					attr->compare ?  l->low ? curr : base
1482 						      : NULL,
1483 					attr->compare ? l->low ? base : curr
1484 						      : NULL,
1485 					page, attr->sreg, l->sbit);
1486 				if (ret)
1487 					return ret;
1488 				have_alarm = 1;
1489 			}
1490 		}
1491 		l++;
1492 	}
1493 	return have_alarm;
1494 }
1495 
1496 static int pmbus_add_sensor_attrs_one(struct i2c_client *client,
1497 				      struct pmbus_data *data,
1498 				      const struct pmbus_driver_info *info,
1499 				      const char *name,
1500 				      int index, int page, int phase,
1501 				      const struct pmbus_sensor_attr *attr,
1502 				      bool paged)
1503 {
1504 	struct pmbus_sensor *base;
1505 	bool upper = !!(attr->gbit & 0xff00);	/* need to check STATUS_WORD */
1506 	int ret;
1507 
1508 	if (attr->label) {
1509 		ret = pmbus_add_label(data, name, index, attr->label,
1510 				      paged ? page + 1 : 0, phase);
1511 		if (ret)
1512 			return ret;
1513 	}
1514 	base = pmbus_add_sensor(data, name, "input", index, page, phase,
1515 				attr->reg, attr->class, true, true, true);
1516 	if (!base)
1517 		return -ENOMEM;
1518 	/* No limit and alarm attributes for phase specific sensors */
1519 	if (attr->sfunc && phase == 0xff) {
1520 		ret = pmbus_add_limit_attrs(client, data, info, name,
1521 					    index, page, base, attr);
1522 		if (ret < 0)
1523 			return ret;
1524 		/*
1525 		 * Add generic alarm attribute only if there are no individual
1526 		 * alarm attributes, if there is a global alarm bit, and if
1527 		 * the generic status register (word or byte, depending on
1528 		 * which global bit is set) for this page is accessible.
1529 		 */
1530 		if (!ret && attr->gbit &&
1531 		    (!upper || data->has_status_word) &&
1532 		    pmbus_check_status_register(client, page)) {
1533 			ret = pmbus_add_boolean(data, name, "alarm", index,
1534 						NULL, NULL,
1535 						page, PMBUS_STATUS_WORD,
1536 						attr->gbit);
1537 			if (ret)
1538 				return ret;
1539 		}
1540 	}
1541 	return 0;
1542 }
1543 
1544 static bool pmbus_sensor_is_paged(const struct pmbus_driver_info *info,
1545 				  const struct pmbus_sensor_attr *attr)
1546 {
1547 	int p;
1548 
1549 	if (attr->paged)
1550 		return true;
1551 
1552 	/*
1553 	 * Some attributes may be present on more than one page despite
1554 	 * not being marked with the paged attribute. If that is the case,
1555 	 * then treat the sensor as being paged and add the page suffix to the
1556 	 * attribute name.
1557 	 * We don't just add the paged attribute to all such attributes, in
1558 	 * order to maintain the un-suffixed labels in the case where the
1559 	 * attribute is only on page 0.
1560 	 */
1561 	for (p = 1; p < info->pages; p++) {
1562 		if (info->func[p] & attr->func)
1563 			return true;
1564 	}
1565 	return false;
1566 }
1567 
1568 static int pmbus_add_sensor_attrs(struct i2c_client *client,
1569 				  struct pmbus_data *data,
1570 				  const char *name,
1571 				  const struct pmbus_sensor_attr *attrs,
1572 				  int nattrs)
1573 {
1574 	const struct pmbus_driver_info *info = data->info;
1575 	int index, i;
1576 	int ret;
1577 
1578 	index = 1;
1579 	for (i = 0; i < nattrs; i++) {
1580 		int page, pages;
1581 		bool paged = pmbus_sensor_is_paged(info, attrs);
1582 
1583 		pages = paged ? info->pages : 1;
1584 		for (page = 0; page < pages; page++) {
1585 			if (info->func[page] & attrs->func) {
1586 				ret = pmbus_add_sensor_attrs_one(client, data, info,
1587 								 name, index, page,
1588 								 0xff, attrs, paged);
1589 				if (ret)
1590 					return ret;
1591 				index++;
1592 			}
1593 			if (info->phases[page]) {
1594 				int phase;
1595 
1596 				for (phase = 0; phase < info->phases[page];
1597 				     phase++) {
1598 					if (!(info->pfunc[phase] & attrs->func))
1599 						continue;
1600 					ret = pmbus_add_sensor_attrs_one(client,
1601 						data, info, name, index, page,
1602 						phase, attrs, paged);
1603 					if (ret)
1604 						return ret;
1605 					index++;
1606 				}
1607 			}
1608 		}
1609 		attrs++;
1610 	}
1611 	return 0;
1612 }
1613 
1614 static const struct pmbus_limit_attr vin_limit_attrs[] = {
1615 	{
1616 		.reg = PMBUS_VIN_UV_WARN_LIMIT,
1617 		.attr = "min",
1618 		.alarm = "min_alarm",
1619 		.sbit = PB_VOLTAGE_UV_WARNING,
1620 	}, {
1621 		.reg = PMBUS_VIN_UV_FAULT_LIMIT,
1622 		.attr = "lcrit",
1623 		.alarm = "lcrit_alarm",
1624 		.sbit = PB_VOLTAGE_UV_FAULT | PB_VOLTAGE_VIN_OFF,
1625 	}, {
1626 		.reg = PMBUS_VIN_OV_WARN_LIMIT,
1627 		.attr = "max",
1628 		.alarm = "max_alarm",
1629 		.sbit = PB_VOLTAGE_OV_WARNING,
1630 	}, {
1631 		.reg = PMBUS_VIN_OV_FAULT_LIMIT,
1632 		.attr = "crit",
1633 		.alarm = "crit_alarm",
1634 		.sbit = PB_VOLTAGE_OV_FAULT,
1635 	}, {
1636 		.reg = PMBUS_VIRT_READ_VIN_AVG,
1637 		.update = true,
1638 		.attr = "average",
1639 	}, {
1640 		.reg = PMBUS_VIRT_READ_VIN_MIN,
1641 		.update = true,
1642 		.attr = "lowest",
1643 	}, {
1644 		.reg = PMBUS_VIRT_READ_VIN_MAX,
1645 		.update = true,
1646 		.attr = "highest",
1647 	}, {
1648 		.reg = PMBUS_VIRT_RESET_VIN_HISTORY,
1649 		.attr = "reset_history",
1650 	}, {
1651 		.reg = PMBUS_MFR_VIN_MIN,
1652 		.attr = "rated_min",
1653 	}, {
1654 		.reg = PMBUS_MFR_VIN_MAX,
1655 		.attr = "rated_max",
1656 	},
1657 };
1658 
1659 static const struct pmbus_limit_attr vmon_limit_attrs[] = {
1660 	{
1661 		.reg = PMBUS_VIRT_VMON_UV_WARN_LIMIT,
1662 		.attr = "min",
1663 		.alarm = "min_alarm",
1664 		.sbit = PB_VOLTAGE_UV_WARNING,
1665 	}, {
1666 		.reg = PMBUS_VIRT_VMON_UV_FAULT_LIMIT,
1667 		.attr = "lcrit",
1668 		.alarm = "lcrit_alarm",
1669 		.sbit = PB_VOLTAGE_UV_FAULT,
1670 	}, {
1671 		.reg = PMBUS_VIRT_VMON_OV_WARN_LIMIT,
1672 		.attr = "max",
1673 		.alarm = "max_alarm",
1674 		.sbit = PB_VOLTAGE_OV_WARNING,
1675 	}, {
1676 		.reg = PMBUS_VIRT_VMON_OV_FAULT_LIMIT,
1677 		.attr = "crit",
1678 		.alarm = "crit_alarm",
1679 		.sbit = PB_VOLTAGE_OV_FAULT,
1680 	}
1681 };
1682 
1683 static const struct pmbus_limit_attr vout_limit_attrs[] = {
1684 	{
1685 		.reg = PMBUS_VOUT_UV_WARN_LIMIT,
1686 		.attr = "min",
1687 		.alarm = "min_alarm",
1688 		.sbit = PB_VOLTAGE_UV_WARNING,
1689 	}, {
1690 		.reg = PMBUS_VOUT_UV_FAULT_LIMIT,
1691 		.attr = "lcrit",
1692 		.alarm = "lcrit_alarm",
1693 		.sbit = PB_VOLTAGE_UV_FAULT,
1694 	}, {
1695 		.reg = PMBUS_VOUT_OV_WARN_LIMIT,
1696 		.attr = "max",
1697 		.alarm = "max_alarm",
1698 		.sbit = PB_VOLTAGE_OV_WARNING,
1699 	}, {
1700 		.reg = PMBUS_VOUT_OV_FAULT_LIMIT,
1701 		.attr = "crit",
1702 		.alarm = "crit_alarm",
1703 		.sbit = PB_VOLTAGE_OV_FAULT,
1704 	}, {
1705 		.reg = PMBUS_VIRT_READ_VOUT_AVG,
1706 		.update = true,
1707 		.attr = "average",
1708 	}, {
1709 		.reg = PMBUS_VIRT_READ_VOUT_MIN,
1710 		.update = true,
1711 		.attr = "lowest",
1712 	}, {
1713 		.reg = PMBUS_VIRT_READ_VOUT_MAX,
1714 		.update = true,
1715 		.attr = "highest",
1716 	}, {
1717 		.reg = PMBUS_VIRT_RESET_VOUT_HISTORY,
1718 		.attr = "reset_history",
1719 	}, {
1720 		.reg = PMBUS_MFR_VOUT_MIN,
1721 		.attr = "rated_min",
1722 	}, {
1723 		.reg = PMBUS_MFR_VOUT_MAX,
1724 		.attr = "rated_max",
1725 	},
1726 };
1727 
1728 static const struct pmbus_sensor_attr voltage_attributes[] = {
1729 	{
1730 		.reg = PMBUS_READ_VIN,
1731 		.class = PSC_VOLTAGE_IN,
1732 		.label = "vin",
1733 		.func = PMBUS_HAVE_VIN,
1734 		.sfunc = PMBUS_HAVE_STATUS_INPUT,
1735 		.sreg = PMBUS_STATUS_INPUT,
1736 		.gbit = PB_STATUS_VIN_UV,
1737 		.limit = vin_limit_attrs,
1738 		.nlimit = ARRAY_SIZE(vin_limit_attrs),
1739 	}, {
1740 		.reg = PMBUS_VIRT_READ_VMON,
1741 		.class = PSC_VOLTAGE_IN,
1742 		.label = "vmon",
1743 		.func = PMBUS_HAVE_VMON,
1744 		.sfunc = PMBUS_HAVE_STATUS_VMON,
1745 		.sreg = PMBUS_VIRT_STATUS_VMON,
1746 		.limit = vmon_limit_attrs,
1747 		.nlimit = ARRAY_SIZE(vmon_limit_attrs),
1748 	}, {
1749 		.reg = PMBUS_READ_VCAP,
1750 		.class = PSC_VOLTAGE_IN,
1751 		.label = "vcap",
1752 		.func = PMBUS_HAVE_VCAP,
1753 	}, {
1754 		.reg = PMBUS_READ_VOUT,
1755 		.class = PSC_VOLTAGE_OUT,
1756 		.label = "vout",
1757 		.paged = true,
1758 		.func = PMBUS_HAVE_VOUT,
1759 		.sfunc = PMBUS_HAVE_STATUS_VOUT,
1760 		.sreg = PMBUS_STATUS_VOUT,
1761 		.gbit = PB_STATUS_VOUT_OV,
1762 		.limit = vout_limit_attrs,
1763 		.nlimit = ARRAY_SIZE(vout_limit_attrs),
1764 	}
1765 };
1766 
1767 /* Current attributes */
1768 
1769 static const struct pmbus_limit_attr iin_limit_attrs[] = {
1770 	{
1771 		.reg = PMBUS_IIN_OC_WARN_LIMIT,
1772 		.attr = "max",
1773 		.alarm = "max_alarm",
1774 		.sbit = PB_IIN_OC_WARNING,
1775 	}, {
1776 		.reg = PMBUS_IIN_OC_FAULT_LIMIT,
1777 		.attr = "crit",
1778 		.alarm = "crit_alarm",
1779 		.sbit = PB_IIN_OC_FAULT,
1780 	}, {
1781 		.reg = PMBUS_VIRT_READ_IIN_AVG,
1782 		.update = true,
1783 		.attr = "average",
1784 	}, {
1785 		.reg = PMBUS_VIRT_READ_IIN_MIN,
1786 		.update = true,
1787 		.attr = "lowest",
1788 	}, {
1789 		.reg = PMBUS_VIRT_READ_IIN_MAX,
1790 		.update = true,
1791 		.attr = "highest",
1792 	}, {
1793 		.reg = PMBUS_VIRT_RESET_IIN_HISTORY,
1794 		.attr = "reset_history",
1795 	}, {
1796 		.reg = PMBUS_MFR_IIN_MAX,
1797 		.attr = "rated_max",
1798 	},
1799 };
1800 
1801 static const struct pmbus_limit_attr iout_limit_attrs[] = {
1802 	{
1803 		.reg = PMBUS_IOUT_OC_WARN_LIMIT,
1804 		.attr = "max",
1805 		.alarm = "max_alarm",
1806 		.sbit = PB_IOUT_OC_WARNING,
1807 	}, {
1808 		.reg = PMBUS_IOUT_UC_FAULT_LIMIT,
1809 		.attr = "lcrit",
1810 		.alarm = "lcrit_alarm",
1811 		.sbit = PB_IOUT_UC_FAULT,
1812 	}, {
1813 		.reg = PMBUS_IOUT_OC_FAULT_LIMIT,
1814 		.attr = "crit",
1815 		.alarm = "crit_alarm",
1816 		.sbit = PB_IOUT_OC_FAULT,
1817 	}, {
1818 		.reg = PMBUS_VIRT_READ_IOUT_AVG,
1819 		.update = true,
1820 		.attr = "average",
1821 	}, {
1822 		.reg = PMBUS_VIRT_READ_IOUT_MIN,
1823 		.update = true,
1824 		.attr = "lowest",
1825 	}, {
1826 		.reg = PMBUS_VIRT_READ_IOUT_MAX,
1827 		.update = true,
1828 		.attr = "highest",
1829 	}, {
1830 		.reg = PMBUS_VIRT_RESET_IOUT_HISTORY,
1831 		.attr = "reset_history",
1832 	}, {
1833 		.reg = PMBUS_MFR_IOUT_MAX,
1834 		.attr = "rated_max",
1835 	},
1836 };
1837 
1838 static const struct pmbus_sensor_attr current_attributes[] = {
1839 	{
1840 		.reg = PMBUS_READ_IIN,
1841 		.class = PSC_CURRENT_IN,
1842 		.label = "iin",
1843 		.func = PMBUS_HAVE_IIN,
1844 		.sfunc = PMBUS_HAVE_STATUS_INPUT,
1845 		.sreg = PMBUS_STATUS_INPUT,
1846 		.gbit = PB_STATUS_INPUT,
1847 		.limit = iin_limit_attrs,
1848 		.nlimit = ARRAY_SIZE(iin_limit_attrs),
1849 	}, {
1850 		.reg = PMBUS_READ_IOUT,
1851 		.class = PSC_CURRENT_OUT,
1852 		.label = "iout",
1853 		.paged = true,
1854 		.func = PMBUS_HAVE_IOUT,
1855 		.sfunc = PMBUS_HAVE_STATUS_IOUT,
1856 		.sreg = PMBUS_STATUS_IOUT,
1857 		.gbit = PB_STATUS_IOUT_OC,
1858 		.limit = iout_limit_attrs,
1859 		.nlimit = ARRAY_SIZE(iout_limit_attrs),
1860 	}
1861 };
1862 
1863 /* Power attributes */
1864 
1865 static const struct pmbus_limit_attr pin_limit_attrs[] = {
1866 	{
1867 		.reg = PMBUS_PIN_OP_WARN_LIMIT,
1868 		.attr = "max",
1869 		.alarm = "alarm",
1870 		.sbit = PB_PIN_OP_WARNING,
1871 	}, {
1872 		.reg = PMBUS_VIRT_READ_PIN_AVG,
1873 		.update = true,
1874 		.attr = "average",
1875 	}, {
1876 		.reg = PMBUS_VIRT_READ_PIN_MIN,
1877 		.update = true,
1878 		.attr = "input_lowest",
1879 	}, {
1880 		.reg = PMBUS_VIRT_READ_PIN_MAX,
1881 		.update = true,
1882 		.attr = "input_highest",
1883 	}, {
1884 		.reg = PMBUS_VIRT_RESET_PIN_HISTORY,
1885 		.attr = "reset_history",
1886 	}, {
1887 		.reg = PMBUS_MFR_PIN_MAX,
1888 		.attr = "rated_max",
1889 	},
1890 };
1891 
1892 static const struct pmbus_limit_attr pout_limit_attrs[] = {
1893 	{
1894 		.reg = PMBUS_POUT_MAX,
1895 		.attr = "cap",
1896 		.alarm = "cap_alarm",
1897 		.sbit = PB_POWER_LIMITING,
1898 	}, {
1899 		.reg = PMBUS_POUT_OP_WARN_LIMIT,
1900 		.attr = "max",
1901 		.alarm = "max_alarm",
1902 		.sbit = PB_POUT_OP_WARNING,
1903 	}, {
1904 		.reg = PMBUS_POUT_OP_FAULT_LIMIT,
1905 		.attr = "crit",
1906 		.alarm = "crit_alarm",
1907 		.sbit = PB_POUT_OP_FAULT,
1908 	}, {
1909 		.reg = PMBUS_VIRT_READ_POUT_AVG,
1910 		.update = true,
1911 		.attr = "average",
1912 	}, {
1913 		.reg = PMBUS_VIRT_READ_POUT_MIN,
1914 		.update = true,
1915 		.attr = "input_lowest",
1916 	}, {
1917 		.reg = PMBUS_VIRT_READ_POUT_MAX,
1918 		.update = true,
1919 		.attr = "input_highest",
1920 	}, {
1921 		.reg = PMBUS_VIRT_RESET_POUT_HISTORY,
1922 		.attr = "reset_history",
1923 	}, {
1924 		.reg = PMBUS_MFR_POUT_MAX,
1925 		.attr = "rated_max",
1926 	},
1927 };
1928 
1929 static const struct pmbus_sensor_attr power_attributes[] = {
1930 	{
1931 		.reg = PMBUS_READ_PIN,
1932 		.class = PSC_POWER,
1933 		.label = "pin",
1934 		.func = PMBUS_HAVE_PIN,
1935 		.sfunc = PMBUS_HAVE_STATUS_INPUT,
1936 		.sreg = PMBUS_STATUS_INPUT,
1937 		.gbit = PB_STATUS_INPUT,
1938 		.limit = pin_limit_attrs,
1939 		.nlimit = ARRAY_SIZE(pin_limit_attrs),
1940 	}, {
1941 		.reg = PMBUS_READ_POUT,
1942 		.class = PSC_POWER,
1943 		.label = "pout",
1944 		.paged = true,
1945 		.func = PMBUS_HAVE_POUT,
1946 		.sfunc = PMBUS_HAVE_STATUS_IOUT,
1947 		.sreg = PMBUS_STATUS_IOUT,
1948 		.limit = pout_limit_attrs,
1949 		.nlimit = ARRAY_SIZE(pout_limit_attrs),
1950 	}
1951 };
1952 
1953 /* Temperature atributes */
1954 
1955 static const struct pmbus_limit_attr temp_limit_attrs[] = {
1956 	{
1957 		.reg = PMBUS_UT_WARN_LIMIT,
1958 		.low = true,
1959 		.attr = "min",
1960 		.alarm = "min_alarm",
1961 		.sbit = PB_TEMP_UT_WARNING,
1962 	}, {
1963 		.reg = PMBUS_UT_FAULT_LIMIT,
1964 		.low = true,
1965 		.attr = "lcrit",
1966 		.alarm = "lcrit_alarm",
1967 		.sbit = PB_TEMP_UT_FAULT,
1968 	}, {
1969 		.reg = PMBUS_OT_WARN_LIMIT,
1970 		.attr = "max",
1971 		.alarm = "max_alarm",
1972 		.sbit = PB_TEMP_OT_WARNING,
1973 	}, {
1974 		.reg = PMBUS_OT_FAULT_LIMIT,
1975 		.attr = "crit",
1976 		.alarm = "crit_alarm",
1977 		.sbit = PB_TEMP_OT_FAULT,
1978 	}, {
1979 		.reg = PMBUS_VIRT_READ_TEMP_MIN,
1980 		.attr = "lowest",
1981 	}, {
1982 		.reg = PMBUS_VIRT_READ_TEMP_AVG,
1983 		.attr = "average",
1984 	}, {
1985 		.reg = PMBUS_VIRT_READ_TEMP_MAX,
1986 		.attr = "highest",
1987 	}, {
1988 		.reg = PMBUS_VIRT_RESET_TEMP_HISTORY,
1989 		.attr = "reset_history",
1990 	}, {
1991 		.reg = PMBUS_MFR_MAX_TEMP_1,
1992 		.attr = "rated_max",
1993 	},
1994 };
1995 
1996 static const struct pmbus_limit_attr temp_limit_attrs2[] = {
1997 	{
1998 		.reg = PMBUS_UT_WARN_LIMIT,
1999 		.low = true,
2000 		.attr = "min",
2001 		.alarm = "min_alarm",
2002 		.sbit = PB_TEMP_UT_WARNING,
2003 	}, {
2004 		.reg = PMBUS_UT_FAULT_LIMIT,
2005 		.low = true,
2006 		.attr = "lcrit",
2007 		.alarm = "lcrit_alarm",
2008 		.sbit = PB_TEMP_UT_FAULT,
2009 	}, {
2010 		.reg = PMBUS_OT_WARN_LIMIT,
2011 		.attr = "max",
2012 		.alarm = "max_alarm",
2013 		.sbit = PB_TEMP_OT_WARNING,
2014 	}, {
2015 		.reg = PMBUS_OT_FAULT_LIMIT,
2016 		.attr = "crit",
2017 		.alarm = "crit_alarm",
2018 		.sbit = PB_TEMP_OT_FAULT,
2019 	}, {
2020 		.reg = PMBUS_VIRT_READ_TEMP2_MIN,
2021 		.attr = "lowest",
2022 	}, {
2023 		.reg = PMBUS_VIRT_READ_TEMP2_AVG,
2024 		.attr = "average",
2025 	}, {
2026 		.reg = PMBUS_VIRT_READ_TEMP2_MAX,
2027 		.attr = "highest",
2028 	}, {
2029 		.reg = PMBUS_VIRT_RESET_TEMP2_HISTORY,
2030 		.attr = "reset_history",
2031 	}, {
2032 		.reg = PMBUS_MFR_MAX_TEMP_2,
2033 		.attr = "rated_max",
2034 	},
2035 };
2036 
2037 static const struct pmbus_limit_attr temp_limit_attrs3[] = {
2038 	{
2039 		.reg = PMBUS_UT_WARN_LIMIT,
2040 		.low = true,
2041 		.attr = "min",
2042 		.alarm = "min_alarm",
2043 		.sbit = PB_TEMP_UT_WARNING,
2044 	}, {
2045 		.reg = PMBUS_UT_FAULT_LIMIT,
2046 		.low = true,
2047 		.attr = "lcrit",
2048 		.alarm = "lcrit_alarm",
2049 		.sbit = PB_TEMP_UT_FAULT,
2050 	}, {
2051 		.reg = PMBUS_OT_WARN_LIMIT,
2052 		.attr = "max",
2053 		.alarm = "max_alarm",
2054 		.sbit = PB_TEMP_OT_WARNING,
2055 	}, {
2056 		.reg = PMBUS_OT_FAULT_LIMIT,
2057 		.attr = "crit",
2058 		.alarm = "crit_alarm",
2059 		.sbit = PB_TEMP_OT_FAULT,
2060 	}, {
2061 		.reg = PMBUS_MFR_MAX_TEMP_3,
2062 		.attr = "rated_max",
2063 	},
2064 };
2065 
2066 static const struct pmbus_sensor_attr temp_attributes[] = {
2067 	{
2068 		.reg = PMBUS_READ_TEMPERATURE_1,
2069 		.class = PSC_TEMPERATURE,
2070 		.paged = true,
2071 		.update = true,
2072 		.compare = true,
2073 		.func = PMBUS_HAVE_TEMP,
2074 		.sfunc = PMBUS_HAVE_STATUS_TEMP,
2075 		.sreg = PMBUS_STATUS_TEMPERATURE,
2076 		.gbit = PB_STATUS_TEMPERATURE,
2077 		.limit = temp_limit_attrs,
2078 		.nlimit = ARRAY_SIZE(temp_limit_attrs),
2079 	}, {
2080 		.reg = PMBUS_READ_TEMPERATURE_2,
2081 		.class = PSC_TEMPERATURE,
2082 		.paged = true,
2083 		.update = true,
2084 		.compare = true,
2085 		.func = PMBUS_HAVE_TEMP2,
2086 		.sfunc = PMBUS_HAVE_STATUS_TEMP,
2087 		.sreg = PMBUS_STATUS_TEMPERATURE,
2088 		.gbit = PB_STATUS_TEMPERATURE,
2089 		.limit = temp_limit_attrs2,
2090 		.nlimit = ARRAY_SIZE(temp_limit_attrs2),
2091 	}, {
2092 		.reg = PMBUS_READ_TEMPERATURE_3,
2093 		.class = PSC_TEMPERATURE,
2094 		.paged = true,
2095 		.update = true,
2096 		.compare = true,
2097 		.func = PMBUS_HAVE_TEMP3,
2098 		.sfunc = PMBUS_HAVE_STATUS_TEMP,
2099 		.sreg = PMBUS_STATUS_TEMPERATURE,
2100 		.gbit = PB_STATUS_TEMPERATURE,
2101 		.limit = temp_limit_attrs3,
2102 		.nlimit = ARRAY_SIZE(temp_limit_attrs3),
2103 	}
2104 };
2105 
2106 static const int pmbus_fan_registers[] = {
2107 	PMBUS_READ_FAN_SPEED_1,
2108 	PMBUS_READ_FAN_SPEED_2,
2109 	PMBUS_READ_FAN_SPEED_3,
2110 	PMBUS_READ_FAN_SPEED_4
2111 };
2112 
2113 static const int pmbus_fan_status_registers[] = {
2114 	PMBUS_STATUS_FAN_12,
2115 	PMBUS_STATUS_FAN_12,
2116 	PMBUS_STATUS_FAN_34,
2117 	PMBUS_STATUS_FAN_34
2118 };
2119 
2120 static const u32 pmbus_fan_flags[] = {
2121 	PMBUS_HAVE_FAN12,
2122 	PMBUS_HAVE_FAN12,
2123 	PMBUS_HAVE_FAN34,
2124 	PMBUS_HAVE_FAN34
2125 };
2126 
2127 static const u32 pmbus_fan_status_flags[] = {
2128 	PMBUS_HAVE_STATUS_FAN12,
2129 	PMBUS_HAVE_STATUS_FAN12,
2130 	PMBUS_HAVE_STATUS_FAN34,
2131 	PMBUS_HAVE_STATUS_FAN34
2132 };
2133 
2134 /* Fans */
2135 
2136 /* Precondition: FAN_CONFIG_x_y and FAN_COMMAND_x must exist for the fan ID */
2137 static int pmbus_add_fan_ctrl(struct i2c_client *client,
2138 		struct pmbus_data *data, int index, int page, int id,
2139 		u8 config)
2140 {
2141 	struct pmbus_sensor *sensor;
2142 
2143 	sensor = pmbus_add_sensor(data, "fan", "target", index, page,
2144 				  0xff, PMBUS_VIRT_FAN_TARGET_1 + id, PSC_FAN,
2145 				  false, false, true);
2146 
2147 	if (!sensor)
2148 		return -ENOMEM;
2149 
2150 	if (!((data->info->func[page] & PMBUS_HAVE_PWM12) ||
2151 			(data->info->func[page] & PMBUS_HAVE_PWM34)))
2152 		return 0;
2153 
2154 	sensor = pmbus_add_sensor(data, "pwm", NULL, index, page,
2155 				  0xff, PMBUS_VIRT_PWM_1 + id, PSC_PWM,
2156 				  false, false, true);
2157 
2158 	if (!sensor)
2159 		return -ENOMEM;
2160 
2161 	sensor = pmbus_add_sensor(data, "pwm", "enable", index, page,
2162 				  0xff, PMBUS_VIRT_PWM_ENABLE_1 + id, PSC_PWM,
2163 				  true, false, false);
2164 
2165 	if (!sensor)
2166 		return -ENOMEM;
2167 
2168 	return 0;
2169 }
2170 
2171 static int pmbus_add_fan_attributes(struct i2c_client *client,
2172 				    struct pmbus_data *data)
2173 {
2174 	const struct pmbus_driver_info *info = data->info;
2175 	int index = 1;
2176 	int page;
2177 	int ret;
2178 
2179 	for (page = 0; page < info->pages; page++) {
2180 		int f;
2181 
2182 		for (f = 0; f < ARRAY_SIZE(pmbus_fan_registers); f++) {
2183 			int regval;
2184 
2185 			if (!(info->func[page] & pmbus_fan_flags[f]))
2186 				break;
2187 
2188 			if (!pmbus_check_word_register(client, page,
2189 						       pmbus_fan_registers[f]))
2190 				break;
2191 
2192 			/*
2193 			 * Skip fan if not installed.
2194 			 * Each fan configuration register covers multiple fans,
2195 			 * so we have to do some magic.
2196 			 */
2197 			regval = _pmbus_read_byte_data(client, page,
2198 				pmbus_fan_config_registers[f]);
2199 			if (regval < 0 ||
2200 			    (!(regval & (PB_FAN_1_INSTALLED >> ((f & 1) * 4)))))
2201 				continue;
2202 
2203 			if (pmbus_add_sensor(data, "fan", "input", index,
2204 					     page, 0xff, pmbus_fan_registers[f],
2205 					     PSC_FAN, true, true, true) == NULL)
2206 				return -ENOMEM;
2207 
2208 			/* Fan control */
2209 			if (pmbus_check_word_register(client, page,
2210 					pmbus_fan_command_registers[f])) {
2211 				ret = pmbus_add_fan_ctrl(client, data, index,
2212 							 page, f, regval);
2213 				if (ret < 0)
2214 					return ret;
2215 			}
2216 
2217 			/*
2218 			 * Each fan status register covers multiple fans,
2219 			 * so we have to do some magic.
2220 			 */
2221 			if ((info->func[page] & pmbus_fan_status_flags[f]) &&
2222 			    pmbus_check_byte_register(client,
2223 					page, pmbus_fan_status_registers[f])) {
2224 				int reg;
2225 
2226 				if (f > 1)	/* fan 3, 4 */
2227 					reg = PMBUS_STATUS_FAN_34;
2228 				else
2229 					reg = PMBUS_STATUS_FAN_12;
2230 				ret = pmbus_add_boolean(data, "fan",
2231 					"alarm", index, NULL, NULL, page, reg,
2232 					PB_FAN_FAN1_WARNING >> (f & 1));
2233 				if (ret)
2234 					return ret;
2235 				ret = pmbus_add_boolean(data, "fan",
2236 					"fault", index, NULL, NULL, page, reg,
2237 					PB_FAN_FAN1_FAULT >> (f & 1));
2238 				if (ret)
2239 					return ret;
2240 			}
2241 			index++;
2242 		}
2243 	}
2244 	return 0;
2245 }
2246 
2247 struct pmbus_samples_attr {
2248 	int reg;
2249 	char *name;
2250 };
2251 
2252 struct pmbus_samples_reg {
2253 	int page;
2254 	struct pmbus_samples_attr *attr;
2255 	struct device_attribute dev_attr;
2256 };
2257 
2258 static struct pmbus_samples_attr pmbus_samples_registers[] = {
2259 	{
2260 		.reg = PMBUS_VIRT_SAMPLES,
2261 		.name = "samples",
2262 	}, {
2263 		.reg = PMBUS_VIRT_IN_SAMPLES,
2264 		.name = "in_samples",
2265 	}, {
2266 		.reg = PMBUS_VIRT_CURR_SAMPLES,
2267 		.name = "curr_samples",
2268 	}, {
2269 		.reg = PMBUS_VIRT_POWER_SAMPLES,
2270 		.name = "power_samples",
2271 	}, {
2272 		.reg = PMBUS_VIRT_TEMP_SAMPLES,
2273 		.name = "temp_samples",
2274 	}
2275 };
2276 
2277 #define to_samples_reg(x) container_of(x, struct pmbus_samples_reg, dev_attr)
2278 
2279 static ssize_t pmbus_show_samples(struct device *dev,
2280 				  struct device_attribute *devattr, char *buf)
2281 {
2282 	int val;
2283 	struct i2c_client *client = to_i2c_client(dev->parent);
2284 	struct pmbus_samples_reg *reg = to_samples_reg(devattr);
2285 	struct pmbus_data *data = i2c_get_clientdata(client);
2286 
2287 	mutex_lock(&data->update_lock);
2288 	val = _pmbus_read_word_data(client, reg->page, 0xff, reg->attr->reg);
2289 	mutex_unlock(&data->update_lock);
2290 	if (val < 0)
2291 		return val;
2292 
2293 	return sysfs_emit(buf, "%d\n", val);
2294 }
2295 
2296 static ssize_t pmbus_set_samples(struct device *dev,
2297 				 struct device_attribute *devattr,
2298 				 const char *buf, size_t count)
2299 {
2300 	int ret;
2301 	long val;
2302 	struct i2c_client *client = to_i2c_client(dev->parent);
2303 	struct pmbus_samples_reg *reg = to_samples_reg(devattr);
2304 	struct pmbus_data *data = i2c_get_clientdata(client);
2305 
2306 	if (kstrtol(buf, 0, &val) < 0)
2307 		return -EINVAL;
2308 
2309 	mutex_lock(&data->update_lock);
2310 	ret = _pmbus_write_word_data(client, reg->page, reg->attr->reg, val);
2311 	mutex_unlock(&data->update_lock);
2312 
2313 	return ret ? : count;
2314 }
2315 
2316 static int pmbus_add_samples_attr(struct pmbus_data *data, int page,
2317 				  struct pmbus_samples_attr *attr)
2318 {
2319 	struct pmbus_samples_reg *reg;
2320 
2321 	reg = devm_kzalloc(data->dev, sizeof(*reg), GFP_KERNEL);
2322 	if (!reg)
2323 		return -ENOMEM;
2324 
2325 	reg->attr = attr;
2326 	reg->page = page;
2327 
2328 	pmbus_dev_attr_init(&reg->dev_attr, attr->name, 0644,
2329 			    pmbus_show_samples, pmbus_set_samples);
2330 
2331 	return pmbus_add_attribute(data, &reg->dev_attr.attr);
2332 }
2333 
2334 static int pmbus_add_samples_attributes(struct i2c_client *client,
2335 					struct pmbus_data *data)
2336 {
2337 	const struct pmbus_driver_info *info = data->info;
2338 	int s;
2339 
2340 	if (!(info->func[0] & PMBUS_HAVE_SAMPLES))
2341 		return 0;
2342 
2343 	for (s = 0; s < ARRAY_SIZE(pmbus_samples_registers); s++) {
2344 		struct pmbus_samples_attr *attr;
2345 		int ret;
2346 
2347 		attr = &pmbus_samples_registers[s];
2348 		if (!pmbus_check_word_register(client, 0, attr->reg))
2349 			continue;
2350 
2351 		ret = pmbus_add_samples_attr(data, 0, attr);
2352 		if (ret)
2353 			return ret;
2354 	}
2355 
2356 	return 0;
2357 }
2358 
2359 static int pmbus_find_attributes(struct i2c_client *client,
2360 				 struct pmbus_data *data)
2361 {
2362 	int ret;
2363 
2364 	/* Voltage sensors */
2365 	ret = pmbus_add_sensor_attrs(client, data, "in", voltage_attributes,
2366 				     ARRAY_SIZE(voltage_attributes));
2367 	if (ret)
2368 		return ret;
2369 
2370 	/* Current sensors */
2371 	ret = pmbus_add_sensor_attrs(client, data, "curr", current_attributes,
2372 				     ARRAY_SIZE(current_attributes));
2373 	if (ret)
2374 		return ret;
2375 
2376 	/* Power sensors */
2377 	ret = pmbus_add_sensor_attrs(client, data, "power", power_attributes,
2378 				     ARRAY_SIZE(power_attributes));
2379 	if (ret)
2380 		return ret;
2381 
2382 	/* Temperature sensors */
2383 	ret = pmbus_add_sensor_attrs(client, data, "temp", temp_attributes,
2384 				     ARRAY_SIZE(temp_attributes));
2385 	if (ret)
2386 		return ret;
2387 
2388 	/* Fans */
2389 	ret = pmbus_add_fan_attributes(client, data);
2390 	if (ret)
2391 		return ret;
2392 
2393 	ret = pmbus_add_samples_attributes(client, data);
2394 	return ret;
2395 }
2396 
2397 /*
2398  * The pmbus_class_attr_map structure maps one sensor class to
2399  * it's corresponding sensor attributes array.
2400  */
2401 struct pmbus_class_attr_map {
2402 	enum pmbus_sensor_classes class;
2403 	int nattr;
2404 	const struct pmbus_sensor_attr *attr;
2405 };
2406 
2407 static const struct pmbus_class_attr_map class_attr_map[] = {
2408 	{
2409 		.class = PSC_VOLTAGE_IN,
2410 		.attr = voltage_attributes,
2411 		.nattr = ARRAY_SIZE(voltage_attributes),
2412 	}, {
2413 		.class = PSC_VOLTAGE_OUT,
2414 		.attr = voltage_attributes,
2415 		.nattr = ARRAY_SIZE(voltage_attributes),
2416 	}, {
2417 		.class = PSC_CURRENT_IN,
2418 		.attr = current_attributes,
2419 		.nattr = ARRAY_SIZE(current_attributes),
2420 	}, {
2421 		.class = PSC_CURRENT_OUT,
2422 		.attr = current_attributes,
2423 		.nattr = ARRAY_SIZE(current_attributes),
2424 	}, {
2425 		.class = PSC_POWER,
2426 		.attr = power_attributes,
2427 		.nattr = ARRAY_SIZE(power_attributes),
2428 	}, {
2429 		.class = PSC_TEMPERATURE,
2430 		.attr = temp_attributes,
2431 		.nattr = ARRAY_SIZE(temp_attributes),
2432 	}
2433 };
2434 
2435 /*
2436  * Read the coefficients for direct mode.
2437  */
2438 static int pmbus_read_coefficients(struct i2c_client *client,
2439 				   struct pmbus_driver_info *info,
2440 				   const struct pmbus_sensor_attr *attr)
2441 {
2442 	int rv;
2443 	union i2c_smbus_data data;
2444 	enum pmbus_sensor_classes class = attr->class;
2445 	s8 R;
2446 	s16 m, b;
2447 
2448 	data.block[0] = 2;
2449 	data.block[1] = attr->reg;
2450 	data.block[2] = 0x01;
2451 
2452 	rv = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2453 			    I2C_SMBUS_WRITE, PMBUS_COEFFICIENTS,
2454 			    I2C_SMBUS_BLOCK_PROC_CALL, &data);
2455 
2456 	if (rv < 0)
2457 		return rv;
2458 
2459 	if (data.block[0] != 5)
2460 		return -EIO;
2461 
2462 	m = data.block[1] | (data.block[2] << 8);
2463 	b = data.block[3] | (data.block[4] << 8);
2464 	R = data.block[5];
2465 	info->m[class] = m;
2466 	info->b[class] = b;
2467 	info->R[class] = R;
2468 
2469 	return rv;
2470 }
2471 
2472 static int pmbus_init_coefficients(struct i2c_client *client,
2473 				   struct pmbus_driver_info *info)
2474 {
2475 	int i, n, ret = -EINVAL;
2476 	const struct pmbus_class_attr_map *map;
2477 	const struct pmbus_sensor_attr *attr;
2478 
2479 	for (i = 0; i < ARRAY_SIZE(class_attr_map); i++) {
2480 		map = &class_attr_map[i];
2481 		if (info->format[map->class] != direct)
2482 			continue;
2483 		for (n = 0; n < map->nattr; n++) {
2484 			attr = &map->attr[n];
2485 			if (map->class != attr->class)
2486 				continue;
2487 			ret = pmbus_read_coefficients(client, info, attr);
2488 			if (ret >= 0)
2489 				break;
2490 		}
2491 		if (ret < 0) {
2492 			dev_err(&client->dev,
2493 				"No coefficients found for sensor class %d\n",
2494 				map->class);
2495 			return -EINVAL;
2496 		}
2497 	}
2498 
2499 	return 0;
2500 }
2501 
2502 /*
2503  * Identify chip parameters.
2504  * This function is called for all chips.
2505  */
2506 static int pmbus_identify_common(struct i2c_client *client,
2507 				 struct pmbus_data *data, int page)
2508 {
2509 	int vout_mode = -1;
2510 
2511 	if (pmbus_check_byte_register(client, page, PMBUS_VOUT_MODE))
2512 		vout_mode = _pmbus_read_byte_data(client, page,
2513 						  PMBUS_VOUT_MODE);
2514 	if (vout_mode >= 0 && vout_mode != 0xff) {
2515 		/*
2516 		 * Not all chips support the VOUT_MODE command,
2517 		 * so a failure to read it is not an error.
2518 		 */
2519 		switch (vout_mode >> 5) {
2520 		case 0:	/* linear mode      */
2521 			if (data->info->format[PSC_VOLTAGE_OUT] != linear)
2522 				return -ENODEV;
2523 
2524 			data->exponent[page] = ((s8)(vout_mode << 3)) >> 3;
2525 			break;
2526 		case 1: /* VID mode         */
2527 			if (data->info->format[PSC_VOLTAGE_OUT] != vid)
2528 				return -ENODEV;
2529 			break;
2530 		case 2:	/* direct mode      */
2531 			if (data->info->format[PSC_VOLTAGE_OUT] != direct)
2532 				return -ENODEV;
2533 			break;
2534 		case 3:	/* ieee 754 half precision */
2535 			if (data->info->format[PSC_VOLTAGE_OUT] != ieee754)
2536 				return -ENODEV;
2537 			break;
2538 		default:
2539 			return -ENODEV;
2540 		}
2541 	}
2542 
2543 	pmbus_clear_fault_page(client, page);
2544 	return 0;
2545 }
2546 
2547 static int pmbus_read_status_byte(struct i2c_client *client, int page)
2548 {
2549 	return _pmbus_read_byte_data(client, page, PMBUS_STATUS_BYTE);
2550 }
2551 
2552 static int pmbus_read_status_word(struct i2c_client *client, int page)
2553 {
2554 	return _pmbus_read_word_data(client, page, 0xff, PMBUS_STATUS_WORD);
2555 }
2556 
2557 /* PEC attribute support */
2558 
2559 static ssize_t pec_show(struct device *dev, struct device_attribute *dummy,
2560 			char *buf)
2561 {
2562 	struct i2c_client *client = to_i2c_client(dev);
2563 
2564 	return sysfs_emit(buf, "%d\n", !!(client->flags & I2C_CLIENT_PEC));
2565 }
2566 
2567 static ssize_t pec_store(struct device *dev, struct device_attribute *dummy,
2568 			 const char *buf, size_t count)
2569 {
2570 	struct i2c_client *client = to_i2c_client(dev);
2571 	bool enable;
2572 	int err;
2573 
2574 	err = kstrtobool(buf, &enable);
2575 	if (err < 0)
2576 		return err;
2577 
2578 	if (enable)
2579 		client->flags |= I2C_CLIENT_PEC;
2580 	else
2581 		client->flags &= ~I2C_CLIENT_PEC;
2582 
2583 	return count;
2584 }
2585 
2586 static DEVICE_ATTR_RW(pec);
2587 
2588 static void pmbus_remove_pec(void *dev)
2589 {
2590 	device_remove_file(dev, &dev_attr_pec);
2591 }
2592 
2593 static int pmbus_init_common(struct i2c_client *client, struct pmbus_data *data,
2594 			     struct pmbus_driver_info *info)
2595 {
2596 	struct device *dev = &client->dev;
2597 	int page, ret;
2598 
2599 	/*
2600 	 * Figure out if PEC is enabled before accessing any other register.
2601 	 * Make sure PEC is disabled, will be enabled later if needed.
2602 	 */
2603 	client->flags &= ~I2C_CLIENT_PEC;
2604 
2605 	/* Enable PEC if the controller and bus supports it */
2606 	if (!(data->flags & PMBUS_NO_CAPABILITY)) {
2607 		ret = i2c_smbus_read_byte_data(client, PMBUS_CAPABILITY);
2608 		if (ret >= 0 && (ret & PB_CAPABILITY_ERROR_CHECK)) {
2609 			if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_PEC))
2610 				client->flags |= I2C_CLIENT_PEC;
2611 		}
2612 	}
2613 
2614 	/*
2615 	 * Some PMBus chips don't support PMBUS_STATUS_WORD, so try
2616 	 * to use PMBUS_STATUS_BYTE instead if that is the case.
2617 	 * Bail out if both registers are not supported.
2618 	 */
2619 	data->read_status = pmbus_read_status_word;
2620 	ret = i2c_smbus_read_word_data(client, PMBUS_STATUS_WORD);
2621 	if (ret < 0 || ret == 0xffff) {
2622 		data->read_status = pmbus_read_status_byte;
2623 		ret = i2c_smbus_read_byte_data(client, PMBUS_STATUS_BYTE);
2624 		if (ret < 0 || ret == 0xff) {
2625 			dev_err(dev, "PMBus status register not found\n");
2626 			return -ENODEV;
2627 		}
2628 	} else {
2629 		data->has_status_word = true;
2630 	}
2631 
2632 	/*
2633 	 * Check if the chip is write protected. If it is, we can not clear
2634 	 * faults, and we should not try it. Also, in that case, writes into
2635 	 * limit registers need to be disabled.
2636 	 */
2637 	if (!(data->flags & PMBUS_NO_WRITE_PROTECT)) {
2638 		ret = i2c_smbus_read_byte_data(client, PMBUS_WRITE_PROTECT);
2639 		if (ret > 0 && (ret & PB_WP_ANY))
2640 			data->flags |= PMBUS_WRITE_PROTECTED | PMBUS_SKIP_STATUS_CHECK;
2641 	}
2642 
2643 	if (data->info->pages)
2644 		pmbus_clear_faults(client);
2645 	else
2646 		pmbus_clear_fault_page(client, -1);
2647 
2648 	if (info->identify) {
2649 		ret = (*info->identify)(client, info);
2650 		if (ret < 0) {
2651 			dev_err(dev, "Chip identification failed\n");
2652 			return ret;
2653 		}
2654 	}
2655 
2656 	if (info->pages <= 0 || info->pages > PMBUS_PAGES) {
2657 		dev_err(dev, "Bad number of PMBus pages: %d\n", info->pages);
2658 		return -ENODEV;
2659 	}
2660 
2661 	for (page = 0; page < info->pages; page++) {
2662 		ret = pmbus_identify_common(client, data, page);
2663 		if (ret < 0) {
2664 			dev_err(dev, "Failed to identify chip capabilities\n");
2665 			return ret;
2666 		}
2667 	}
2668 
2669 	if (data->flags & PMBUS_USE_COEFFICIENTS_CMD) {
2670 		if (!i2c_check_functionality(client->adapter,
2671 					     I2C_FUNC_SMBUS_BLOCK_PROC_CALL))
2672 			return -ENODEV;
2673 
2674 		ret = pmbus_init_coefficients(client, info);
2675 		if (ret < 0)
2676 			return ret;
2677 	}
2678 
2679 	if (client->flags & I2C_CLIENT_PEC) {
2680 		/*
2681 		 * If I2C_CLIENT_PEC is set here, both the I2C adapter and the
2682 		 * chip support PEC. Add 'pec' attribute to client device to let
2683 		 * the user control it.
2684 		 */
2685 		ret = device_create_file(dev, &dev_attr_pec);
2686 		if (ret)
2687 			return ret;
2688 		ret = devm_add_action_or_reset(dev, pmbus_remove_pec, dev);
2689 		if (ret)
2690 			return ret;
2691 	}
2692 
2693 	return 0;
2694 }
2695 
2696 /* A PMBus status flag and the corresponding REGULATOR_ERROR_* and REGULATOR_EVENTS_* flag */
2697 struct pmbus_status_assoc {
2698 	int pflag, rflag, eflag;
2699 };
2700 
2701 /* PMBus->regulator bit mappings for a PMBus status register */
2702 struct pmbus_status_category {
2703 	int func;
2704 	int reg;
2705 	const struct pmbus_status_assoc *bits; /* zero-terminated */
2706 };
2707 
2708 static const struct pmbus_status_category __maybe_unused pmbus_status_flag_map[] = {
2709 	{
2710 		.func = PMBUS_HAVE_STATUS_VOUT,
2711 		.reg = PMBUS_STATUS_VOUT,
2712 		.bits = (const struct pmbus_status_assoc[]) {
2713 			{ PB_VOLTAGE_UV_WARNING, REGULATOR_ERROR_UNDER_VOLTAGE_WARN,
2714 			REGULATOR_EVENT_UNDER_VOLTAGE_WARN },
2715 			{ PB_VOLTAGE_UV_FAULT,   REGULATOR_ERROR_UNDER_VOLTAGE,
2716 			REGULATOR_EVENT_UNDER_VOLTAGE },
2717 			{ PB_VOLTAGE_OV_WARNING, REGULATOR_ERROR_OVER_VOLTAGE_WARN,
2718 			REGULATOR_EVENT_OVER_VOLTAGE_WARN },
2719 			{ PB_VOLTAGE_OV_FAULT,   REGULATOR_ERROR_REGULATION_OUT,
2720 			REGULATOR_EVENT_OVER_VOLTAGE_WARN },
2721 			{ },
2722 		},
2723 	}, {
2724 		.func = PMBUS_HAVE_STATUS_IOUT,
2725 		.reg = PMBUS_STATUS_IOUT,
2726 		.bits = (const struct pmbus_status_assoc[]) {
2727 			{ PB_IOUT_OC_WARNING,   REGULATOR_ERROR_OVER_CURRENT_WARN,
2728 			REGULATOR_EVENT_OVER_CURRENT_WARN },
2729 			{ PB_IOUT_OC_FAULT,     REGULATOR_ERROR_OVER_CURRENT,
2730 			REGULATOR_EVENT_OVER_CURRENT },
2731 			{ PB_IOUT_OC_LV_FAULT,  REGULATOR_ERROR_OVER_CURRENT,
2732 			REGULATOR_EVENT_OVER_CURRENT },
2733 			{ },
2734 		},
2735 	}, {
2736 		.func = PMBUS_HAVE_STATUS_TEMP,
2737 		.reg = PMBUS_STATUS_TEMPERATURE,
2738 		.bits = (const struct pmbus_status_assoc[]) {
2739 			{ PB_TEMP_OT_WARNING,    REGULATOR_ERROR_OVER_TEMP_WARN,
2740 			REGULATOR_EVENT_OVER_TEMP_WARN },
2741 			{ PB_TEMP_OT_FAULT,      REGULATOR_ERROR_OVER_TEMP,
2742 			REGULATOR_EVENT_OVER_TEMP },
2743 			{ },
2744 		},
2745 	},
2746 };
2747 
2748 static int _pmbus_is_enabled(struct device *dev, u8 page)
2749 {
2750 	struct i2c_client *client = to_i2c_client(dev->parent);
2751 	int ret;
2752 
2753 	ret = _pmbus_read_byte_data(client, page, PMBUS_OPERATION);
2754 
2755 	if (ret < 0)
2756 		return ret;
2757 
2758 	return !!(ret & PB_OPERATION_CONTROL_ON);
2759 }
2760 
2761 static int __maybe_unused pmbus_is_enabled(struct device *dev, u8 page)
2762 {
2763 	struct i2c_client *client = to_i2c_client(dev->parent);
2764 	struct pmbus_data *data = i2c_get_clientdata(client);
2765 	int ret;
2766 
2767 	mutex_lock(&data->update_lock);
2768 	ret = _pmbus_is_enabled(dev, page);
2769 	mutex_unlock(&data->update_lock);
2770 
2771 	return !!(ret & PB_OPERATION_CONTROL_ON);
2772 }
2773 
2774 #define to_dev_attr(_dev_attr) \
2775 	container_of(_dev_attr, struct device_attribute, attr)
2776 
2777 static void pmbus_notify(struct pmbus_data *data, int page, int reg, int flags)
2778 {
2779 	int i;
2780 
2781 	for (i = 0; i < data->num_attributes; i++) {
2782 		struct device_attribute *da = to_dev_attr(data->group.attrs[i]);
2783 		struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
2784 		int index = attr->index;
2785 		u16 smask = pb_index_to_mask(index);
2786 		u8 spage = pb_index_to_page(index);
2787 		u16 sreg = pb_index_to_reg(index);
2788 
2789 		if (reg == sreg && page == spage && (smask & flags)) {
2790 			dev_dbg(data->dev, "sysfs notify: %s", da->attr.name);
2791 			sysfs_notify(&data->dev->kobj, NULL, da->attr.name);
2792 			kobject_uevent(&data->dev->kobj, KOBJ_CHANGE);
2793 			flags &= ~smask;
2794 		}
2795 
2796 		if (!flags)
2797 			break;
2798 	}
2799 }
2800 
2801 static int _pmbus_get_flags(struct pmbus_data *data, u8 page, unsigned int *flags,
2802 			   unsigned int *event, bool notify)
2803 {
2804 	int i, status;
2805 	const struct pmbus_status_category *cat;
2806 	const struct pmbus_status_assoc *bit;
2807 	struct device *dev = data->dev;
2808 	struct i2c_client *client = to_i2c_client(dev);
2809 	int func = data->info->func[page];
2810 
2811 	*flags = 0;
2812 	*event = 0;
2813 
2814 	for (i = 0; i < ARRAY_SIZE(pmbus_status_flag_map); i++) {
2815 		cat = &pmbus_status_flag_map[i];
2816 		if (!(func & cat->func))
2817 			continue;
2818 
2819 		status = _pmbus_read_byte_data(client, page, cat->reg);
2820 		if (status < 0)
2821 			return status;
2822 
2823 		for (bit = cat->bits; bit->pflag; bit++)
2824 			if (status & bit->pflag) {
2825 				*flags |= bit->rflag;
2826 				*event |= bit->eflag;
2827 			}
2828 
2829 		if (notify && status)
2830 			pmbus_notify(data, page, cat->reg, status);
2831 
2832 	}
2833 
2834 	/*
2835 	 * Map what bits of STATUS_{WORD,BYTE} we can to REGULATOR_ERROR_*
2836 	 * bits.  Some of the other bits are tempting (especially for cases
2837 	 * where we don't have the relevant PMBUS_HAVE_STATUS_*
2838 	 * functionality), but there's an unfortunate ambiguity in that
2839 	 * they're defined as indicating a fault *or* a warning, so we can't
2840 	 * easily determine whether to report REGULATOR_ERROR_<foo> or
2841 	 * REGULATOR_ERROR_<foo>_WARN.
2842 	 */
2843 	status = pmbus_get_status(client, page, PMBUS_STATUS_WORD);
2844 	if (status < 0)
2845 		return status;
2846 
2847 	if (_pmbus_is_enabled(dev, page)) {
2848 		if (status & PB_STATUS_OFF) {
2849 			*flags |= REGULATOR_ERROR_FAIL;
2850 			*event |= REGULATOR_EVENT_FAIL;
2851 		}
2852 
2853 		if (status & PB_STATUS_POWER_GOOD_N) {
2854 			*flags |= REGULATOR_ERROR_REGULATION_OUT;
2855 			*event |= REGULATOR_EVENT_REGULATION_OUT;
2856 		}
2857 	}
2858 	/*
2859 	 * Unlike most other status bits, PB_STATUS_{IOUT_OC,VOUT_OV} are
2860 	 * defined strictly as fault indicators (not warnings).
2861 	 */
2862 	if (status & PB_STATUS_IOUT_OC) {
2863 		*flags |= REGULATOR_ERROR_OVER_CURRENT;
2864 		*event |= REGULATOR_EVENT_OVER_CURRENT;
2865 	}
2866 	if (status & PB_STATUS_VOUT_OV) {
2867 		*flags |= REGULATOR_ERROR_REGULATION_OUT;
2868 		*event |= REGULATOR_EVENT_FAIL;
2869 	}
2870 
2871 	/*
2872 	 * If we haven't discovered any thermal faults or warnings via
2873 	 * PMBUS_STATUS_TEMPERATURE, map PB_STATUS_TEMPERATURE to a warning as
2874 	 * a (conservative) best-effort interpretation.
2875 	 */
2876 	if (!(*flags & (REGULATOR_ERROR_OVER_TEMP | REGULATOR_ERROR_OVER_TEMP_WARN)) &&
2877 	    (status & PB_STATUS_TEMPERATURE)) {
2878 		*flags |= REGULATOR_ERROR_OVER_TEMP_WARN;
2879 		*event |= REGULATOR_EVENT_OVER_TEMP_WARN;
2880 	}
2881 
2882 
2883 	return 0;
2884 }
2885 
2886 static int __maybe_unused pmbus_get_flags(struct pmbus_data *data, u8 page, unsigned int *flags,
2887 					  unsigned int *event, bool notify)
2888 {
2889 	int ret;
2890 
2891 	mutex_lock(&data->update_lock);
2892 	ret = _pmbus_get_flags(data, page, flags, event, notify);
2893 	mutex_unlock(&data->update_lock);
2894 
2895 	return ret;
2896 }
2897 
2898 #if IS_ENABLED(CONFIG_REGULATOR)
2899 static int pmbus_regulator_is_enabled(struct regulator_dev *rdev)
2900 {
2901 	return pmbus_is_enabled(rdev_get_dev(rdev), rdev_get_id(rdev));
2902 }
2903 
2904 static int _pmbus_regulator_on_off(struct regulator_dev *rdev, bool enable)
2905 {
2906 	struct device *dev = rdev_get_dev(rdev);
2907 	struct i2c_client *client = to_i2c_client(dev->parent);
2908 	struct pmbus_data *data = i2c_get_clientdata(client);
2909 	u8 page = rdev_get_id(rdev);
2910 	int ret;
2911 
2912 	mutex_lock(&data->update_lock);
2913 	ret = pmbus_update_byte_data(client, page, PMBUS_OPERATION,
2914 				     PB_OPERATION_CONTROL_ON,
2915 				     enable ? PB_OPERATION_CONTROL_ON : 0);
2916 	mutex_unlock(&data->update_lock);
2917 
2918 	return ret;
2919 }
2920 
2921 static int pmbus_regulator_enable(struct regulator_dev *rdev)
2922 {
2923 	return _pmbus_regulator_on_off(rdev, 1);
2924 }
2925 
2926 static int pmbus_regulator_disable(struct regulator_dev *rdev)
2927 {
2928 	return _pmbus_regulator_on_off(rdev, 0);
2929 }
2930 
2931 static int pmbus_regulator_get_error_flags(struct regulator_dev *rdev, unsigned int *flags)
2932 {
2933 	struct device *dev = rdev_get_dev(rdev);
2934 	struct i2c_client *client = to_i2c_client(dev->parent);
2935 	struct pmbus_data *data = i2c_get_clientdata(client);
2936 	int event;
2937 
2938 	return pmbus_get_flags(data, rdev_get_id(rdev), flags, &event, false);
2939 }
2940 
2941 static int pmbus_regulator_get_status(struct regulator_dev *rdev)
2942 {
2943 	struct device *dev = rdev_get_dev(rdev);
2944 	struct i2c_client *client = to_i2c_client(dev->parent);
2945 	struct pmbus_data *data = i2c_get_clientdata(client);
2946 	u8 page = rdev_get_id(rdev);
2947 	int status, ret;
2948 
2949 	mutex_lock(&data->update_lock);
2950 	status = pmbus_get_status(client, page, PMBUS_STATUS_WORD);
2951 	if (status < 0) {
2952 		ret = status;
2953 		goto unlock;
2954 	}
2955 
2956 	if (status & PB_STATUS_OFF) {
2957 		ret = REGULATOR_STATUS_OFF;
2958 		goto unlock;
2959 	}
2960 
2961 	/* If regulator is ON & reports power good then return ON */
2962 	if (!(status & PB_STATUS_POWER_GOOD_N)) {
2963 		ret = REGULATOR_STATUS_ON;
2964 		goto unlock;
2965 	}
2966 
2967 	ret = pmbus_regulator_get_error_flags(rdev, &status);
2968 	if (ret)
2969 		goto unlock;
2970 
2971 	if (status & (REGULATOR_ERROR_UNDER_VOLTAGE | REGULATOR_ERROR_OVER_CURRENT |
2972 	   REGULATOR_ERROR_REGULATION_OUT | REGULATOR_ERROR_FAIL | REGULATOR_ERROR_OVER_TEMP)) {
2973 		ret = REGULATOR_STATUS_ERROR;
2974 		goto unlock;
2975 	}
2976 
2977 	ret = REGULATOR_STATUS_UNDEFINED;
2978 
2979 unlock:
2980 	mutex_unlock(&data->update_lock);
2981 	return ret;
2982 }
2983 
2984 static int pmbus_regulator_get_low_margin(struct i2c_client *client, int page)
2985 {
2986 	struct pmbus_data *data = i2c_get_clientdata(client);
2987 	struct pmbus_sensor s = {
2988 		.page = page,
2989 		.class = PSC_VOLTAGE_OUT,
2990 		.convert = true,
2991 		.data = -1,
2992 	};
2993 
2994 	if (data->vout_low[page] < 0) {
2995 		if (pmbus_check_word_register(client, page, PMBUS_MFR_VOUT_MIN))
2996 			s.data = _pmbus_read_word_data(client, page, 0xff,
2997 						       PMBUS_MFR_VOUT_MIN);
2998 		if (s.data < 0) {
2999 			s.data = _pmbus_read_word_data(client, page, 0xff,
3000 						       PMBUS_VOUT_MARGIN_LOW);
3001 			if (s.data < 0)
3002 				return s.data;
3003 		}
3004 		data->vout_low[page] = pmbus_reg2data(data, &s);
3005 	}
3006 
3007 	return data->vout_low[page];
3008 }
3009 
3010 static int pmbus_regulator_get_high_margin(struct i2c_client *client, int page)
3011 {
3012 	struct pmbus_data *data = i2c_get_clientdata(client);
3013 	struct pmbus_sensor s = {
3014 		.page = page,
3015 		.class = PSC_VOLTAGE_OUT,
3016 		.convert = true,
3017 		.data = -1,
3018 	};
3019 
3020 	if (data->vout_high[page] < 0) {
3021 		if (pmbus_check_word_register(client, page, PMBUS_MFR_VOUT_MAX))
3022 			s.data = _pmbus_read_word_data(client, page, 0xff,
3023 						       PMBUS_MFR_VOUT_MAX);
3024 		if (s.data < 0) {
3025 			s.data = _pmbus_read_word_data(client, page, 0xff,
3026 						       PMBUS_VOUT_MARGIN_HIGH);
3027 			if (s.data < 0)
3028 				return s.data;
3029 		}
3030 		data->vout_high[page] = pmbus_reg2data(data, &s);
3031 	}
3032 
3033 	return data->vout_high[page];
3034 }
3035 
3036 static int pmbus_regulator_get_voltage(struct regulator_dev *rdev)
3037 {
3038 	struct device *dev = rdev_get_dev(rdev);
3039 	struct i2c_client *client = to_i2c_client(dev->parent);
3040 	struct pmbus_data *data = i2c_get_clientdata(client);
3041 	struct pmbus_sensor s = {
3042 		.page = rdev_get_id(rdev),
3043 		.class = PSC_VOLTAGE_OUT,
3044 		.convert = true,
3045 	};
3046 
3047 	s.data = _pmbus_read_word_data(client, s.page, 0xff, PMBUS_READ_VOUT);
3048 	if (s.data < 0)
3049 		return s.data;
3050 
3051 	return (int)pmbus_reg2data(data, &s) * 1000; /* unit is uV */
3052 }
3053 
3054 static int pmbus_regulator_set_voltage(struct regulator_dev *rdev, int min_uv,
3055 				       int max_uv, unsigned int *selector)
3056 {
3057 	struct device *dev = rdev_get_dev(rdev);
3058 	struct i2c_client *client = to_i2c_client(dev->parent);
3059 	struct pmbus_data *data = i2c_get_clientdata(client);
3060 	struct pmbus_sensor s = {
3061 		.page = rdev_get_id(rdev),
3062 		.class = PSC_VOLTAGE_OUT,
3063 		.convert = true,
3064 		.data = -1,
3065 	};
3066 	int val = DIV_ROUND_CLOSEST(min_uv, 1000); /* convert to mV */
3067 	int low, high;
3068 
3069 	*selector = 0;
3070 
3071 	low = pmbus_regulator_get_low_margin(client, s.page);
3072 	if (low < 0)
3073 		return low;
3074 
3075 	high = pmbus_regulator_get_high_margin(client, s.page);
3076 	if (high < 0)
3077 		return high;
3078 
3079 	/* Make sure we are within margins */
3080 	if (low > val)
3081 		val = low;
3082 	if (high < val)
3083 		val = high;
3084 
3085 	val = pmbus_data2reg(data, &s, val);
3086 
3087 	return _pmbus_write_word_data(client, s.page, PMBUS_VOUT_COMMAND, (u16)val);
3088 }
3089 
3090 static int pmbus_regulator_list_voltage(struct regulator_dev *rdev,
3091 					 unsigned int selector)
3092 {
3093 	struct device *dev = rdev_get_dev(rdev);
3094 	struct i2c_client *client = to_i2c_client(dev->parent);
3095 	int val, low, high;
3096 
3097 	if (selector >= rdev->desc->n_voltages ||
3098 	    selector < rdev->desc->linear_min_sel)
3099 		return -EINVAL;
3100 
3101 	selector -= rdev->desc->linear_min_sel;
3102 	val = DIV_ROUND_CLOSEST(rdev->desc->min_uV +
3103 				(rdev->desc->uV_step * selector), 1000); /* convert to mV */
3104 
3105 	low = pmbus_regulator_get_low_margin(client, rdev_get_id(rdev));
3106 	if (low < 0)
3107 		return low;
3108 
3109 	high = pmbus_regulator_get_high_margin(client, rdev_get_id(rdev));
3110 	if (high < 0)
3111 		return high;
3112 
3113 	if (val >= low && val <= high)
3114 		return val * 1000; /* unit is uV */
3115 
3116 	return 0;
3117 }
3118 
3119 const struct regulator_ops pmbus_regulator_ops = {
3120 	.enable = pmbus_regulator_enable,
3121 	.disable = pmbus_regulator_disable,
3122 	.is_enabled = pmbus_regulator_is_enabled,
3123 	.get_error_flags = pmbus_regulator_get_error_flags,
3124 	.get_status = pmbus_regulator_get_status,
3125 	.get_voltage = pmbus_regulator_get_voltage,
3126 	.set_voltage = pmbus_regulator_set_voltage,
3127 	.list_voltage = pmbus_regulator_list_voltage,
3128 };
3129 EXPORT_SYMBOL_NS_GPL(pmbus_regulator_ops, PMBUS);
3130 
3131 static int pmbus_regulator_register(struct pmbus_data *data)
3132 {
3133 	struct device *dev = data->dev;
3134 	const struct pmbus_driver_info *info = data->info;
3135 	const struct pmbus_platform_data *pdata = dev_get_platdata(dev);
3136 	int i;
3137 
3138 	data->rdevs = devm_kzalloc(dev, sizeof(struct regulator_dev *) * info->num_regulators,
3139 				   GFP_KERNEL);
3140 	if (!data->rdevs)
3141 		return -ENOMEM;
3142 
3143 	for (i = 0; i < info->num_regulators; i++) {
3144 		struct regulator_config config = { };
3145 
3146 		config.dev = dev;
3147 		config.driver_data = data;
3148 
3149 		if (pdata && pdata->reg_init_data)
3150 			config.init_data = &pdata->reg_init_data[i];
3151 
3152 		data->rdevs[i] = devm_regulator_register(dev, &info->reg_desc[i],
3153 							 &config);
3154 		if (IS_ERR(data->rdevs[i]))
3155 			return dev_err_probe(dev, PTR_ERR(data->rdevs[i]),
3156 					     "Failed to register %s regulator\n",
3157 					     info->reg_desc[i].name);
3158 	}
3159 
3160 	return 0;
3161 }
3162 
3163 static int pmbus_regulator_notify(struct pmbus_data *data, int page, int event)
3164 {
3165 		int j;
3166 
3167 		for (j = 0; j < data->info->num_regulators; j++) {
3168 			if (page == rdev_get_id(data->rdevs[j])) {
3169 				regulator_notifier_call_chain(data->rdevs[j], event, NULL);
3170 				break;
3171 			}
3172 		}
3173 		return 0;
3174 }
3175 #else
3176 static int pmbus_regulator_register(struct pmbus_data *data)
3177 {
3178 	return 0;
3179 }
3180 
3181 static int pmbus_regulator_notify(struct pmbus_data *data, int page, int event)
3182 {
3183 		return 0;
3184 }
3185 #endif
3186 
3187 static int pmbus_write_smbalert_mask(struct i2c_client *client, u8 page, u8 reg, u8 val)
3188 {
3189 	return pmbus_write_word_data(client, page, PMBUS_SMBALERT_MASK, reg | (val << 8));
3190 }
3191 
3192 static irqreturn_t pmbus_fault_handler(int irq, void *pdata)
3193 {
3194 	struct pmbus_data *data = pdata;
3195 	struct i2c_client *client = to_i2c_client(data->dev);
3196 
3197 	int i, status, event;
3198 	mutex_lock(&data->update_lock);
3199 	for (i = 0; i < data->info->pages; i++) {
3200 		_pmbus_get_flags(data, i, &status, &event, true);
3201 
3202 		if (event)
3203 			pmbus_regulator_notify(data, i, event);
3204 	}
3205 
3206 	pmbus_clear_faults(client);
3207 	mutex_unlock(&data->update_lock);
3208 
3209 	return IRQ_HANDLED;
3210 }
3211 
3212 static int pmbus_irq_setup(struct i2c_client *client, struct pmbus_data *data)
3213 {
3214 	struct device *dev = &client->dev;
3215 	const struct pmbus_status_category *cat;
3216 	const struct pmbus_status_assoc *bit;
3217 	int i, j, err, func;
3218 	u8 mask;
3219 
3220 	static const u8 misc_status[] = {PMBUS_STATUS_CML, PMBUS_STATUS_OTHER,
3221 					 PMBUS_STATUS_MFR_SPECIFIC, PMBUS_STATUS_FAN_12,
3222 					 PMBUS_STATUS_FAN_34};
3223 
3224 	if (!client->irq)
3225 		return 0;
3226 
3227 	for (i = 0; i < data->info->pages; i++) {
3228 		func = data->info->func[i];
3229 
3230 		for (j = 0; j < ARRAY_SIZE(pmbus_status_flag_map); j++) {
3231 			cat = &pmbus_status_flag_map[j];
3232 			if (!(func & cat->func))
3233 				continue;
3234 			mask = 0;
3235 			for (bit = cat->bits; bit->pflag; bit++)
3236 				mask |= bit->pflag;
3237 
3238 			err = pmbus_write_smbalert_mask(client, i, cat->reg, ~mask);
3239 			if (err)
3240 				dev_dbg_once(dev, "Failed to set smbalert for reg 0x%02x\n",
3241 					     cat->reg);
3242 		}
3243 
3244 		for (j = 0; j < ARRAY_SIZE(misc_status); j++)
3245 			pmbus_write_smbalert_mask(client, i, misc_status[j], 0xff);
3246 	}
3247 
3248 	/* Register notifiers */
3249 	err = devm_request_threaded_irq(dev, client->irq, NULL, pmbus_fault_handler,
3250 					IRQF_ONESHOT, "pmbus-irq", data);
3251 	if (err) {
3252 		dev_err(dev, "failed to request an irq %d\n", err);
3253 		return err;
3254 	}
3255 
3256 	return 0;
3257 }
3258 
3259 static struct dentry *pmbus_debugfs_dir;	/* pmbus debugfs directory */
3260 
3261 #if IS_ENABLED(CONFIG_DEBUG_FS)
3262 static int pmbus_debugfs_get(void *data, u64 *val)
3263 {
3264 	int rc;
3265 	struct pmbus_debugfs_entry *entry = data;
3266 	struct pmbus_data *pdata = i2c_get_clientdata(entry->client);
3267 
3268 	rc = mutex_lock_interruptible(&pdata->update_lock);
3269 	if (rc)
3270 		return rc;
3271 	rc = _pmbus_read_byte_data(entry->client, entry->page, entry->reg);
3272 	mutex_unlock(&pdata->update_lock);
3273 	if (rc < 0)
3274 		return rc;
3275 
3276 	*val = rc;
3277 
3278 	return 0;
3279 }
3280 DEFINE_DEBUGFS_ATTRIBUTE(pmbus_debugfs_ops, pmbus_debugfs_get, NULL,
3281 			 "0x%02llx\n");
3282 
3283 static int pmbus_debugfs_get_status(void *data, u64 *val)
3284 {
3285 	int rc;
3286 	struct pmbus_debugfs_entry *entry = data;
3287 	struct pmbus_data *pdata = i2c_get_clientdata(entry->client);
3288 
3289 	rc = mutex_lock_interruptible(&pdata->update_lock);
3290 	if (rc)
3291 		return rc;
3292 	rc = pdata->read_status(entry->client, entry->page);
3293 	mutex_unlock(&pdata->update_lock);
3294 	if (rc < 0)
3295 		return rc;
3296 
3297 	*val = rc;
3298 
3299 	return 0;
3300 }
3301 DEFINE_DEBUGFS_ATTRIBUTE(pmbus_debugfs_ops_status, pmbus_debugfs_get_status,
3302 			 NULL, "0x%04llx\n");
3303 
3304 static ssize_t pmbus_debugfs_mfr_read(struct file *file, char __user *buf,
3305 				       size_t count, loff_t *ppos)
3306 {
3307 	int rc;
3308 	struct pmbus_debugfs_entry *entry = file->private_data;
3309 	struct pmbus_data *pdata = i2c_get_clientdata(entry->client);
3310 	char data[I2C_SMBUS_BLOCK_MAX + 2] = { 0 };
3311 
3312 	rc = mutex_lock_interruptible(&pdata->update_lock);
3313 	if (rc)
3314 		return rc;
3315 	rc = pmbus_read_block_data(entry->client, entry->page, entry->reg,
3316 				   data);
3317 	mutex_unlock(&pdata->update_lock);
3318 	if (rc < 0)
3319 		return rc;
3320 
3321 	/* Add newline at the end of a read data */
3322 	data[rc] = '\n';
3323 
3324 	/* Include newline into the length */
3325 	rc += 1;
3326 
3327 	return simple_read_from_buffer(buf, count, ppos, data, rc);
3328 }
3329 
3330 static const struct file_operations pmbus_debugfs_ops_mfr = {
3331 	.llseek = noop_llseek,
3332 	.read = pmbus_debugfs_mfr_read,
3333 	.write = NULL,
3334 	.open = simple_open,
3335 };
3336 
3337 static void pmbus_remove_debugfs(void *data)
3338 {
3339 	struct dentry *entry = data;
3340 
3341 	debugfs_remove_recursive(entry);
3342 }
3343 
3344 static int pmbus_init_debugfs(struct i2c_client *client,
3345 			      struct pmbus_data *data)
3346 {
3347 	int i, idx = 0;
3348 	char name[PMBUS_NAME_SIZE];
3349 	struct pmbus_debugfs_entry *entries;
3350 
3351 	if (!pmbus_debugfs_dir)
3352 		return -ENODEV;
3353 
3354 	/*
3355 	 * Create the debugfs directory for this device. Use the hwmon device
3356 	 * name to avoid conflicts (hwmon numbers are globally unique).
3357 	 */
3358 	data->debugfs = debugfs_create_dir(dev_name(data->hwmon_dev),
3359 					   pmbus_debugfs_dir);
3360 	if (IS_ERR_OR_NULL(data->debugfs)) {
3361 		data->debugfs = NULL;
3362 		return -ENODEV;
3363 	}
3364 
3365 	/*
3366 	 * Allocate the max possible entries we need.
3367 	 * 6 entries device-specific
3368 	 * 10 entries page-specific
3369 	 */
3370 	entries = devm_kcalloc(data->dev,
3371 			       6 + data->info->pages * 10, sizeof(*entries),
3372 			       GFP_KERNEL);
3373 	if (!entries)
3374 		return -ENOMEM;
3375 
3376 	/*
3377 	 * Add device-specific entries.
3378 	 * Please note that the PMBUS standard allows all registers to be
3379 	 * page-specific.
3380 	 * To reduce the number of debugfs entries for devices with many pages
3381 	 * assume that values of the following registers are the same for all
3382 	 * pages and report values only for page 0.
3383 	 */
3384 	if (pmbus_check_block_register(client, 0, PMBUS_MFR_ID)) {
3385 		entries[idx].client = client;
3386 		entries[idx].page = 0;
3387 		entries[idx].reg = PMBUS_MFR_ID;
3388 		debugfs_create_file("mfr_id", 0444, data->debugfs,
3389 				    &entries[idx++],
3390 				    &pmbus_debugfs_ops_mfr);
3391 	}
3392 
3393 	if (pmbus_check_block_register(client, 0, PMBUS_MFR_MODEL)) {
3394 		entries[idx].client = client;
3395 		entries[idx].page = 0;
3396 		entries[idx].reg = PMBUS_MFR_MODEL;
3397 		debugfs_create_file("mfr_model", 0444, data->debugfs,
3398 				    &entries[idx++],
3399 				    &pmbus_debugfs_ops_mfr);
3400 	}
3401 
3402 	if (pmbus_check_block_register(client, 0, PMBUS_MFR_REVISION)) {
3403 		entries[idx].client = client;
3404 		entries[idx].page = 0;
3405 		entries[idx].reg = PMBUS_MFR_REVISION;
3406 		debugfs_create_file("mfr_revision", 0444, data->debugfs,
3407 				    &entries[idx++],
3408 				    &pmbus_debugfs_ops_mfr);
3409 	}
3410 
3411 	if (pmbus_check_block_register(client, 0, PMBUS_MFR_LOCATION)) {
3412 		entries[idx].client = client;
3413 		entries[idx].page = 0;
3414 		entries[idx].reg = PMBUS_MFR_LOCATION;
3415 		debugfs_create_file("mfr_location", 0444, data->debugfs,
3416 				    &entries[idx++],
3417 				    &pmbus_debugfs_ops_mfr);
3418 	}
3419 
3420 	if (pmbus_check_block_register(client, 0, PMBUS_MFR_DATE)) {
3421 		entries[idx].client = client;
3422 		entries[idx].page = 0;
3423 		entries[idx].reg = PMBUS_MFR_DATE;
3424 		debugfs_create_file("mfr_date", 0444, data->debugfs,
3425 				    &entries[idx++],
3426 				    &pmbus_debugfs_ops_mfr);
3427 	}
3428 
3429 	if (pmbus_check_block_register(client, 0, PMBUS_MFR_SERIAL)) {
3430 		entries[idx].client = client;
3431 		entries[idx].page = 0;
3432 		entries[idx].reg = PMBUS_MFR_SERIAL;
3433 		debugfs_create_file("mfr_serial", 0444, data->debugfs,
3434 				    &entries[idx++],
3435 				    &pmbus_debugfs_ops_mfr);
3436 	}
3437 
3438 	/* Add page specific entries */
3439 	for (i = 0; i < data->info->pages; ++i) {
3440 		/* Check accessibility of status register if it's not page 0 */
3441 		if (!i || pmbus_check_status_register(client, i)) {
3442 			/* No need to set reg as we have special read op. */
3443 			entries[idx].client = client;
3444 			entries[idx].page = i;
3445 			scnprintf(name, PMBUS_NAME_SIZE, "status%d", i);
3446 			debugfs_create_file(name, 0444, data->debugfs,
3447 					    &entries[idx++],
3448 					    &pmbus_debugfs_ops_status);
3449 		}
3450 
3451 		if (data->info->func[i] & PMBUS_HAVE_STATUS_VOUT) {
3452 			entries[idx].client = client;
3453 			entries[idx].page = i;
3454 			entries[idx].reg = PMBUS_STATUS_VOUT;
3455 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_vout", i);
3456 			debugfs_create_file(name, 0444, data->debugfs,
3457 					    &entries[idx++],
3458 					    &pmbus_debugfs_ops);
3459 		}
3460 
3461 		if (data->info->func[i] & PMBUS_HAVE_STATUS_IOUT) {
3462 			entries[idx].client = client;
3463 			entries[idx].page = i;
3464 			entries[idx].reg = PMBUS_STATUS_IOUT;
3465 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_iout", i);
3466 			debugfs_create_file(name, 0444, data->debugfs,
3467 					    &entries[idx++],
3468 					    &pmbus_debugfs_ops);
3469 		}
3470 
3471 		if (data->info->func[i] & PMBUS_HAVE_STATUS_INPUT) {
3472 			entries[idx].client = client;
3473 			entries[idx].page = i;
3474 			entries[idx].reg = PMBUS_STATUS_INPUT;
3475 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_input", i);
3476 			debugfs_create_file(name, 0444, data->debugfs,
3477 					    &entries[idx++],
3478 					    &pmbus_debugfs_ops);
3479 		}
3480 
3481 		if (data->info->func[i] & PMBUS_HAVE_STATUS_TEMP) {
3482 			entries[idx].client = client;
3483 			entries[idx].page = i;
3484 			entries[idx].reg = PMBUS_STATUS_TEMPERATURE;
3485 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_temp", i);
3486 			debugfs_create_file(name, 0444, data->debugfs,
3487 					    &entries[idx++],
3488 					    &pmbus_debugfs_ops);
3489 		}
3490 
3491 		if (pmbus_check_byte_register(client, i, PMBUS_STATUS_CML)) {
3492 			entries[idx].client = client;
3493 			entries[idx].page = i;
3494 			entries[idx].reg = PMBUS_STATUS_CML;
3495 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_cml", i);
3496 			debugfs_create_file(name, 0444, data->debugfs,
3497 					    &entries[idx++],
3498 					    &pmbus_debugfs_ops);
3499 		}
3500 
3501 		if (pmbus_check_byte_register(client, i, PMBUS_STATUS_OTHER)) {
3502 			entries[idx].client = client;
3503 			entries[idx].page = i;
3504 			entries[idx].reg = PMBUS_STATUS_OTHER;
3505 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_other", i);
3506 			debugfs_create_file(name, 0444, data->debugfs,
3507 					    &entries[idx++],
3508 					    &pmbus_debugfs_ops);
3509 		}
3510 
3511 		if (pmbus_check_byte_register(client, i,
3512 					      PMBUS_STATUS_MFR_SPECIFIC)) {
3513 			entries[idx].client = client;
3514 			entries[idx].page = i;
3515 			entries[idx].reg = PMBUS_STATUS_MFR_SPECIFIC;
3516 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_mfr", i);
3517 			debugfs_create_file(name, 0444, data->debugfs,
3518 					    &entries[idx++],
3519 					    &pmbus_debugfs_ops);
3520 		}
3521 
3522 		if (data->info->func[i] & PMBUS_HAVE_STATUS_FAN12) {
3523 			entries[idx].client = client;
3524 			entries[idx].page = i;
3525 			entries[idx].reg = PMBUS_STATUS_FAN_12;
3526 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_fan12", i);
3527 			debugfs_create_file(name, 0444, data->debugfs,
3528 					    &entries[idx++],
3529 					    &pmbus_debugfs_ops);
3530 		}
3531 
3532 		if (data->info->func[i] & PMBUS_HAVE_STATUS_FAN34) {
3533 			entries[idx].client = client;
3534 			entries[idx].page = i;
3535 			entries[idx].reg = PMBUS_STATUS_FAN_34;
3536 			scnprintf(name, PMBUS_NAME_SIZE, "status%d_fan34", i);
3537 			debugfs_create_file(name, 0444, data->debugfs,
3538 					    &entries[idx++],
3539 					    &pmbus_debugfs_ops);
3540 		}
3541 	}
3542 
3543 	return devm_add_action_or_reset(data->dev,
3544 					pmbus_remove_debugfs, data->debugfs);
3545 }
3546 #else
3547 static int pmbus_init_debugfs(struct i2c_client *client,
3548 			      struct pmbus_data *data)
3549 {
3550 	return 0;
3551 }
3552 #endif	/* IS_ENABLED(CONFIG_DEBUG_FS) */
3553 
3554 int pmbus_do_probe(struct i2c_client *client, struct pmbus_driver_info *info)
3555 {
3556 	struct device *dev = &client->dev;
3557 	const struct pmbus_platform_data *pdata = dev_get_platdata(dev);
3558 	struct pmbus_data *data;
3559 	size_t groups_num = 0;
3560 	int ret;
3561 	int i;
3562 	char *name;
3563 
3564 	if (!info)
3565 		return -ENODEV;
3566 
3567 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_WRITE_BYTE
3568 				     | I2C_FUNC_SMBUS_BYTE_DATA
3569 				     | I2C_FUNC_SMBUS_WORD_DATA))
3570 		return -ENODEV;
3571 
3572 	data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL);
3573 	if (!data)
3574 		return -ENOMEM;
3575 
3576 	if (info->groups)
3577 		while (info->groups[groups_num])
3578 			groups_num++;
3579 
3580 	data->groups = devm_kcalloc(dev, groups_num + 2, sizeof(void *),
3581 				    GFP_KERNEL);
3582 	if (!data->groups)
3583 		return -ENOMEM;
3584 
3585 	i2c_set_clientdata(client, data);
3586 	mutex_init(&data->update_lock);
3587 	data->dev = dev;
3588 
3589 	if (pdata)
3590 		data->flags = pdata->flags;
3591 	data->info = info;
3592 	data->currpage = -1;
3593 	data->currphase = -1;
3594 
3595 	for (i = 0; i < ARRAY_SIZE(data->vout_low); i++) {
3596 		data->vout_low[i] = -1;
3597 		data->vout_high[i] = -1;
3598 	}
3599 
3600 	ret = pmbus_init_common(client, data, info);
3601 	if (ret < 0)
3602 		return ret;
3603 
3604 	ret = pmbus_find_attributes(client, data);
3605 	if (ret)
3606 		return ret;
3607 
3608 	/*
3609 	 * If there are no attributes, something is wrong.
3610 	 * Bail out instead of trying to register nothing.
3611 	 */
3612 	if (!data->num_attributes) {
3613 		dev_err(dev, "No attributes found\n");
3614 		return -ENODEV;
3615 	}
3616 
3617 	name = devm_kstrdup(dev, client->name, GFP_KERNEL);
3618 	if (!name)
3619 		return -ENOMEM;
3620 	strreplace(name, '-', '_');
3621 
3622 	data->groups[0] = &data->group;
3623 	memcpy(data->groups + 1, info->groups, sizeof(void *) * groups_num);
3624 	data->hwmon_dev = devm_hwmon_device_register_with_groups(dev,
3625 					name, data, data->groups);
3626 	if (IS_ERR(data->hwmon_dev)) {
3627 		dev_err(dev, "Failed to register hwmon device\n");
3628 		return PTR_ERR(data->hwmon_dev);
3629 	}
3630 
3631 	ret = pmbus_regulator_register(data);
3632 	if (ret)
3633 		return ret;
3634 
3635 	ret = pmbus_irq_setup(client, data);
3636 	if (ret)
3637 		return ret;
3638 
3639 	ret = pmbus_init_debugfs(client, data);
3640 	if (ret)
3641 		dev_warn(dev, "Failed to register debugfs\n");
3642 
3643 	return 0;
3644 }
3645 EXPORT_SYMBOL_NS_GPL(pmbus_do_probe, PMBUS);
3646 
3647 struct dentry *pmbus_get_debugfs_dir(struct i2c_client *client)
3648 {
3649 	struct pmbus_data *data = i2c_get_clientdata(client);
3650 
3651 	return data->debugfs;
3652 }
3653 EXPORT_SYMBOL_NS_GPL(pmbus_get_debugfs_dir, PMBUS);
3654 
3655 int pmbus_lock_interruptible(struct i2c_client *client)
3656 {
3657 	struct pmbus_data *data = i2c_get_clientdata(client);
3658 
3659 	return mutex_lock_interruptible(&data->update_lock);
3660 }
3661 EXPORT_SYMBOL_NS_GPL(pmbus_lock_interruptible, PMBUS);
3662 
3663 void pmbus_unlock(struct i2c_client *client)
3664 {
3665 	struct pmbus_data *data = i2c_get_clientdata(client);
3666 
3667 	mutex_unlock(&data->update_lock);
3668 }
3669 EXPORT_SYMBOL_NS_GPL(pmbus_unlock, PMBUS);
3670 
3671 static int __init pmbus_core_init(void)
3672 {
3673 	pmbus_debugfs_dir = debugfs_create_dir("pmbus", NULL);
3674 	if (IS_ERR(pmbus_debugfs_dir))
3675 		pmbus_debugfs_dir = NULL;
3676 
3677 	return 0;
3678 }
3679 
3680 static void __exit pmbus_core_exit(void)
3681 {
3682 	debugfs_remove_recursive(pmbus_debugfs_dir);
3683 }
3684 
3685 module_init(pmbus_core_init);
3686 module_exit(pmbus_core_exit);
3687 
3688 MODULE_AUTHOR("Guenter Roeck");
3689 MODULE_DESCRIPTION("PMBus core driver");
3690 MODULE_LICENSE("GPL");
3691