xref: /linux/drivers/power/supply/power_supply_core.c (revision 205a7309cccd34ad49c2b6b1b59b907c12395d6c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  Universal power supply monitor class
4  *
5  *  Copyright © 2007  Anton Vorontsov <cbou@mail.ru>
6  *  Copyright © 2004  Szabolcs Gyurko
7  *  Copyright © 2003  Ian Molton <spyro@f2s.com>
8  *
9  *  Modified: 2004, Oct     Szabolcs Gyurko
10  */
11 
12 #include <linux/cleanup.h>
13 #include <linux/module.h>
14 #include <linux/types.h>
15 #include <linux/init.h>
16 #include <linux/slab.h>
17 #include <linux/delay.h>
18 #include <linux/device.h>
19 #include <linux/notifier.h>
20 #include <linux/err.h>
21 #include <linux/of.h>
22 #include <linux/power_supply.h>
23 #include <linux/property.h>
24 #include <linux/thermal.h>
25 #include <linux/fixp-arith.h>
26 #include "power_supply.h"
27 #include "samsung-sdi-battery.h"
28 
29 static const struct class power_supply_class = {
30 	.name = "power_supply",
31 	.dev_uevent = power_supply_uevent,
32 };
33 
34 static BLOCKING_NOTIFIER_HEAD(power_supply_notifier);
35 
36 static const struct device_type power_supply_dev_type = {
37 	.name = "power_supply",
38 	.groups = power_supply_attr_groups,
39 };
40 
41 #define POWER_SUPPLY_DEFERRED_REGISTER_TIME	msecs_to_jiffies(10)
42 
43 static bool __power_supply_is_supplied_by(struct power_supply *supplier,
44 					 struct power_supply *supply)
45 {
46 	int i;
47 
48 	if (!supply->supplied_from && !supplier->supplied_to)
49 		return false;
50 
51 	/* Support both supplied_to and supplied_from modes */
52 	if (supply->supplied_from) {
53 		if (!supplier->desc->name)
54 			return false;
55 		for (i = 0; i < supply->num_supplies; i++)
56 			if (!strcmp(supplier->desc->name, supply->supplied_from[i]))
57 				return true;
58 	} else {
59 		if (!supply->desc->name)
60 			return false;
61 		for (i = 0; i < supplier->num_supplicants; i++)
62 			if (!strcmp(supplier->supplied_to[i], supply->desc->name))
63 				return true;
64 	}
65 
66 	return false;
67 }
68 
69 static int __power_supply_changed_work(struct power_supply *pst, void *data)
70 {
71 	struct power_supply *psy = data;
72 
73 	if (__power_supply_is_supplied_by(psy, pst))
74 		power_supply_external_power_changed(pst);
75 
76 	return 0;
77 }
78 
79 static void power_supply_changed_work(struct work_struct *work)
80 {
81 	int ret;
82 	unsigned long flags;
83 	struct power_supply *psy = container_of(work, struct power_supply,
84 						changed_work);
85 
86 	dev_dbg(&psy->dev, "%s\n", __func__);
87 
88 	spin_lock_irqsave(&psy->changed_lock, flags);
89 
90 	if (unlikely(psy->update_groups)) {
91 		psy->update_groups = false;
92 		spin_unlock_irqrestore(&psy->changed_lock, flags);
93 		ret = sysfs_update_groups(&psy->dev.kobj, power_supply_dev_type.groups);
94 		if (ret)
95 			dev_warn(&psy->dev, "failed to update sysfs groups: %pe\n", ERR_PTR(ret));
96 		spin_lock_irqsave(&psy->changed_lock, flags);
97 	}
98 
99 	/*
100 	 * Check 'changed' here to avoid issues due to race between
101 	 * power_supply_changed() and this routine. In worst case
102 	 * power_supply_changed() can be called again just before we take above
103 	 * lock. During the first call of this routine we will mark 'changed' as
104 	 * false and it will stay false for the next call as well.
105 	 */
106 	if (likely(psy->changed)) {
107 		psy->changed = false;
108 		spin_unlock_irqrestore(&psy->changed_lock, flags);
109 		power_supply_for_each_psy(psy, __power_supply_changed_work);
110 		power_supply_update_leds(psy);
111 		blocking_notifier_call_chain(&power_supply_notifier,
112 				PSY_EVENT_PROP_CHANGED, psy);
113 		kobject_uevent(&psy->dev.kobj, KOBJ_CHANGE);
114 		spin_lock_irqsave(&psy->changed_lock, flags);
115 	}
116 
117 	/*
118 	 * Hold the wakeup_source until all events are processed.
119 	 * power_supply_changed() might have called again and have set 'changed'
120 	 * to true.
121 	 */
122 	if (likely(!psy->changed))
123 		pm_relax(&psy->dev);
124 	spin_unlock_irqrestore(&psy->changed_lock, flags);
125 }
126 
127 struct psy_for_each_psy_cb_data {
128 	int (*fn)(struct power_supply *psy, void *data);
129 	void *data;
130 };
131 
132 static int psy_for_each_psy_cb(struct device *dev, void *data)
133 {
134 	struct psy_for_each_psy_cb_data *cb_data = data;
135 	struct power_supply *psy = dev_to_psy(dev);
136 
137 	return cb_data->fn(psy, cb_data->data);
138 }
139 
140 int power_supply_for_each_psy(void *data, int (*fn)(struct power_supply *psy, void *data))
141 {
142 	struct psy_for_each_psy_cb_data cb_data = {
143 		.fn = fn,
144 		.data = data,
145 	};
146 
147 	return class_for_each_device(&power_supply_class, NULL, &cb_data, psy_for_each_psy_cb);
148 }
149 EXPORT_SYMBOL_GPL(power_supply_for_each_psy);
150 
151 void power_supply_changed(struct power_supply *psy)
152 {
153 	unsigned long flags;
154 
155 	dev_dbg(&psy->dev, "%s\n", __func__);
156 
157 	spin_lock_irqsave(&psy->changed_lock, flags);
158 	psy->changed = true;
159 	pm_stay_awake(&psy->dev);
160 	spin_unlock_irqrestore(&psy->changed_lock, flags);
161 	schedule_work(&psy->changed_work);
162 }
163 EXPORT_SYMBOL_GPL(power_supply_changed);
164 
165 /*
166  * Notify that power supply was registered after parent finished the probing.
167  *
168  * Often power supply is registered from driver's probe function. However
169  * calling power_supply_changed() directly from power_supply_register()
170  * would lead to execution of get_property() function provided by the driver
171  * too early - before the probe ends.
172  *
173  * Avoid that by waiting on parent's mutex.
174  */
175 static void power_supply_deferred_register_work(struct work_struct *work)
176 {
177 	struct power_supply *psy = container_of(work, struct power_supply,
178 						deferred_register_work.work);
179 
180 	if (psy->dev.parent) {
181 		while (!device_trylock(psy->dev.parent)) {
182 			if (psy->removing)
183 				return;
184 			msleep(10);
185 		}
186 	}
187 
188 	power_supply_changed(psy);
189 
190 	if (psy->dev.parent)
191 		device_unlock(psy->dev.parent);
192 }
193 
194 #ifdef CONFIG_OF
195 static int __power_supply_populate_supplied_from(struct power_supply *epsy,
196 						 void *data)
197 {
198 	struct power_supply *psy = data;
199 	struct device_node *np;
200 	int i = 0;
201 
202 	do {
203 		np = of_parse_phandle(psy->dev.of_node, "power-supplies", i++);
204 		if (!np)
205 			break;
206 
207 		if (np == epsy->dev.of_node) {
208 			dev_dbg(&psy->dev, "%s: Found supply : %s\n",
209 				psy->desc->name, epsy->desc->name);
210 			psy->supplied_from[i-1] = (char *)epsy->desc->name;
211 			psy->num_supplies++;
212 			of_node_put(np);
213 			break;
214 		}
215 		of_node_put(np);
216 	} while (np);
217 
218 	return 0;
219 }
220 
221 static int power_supply_populate_supplied_from(struct power_supply *psy)
222 {
223 	int error;
224 
225 	error = power_supply_for_each_psy(psy, __power_supply_populate_supplied_from);
226 
227 	dev_dbg(&psy->dev, "%s %d\n", __func__, error);
228 
229 	return error;
230 }
231 
232 static int  __power_supply_find_supply_from_node(struct power_supply *epsy,
233 						 void *data)
234 {
235 	struct device_node *np = data;
236 
237 	/* returning non-zero breaks out of power_supply_for_each_psy loop */
238 	if (epsy->dev.of_node == np)
239 		return 1;
240 
241 	return 0;
242 }
243 
244 static int power_supply_find_supply_from_node(struct device_node *supply_node)
245 {
246 	int error;
247 
248 	/*
249 	 * power_supply_for_each_psy() either returns its own errors or values
250 	 * returned by __power_supply_find_supply_from_node().
251 	 *
252 	 * __power_supply_find_supply_from_node() will return 0 (no match)
253 	 * or 1 (match).
254 	 *
255 	 * We return 0 if power_supply_for_each_psy() returned 1, -EPROBE_DEFER if
256 	 * it returned 0, or error as returned by it.
257 	 */
258 	error = power_supply_for_each_psy(supply_node, __power_supply_find_supply_from_node);
259 
260 	return error ? (error == 1 ? 0 : error) : -EPROBE_DEFER;
261 }
262 
263 static int power_supply_check_supplies(struct power_supply *psy)
264 {
265 	struct device_node *np;
266 	int cnt = 0;
267 
268 	/* If there is already a list honor it */
269 	if (psy->supplied_from && psy->num_supplies > 0)
270 		return 0;
271 
272 	/* No device node found, nothing to do */
273 	if (!psy->dev.of_node)
274 		return 0;
275 
276 	do {
277 		int ret;
278 
279 		np = of_parse_phandle(psy->dev.of_node, "power-supplies", cnt++);
280 		if (!np)
281 			break;
282 
283 		ret = power_supply_find_supply_from_node(np);
284 		of_node_put(np);
285 
286 		if (ret) {
287 			dev_dbg(&psy->dev, "Failed to find supply!\n");
288 			return ret;
289 		}
290 	} while (np);
291 
292 	/* Missing valid "power-supplies" entries */
293 	if (cnt == 1)
294 		return 0;
295 
296 	/* All supplies found, allocate char ** array for filling */
297 	psy->supplied_from = devm_kzalloc(&psy->dev, sizeof(*psy->supplied_from),
298 					  GFP_KERNEL);
299 	if (!psy->supplied_from)
300 		return -ENOMEM;
301 
302 	*psy->supplied_from = devm_kcalloc(&psy->dev,
303 					   cnt - 1, sizeof(**psy->supplied_from),
304 					   GFP_KERNEL);
305 	if (!*psy->supplied_from)
306 		return -ENOMEM;
307 
308 	return power_supply_populate_supplied_from(psy);
309 }
310 #else
311 static int power_supply_check_supplies(struct power_supply *psy)
312 {
313 	int nval, ret;
314 
315 	if (!psy->dev.parent)
316 		return 0;
317 
318 	nval = device_property_string_array_count(psy->dev.parent, "supplied-from");
319 	if (nval <= 0)
320 		return 0;
321 
322 	psy->supplied_from = devm_kmalloc_array(&psy->dev, nval,
323 						sizeof(char *), GFP_KERNEL);
324 	if (!psy->supplied_from)
325 		return -ENOMEM;
326 
327 	ret = device_property_read_string_array(psy->dev.parent,
328 		"supplied-from", (const char **)psy->supplied_from, nval);
329 	if (ret < 0)
330 		return ret;
331 
332 	psy->num_supplies = nval;
333 
334 	return 0;
335 }
336 #endif
337 
338 struct psy_am_i_supplied_data {
339 	struct power_supply *psy;
340 	unsigned int count;
341 };
342 
343 static int __power_supply_am_i_supplied(struct power_supply *epsy, void *_data)
344 {
345 	union power_supply_propval ret = {0,};
346 	struct psy_am_i_supplied_data *data = _data;
347 
348 	if (__power_supply_is_supplied_by(epsy, data->psy)) {
349 		data->count++;
350 		if (!epsy->desc->get_property(epsy, POWER_SUPPLY_PROP_ONLINE,
351 					&ret))
352 			return ret.intval;
353 	}
354 
355 	return 0;
356 }
357 
358 int power_supply_am_i_supplied(struct power_supply *psy)
359 {
360 	struct psy_am_i_supplied_data data = { psy, 0 };
361 	int error;
362 
363 	error = power_supply_for_each_psy(&data, __power_supply_am_i_supplied);
364 
365 	dev_dbg(&psy->dev, "%s count %u err %d\n", __func__, data.count, error);
366 
367 	if (data.count == 0)
368 		return -ENODEV;
369 
370 	return error;
371 }
372 EXPORT_SYMBOL_GPL(power_supply_am_i_supplied);
373 
374 static int __power_supply_is_system_supplied(struct power_supply *psy, void *data)
375 {
376 	union power_supply_propval ret = {0,};
377 	unsigned int *count = data;
378 
379 	if (!psy->desc->get_property(psy, POWER_SUPPLY_PROP_SCOPE, &ret))
380 		if (ret.intval == POWER_SUPPLY_SCOPE_DEVICE)
381 			return 0;
382 
383 	(*count)++;
384 	if (psy->desc->type != POWER_SUPPLY_TYPE_BATTERY)
385 		if (!psy->desc->get_property(psy, POWER_SUPPLY_PROP_ONLINE,
386 					&ret))
387 			return ret.intval;
388 
389 	return 0;
390 }
391 
392 int power_supply_is_system_supplied(void)
393 {
394 	int error;
395 	unsigned int count = 0;
396 
397 	error = power_supply_for_each_psy(&count, __power_supply_is_system_supplied);
398 
399 	/*
400 	 * If no system scope power class device was found at all, most probably we
401 	 * are running on a desktop system, so assume we are on mains power.
402 	 */
403 	if (count == 0)
404 		return 1;
405 
406 	return error;
407 }
408 EXPORT_SYMBOL_GPL(power_supply_is_system_supplied);
409 
410 struct psy_get_supplier_prop_data {
411 	struct power_supply *psy;
412 	enum power_supply_property psp;
413 	union power_supply_propval *val;
414 };
415 
416 static int __power_supply_get_supplier_property(struct power_supply *epsy, void *_data)
417 {
418 	struct psy_get_supplier_prop_data *data = _data;
419 
420 	if (__power_supply_is_supplied_by(epsy, data->psy))
421 		if (!power_supply_get_property(epsy, data->psp, data->val))
422 			return 1; /* Success */
423 
424 	return 0; /* Continue iterating */
425 }
426 
427 int power_supply_get_property_from_supplier(struct power_supply *psy,
428 					    enum power_supply_property psp,
429 					    union power_supply_propval *val)
430 {
431 	struct psy_get_supplier_prop_data data = {
432 		.psy = psy,
433 		.psp = psp,
434 		.val = val,
435 	};
436 	int ret;
437 
438 	/*
439 	 * This function is not intended for use with a supply with multiple
440 	 * suppliers, we simply pick the first supply to report the psp.
441 	 */
442 	ret = power_supply_for_each_psy(&data, __power_supply_get_supplier_property);
443 	if (ret < 0)
444 		return ret;
445 	if (ret == 0)
446 		return -ENODEV;
447 
448 	return 0;
449 }
450 EXPORT_SYMBOL_GPL(power_supply_get_property_from_supplier);
451 
452 static int power_supply_match_device_by_name(struct device *dev, const void *data)
453 {
454 	const char *name = data;
455 	struct power_supply *psy = dev_to_psy(dev);
456 
457 	return strcmp(psy->desc->name, name) == 0;
458 }
459 
460 /**
461  * power_supply_get_by_name() - Search for a power supply and returns its ref
462  * @name: Power supply name to fetch
463  *
464  * If power supply was found, it increases reference count for the
465  * internal power supply's device. The user should power_supply_put()
466  * after usage.
467  *
468  * Return: On success returns a reference to a power supply with
469  * matching name equals to @name, a NULL otherwise.
470  */
471 struct power_supply *power_supply_get_by_name(const char *name)
472 {
473 	struct power_supply *psy = NULL;
474 	struct device *dev = class_find_device(&power_supply_class, NULL, name,
475 					       power_supply_match_device_by_name);
476 
477 	if (dev) {
478 		psy = dev_to_psy(dev);
479 		atomic_inc(&psy->use_cnt);
480 	}
481 
482 	return psy;
483 }
484 EXPORT_SYMBOL_GPL(power_supply_get_by_name);
485 
486 /**
487  * power_supply_put() - Drop reference obtained with power_supply_get_by_name
488  * @psy: Reference to put
489  *
490  * The reference to power supply should be put before unregistering
491  * the power supply.
492  */
493 void power_supply_put(struct power_supply *psy)
494 {
495 	atomic_dec(&psy->use_cnt);
496 	put_device(&psy->dev);
497 }
498 EXPORT_SYMBOL_GPL(power_supply_put);
499 
500 #ifdef CONFIG_OF
501 static int power_supply_match_device_node(struct device *dev, const void *data)
502 {
503 	return dev->parent && dev->parent->of_node == data;
504 }
505 
506 /**
507  * power_supply_get_by_phandle() - Search for a power supply and returns its ref
508  * @np: Pointer to device node holding phandle property
509  * @property: Name of property holding a power supply name
510  *
511  * If power supply was found, it increases reference count for the
512  * internal power supply's device. The user should power_supply_put()
513  * after usage.
514  *
515  * Return: On success returns a reference to a power supply with
516  * matching name equals to value under @property, NULL or ERR_PTR otherwise.
517  */
518 struct power_supply *power_supply_get_by_phandle(struct device_node *np,
519 							const char *property)
520 {
521 	struct device_node *power_supply_np;
522 	struct power_supply *psy = NULL;
523 	struct device *dev;
524 
525 	power_supply_np = of_parse_phandle(np, property, 0);
526 	if (!power_supply_np)
527 		return ERR_PTR(-ENODEV);
528 
529 	dev = class_find_device(&power_supply_class, NULL, power_supply_np,
530 				power_supply_match_device_node);
531 
532 	of_node_put(power_supply_np);
533 
534 	if (dev) {
535 		psy = dev_to_psy(dev);
536 		atomic_inc(&psy->use_cnt);
537 	}
538 
539 	return psy;
540 }
541 EXPORT_SYMBOL_GPL(power_supply_get_by_phandle);
542 
543 static void devm_power_supply_put(struct device *dev, void *res)
544 {
545 	struct power_supply **psy = res;
546 
547 	power_supply_put(*psy);
548 }
549 
550 /**
551  * devm_power_supply_get_by_phandle() - Resource managed version of
552  *  power_supply_get_by_phandle()
553  * @dev: Pointer to device holding phandle property
554  * @property: Name of property holding a power supply phandle
555  *
556  * Return: On success returns a reference to a power supply with
557  * matching name equals to value under @property, NULL or ERR_PTR otherwise.
558  */
559 struct power_supply *devm_power_supply_get_by_phandle(struct device *dev,
560 						      const char *property)
561 {
562 	struct power_supply **ptr, *psy;
563 
564 	if (!dev->of_node)
565 		return ERR_PTR(-ENODEV);
566 
567 	ptr = devres_alloc(devm_power_supply_put, sizeof(*ptr), GFP_KERNEL);
568 	if (!ptr)
569 		return ERR_PTR(-ENOMEM);
570 
571 	psy = power_supply_get_by_phandle(dev->of_node, property);
572 	if (IS_ERR_OR_NULL(psy)) {
573 		devres_free(ptr);
574 	} else {
575 		*ptr = psy;
576 		devres_add(dev, ptr);
577 	}
578 	return psy;
579 }
580 EXPORT_SYMBOL_GPL(devm_power_supply_get_by_phandle);
581 #endif /* CONFIG_OF */
582 
583 int power_supply_get_battery_info(struct power_supply *psy,
584 				  struct power_supply_battery_info **info_out)
585 {
586 	struct power_supply_resistance_temp_table *resist_table;
587 	struct power_supply_battery_info *info;
588 	struct device_node *battery_np = NULL;
589 	struct fwnode_reference_args args;
590 	struct fwnode_handle *fwnode = NULL;
591 	const char *value;
592 	int err, len, index;
593 	const __be32 *list;
594 	u32 min_max[2];
595 
596 	if (psy->dev.of_node) {
597 		battery_np = of_parse_phandle(psy->dev.of_node, "monitored-battery", 0);
598 		if (!battery_np)
599 			return -ENODEV;
600 
601 		fwnode = fwnode_handle_get(of_fwnode_handle(battery_np));
602 	} else if (psy->dev.parent) {
603 		err = fwnode_property_get_reference_args(
604 					dev_fwnode(psy->dev.parent),
605 					"monitored-battery", NULL, 0, 0, &args);
606 		if (err)
607 			return err;
608 
609 		fwnode = args.fwnode;
610 	}
611 
612 	if (!fwnode)
613 		return -ENOENT;
614 
615 	err = fwnode_property_read_string(fwnode, "compatible", &value);
616 	if (err)
617 		goto out_put_node;
618 
619 
620 	/* Try static batteries first */
621 	err = samsung_sdi_battery_get_info(&psy->dev, value, &info);
622 	if (!err)
623 		goto out_ret_pointer;
624 	else if (err == -ENODEV)
625 		/*
626 		 * Device does not have a static battery.
627 		 * Proceed to look for a simple battery.
628 		 */
629 		err = 0;
630 
631 	if (strcmp("simple-battery", value)) {
632 		err = -ENODEV;
633 		goto out_put_node;
634 	}
635 
636 	info = devm_kzalloc(&psy->dev, sizeof(*info), GFP_KERNEL);
637 	if (!info) {
638 		err = -ENOMEM;
639 		goto out_put_node;
640 	}
641 
642 	info->technology                     = POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
643 	info->energy_full_design_uwh         = -EINVAL;
644 	info->charge_full_design_uah         = -EINVAL;
645 	info->voltage_min_design_uv          = -EINVAL;
646 	info->voltage_max_design_uv          = -EINVAL;
647 	info->precharge_current_ua           = -EINVAL;
648 	info->charge_term_current_ua         = -EINVAL;
649 	info->constant_charge_current_max_ua = -EINVAL;
650 	info->constant_charge_voltage_max_uv = -EINVAL;
651 	info->tricklecharge_current_ua       = -EINVAL;
652 	info->precharge_voltage_max_uv       = -EINVAL;
653 	info->charge_restart_voltage_uv      = -EINVAL;
654 	info->overvoltage_limit_uv           = -EINVAL;
655 	info->maintenance_charge             = NULL;
656 	info->alert_low_temp_charge_current_ua = -EINVAL;
657 	info->alert_low_temp_charge_voltage_uv = -EINVAL;
658 	info->alert_high_temp_charge_current_ua = -EINVAL;
659 	info->alert_high_temp_charge_voltage_uv = -EINVAL;
660 	info->temp_ambient_alert_min         = INT_MIN;
661 	info->temp_ambient_alert_max         = INT_MAX;
662 	info->temp_alert_min                 = INT_MIN;
663 	info->temp_alert_max                 = INT_MAX;
664 	info->temp_min                       = INT_MIN;
665 	info->temp_max                       = INT_MAX;
666 	info->factory_internal_resistance_uohm  = -EINVAL;
667 	info->resist_table                   = NULL;
668 	info->bti_resistance_ohm             = -EINVAL;
669 	info->bti_resistance_tolerance       = -EINVAL;
670 
671 	for (index = 0; index < POWER_SUPPLY_OCV_TEMP_MAX; index++) {
672 		info->ocv_table[index]       = NULL;
673 		info->ocv_temp[index]        = -EINVAL;
674 		info->ocv_table_size[index]  = -EINVAL;
675 	}
676 
677 	/* The property and field names below must correspond to elements
678 	 * in enum power_supply_property. For reasoning, see
679 	 * Documentation/power/power_supply_class.rst.
680 	 */
681 
682 	if (!fwnode_property_read_string(fwnode, "device-chemistry", &value)) {
683 		if (!strcmp("nickel-cadmium", value))
684 			info->technology = POWER_SUPPLY_TECHNOLOGY_NiCd;
685 		else if (!strcmp("nickel-metal-hydride", value))
686 			info->technology = POWER_SUPPLY_TECHNOLOGY_NiMH;
687 		else if (!strcmp("lithium-ion", value))
688 			/* Imprecise lithium-ion type */
689 			info->technology = POWER_SUPPLY_TECHNOLOGY_LION;
690 		else if (!strcmp("lithium-ion-polymer", value))
691 			info->technology = POWER_SUPPLY_TECHNOLOGY_LIPO;
692 		else if (!strcmp("lithium-ion-iron-phosphate", value))
693 			info->technology = POWER_SUPPLY_TECHNOLOGY_LiFe;
694 		else if (!strcmp("lithium-ion-manganese-oxide", value))
695 			info->technology = POWER_SUPPLY_TECHNOLOGY_LiMn;
696 		else
697 			dev_warn(&psy->dev, "%s unknown battery type\n", value);
698 	}
699 
700 	fwnode_property_read_u32(fwnode, "energy-full-design-microwatt-hours",
701 			     &info->energy_full_design_uwh);
702 	fwnode_property_read_u32(fwnode, "charge-full-design-microamp-hours",
703 			     &info->charge_full_design_uah);
704 	fwnode_property_read_u32(fwnode, "voltage-min-design-microvolt",
705 			     &info->voltage_min_design_uv);
706 	fwnode_property_read_u32(fwnode, "voltage-max-design-microvolt",
707 			     &info->voltage_max_design_uv);
708 	fwnode_property_read_u32(fwnode, "trickle-charge-current-microamp",
709 			     &info->tricklecharge_current_ua);
710 	fwnode_property_read_u32(fwnode, "precharge-current-microamp",
711 			     &info->precharge_current_ua);
712 	fwnode_property_read_u32(fwnode, "precharge-upper-limit-microvolt",
713 			     &info->precharge_voltage_max_uv);
714 	fwnode_property_read_u32(fwnode, "charge-term-current-microamp",
715 			     &info->charge_term_current_ua);
716 	fwnode_property_read_u32(fwnode, "re-charge-voltage-microvolt",
717 			     &info->charge_restart_voltage_uv);
718 	fwnode_property_read_u32(fwnode, "over-voltage-threshold-microvolt",
719 			     &info->overvoltage_limit_uv);
720 	fwnode_property_read_u32(fwnode, "constant-charge-current-max-microamp",
721 			     &info->constant_charge_current_max_ua);
722 	fwnode_property_read_u32(fwnode, "constant-charge-voltage-max-microvolt",
723 			     &info->constant_charge_voltage_max_uv);
724 	fwnode_property_read_u32(fwnode, "factory-internal-resistance-micro-ohms",
725 			     &info->factory_internal_resistance_uohm);
726 
727 	if (!fwnode_property_read_u32_array(fwnode, "ambient-celsius",
728 					    min_max, ARRAY_SIZE(min_max))) {
729 		info->temp_ambient_alert_min = min_max[0];
730 		info->temp_ambient_alert_max = min_max[1];
731 	}
732 	if (!fwnode_property_read_u32_array(fwnode, "alert-celsius",
733 					    min_max, ARRAY_SIZE(min_max))) {
734 		info->temp_alert_min = min_max[0];
735 		info->temp_alert_max = min_max[1];
736 	}
737 	if (!fwnode_property_read_u32_array(fwnode, "operating-range-celsius",
738 					    min_max, ARRAY_SIZE(min_max))) {
739 		info->temp_min = min_max[0];
740 		info->temp_max = min_max[1];
741 	}
742 
743 	/*
744 	 * The below code uses raw of-data parsing to parse
745 	 * /schemas/types.yaml#/definitions/uint32-matrix
746 	 * data, so for now this is only support with of.
747 	 */
748 	if (!battery_np)
749 		goto out_ret_pointer;
750 
751 	len = of_property_count_u32_elems(battery_np, "ocv-capacity-celsius");
752 	if (len < 0 && len != -EINVAL) {
753 		err = len;
754 		goto out_put_node;
755 	} else if (len > POWER_SUPPLY_OCV_TEMP_MAX) {
756 		dev_err(&psy->dev, "Too many temperature values\n");
757 		err = -EINVAL;
758 		goto out_put_node;
759 	} else if (len > 0) {
760 		of_property_read_u32_array(battery_np, "ocv-capacity-celsius",
761 					   info->ocv_temp, len);
762 	}
763 
764 	for (index = 0; index < len; index++) {
765 		struct power_supply_battery_ocv_table *table;
766 		int i, tab_len, size;
767 
768 		char *propname __free(kfree) = kasprintf(GFP_KERNEL, "ocv-capacity-table-%d",
769 							 index);
770 		if (!propname) {
771 			power_supply_put_battery_info(psy, info);
772 			err = -ENOMEM;
773 			goto out_put_node;
774 		}
775 		list = of_get_property(battery_np, propname, &size);
776 		if (!list || !size) {
777 			dev_err(&psy->dev, "failed to get %s\n", propname);
778 			power_supply_put_battery_info(psy, info);
779 			err = -EINVAL;
780 			goto out_put_node;
781 		}
782 
783 		tab_len = size / (2 * sizeof(__be32));
784 		info->ocv_table_size[index] = tab_len;
785 
786 		info->ocv_table[index] = table =
787 			devm_kcalloc(&psy->dev, tab_len, sizeof(*table), GFP_KERNEL);
788 		if (!info->ocv_table[index]) {
789 			power_supply_put_battery_info(psy, info);
790 			err = -ENOMEM;
791 			goto out_put_node;
792 		}
793 
794 		for (i = 0; i < tab_len; i++) {
795 			table[i].ocv = be32_to_cpu(*list);
796 			list++;
797 			table[i].capacity = be32_to_cpu(*list);
798 			list++;
799 		}
800 	}
801 
802 	list = of_get_property(battery_np, "resistance-temp-table", &len);
803 	if (!list || !len)
804 		goto out_ret_pointer;
805 
806 	info->resist_table_size = len / (2 * sizeof(__be32));
807 	info->resist_table = resist_table = devm_kcalloc(&psy->dev,
808 							 info->resist_table_size,
809 							 sizeof(*resist_table),
810 							 GFP_KERNEL);
811 	if (!info->resist_table) {
812 		power_supply_put_battery_info(psy, info);
813 		err = -ENOMEM;
814 		goto out_put_node;
815 	}
816 
817 	for (index = 0; index < info->resist_table_size; index++) {
818 		resist_table[index].temp = be32_to_cpu(*list++);
819 		resist_table[index].resistance = be32_to_cpu(*list++);
820 	}
821 
822 out_ret_pointer:
823 	/* Finally return the whole thing */
824 	*info_out = info;
825 
826 out_put_node:
827 	fwnode_handle_put(fwnode);
828 	of_node_put(battery_np);
829 	return err;
830 }
831 EXPORT_SYMBOL_GPL(power_supply_get_battery_info);
832 
833 void power_supply_put_battery_info(struct power_supply *psy,
834 				   struct power_supply_battery_info *info)
835 {
836 	int i;
837 
838 	for (i = 0; i < POWER_SUPPLY_OCV_TEMP_MAX; i++) {
839 		if (info->ocv_table[i])
840 			devm_kfree(&psy->dev, info->ocv_table[i]);
841 	}
842 
843 	if (info->resist_table)
844 		devm_kfree(&psy->dev, info->resist_table);
845 
846 	devm_kfree(&psy->dev, info);
847 }
848 EXPORT_SYMBOL_GPL(power_supply_put_battery_info);
849 
850 const enum power_supply_property power_supply_battery_info_properties[] = {
851 	POWER_SUPPLY_PROP_TECHNOLOGY,
852 	POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
853 	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
854 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
855 	POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
856 	POWER_SUPPLY_PROP_PRECHARGE_CURRENT,
857 	POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT,
858 	POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX,
859 	POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX,
860 	POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN,
861 	POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX,
862 	POWER_SUPPLY_PROP_TEMP_ALERT_MIN,
863 	POWER_SUPPLY_PROP_TEMP_ALERT_MAX,
864 	POWER_SUPPLY_PROP_TEMP_MIN,
865 	POWER_SUPPLY_PROP_TEMP_MAX,
866 };
867 EXPORT_SYMBOL_GPL(power_supply_battery_info_properties);
868 
869 const size_t power_supply_battery_info_properties_size = ARRAY_SIZE(power_supply_battery_info_properties);
870 EXPORT_SYMBOL_GPL(power_supply_battery_info_properties_size);
871 
872 bool power_supply_battery_info_has_prop(struct power_supply_battery_info *info,
873 					enum power_supply_property psp)
874 {
875 	if (!info)
876 		return false;
877 
878 	switch (psp) {
879 	case POWER_SUPPLY_PROP_TECHNOLOGY:
880 		return info->technology != POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
881 	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
882 		return info->energy_full_design_uwh >= 0;
883 	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
884 		return info->charge_full_design_uah >= 0;
885 	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
886 		return info->voltage_min_design_uv >= 0;
887 	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
888 		return info->voltage_max_design_uv >= 0;
889 	case POWER_SUPPLY_PROP_PRECHARGE_CURRENT:
890 		return info->precharge_current_ua >= 0;
891 	case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT:
892 		return info->charge_term_current_ua >= 0;
893 	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
894 		return info->constant_charge_current_max_ua >= 0;
895 	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
896 		return info->constant_charge_voltage_max_uv >= 0;
897 	case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN:
898 		return info->temp_ambient_alert_min > INT_MIN;
899 	case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX:
900 		return info->temp_ambient_alert_max < INT_MAX;
901 	case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
902 		return info->temp_alert_min > INT_MIN;
903 	case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
904 		return info->temp_alert_max < INT_MAX;
905 	case POWER_SUPPLY_PROP_TEMP_MIN:
906 		return info->temp_min > INT_MIN;
907 	case POWER_SUPPLY_PROP_TEMP_MAX:
908 		return info->temp_max < INT_MAX;
909 	default:
910 		return false;
911 	}
912 }
913 EXPORT_SYMBOL_GPL(power_supply_battery_info_has_prop);
914 
915 int power_supply_battery_info_get_prop(struct power_supply_battery_info *info,
916 				       enum power_supply_property psp,
917 				       union power_supply_propval *val)
918 {
919 	if (!info)
920 		return -EINVAL;
921 
922 	if (!power_supply_battery_info_has_prop(info, psp))
923 		return -EINVAL;
924 
925 	switch (psp) {
926 	case POWER_SUPPLY_PROP_TECHNOLOGY:
927 		val->intval = info->technology;
928 		return 0;
929 	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
930 		val->intval = info->energy_full_design_uwh;
931 		return 0;
932 	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
933 		val->intval = info->charge_full_design_uah;
934 		return 0;
935 	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
936 		val->intval = info->voltage_min_design_uv;
937 		return 0;
938 	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
939 		val->intval = info->voltage_max_design_uv;
940 		return 0;
941 	case POWER_SUPPLY_PROP_PRECHARGE_CURRENT:
942 		val->intval = info->precharge_current_ua;
943 		return 0;
944 	case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT:
945 		val->intval = info->charge_term_current_ua;
946 		return 0;
947 	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
948 		val->intval = info->constant_charge_current_max_ua;
949 		return 0;
950 	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
951 		val->intval = info->constant_charge_voltage_max_uv;
952 		return 0;
953 	case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN:
954 		val->intval = info->temp_ambient_alert_min;
955 		return 0;
956 	case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX:
957 		val->intval = info->temp_ambient_alert_max;
958 		return 0;
959 	case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
960 		val->intval = info->temp_alert_min;
961 		return 0;
962 	case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
963 		val->intval = info->temp_alert_max;
964 		return 0;
965 	case POWER_SUPPLY_PROP_TEMP_MIN:
966 		val->intval = info->temp_min;
967 		return 0;
968 	case POWER_SUPPLY_PROP_TEMP_MAX:
969 		val->intval = info->temp_max;
970 		return 0;
971 	default:
972 		return -EINVAL;
973 	}
974 }
975 EXPORT_SYMBOL_GPL(power_supply_battery_info_get_prop);
976 
977 /**
978  * power_supply_temp2resist_simple() - find the battery internal resistance
979  * percent from temperature
980  * @table: Pointer to battery resistance temperature table
981  * @table_len: The table length
982  * @temp: Current temperature
983  *
984  * This helper function is used to look up battery internal resistance percent
985  * according to current temperature value from the resistance temperature table,
986  * and the table must be ordered descending. Then the actual battery internal
987  * resistance = the ideal battery internal resistance * percent / 100.
988  *
989  * Return: the battery internal resistance percent
990  */
991 int power_supply_temp2resist_simple(const struct power_supply_resistance_temp_table *table,
992 				    int table_len, int temp)
993 {
994 	int i, high, low;
995 
996 	for (i = 0; i < table_len; i++)
997 		if (temp > table[i].temp)
998 			break;
999 
1000 	/* The library function will deal with high == low */
1001 	if (i == 0)
1002 		high = low = i;
1003 	else if (i == table_len)
1004 		high = low = i - 1;
1005 	else
1006 		high = (low = i) - 1;
1007 
1008 	return fixp_linear_interpolate(table[low].temp,
1009 				       table[low].resistance,
1010 				       table[high].temp,
1011 				       table[high].resistance,
1012 				       temp);
1013 }
1014 EXPORT_SYMBOL_GPL(power_supply_temp2resist_simple);
1015 
1016 /**
1017  * power_supply_vbat2ri() - find the battery internal resistance
1018  * from the battery voltage
1019  * @info: The battery information container
1020  * @vbat_uv: The battery voltage in microvolt
1021  * @charging: If we are charging (true) or not (false)
1022  *
1023  * This helper function is used to look up battery internal resistance
1024  * according to current battery voltage. Depending on whether the battery
1025  * is currently charging or not, different resistance will be returned.
1026  *
1027  * Returns the internal resistance in microohm or negative error code.
1028  */
1029 int power_supply_vbat2ri(struct power_supply_battery_info *info,
1030 			 int vbat_uv, bool charging)
1031 {
1032 	const struct power_supply_vbat_ri_table *vbat2ri;
1033 	int table_len;
1034 	int i, high, low;
1035 
1036 	/*
1037 	 * If we are charging, and the battery supplies a separate table
1038 	 * for this state, we use that in order to compensate for the
1039 	 * charging voltage. Otherwise we use the main table.
1040 	 */
1041 	if (charging && info->vbat2ri_charging) {
1042 		vbat2ri = info->vbat2ri_charging;
1043 		table_len = info->vbat2ri_charging_size;
1044 	} else {
1045 		vbat2ri = info->vbat2ri_discharging;
1046 		table_len = info->vbat2ri_discharging_size;
1047 	}
1048 
1049 	/*
1050 	 * If no tables are specified, or if we are above the highest voltage in
1051 	 * the voltage table, just return the factory specified internal resistance.
1052 	 */
1053 	if (!vbat2ri || (table_len <= 0) || (vbat_uv > vbat2ri[0].vbat_uv)) {
1054 		if (charging && (info->factory_internal_resistance_charging_uohm > 0))
1055 			return info->factory_internal_resistance_charging_uohm;
1056 		else
1057 			return info->factory_internal_resistance_uohm;
1058 	}
1059 
1060 	/* Break loop at table_len - 1 because that is the highest index */
1061 	for (i = 0; i < table_len - 1; i++)
1062 		if (vbat_uv > vbat2ri[i].vbat_uv)
1063 			break;
1064 
1065 	/* The library function will deal with high == low */
1066 	if ((i == 0) || (i == (table_len - 1)))
1067 		high = i;
1068 	else
1069 		high = i - 1;
1070 	low = i;
1071 
1072 	return fixp_linear_interpolate(vbat2ri[low].vbat_uv,
1073 				       vbat2ri[low].ri_uohm,
1074 				       vbat2ri[high].vbat_uv,
1075 				       vbat2ri[high].ri_uohm,
1076 				       vbat_uv);
1077 }
1078 EXPORT_SYMBOL_GPL(power_supply_vbat2ri);
1079 
1080 const struct power_supply_maintenance_charge_table *
1081 power_supply_get_maintenance_charging_setting(struct power_supply_battery_info *info,
1082 					      int index)
1083 {
1084 	if (index >= info->maintenance_charge_size)
1085 		return NULL;
1086 	return &info->maintenance_charge[index];
1087 }
1088 EXPORT_SYMBOL_GPL(power_supply_get_maintenance_charging_setting);
1089 
1090 /**
1091  * power_supply_ocv2cap_simple() - find the battery capacity
1092  * @table: Pointer to battery OCV lookup table
1093  * @table_len: OCV table length
1094  * @ocv: Current OCV value
1095  *
1096  * This helper function is used to look up battery capacity according to
1097  * current OCV value from one OCV table, and the OCV table must be ordered
1098  * descending.
1099  *
1100  * Return: the battery capacity.
1101  */
1102 int power_supply_ocv2cap_simple(const struct power_supply_battery_ocv_table *table,
1103 				int table_len, int ocv)
1104 {
1105 	int i, high, low;
1106 
1107 	for (i = 0; i < table_len; i++)
1108 		if (ocv > table[i].ocv)
1109 			break;
1110 
1111 	/* The library function will deal with high == low */
1112 	if (i == 0)
1113 		high = low = i;
1114 	else if (i == table_len)
1115 		high = low = i - 1;
1116 	else
1117 		high = (low = i) - 1;
1118 
1119 	return fixp_linear_interpolate(table[low].ocv,
1120 				       table[low].capacity,
1121 				       table[high].ocv,
1122 				       table[high].capacity,
1123 				       ocv);
1124 }
1125 EXPORT_SYMBOL_GPL(power_supply_ocv2cap_simple);
1126 
1127 const struct power_supply_battery_ocv_table *
1128 power_supply_find_ocv2cap_table(struct power_supply_battery_info *info,
1129 				int temp, int *table_len)
1130 {
1131 	int best_temp_diff = INT_MAX, temp_diff;
1132 	u8 i, best_index = 0;
1133 
1134 	if (!info->ocv_table[0])
1135 		return NULL;
1136 
1137 	for (i = 0; i < POWER_SUPPLY_OCV_TEMP_MAX; i++) {
1138 		/* Out of capacity tables */
1139 		if (!info->ocv_table[i])
1140 			break;
1141 
1142 		temp_diff = abs(info->ocv_temp[i] - temp);
1143 
1144 		if (temp_diff < best_temp_diff) {
1145 			best_temp_diff = temp_diff;
1146 			best_index = i;
1147 		}
1148 	}
1149 
1150 	*table_len = info->ocv_table_size[best_index];
1151 	return info->ocv_table[best_index];
1152 }
1153 EXPORT_SYMBOL_GPL(power_supply_find_ocv2cap_table);
1154 
1155 int power_supply_batinfo_ocv2cap(struct power_supply_battery_info *info,
1156 				 int ocv, int temp)
1157 {
1158 	const struct power_supply_battery_ocv_table *table;
1159 	int table_len;
1160 
1161 	table = power_supply_find_ocv2cap_table(info, temp, &table_len);
1162 	if (!table)
1163 		return -EINVAL;
1164 
1165 	return power_supply_ocv2cap_simple(table, table_len, ocv);
1166 }
1167 EXPORT_SYMBOL_GPL(power_supply_batinfo_ocv2cap);
1168 
1169 bool power_supply_battery_bti_in_range(struct power_supply_battery_info *info,
1170 				       int resistance)
1171 {
1172 	int low, high;
1173 
1174 	/* Nothing like this can be checked */
1175 	if (info->bti_resistance_ohm <= 0)
1176 		return false;
1177 
1178 	/* This will be extremely strict and unlikely to work */
1179 	if (info->bti_resistance_tolerance <= 0)
1180 		return (info->bti_resistance_ohm == resistance);
1181 
1182 	low = info->bti_resistance_ohm -
1183 		(info->bti_resistance_ohm * info->bti_resistance_tolerance) / 100;
1184 	high = info->bti_resistance_ohm +
1185 		(info->bti_resistance_ohm * info->bti_resistance_tolerance) / 100;
1186 
1187 	return ((resistance >= low) && (resistance <= high));
1188 }
1189 EXPORT_SYMBOL_GPL(power_supply_battery_bti_in_range);
1190 
1191 static bool psy_desc_has_property(const struct power_supply_desc *psy_desc,
1192 				  enum power_supply_property psp)
1193 {
1194 	bool found = false;
1195 	int i;
1196 
1197 	for (i = 0; i < psy_desc->num_properties; i++) {
1198 		if (psy_desc->properties[i] == psp) {
1199 			found = true;
1200 			break;
1201 		}
1202 	}
1203 
1204 	return found;
1205 }
1206 
1207 bool power_supply_ext_has_property(const struct power_supply_ext *psy_ext,
1208 				   enum power_supply_property psp)
1209 {
1210 	int i;
1211 
1212 	for (i = 0; i < psy_ext->num_properties; i++)
1213 		if (psy_ext->properties[i] == psp)
1214 			return true;
1215 
1216 	return false;
1217 }
1218 
1219 bool power_supply_has_property(struct power_supply *psy,
1220 			       enum power_supply_property psp)
1221 {
1222 	struct power_supply_ext_registration *reg;
1223 
1224 	if (psy_desc_has_property(psy->desc, psp))
1225 		return true;
1226 
1227 	if (power_supply_battery_info_has_prop(psy->battery_info, psp))
1228 		return true;
1229 
1230 	power_supply_for_each_extension(reg, psy) {
1231 		if (power_supply_ext_has_property(reg->ext, psp))
1232 			return true;
1233 	}
1234 
1235 	return false;
1236 }
1237 
1238 static int __power_supply_get_property(struct power_supply *psy, enum power_supply_property psp,
1239 				       union power_supply_propval *val, bool use_extensions)
1240 {
1241 	struct power_supply_ext_registration *reg;
1242 
1243 	if (atomic_read(&psy->use_cnt) <= 0) {
1244 		if (!psy->initialized)
1245 			return -EAGAIN;
1246 		return -ENODEV;
1247 	}
1248 
1249 	if (use_extensions) {
1250 		scoped_guard(rwsem_read, &psy->extensions_sem) {
1251 			power_supply_for_each_extension(reg, psy) {
1252 				if (!power_supply_ext_has_property(reg->ext, psp))
1253 					continue;
1254 
1255 				return reg->ext->get_property(psy, reg->ext, reg->data, psp, val);
1256 			}
1257 		}
1258 	}
1259 
1260 	if (psy_desc_has_property(psy->desc, psp))
1261 		return psy->desc->get_property(psy, psp, val);
1262 	else if (power_supply_battery_info_has_prop(psy->battery_info, psp))
1263 		return power_supply_battery_info_get_prop(psy->battery_info, psp, val);
1264 	else
1265 		return -EINVAL;
1266 }
1267 
1268 int power_supply_get_property(struct power_supply *psy, enum power_supply_property psp,
1269 			      union power_supply_propval *val)
1270 {
1271 	return __power_supply_get_property(psy, psp, val, true);
1272 }
1273 EXPORT_SYMBOL_GPL(power_supply_get_property);
1274 
1275 /**
1276  * power_supply_get_property_direct - Read a power supply property without checking for extensions
1277  * @psy: The power supply
1278  * @psp: The power supply property to read
1279  * @val: The resulting value of the power supply property
1280  *
1281  * Read a power supply property without taking into account any power supply extensions registered
1282  * on the given power supply. This is mostly useful for power supply extensions that want to access
1283  * their own power supply as using power_supply_get_property() directly will result in a potential
1284  * deadlock.
1285  *
1286  * Return: 0 on success or negative error code on failure.
1287  */
1288 int power_supply_get_property_direct(struct power_supply *psy, enum power_supply_property psp,
1289 				     union power_supply_propval *val)
1290 {
1291         return __power_supply_get_property(psy, psp, val, false);
1292 }
1293 EXPORT_SYMBOL_GPL(power_supply_get_property_direct);
1294 
1295 
1296 static int __power_supply_set_property(struct power_supply *psy, enum power_supply_property psp,
1297 				       const union power_supply_propval *val, bool use_extensions)
1298 {
1299 	struct power_supply_ext_registration *reg;
1300 
1301 	if (atomic_read(&psy->use_cnt) <= 0)
1302 		return -ENODEV;
1303 
1304 	if (use_extensions) {
1305 		scoped_guard(rwsem_read, &psy->extensions_sem) {
1306 			power_supply_for_each_extension(reg, psy) {
1307 				if (!power_supply_ext_has_property(reg->ext, psp))
1308 					continue;
1309 
1310 				if (reg->ext->set_property)
1311 					return reg->ext->set_property(psy, reg->ext, reg->data,
1312 								      psp, val);
1313 				else
1314 					return -ENODEV;
1315 			}
1316 		}
1317 	}
1318 
1319 	if (!psy->desc->set_property)
1320 		return -ENODEV;
1321 
1322 	return psy->desc->set_property(psy, psp, val);
1323 }
1324 
1325 int power_supply_set_property(struct power_supply *psy, enum power_supply_property psp,
1326 			      const union power_supply_propval *val)
1327 {
1328 	return __power_supply_set_property(psy, psp, val, true);
1329 }
1330 EXPORT_SYMBOL_GPL(power_supply_set_property);
1331 
1332 /**
1333  * power_supply_set_property_direct - Write a power supply property without checking for extensions
1334  * @psy: The power supply
1335  * @psp: The power supply property to write
1336  * @val: The value to write to the power supply property
1337  *
1338  * Write a power supply property without taking into account any power supply extensions registered
1339  * on the given power supply. This is mostly useful for power supply extensions that want to access
1340  * their own power supply as using power_supply_set_property() directly will result in a potential
1341  * deadlock.
1342  *
1343  * Return: 0 on success or negative error code on failure.
1344  */
1345 int power_supply_set_property_direct(struct power_supply *psy, enum power_supply_property psp,
1346 				     const union power_supply_propval *val)
1347 {
1348 	return __power_supply_set_property(psy, psp, val, false);
1349 }
1350 EXPORT_SYMBOL_GPL(power_supply_set_property_direct);
1351 
1352 int power_supply_property_is_writeable(struct power_supply *psy,
1353 					enum power_supply_property psp)
1354 {
1355 	struct power_supply_ext_registration *reg;
1356 
1357 	power_supply_for_each_extension(reg, psy) {
1358 		if (power_supply_ext_has_property(reg->ext, psp)) {
1359 			if (reg->ext->property_is_writeable)
1360 				return reg->ext->property_is_writeable(psy, reg->ext,
1361 								       reg->data, psp);
1362 			else
1363 				return 0;
1364 		}
1365 	}
1366 
1367 	if (!psy->desc->property_is_writeable)
1368 		return 0;
1369 
1370 	return psy->desc->property_is_writeable(psy, psp);
1371 }
1372 
1373 void power_supply_external_power_changed(struct power_supply *psy)
1374 {
1375 	if (atomic_read(&psy->use_cnt) <= 0 ||
1376 			!psy->desc->external_power_changed)
1377 		return;
1378 
1379 	psy->desc->external_power_changed(psy);
1380 }
1381 EXPORT_SYMBOL_GPL(power_supply_external_power_changed);
1382 
1383 int power_supply_powers(struct power_supply *psy, struct device *dev)
1384 {
1385 	return sysfs_create_link(&psy->dev.kobj, &dev->kobj, "powers");
1386 }
1387 EXPORT_SYMBOL_GPL(power_supply_powers);
1388 
1389 static int power_supply_update_sysfs_and_hwmon(struct power_supply *psy)
1390 {
1391 	unsigned long flags;
1392 
1393 	spin_lock_irqsave(&psy->changed_lock, flags);
1394 	psy->update_groups = true;
1395 	spin_unlock_irqrestore(&psy->changed_lock, flags);
1396 
1397 	power_supply_changed(psy);
1398 
1399 	power_supply_remove_hwmon_sysfs(psy);
1400 	return power_supply_add_hwmon_sysfs(psy);
1401 }
1402 
1403 int power_supply_register_extension(struct power_supply *psy, const struct power_supply_ext *ext,
1404 				    struct device *dev, void *data)
1405 {
1406 	struct power_supply_ext_registration *reg;
1407 	size_t i;
1408 	int ret;
1409 
1410 	if (!psy || !dev || !ext || !ext->name || !ext->properties || !ext->num_properties)
1411 		return -EINVAL;
1412 
1413 	guard(rwsem_write)(&psy->extensions_sem);
1414 
1415 	power_supply_for_each_extension(reg, psy)
1416 		if (strcmp(ext->name, reg->ext->name) == 0)
1417 			return -EEXIST;
1418 
1419 	for (i = 0; i < ext->num_properties; i++)
1420 		if (power_supply_has_property(psy, ext->properties[i]))
1421 			return -EEXIST;
1422 
1423 	reg = kmalloc(sizeof(*reg), GFP_KERNEL);
1424 	if (!reg)
1425 		return -ENOMEM;
1426 
1427 	reg->ext = ext;
1428 	reg->dev = dev;
1429 	reg->data = data;
1430 	list_add(&reg->list_head, &psy->extensions);
1431 
1432 	ret = power_supply_sysfs_add_extension(psy, ext, dev);
1433 	if (ret)
1434 		goto sysfs_add_failed;
1435 
1436 	ret = power_supply_update_sysfs_and_hwmon(psy);
1437 	if (ret)
1438 		goto sysfs_hwmon_failed;
1439 
1440 	return 0;
1441 
1442 sysfs_hwmon_failed:
1443 	power_supply_sysfs_remove_extension(psy, ext);
1444 sysfs_add_failed:
1445 	list_del(&reg->list_head);
1446 	kfree(reg);
1447 	return ret;
1448 }
1449 EXPORT_SYMBOL_GPL(power_supply_register_extension);
1450 
1451 void power_supply_unregister_extension(struct power_supply *psy, const struct power_supply_ext *ext)
1452 {
1453 	struct power_supply_ext_registration *reg;
1454 
1455 	guard(rwsem_write)(&psy->extensions_sem);
1456 
1457 	power_supply_for_each_extension(reg, psy) {
1458 		if (reg->ext == ext) {
1459 			list_del(&reg->list_head);
1460 			power_supply_sysfs_remove_extension(psy, ext);
1461 			kfree(reg);
1462 			power_supply_update_sysfs_and_hwmon(psy);
1463 			return;
1464 		}
1465 	}
1466 
1467 	dev_warn(&psy->dev, "Trying to unregister invalid extension");
1468 }
1469 EXPORT_SYMBOL_GPL(power_supply_unregister_extension);
1470 
1471 static void power_supply_dev_release(struct device *dev)
1472 {
1473 	struct power_supply *psy = to_power_supply(dev);
1474 
1475 	dev_dbg(dev, "%s\n", __func__);
1476 	kfree(psy);
1477 }
1478 
1479 int power_supply_reg_notifier(struct notifier_block *nb)
1480 {
1481 	return blocking_notifier_chain_register(&power_supply_notifier, nb);
1482 }
1483 EXPORT_SYMBOL_GPL(power_supply_reg_notifier);
1484 
1485 void power_supply_unreg_notifier(struct notifier_block *nb)
1486 {
1487 	blocking_notifier_chain_unregister(&power_supply_notifier, nb);
1488 }
1489 EXPORT_SYMBOL_GPL(power_supply_unreg_notifier);
1490 
1491 #ifdef CONFIG_THERMAL
1492 static int power_supply_read_temp(struct thermal_zone_device *tzd,
1493 		int *temp)
1494 {
1495 	struct power_supply *psy;
1496 	union power_supply_propval val;
1497 	int ret;
1498 
1499 	WARN_ON(tzd == NULL);
1500 	psy = thermal_zone_device_priv(tzd);
1501 	ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_TEMP, &val);
1502 	if (ret)
1503 		return ret;
1504 
1505 	/* Convert tenths of degree Celsius to milli degree Celsius. */
1506 	*temp = val.intval * 100;
1507 
1508 	return ret;
1509 }
1510 
1511 static const struct thermal_zone_device_ops psy_tzd_ops = {
1512 	.get_temp = power_supply_read_temp,
1513 };
1514 
1515 static int psy_register_thermal(struct power_supply *psy)
1516 {
1517 	int ret;
1518 
1519 	if (psy->desc->no_thermal)
1520 		return 0;
1521 
1522 	/* Register battery zone device psy reports temperature */
1523 	if (psy_desc_has_property(psy->desc, POWER_SUPPLY_PROP_TEMP)) {
1524 		/* Prefer our hwmon device and avoid duplicates */
1525 		struct thermal_zone_params tzp = {
1526 			.no_hwmon = IS_ENABLED(CONFIG_POWER_SUPPLY_HWMON)
1527 		};
1528 		psy->tzd = thermal_tripless_zone_device_register(psy->desc->name,
1529 				psy, &psy_tzd_ops, &tzp);
1530 		if (IS_ERR(psy->tzd))
1531 			return PTR_ERR(psy->tzd);
1532 		ret = thermal_zone_device_enable(psy->tzd);
1533 		if (ret)
1534 			thermal_zone_device_unregister(psy->tzd);
1535 		return ret;
1536 	}
1537 
1538 	return 0;
1539 }
1540 
1541 static void psy_unregister_thermal(struct power_supply *psy)
1542 {
1543 	if (IS_ERR_OR_NULL(psy->tzd))
1544 		return;
1545 	thermal_zone_device_unregister(psy->tzd);
1546 }
1547 
1548 #else
1549 static int psy_register_thermal(struct power_supply *psy)
1550 {
1551 	return 0;
1552 }
1553 
1554 static void psy_unregister_thermal(struct power_supply *psy)
1555 {
1556 }
1557 #endif
1558 
1559 static struct power_supply *__must_check
1560 __power_supply_register(struct device *parent,
1561 				   const struct power_supply_desc *desc,
1562 				   const struct power_supply_config *cfg)
1563 {
1564 	struct device *dev;
1565 	struct power_supply *psy;
1566 	int rc;
1567 
1568 	if (!desc || !desc->name || !desc->properties || !desc->num_properties)
1569 		return ERR_PTR(-EINVAL);
1570 
1571 	if (!parent)
1572 		pr_warn("%s: Expected proper parent device for '%s'\n",
1573 			__func__, desc->name);
1574 
1575 	psy = kzalloc(sizeof(*psy), GFP_KERNEL);
1576 	if (!psy)
1577 		return ERR_PTR(-ENOMEM);
1578 
1579 	dev = &psy->dev;
1580 
1581 	device_initialize(dev);
1582 
1583 	dev->class = &power_supply_class;
1584 	dev->type = &power_supply_dev_type;
1585 	dev->parent = parent;
1586 	dev->release = power_supply_dev_release;
1587 	dev_set_drvdata(dev, psy);
1588 	psy->desc = desc;
1589 	if (cfg) {
1590 		dev->groups = cfg->attr_grp;
1591 		psy->drv_data = cfg->drv_data;
1592 		dev->of_node =
1593 			cfg->fwnode ? to_of_node(cfg->fwnode) : cfg->of_node;
1594 		psy->supplied_to = cfg->supplied_to;
1595 		psy->num_supplicants = cfg->num_supplicants;
1596 	}
1597 
1598 	rc = dev_set_name(dev, "%s", desc->name);
1599 	if (rc)
1600 		goto dev_set_name_failed;
1601 
1602 	INIT_WORK(&psy->changed_work, power_supply_changed_work);
1603 	INIT_DELAYED_WORK(&psy->deferred_register_work,
1604 			  power_supply_deferred_register_work);
1605 
1606 	rc = power_supply_check_supplies(psy);
1607 	if (rc) {
1608 		dev_dbg(dev, "Not all required supplies found, defer probe\n");
1609 		goto check_supplies_failed;
1610 	}
1611 
1612 	/*
1613 	 * Expose constant battery info, if it is available. While there are
1614 	 * some chargers accessing constant battery data, we only want to
1615 	 * expose battery data to userspace for battery devices.
1616 	 */
1617 	if (desc->type == POWER_SUPPLY_TYPE_BATTERY) {
1618 		rc = power_supply_get_battery_info(psy, &psy->battery_info);
1619 		if (rc && rc != -ENODEV && rc != -ENOENT)
1620 			goto check_supplies_failed;
1621 	}
1622 
1623 	spin_lock_init(&psy->changed_lock);
1624 	init_rwsem(&psy->extensions_sem);
1625 	INIT_LIST_HEAD(&psy->extensions);
1626 
1627 	rc = device_add(dev);
1628 	if (rc)
1629 		goto device_add_failed;
1630 
1631 	rc = device_init_wakeup(dev, cfg ? !cfg->no_wakeup_source : true);
1632 	if (rc)
1633 		goto wakeup_init_failed;
1634 
1635 	rc = psy_register_thermal(psy);
1636 	if (rc)
1637 		goto register_thermal_failed;
1638 
1639 	rc = power_supply_create_triggers(psy);
1640 	if (rc)
1641 		goto create_triggers_failed;
1642 
1643 	scoped_guard(rwsem_read, &psy->extensions_sem) {
1644 		rc = power_supply_add_hwmon_sysfs(psy);
1645 		if (rc)
1646 			goto add_hwmon_sysfs_failed;
1647 	}
1648 
1649 	/*
1650 	 * Update use_cnt after any uevents (most notably from device_add()).
1651 	 * We are here still during driver's probe but
1652 	 * the power_supply_uevent() calls back driver's get_property
1653 	 * method so:
1654 	 * 1. Driver did not assigned the returned struct power_supply,
1655 	 * 2. Driver could not finish initialization (anything in its probe
1656 	 *    after calling power_supply_register()).
1657 	 */
1658 	atomic_inc(&psy->use_cnt);
1659 	psy->initialized = true;
1660 
1661 	queue_delayed_work(system_power_efficient_wq,
1662 			   &psy->deferred_register_work,
1663 			   POWER_SUPPLY_DEFERRED_REGISTER_TIME);
1664 
1665 	return psy;
1666 
1667 add_hwmon_sysfs_failed:
1668 	power_supply_remove_triggers(psy);
1669 create_triggers_failed:
1670 	psy_unregister_thermal(psy);
1671 register_thermal_failed:
1672 wakeup_init_failed:
1673 	device_del(dev);
1674 device_add_failed:
1675 check_supplies_failed:
1676 dev_set_name_failed:
1677 	put_device(dev);
1678 	return ERR_PTR(rc);
1679 }
1680 
1681 /**
1682  * power_supply_register() - Register new power supply
1683  * @parent:	Device to be a parent of power supply's device, usually
1684  *		the device which probe function calls this
1685  * @desc:	Description of power supply, must be valid through whole
1686  *		lifetime of this power supply
1687  * @cfg:	Run-time specific configuration accessed during registering,
1688  *		may be NULL
1689  *
1690  * Return: A pointer to newly allocated power_supply on success
1691  * or ERR_PTR otherwise.
1692  * Use power_supply_unregister() on returned power_supply pointer to release
1693  * resources.
1694  */
1695 struct power_supply *__must_check power_supply_register(struct device *parent,
1696 		const struct power_supply_desc *desc,
1697 		const struct power_supply_config *cfg)
1698 {
1699 	return __power_supply_register(parent, desc, cfg);
1700 }
1701 EXPORT_SYMBOL_GPL(power_supply_register);
1702 
1703 static void devm_power_supply_release(struct device *dev, void *res)
1704 {
1705 	struct power_supply **psy = res;
1706 
1707 	power_supply_unregister(*psy);
1708 }
1709 
1710 /**
1711  * devm_power_supply_register() - Register managed power supply
1712  * @parent:	Device to be a parent of power supply's device, usually
1713  *		the device which probe function calls this
1714  * @desc:	Description of power supply, must be valid through whole
1715  *		lifetime of this power supply
1716  * @cfg:	Run-time specific configuration accessed during registering,
1717  *		may be NULL
1718  *
1719  * Return: A pointer to newly allocated power_supply on success
1720  * or ERR_PTR otherwise.
1721  * The returned power_supply pointer will be automatically unregistered
1722  * on driver detach.
1723  */
1724 struct power_supply *__must_check
1725 devm_power_supply_register(struct device *parent,
1726 		const struct power_supply_desc *desc,
1727 		const struct power_supply_config *cfg)
1728 {
1729 	struct power_supply **ptr, *psy;
1730 
1731 	ptr = devres_alloc(devm_power_supply_release, sizeof(*ptr), GFP_KERNEL);
1732 
1733 	if (!ptr)
1734 		return ERR_PTR(-ENOMEM);
1735 	psy = __power_supply_register(parent, desc, cfg);
1736 	if (IS_ERR(psy)) {
1737 		devres_free(ptr);
1738 	} else {
1739 		*ptr = psy;
1740 		devres_add(parent, ptr);
1741 	}
1742 	return psy;
1743 }
1744 EXPORT_SYMBOL_GPL(devm_power_supply_register);
1745 
1746 /**
1747  * power_supply_unregister() - Remove this power supply from system
1748  * @psy:	Pointer to power supply to unregister
1749  *
1750  * Remove this power supply from the system. The resources of power supply
1751  * will be freed here or on last power_supply_put() call.
1752  */
1753 void power_supply_unregister(struct power_supply *psy)
1754 {
1755 	WARN_ON(atomic_dec_return(&psy->use_cnt));
1756 	psy->removing = true;
1757 	cancel_work_sync(&psy->changed_work);
1758 	cancel_delayed_work_sync(&psy->deferred_register_work);
1759 	sysfs_remove_link(&psy->dev.kobj, "powers");
1760 	power_supply_remove_hwmon_sysfs(psy);
1761 	power_supply_remove_triggers(psy);
1762 	psy_unregister_thermal(psy);
1763 	device_init_wakeup(&psy->dev, false);
1764 	device_unregister(&psy->dev);
1765 }
1766 EXPORT_SYMBOL_GPL(power_supply_unregister);
1767 
1768 void *power_supply_get_drvdata(struct power_supply *psy)
1769 {
1770 	return psy->drv_data;
1771 }
1772 EXPORT_SYMBOL_GPL(power_supply_get_drvdata);
1773 
1774 static int __init power_supply_class_init(void)
1775 {
1776 	power_supply_init_attrs();
1777 	return class_register(&power_supply_class);
1778 }
1779 
1780 static void __exit power_supply_class_exit(void)
1781 {
1782 	class_unregister(&power_supply_class);
1783 }
1784 
1785 subsys_initcall(power_supply_class_init);
1786 module_exit(power_supply_class_exit);
1787 
1788 MODULE_DESCRIPTION("Universal power supply monitor class");
1789 MODULE_AUTHOR("Ian Molton <spyro@f2s.com>");
1790 MODULE_AUTHOR("Szabolcs Gyurko");
1791 MODULE_AUTHOR("Anton Vorontsov <cbou@mail.ru>");
1792