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