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