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 
__power_supply_is_supplied_by(struct power_supply * supplier,struct power_supply * supply)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 
__power_supply_changed_work(struct device * dev,void * data)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 
power_supply_changed_work(struct work_struct * work)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 
power_supply_changed(struct power_supply * psy)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  */
power_supply_deferred_register_work(struct work_struct * work)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
__power_supply_populate_supplied_from(struct device * dev,void * data)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 
power_supply_populate_supplied_from(struct power_supply * psy)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 
__power_supply_find_supply_from_node(struct device * dev,void * data)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 
power_supply_find_supply_from_node(struct device_node * supply_node)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 
power_supply_check_supplies(struct power_supply * psy)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
power_supply_check_supplies(struct power_supply * psy)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 
__power_supply_am_i_supplied(struct device * dev,void * _data)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 
power_supply_am_i_supplied(struct power_supply * psy)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 
__power_supply_is_system_supplied(struct device * dev,void * data)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 	(*count)++;
352 	if (psy->desc->type != POWER_SUPPLY_TYPE_BATTERY)
353 		if (!psy->desc->get_property(psy, POWER_SUPPLY_PROP_ONLINE,
354 					&ret))
355 			return ret.intval;
356 
357 	return 0;
358 }
359 
power_supply_is_system_supplied(void)360 int power_supply_is_system_supplied(void)
361 {
362 	int error;
363 	unsigned int count = 0;
364 
365 	error = class_for_each_device(power_supply_class, NULL, &count,
366 				      __power_supply_is_system_supplied);
367 
368 	/*
369 	 * If no power class device was found at all, most probably we are
370 	 * running on a desktop system, so assume we are on mains power.
371 	 */
372 	if (count == 0)
373 		return 1;
374 
375 	return error;
376 }
377 EXPORT_SYMBOL_GPL(power_supply_is_system_supplied);
378 
379 struct psy_get_supplier_prop_data {
380 	struct power_supply *psy;
381 	enum power_supply_property psp;
382 	union power_supply_propval *val;
383 };
384 
__power_supply_get_supplier_property(struct device * dev,void * _data)385 static int __power_supply_get_supplier_property(struct device *dev, void *_data)
386 {
387 	struct power_supply *epsy = dev_get_drvdata(dev);
388 	struct psy_get_supplier_prop_data *data = _data;
389 
390 	if (__power_supply_is_supplied_by(epsy, data->psy))
391 		if (!epsy->desc->get_property(epsy, data->psp, data->val))
392 			return 1; /* Success */
393 
394 	return 0; /* Continue iterating */
395 }
396 
power_supply_get_property_from_supplier(struct power_supply * psy,enum power_supply_property psp,union power_supply_propval * val)397 int power_supply_get_property_from_supplier(struct power_supply *psy,
398 					    enum power_supply_property psp,
399 					    union power_supply_propval *val)
400 {
401 	struct psy_get_supplier_prop_data data = {
402 		.psy = psy,
403 		.psp = psp,
404 		.val = val,
405 	};
406 	int ret;
407 
408 	/*
409 	 * This function is not intended for use with a supply with multiple
410 	 * suppliers, we simply pick the first supply to report the psp.
411 	 */
412 	ret = class_for_each_device(power_supply_class, NULL, &data,
413 				    __power_supply_get_supplier_property);
414 	if (ret < 0)
415 		return ret;
416 	if (ret == 0)
417 		return -ENODEV;
418 
419 	return 0;
420 }
421 EXPORT_SYMBOL_GPL(power_supply_get_property_from_supplier);
422 
power_supply_set_battery_charged(struct power_supply * psy)423 int power_supply_set_battery_charged(struct power_supply *psy)
424 {
425 	if (atomic_read(&psy->use_cnt) >= 0 &&
426 			psy->desc->type == POWER_SUPPLY_TYPE_BATTERY &&
427 			psy->desc->set_charged) {
428 		psy->desc->set_charged(psy);
429 		return 0;
430 	}
431 
432 	return -EINVAL;
433 }
434 EXPORT_SYMBOL_GPL(power_supply_set_battery_charged);
435 
power_supply_match_device_by_name(struct device * dev,const void * data)436 static int power_supply_match_device_by_name(struct device *dev, const void *data)
437 {
438 	const char *name = data;
439 	struct power_supply *psy = dev_get_drvdata(dev);
440 
441 	return strcmp(psy->desc->name, name) == 0;
442 }
443 
444 /**
445  * power_supply_get_by_name() - Search for a power supply and returns its ref
446  * @name: Power supply name to fetch
447  *
448  * If power supply was found, it increases reference count for the
449  * internal power supply's device. The user should power_supply_put()
450  * after usage.
451  *
452  * Return: On success returns a reference to a power supply with
453  * matching name equals to @name, a NULL otherwise.
454  */
power_supply_get_by_name(const char * name)455 struct power_supply *power_supply_get_by_name(const char *name)
456 {
457 	struct power_supply *psy = NULL;
458 	struct device *dev = class_find_device(power_supply_class, NULL, name,
459 					power_supply_match_device_by_name);
460 
461 	if (dev) {
462 		psy = dev_get_drvdata(dev);
463 		atomic_inc(&psy->use_cnt);
464 	}
465 
466 	return psy;
467 }
468 EXPORT_SYMBOL_GPL(power_supply_get_by_name);
469 
470 /**
471  * power_supply_put() - Drop reference obtained with power_supply_get_by_name
472  * @psy: Reference to put
473  *
474  * The reference to power supply should be put before unregistering
475  * the power supply.
476  */
power_supply_put(struct power_supply * psy)477 void power_supply_put(struct power_supply *psy)
478 {
479 	might_sleep();
480 
481 	atomic_dec(&psy->use_cnt);
482 	put_device(&psy->dev);
483 }
484 EXPORT_SYMBOL_GPL(power_supply_put);
485 
486 #ifdef CONFIG_OF
power_supply_match_device_node(struct device * dev,const void * data)487 static int power_supply_match_device_node(struct device *dev, const void *data)
488 {
489 	return dev->parent && dev->parent->of_node == data;
490 }
491 
492 /**
493  * power_supply_get_by_phandle() - Search for a power supply and returns its ref
494  * @np: Pointer to device node holding phandle property
495  * @property: Name of property holding a power supply name
496  *
497  * If power supply was found, it increases reference count for the
498  * internal power supply's device. The user should power_supply_put()
499  * after usage.
500  *
501  * Return: On success returns a reference to a power supply with
502  * matching name equals to value under @property, NULL or ERR_PTR otherwise.
503  */
power_supply_get_by_phandle(struct device_node * np,const char * property)504 struct power_supply *power_supply_get_by_phandle(struct device_node *np,
505 							const char *property)
506 {
507 	struct device_node *power_supply_np;
508 	struct power_supply *psy = NULL;
509 	struct device *dev;
510 
511 	power_supply_np = of_parse_phandle(np, property, 0);
512 	if (!power_supply_np)
513 		return ERR_PTR(-ENODEV);
514 
515 	dev = class_find_device(power_supply_class, NULL, power_supply_np,
516 						power_supply_match_device_node);
517 
518 	of_node_put(power_supply_np);
519 
520 	if (dev) {
521 		psy = dev_get_drvdata(dev);
522 		atomic_inc(&psy->use_cnt);
523 	}
524 
525 	return psy;
526 }
527 EXPORT_SYMBOL_GPL(power_supply_get_by_phandle);
528 
devm_power_supply_put(struct device * dev,void * res)529 static void devm_power_supply_put(struct device *dev, void *res)
530 {
531 	struct power_supply **psy = res;
532 
533 	power_supply_put(*psy);
534 }
535 
536 /**
537  * devm_power_supply_get_by_phandle() - Resource managed version of
538  *  power_supply_get_by_phandle()
539  * @dev: Pointer to device holding phandle property
540  * @property: Name of property holding a power supply phandle
541  *
542  * Return: On success returns a reference to a power supply with
543  * matching name equals to value under @property, NULL or ERR_PTR otherwise.
544  */
devm_power_supply_get_by_phandle(struct device * dev,const char * property)545 struct power_supply *devm_power_supply_get_by_phandle(struct device *dev,
546 						      const char *property)
547 {
548 	struct power_supply **ptr, *psy;
549 
550 	if (!dev->of_node)
551 		return ERR_PTR(-ENODEV);
552 
553 	ptr = devres_alloc(devm_power_supply_put, sizeof(*ptr), GFP_KERNEL);
554 	if (!ptr)
555 		return ERR_PTR(-ENOMEM);
556 
557 	psy = power_supply_get_by_phandle(dev->of_node, property);
558 	if (IS_ERR_OR_NULL(psy)) {
559 		devres_free(ptr);
560 	} else {
561 		*ptr = psy;
562 		devres_add(dev, ptr);
563 	}
564 	return psy;
565 }
566 EXPORT_SYMBOL_GPL(devm_power_supply_get_by_phandle);
567 #endif /* CONFIG_OF */
568 
power_supply_get_battery_info(struct power_supply * psy,struct power_supply_battery_info ** info_out)569 int power_supply_get_battery_info(struct power_supply *psy,
570 				  struct power_supply_battery_info **info_out)
571 {
572 	struct power_supply_resistance_temp_table *resist_table;
573 	struct power_supply_battery_info *info;
574 	struct device_node *battery_np = NULL;
575 	struct fwnode_reference_args args;
576 	struct fwnode_handle *fwnode;
577 	const char *value;
578 	int err, len, index;
579 	const __be32 *list;
580 	u32 min_max[2];
581 
582 	if (psy->of_node) {
583 		battery_np = of_parse_phandle(psy->of_node, "monitored-battery", 0);
584 		if (!battery_np)
585 			return -ENODEV;
586 
587 		fwnode = fwnode_handle_get(of_fwnode_handle(battery_np));
588 	} else {
589 		err = fwnode_property_get_reference_args(
590 					dev_fwnode(psy->dev.parent),
591 					"monitored-battery", NULL, 0, 0, &args);
592 		if (err)
593 			return err;
594 
595 		fwnode = args.fwnode;
596 	}
597 
598 	err = fwnode_property_read_string(fwnode, "compatible", &value);
599 	if (err)
600 		goto out_put_node;
601 
602 
603 	/* Try static batteries first */
604 	err = samsung_sdi_battery_get_info(&psy->dev, value, &info);
605 	if (!err)
606 		goto out_ret_pointer;
607 	else if (err == -ENODEV)
608 		/*
609 		 * Device does not have a static battery.
610 		 * Proceed to look for a simple battery.
611 		 */
612 		err = 0;
613 
614 	if (strcmp("simple-battery", value)) {
615 		err = -ENODEV;
616 		goto out_put_node;
617 	}
618 
619 	info = devm_kzalloc(&psy->dev, sizeof(*info), GFP_KERNEL);
620 	if (!info) {
621 		err = -ENOMEM;
622 		goto out_put_node;
623 	}
624 
625 	info->technology                     = POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
626 	info->energy_full_design_uwh         = -EINVAL;
627 	info->charge_full_design_uah         = -EINVAL;
628 	info->voltage_min_design_uv          = -EINVAL;
629 	info->voltage_max_design_uv          = -EINVAL;
630 	info->precharge_current_ua           = -EINVAL;
631 	info->charge_term_current_ua         = -EINVAL;
632 	info->constant_charge_current_max_ua = -EINVAL;
633 	info->constant_charge_voltage_max_uv = -EINVAL;
634 	info->tricklecharge_current_ua       = -EINVAL;
635 	info->precharge_voltage_max_uv       = -EINVAL;
636 	info->charge_restart_voltage_uv      = -EINVAL;
637 	info->overvoltage_limit_uv           = -EINVAL;
638 	info->maintenance_charge             = NULL;
639 	info->alert_low_temp_charge_current_ua = -EINVAL;
640 	info->alert_low_temp_charge_voltage_uv = -EINVAL;
641 	info->alert_high_temp_charge_current_ua = -EINVAL;
642 	info->alert_high_temp_charge_voltage_uv = -EINVAL;
643 	info->temp_ambient_alert_min         = INT_MIN;
644 	info->temp_ambient_alert_max         = INT_MAX;
645 	info->temp_alert_min                 = INT_MIN;
646 	info->temp_alert_max                 = INT_MAX;
647 	info->temp_min                       = INT_MIN;
648 	info->temp_max                       = INT_MAX;
649 	info->factory_internal_resistance_uohm  = -EINVAL;
650 	info->resist_table                   = NULL;
651 	info->bti_resistance_ohm             = -EINVAL;
652 	info->bti_resistance_tolerance       = -EINVAL;
653 
654 	for (index = 0; index < POWER_SUPPLY_OCV_TEMP_MAX; index++) {
655 		info->ocv_table[index]       = NULL;
656 		info->ocv_temp[index]        = -EINVAL;
657 		info->ocv_table_size[index]  = -EINVAL;
658 	}
659 
660 	/* The property and field names below must correspond to elements
661 	 * in enum power_supply_property. For reasoning, see
662 	 * Documentation/power/power_supply_class.rst.
663 	 */
664 
665 	if (!fwnode_property_read_string(fwnode, "device-chemistry", &value)) {
666 		if (!strcmp("nickel-cadmium", value))
667 			info->technology = POWER_SUPPLY_TECHNOLOGY_NiCd;
668 		else if (!strcmp("nickel-metal-hydride", value))
669 			info->technology = POWER_SUPPLY_TECHNOLOGY_NiMH;
670 		else if (!strcmp("lithium-ion", value))
671 			/* Imprecise lithium-ion type */
672 			info->technology = POWER_SUPPLY_TECHNOLOGY_LION;
673 		else if (!strcmp("lithium-ion-polymer", value))
674 			info->technology = POWER_SUPPLY_TECHNOLOGY_LIPO;
675 		else if (!strcmp("lithium-ion-iron-phosphate", value))
676 			info->technology = POWER_SUPPLY_TECHNOLOGY_LiFe;
677 		else if (!strcmp("lithium-ion-manganese-oxide", value))
678 			info->technology = POWER_SUPPLY_TECHNOLOGY_LiMn;
679 		else
680 			dev_warn(&psy->dev, "%s unknown battery type\n", value);
681 	}
682 
683 	fwnode_property_read_u32(fwnode, "energy-full-design-microwatt-hours",
684 			     &info->energy_full_design_uwh);
685 	fwnode_property_read_u32(fwnode, "charge-full-design-microamp-hours",
686 			     &info->charge_full_design_uah);
687 	fwnode_property_read_u32(fwnode, "voltage-min-design-microvolt",
688 			     &info->voltage_min_design_uv);
689 	fwnode_property_read_u32(fwnode, "voltage-max-design-microvolt",
690 			     &info->voltage_max_design_uv);
691 	fwnode_property_read_u32(fwnode, "trickle-charge-current-microamp",
692 			     &info->tricklecharge_current_ua);
693 	fwnode_property_read_u32(fwnode, "precharge-current-microamp",
694 			     &info->precharge_current_ua);
695 	fwnode_property_read_u32(fwnode, "precharge-upper-limit-microvolt",
696 			     &info->precharge_voltage_max_uv);
697 	fwnode_property_read_u32(fwnode, "charge-term-current-microamp",
698 			     &info->charge_term_current_ua);
699 	fwnode_property_read_u32(fwnode, "re-charge-voltage-microvolt",
700 			     &info->charge_restart_voltage_uv);
701 	fwnode_property_read_u32(fwnode, "over-voltage-threshold-microvolt",
702 			     &info->overvoltage_limit_uv);
703 	fwnode_property_read_u32(fwnode, "constant-charge-current-max-microamp",
704 			     &info->constant_charge_current_max_ua);
705 	fwnode_property_read_u32(fwnode, "constant-charge-voltage-max-microvolt",
706 			     &info->constant_charge_voltage_max_uv);
707 	fwnode_property_read_u32(fwnode, "factory-internal-resistance-micro-ohms",
708 			     &info->factory_internal_resistance_uohm);
709 
710 	if (!fwnode_property_read_u32_array(fwnode, "ambient-celsius",
711 					    min_max, ARRAY_SIZE(min_max))) {
712 		info->temp_ambient_alert_min = min_max[0];
713 		info->temp_ambient_alert_max = min_max[1];
714 	}
715 	if (!fwnode_property_read_u32_array(fwnode, "alert-celsius",
716 					    min_max, ARRAY_SIZE(min_max))) {
717 		info->temp_alert_min = min_max[0];
718 		info->temp_alert_max = min_max[1];
719 	}
720 	if (!fwnode_property_read_u32_array(fwnode, "operating-range-celsius",
721 					    min_max, ARRAY_SIZE(min_max))) {
722 		info->temp_min = min_max[0];
723 		info->temp_max = min_max[1];
724 	}
725 
726 	/*
727 	 * The below code uses raw of-data parsing to parse
728 	 * /schemas/types.yaml#/definitions/uint32-matrix
729 	 * data, so for now this is only support with of.
730 	 */
731 	if (!battery_np)
732 		goto out_ret_pointer;
733 
734 	len = of_property_count_u32_elems(battery_np, "ocv-capacity-celsius");
735 	if (len < 0 && len != -EINVAL) {
736 		err = len;
737 		goto out_put_node;
738 	} else if (len > POWER_SUPPLY_OCV_TEMP_MAX) {
739 		dev_err(&psy->dev, "Too many temperature values\n");
740 		err = -EINVAL;
741 		goto out_put_node;
742 	} else if (len > 0) {
743 		of_property_read_u32_array(battery_np, "ocv-capacity-celsius",
744 					   info->ocv_temp, len);
745 	}
746 
747 	for (index = 0; index < len; index++) {
748 		struct power_supply_battery_ocv_table *table;
749 		char *propname;
750 		int i, tab_len, size;
751 
752 		propname = kasprintf(GFP_KERNEL, "ocv-capacity-table-%d", index);
753 		if (!propname) {
754 			power_supply_put_battery_info(psy, info);
755 			err = -ENOMEM;
756 			goto out_put_node;
757 		}
758 		list = of_get_property(battery_np, propname, &size);
759 		if (!list || !size) {
760 			dev_err(&psy->dev, "failed to get %s\n", propname);
761 			kfree(propname);
762 			power_supply_put_battery_info(psy, info);
763 			err = -EINVAL;
764 			goto out_put_node;
765 		}
766 
767 		kfree(propname);
768 		tab_len = size / (2 * sizeof(__be32));
769 		info->ocv_table_size[index] = tab_len;
770 
771 		table = info->ocv_table[index] =
772 			devm_kcalloc(&psy->dev, tab_len, sizeof(*table), GFP_KERNEL);
773 		if (!info->ocv_table[index]) {
774 			power_supply_put_battery_info(psy, info);
775 			err = -ENOMEM;
776 			goto out_put_node;
777 		}
778 
779 		for (i = 0; i < tab_len; i++) {
780 			table[i].ocv = be32_to_cpu(*list);
781 			list++;
782 			table[i].capacity = be32_to_cpu(*list);
783 			list++;
784 		}
785 	}
786 
787 	list = of_get_property(battery_np, "resistance-temp-table", &len);
788 	if (!list || !len)
789 		goto out_ret_pointer;
790 
791 	info->resist_table_size = len / (2 * sizeof(__be32));
792 	resist_table = info->resist_table = devm_kcalloc(&psy->dev,
793 							 info->resist_table_size,
794 							 sizeof(*resist_table),
795 							 GFP_KERNEL);
796 	if (!info->resist_table) {
797 		power_supply_put_battery_info(psy, info);
798 		err = -ENOMEM;
799 		goto out_put_node;
800 	}
801 
802 	for (index = 0; index < info->resist_table_size; index++) {
803 		resist_table[index].temp = be32_to_cpu(*list++);
804 		resist_table[index].resistance = be32_to_cpu(*list++);
805 	}
806 
807 out_ret_pointer:
808 	/* Finally return the whole thing */
809 	*info_out = info;
810 
811 out_put_node:
812 	fwnode_handle_put(fwnode);
813 	of_node_put(battery_np);
814 	return err;
815 }
816 EXPORT_SYMBOL_GPL(power_supply_get_battery_info);
817 
power_supply_put_battery_info(struct power_supply * psy,struct power_supply_battery_info * info)818 void power_supply_put_battery_info(struct power_supply *psy,
819 				   struct power_supply_battery_info *info)
820 {
821 	int i;
822 
823 	for (i = 0; i < POWER_SUPPLY_OCV_TEMP_MAX; i++) {
824 		if (info->ocv_table[i])
825 			devm_kfree(&psy->dev, info->ocv_table[i]);
826 	}
827 
828 	if (info->resist_table)
829 		devm_kfree(&psy->dev, info->resist_table);
830 
831 	devm_kfree(&psy->dev, info);
832 }
833 EXPORT_SYMBOL_GPL(power_supply_put_battery_info);
834 
835 /**
836  * power_supply_temp2resist_simple() - find the battery internal resistance
837  * percent from temperature
838  * @table: Pointer to battery resistance temperature table
839  * @table_len: The table length
840  * @temp: Current temperature
841  *
842  * This helper function is used to look up battery internal resistance percent
843  * according to current temperature value from the resistance temperature table,
844  * and the table must be ordered descending. Then the actual battery internal
845  * resistance = the ideal battery internal resistance * percent / 100.
846  *
847  * Return: the battery internal resistance percent
848  */
power_supply_temp2resist_simple(struct power_supply_resistance_temp_table * table,int table_len,int temp)849 int power_supply_temp2resist_simple(struct power_supply_resistance_temp_table *table,
850 				    int table_len, int temp)
851 {
852 	int i, high, low;
853 
854 	for (i = 0; i < table_len; i++)
855 		if (temp > table[i].temp)
856 			break;
857 
858 	/* The library function will deal with high == low */
859 	if (i == 0)
860 		high = low = i;
861 	else if (i == table_len)
862 		high = low = i - 1;
863 	else
864 		high = (low = i) - 1;
865 
866 	return fixp_linear_interpolate(table[low].temp,
867 				       table[low].resistance,
868 				       table[high].temp,
869 				       table[high].resistance,
870 				       temp);
871 }
872 EXPORT_SYMBOL_GPL(power_supply_temp2resist_simple);
873 
874 /**
875  * power_supply_vbat2ri() - find the battery internal resistance
876  * from the battery voltage
877  * @info: The battery information container
878  * @table: Pointer to battery resistance temperature table
879  * @vbat_uv: The battery voltage in microvolt
880  * @charging: If we are charging (true) or not (false)
881  *
882  * This helper function is used to look up battery internal resistance
883  * according to current battery voltage. Depending on whether the battery
884  * is currently charging or not, different resistance will be returned.
885  *
886  * Returns the internal resistance in microohm or negative error code.
887  */
power_supply_vbat2ri(struct power_supply_battery_info * info,int vbat_uv,bool charging)888 int power_supply_vbat2ri(struct power_supply_battery_info *info,
889 			 int vbat_uv, bool charging)
890 {
891 	struct power_supply_vbat_ri_table *vbat2ri;
892 	int table_len;
893 	int i, high, low;
894 
895 	/*
896 	 * If we are charging, and the battery supplies a separate table
897 	 * for this state, we use that in order to compensate for the
898 	 * charging voltage. Otherwise we use the main table.
899 	 */
900 	if (charging && info->vbat2ri_charging) {
901 		vbat2ri = info->vbat2ri_charging;
902 		table_len = info->vbat2ri_charging_size;
903 	} else {
904 		vbat2ri = info->vbat2ri_discharging;
905 		table_len = info->vbat2ri_discharging_size;
906 	}
907 
908 	/*
909 	 * If no tables are specified, or if we are above the highest voltage in
910 	 * the voltage table, just return the factory specified internal resistance.
911 	 */
912 	if (!vbat2ri || (table_len <= 0) || (vbat_uv > vbat2ri[0].vbat_uv)) {
913 		if (charging && (info->factory_internal_resistance_charging_uohm > 0))
914 			return info->factory_internal_resistance_charging_uohm;
915 		else
916 			return info->factory_internal_resistance_uohm;
917 	}
918 
919 	/* Break loop at table_len - 1 because that is the highest index */
920 	for (i = 0; i < table_len - 1; i++)
921 		if (vbat_uv > vbat2ri[i].vbat_uv)
922 			break;
923 
924 	/* The library function will deal with high == low */
925 	if ((i == 0) || (i == (table_len - 1)))
926 		high = i;
927 	else
928 		high = i - 1;
929 	low = i;
930 
931 	return fixp_linear_interpolate(vbat2ri[low].vbat_uv,
932 				       vbat2ri[low].ri_uohm,
933 				       vbat2ri[high].vbat_uv,
934 				       vbat2ri[high].ri_uohm,
935 				       vbat_uv);
936 }
937 EXPORT_SYMBOL_GPL(power_supply_vbat2ri);
938 
939 struct power_supply_maintenance_charge_table *
power_supply_get_maintenance_charging_setting(struct power_supply_battery_info * info,int index)940 power_supply_get_maintenance_charging_setting(struct power_supply_battery_info *info,
941 					      int index)
942 {
943 	if (index >= info->maintenance_charge_size)
944 		return NULL;
945 	return &info->maintenance_charge[index];
946 }
947 EXPORT_SYMBOL_GPL(power_supply_get_maintenance_charging_setting);
948 
949 /**
950  * power_supply_ocv2cap_simple() - find the battery capacity
951  * @table: Pointer to battery OCV lookup table
952  * @table_len: OCV table length
953  * @ocv: Current OCV value
954  *
955  * This helper function is used to look up battery capacity according to
956  * current OCV value from one OCV table, and the OCV table must be ordered
957  * descending.
958  *
959  * Return: the battery capacity.
960  */
power_supply_ocv2cap_simple(struct power_supply_battery_ocv_table * table,int table_len,int ocv)961 int power_supply_ocv2cap_simple(struct power_supply_battery_ocv_table *table,
962 				int table_len, int ocv)
963 {
964 	int i, high, low;
965 
966 	for (i = 0; i < table_len; i++)
967 		if (ocv > table[i].ocv)
968 			break;
969 
970 	/* The library function will deal with high == low */
971 	if (i == 0)
972 		high = low = i;
973 	else if (i == table_len)
974 		high = low = i - 1;
975 	else
976 		high = (low = i) - 1;
977 
978 	return fixp_linear_interpolate(table[low].ocv,
979 				       table[low].capacity,
980 				       table[high].ocv,
981 				       table[high].capacity,
982 				       ocv);
983 }
984 EXPORT_SYMBOL_GPL(power_supply_ocv2cap_simple);
985 
986 struct power_supply_battery_ocv_table *
power_supply_find_ocv2cap_table(struct power_supply_battery_info * info,int temp,int * table_len)987 power_supply_find_ocv2cap_table(struct power_supply_battery_info *info,
988 				int temp, int *table_len)
989 {
990 	int best_temp_diff = INT_MAX, temp_diff;
991 	u8 i, best_index = 0;
992 
993 	if (!info->ocv_table[0])
994 		return NULL;
995 
996 	for (i = 0; i < POWER_SUPPLY_OCV_TEMP_MAX; i++) {
997 		/* Out of capacity tables */
998 		if (!info->ocv_table[i])
999 			break;
1000 
1001 		temp_diff = abs(info->ocv_temp[i] - temp);
1002 
1003 		if (temp_diff < best_temp_diff) {
1004 			best_temp_diff = temp_diff;
1005 			best_index = i;
1006 		}
1007 	}
1008 
1009 	*table_len = info->ocv_table_size[best_index];
1010 	return info->ocv_table[best_index];
1011 }
1012 EXPORT_SYMBOL_GPL(power_supply_find_ocv2cap_table);
1013 
power_supply_batinfo_ocv2cap(struct power_supply_battery_info * info,int ocv,int temp)1014 int power_supply_batinfo_ocv2cap(struct power_supply_battery_info *info,
1015 				 int ocv, int temp)
1016 {
1017 	struct power_supply_battery_ocv_table *table;
1018 	int table_len;
1019 
1020 	table = power_supply_find_ocv2cap_table(info, temp, &table_len);
1021 	if (!table)
1022 		return -EINVAL;
1023 
1024 	return power_supply_ocv2cap_simple(table, table_len, ocv);
1025 }
1026 EXPORT_SYMBOL_GPL(power_supply_batinfo_ocv2cap);
1027 
power_supply_battery_bti_in_range(struct power_supply_battery_info * info,int resistance)1028 bool power_supply_battery_bti_in_range(struct power_supply_battery_info *info,
1029 				       int resistance)
1030 {
1031 	int low, high;
1032 
1033 	/* Nothing like this can be checked */
1034 	if (info->bti_resistance_ohm <= 0)
1035 		return false;
1036 
1037 	/* This will be extremely strict and unlikely to work */
1038 	if (info->bti_resistance_tolerance <= 0)
1039 		return (info->bti_resistance_ohm == resistance);
1040 
1041 	low = info->bti_resistance_ohm -
1042 		(info->bti_resistance_ohm * info->bti_resistance_tolerance) / 100;
1043 	high = info->bti_resistance_ohm +
1044 		(info->bti_resistance_ohm * info->bti_resistance_tolerance) / 100;
1045 
1046 	return ((resistance >= low) && (resistance <= high));
1047 }
1048 EXPORT_SYMBOL_GPL(power_supply_battery_bti_in_range);
1049 
power_supply_get_property(struct power_supply * psy,enum power_supply_property psp,union power_supply_propval * val)1050 int power_supply_get_property(struct power_supply *psy,
1051 			    enum power_supply_property psp,
1052 			    union power_supply_propval *val)
1053 {
1054 	if (atomic_read(&psy->use_cnt) <= 0) {
1055 		if (!psy->initialized)
1056 			return -EAGAIN;
1057 		return -ENODEV;
1058 	}
1059 
1060 	return psy->desc->get_property(psy, psp, val);
1061 }
1062 EXPORT_SYMBOL_GPL(power_supply_get_property);
1063 
power_supply_set_property(struct power_supply * psy,enum power_supply_property psp,const union power_supply_propval * val)1064 int power_supply_set_property(struct power_supply *psy,
1065 			    enum power_supply_property psp,
1066 			    const union power_supply_propval *val)
1067 {
1068 	if (atomic_read(&psy->use_cnt) <= 0 || !psy->desc->set_property)
1069 		return -ENODEV;
1070 
1071 	return psy->desc->set_property(psy, psp, val);
1072 }
1073 EXPORT_SYMBOL_GPL(power_supply_set_property);
1074 
power_supply_property_is_writeable(struct power_supply * psy,enum power_supply_property psp)1075 int power_supply_property_is_writeable(struct power_supply *psy,
1076 					enum power_supply_property psp)
1077 {
1078 	if (atomic_read(&psy->use_cnt) <= 0 ||
1079 			!psy->desc->property_is_writeable)
1080 		return -ENODEV;
1081 
1082 	return psy->desc->property_is_writeable(psy, psp);
1083 }
1084 EXPORT_SYMBOL_GPL(power_supply_property_is_writeable);
1085 
power_supply_external_power_changed(struct power_supply * psy)1086 void power_supply_external_power_changed(struct power_supply *psy)
1087 {
1088 	if (atomic_read(&psy->use_cnt) <= 0 ||
1089 			!psy->desc->external_power_changed)
1090 		return;
1091 
1092 	psy->desc->external_power_changed(psy);
1093 }
1094 EXPORT_SYMBOL_GPL(power_supply_external_power_changed);
1095 
power_supply_powers(struct power_supply * psy,struct device * dev)1096 int power_supply_powers(struct power_supply *psy, struct device *dev)
1097 {
1098 	return sysfs_create_link(&psy->dev.kobj, &dev->kobj, "powers");
1099 }
1100 EXPORT_SYMBOL_GPL(power_supply_powers);
1101 
power_supply_dev_release(struct device * dev)1102 static void power_supply_dev_release(struct device *dev)
1103 {
1104 	struct power_supply *psy = to_power_supply(dev);
1105 	dev_dbg(dev, "%s\n", __func__);
1106 	kfree(psy);
1107 }
1108 
power_supply_reg_notifier(struct notifier_block * nb)1109 int power_supply_reg_notifier(struct notifier_block *nb)
1110 {
1111 	return atomic_notifier_chain_register(&power_supply_notifier, nb);
1112 }
1113 EXPORT_SYMBOL_GPL(power_supply_reg_notifier);
1114 
power_supply_unreg_notifier(struct notifier_block * nb)1115 void power_supply_unreg_notifier(struct notifier_block *nb)
1116 {
1117 	atomic_notifier_chain_unregister(&power_supply_notifier, nb);
1118 }
1119 EXPORT_SYMBOL_GPL(power_supply_unreg_notifier);
1120 
psy_has_property(const struct power_supply_desc * psy_desc,enum power_supply_property psp)1121 static bool psy_has_property(const struct power_supply_desc *psy_desc,
1122 			     enum power_supply_property psp)
1123 {
1124 	bool found = false;
1125 	int i;
1126 
1127 	for (i = 0; i < psy_desc->num_properties; i++) {
1128 		if (psy_desc->properties[i] == psp) {
1129 			found = true;
1130 			break;
1131 		}
1132 	}
1133 
1134 	return found;
1135 }
1136 
1137 #ifdef CONFIG_THERMAL
power_supply_read_temp(struct thermal_zone_device * tzd,int * temp)1138 static int power_supply_read_temp(struct thermal_zone_device *tzd,
1139 		int *temp)
1140 {
1141 	struct power_supply *psy;
1142 	union power_supply_propval val;
1143 	int ret;
1144 
1145 	WARN_ON(tzd == NULL);
1146 	psy = tzd->devdata;
1147 	ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_TEMP, &val);
1148 	if (ret)
1149 		return ret;
1150 
1151 	/* Convert tenths of degree Celsius to milli degree Celsius. */
1152 	*temp = val.intval * 100;
1153 
1154 	return ret;
1155 }
1156 
1157 static struct thermal_zone_device_ops psy_tzd_ops = {
1158 	.get_temp = power_supply_read_temp,
1159 };
1160 
psy_register_thermal(struct power_supply * psy)1161 static int psy_register_thermal(struct power_supply *psy)
1162 {
1163 	int ret;
1164 
1165 	if (psy->desc->no_thermal)
1166 		return 0;
1167 
1168 	/* Register battery zone device psy reports temperature */
1169 	if (psy_has_property(psy->desc, POWER_SUPPLY_PROP_TEMP)) {
1170 		psy->tzd = thermal_zone_device_register(psy->desc->name,
1171 				0, 0, psy, &psy_tzd_ops, NULL, 0, 0);
1172 		if (IS_ERR(psy->tzd))
1173 			return PTR_ERR(psy->tzd);
1174 		ret = thermal_zone_device_enable(psy->tzd);
1175 		if (ret)
1176 			thermal_zone_device_unregister(psy->tzd);
1177 		return ret;
1178 	}
1179 
1180 	return 0;
1181 }
1182 
psy_unregister_thermal(struct power_supply * psy)1183 static void psy_unregister_thermal(struct power_supply *psy)
1184 {
1185 	if (IS_ERR_OR_NULL(psy->tzd))
1186 		return;
1187 	thermal_zone_device_unregister(psy->tzd);
1188 }
1189 
1190 /* thermal cooling device callbacks */
ps_get_max_charge_cntl_limit(struct thermal_cooling_device * tcd,unsigned long * state)1191 static int ps_get_max_charge_cntl_limit(struct thermal_cooling_device *tcd,
1192 					unsigned long *state)
1193 {
1194 	struct power_supply *psy;
1195 	union power_supply_propval val;
1196 	int ret;
1197 
1198 	psy = tcd->devdata;
1199 	ret = power_supply_get_property(psy,
1200 			POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT_MAX, &val);
1201 	if (ret)
1202 		return ret;
1203 
1204 	*state = val.intval;
1205 
1206 	return ret;
1207 }
1208 
ps_get_cur_charge_cntl_limit(struct thermal_cooling_device * tcd,unsigned long * state)1209 static int ps_get_cur_charge_cntl_limit(struct thermal_cooling_device *tcd,
1210 					unsigned long *state)
1211 {
1212 	struct power_supply *psy;
1213 	union power_supply_propval val;
1214 	int ret;
1215 
1216 	psy = tcd->devdata;
1217 	ret = power_supply_get_property(psy,
1218 			POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT, &val);
1219 	if (ret)
1220 		return ret;
1221 
1222 	*state = val.intval;
1223 
1224 	return ret;
1225 }
1226 
ps_set_cur_charge_cntl_limit(struct thermal_cooling_device * tcd,unsigned long state)1227 static int ps_set_cur_charge_cntl_limit(struct thermal_cooling_device *tcd,
1228 					unsigned long state)
1229 {
1230 	struct power_supply *psy;
1231 	union power_supply_propval val;
1232 	int ret;
1233 
1234 	psy = tcd->devdata;
1235 	val.intval = state;
1236 	ret = psy->desc->set_property(psy,
1237 		POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT, &val);
1238 
1239 	return ret;
1240 }
1241 
1242 static const struct thermal_cooling_device_ops psy_tcd_ops = {
1243 	.get_max_state = ps_get_max_charge_cntl_limit,
1244 	.get_cur_state = ps_get_cur_charge_cntl_limit,
1245 	.set_cur_state = ps_set_cur_charge_cntl_limit,
1246 };
1247 
psy_register_cooler(struct power_supply * psy)1248 static int psy_register_cooler(struct power_supply *psy)
1249 {
1250 	/* Register for cooling device if psy can control charging */
1251 	if (psy_has_property(psy->desc, POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT)) {
1252 		psy->tcd = thermal_cooling_device_register(
1253 			(char *)psy->desc->name,
1254 			psy, &psy_tcd_ops);
1255 		return PTR_ERR_OR_ZERO(psy->tcd);
1256 	}
1257 
1258 	return 0;
1259 }
1260 
psy_unregister_cooler(struct power_supply * psy)1261 static void psy_unregister_cooler(struct power_supply *psy)
1262 {
1263 	if (IS_ERR_OR_NULL(psy->tcd))
1264 		return;
1265 	thermal_cooling_device_unregister(psy->tcd);
1266 }
1267 #else
psy_register_thermal(struct power_supply * psy)1268 static int psy_register_thermal(struct power_supply *psy)
1269 {
1270 	return 0;
1271 }
1272 
psy_unregister_thermal(struct power_supply * psy)1273 static void psy_unregister_thermal(struct power_supply *psy)
1274 {
1275 }
1276 
psy_register_cooler(struct power_supply * psy)1277 static int psy_register_cooler(struct power_supply *psy)
1278 {
1279 	return 0;
1280 }
1281 
psy_unregister_cooler(struct power_supply * psy)1282 static void psy_unregister_cooler(struct power_supply *psy)
1283 {
1284 }
1285 #endif
1286 
1287 static struct power_supply *__must_check
__power_supply_register(struct device * parent,const struct power_supply_desc * desc,const struct power_supply_config * cfg,bool ws)1288 __power_supply_register(struct device *parent,
1289 				   const struct power_supply_desc *desc,
1290 				   const struct power_supply_config *cfg,
1291 				   bool ws)
1292 {
1293 	struct device *dev;
1294 	struct power_supply *psy;
1295 	int rc;
1296 
1297 	if (!parent)
1298 		pr_warn("%s: Expected proper parent device for '%s'\n",
1299 			__func__, desc->name);
1300 
1301 	if (!desc || !desc->name || !desc->properties || !desc->num_properties)
1302 		return ERR_PTR(-EINVAL);
1303 
1304 	if (psy_has_property(desc, POWER_SUPPLY_PROP_USB_TYPE) &&
1305 	    (!desc->usb_types || !desc->num_usb_types))
1306 		return ERR_PTR(-EINVAL);
1307 
1308 	psy = kzalloc(sizeof(*psy), GFP_KERNEL);
1309 	if (!psy)
1310 		return ERR_PTR(-ENOMEM);
1311 
1312 	dev = &psy->dev;
1313 
1314 	device_initialize(dev);
1315 
1316 	dev->class = power_supply_class;
1317 	dev->type = &power_supply_dev_type;
1318 	dev->parent = parent;
1319 	dev->release = power_supply_dev_release;
1320 	dev_set_drvdata(dev, psy);
1321 	psy->desc = desc;
1322 	if (cfg) {
1323 		dev->groups = cfg->attr_grp;
1324 		psy->drv_data = cfg->drv_data;
1325 		psy->of_node =
1326 			cfg->fwnode ? to_of_node(cfg->fwnode) : cfg->of_node;
1327 		psy->supplied_to = cfg->supplied_to;
1328 		psy->num_supplicants = cfg->num_supplicants;
1329 	}
1330 
1331 	rc = dev_set_name(dev, "%s", desc->name);
1332 	if (rc)
1333 		goto dev_set_name_failed;
1334 
1335 	INIT_WORK(&psy->changed_work, power_supply_changed_work);
1336 	INIT_DELAYED_WORK(&psy->deferred_register_work,
1337 			  power_supply_deferred_register_work);
1338 
1339 	rc = power_supply_check_supplies(psy);
1340 	if (rc) {
1341 		dev_dbg(dev, "Not all required supplies found, defer probe\n");
1342 		goto check_supplies_failed;
1343 	}
1344 
1345 	spin_lock_init(&psy->changed_lock);
1346 	rc = device_add(dev);
1347 	if (rc)
1348 		goto device_add_failed;
1349 
1350 	rc = device_init_wakeup(dev, ws);
1351 	if (rc)
1352 		goto wakeup_init_failed;
1353 
1354 	rc = psy_register_thermal(psy);
1355 	if (rc)
1356 		goto register_thermal_failed;
1357 
1358 	rc = psy_register_cooler(psy);
1359 	if (rc)
1360 		goto register_cooler_failed;
1361 
1362 	rc = power_supply_create_triggers(psy);
1363 	if (rc)
1364 		goto create_triggers_failed;
1365 
1366 	rc = power_supply_add_hwmon_sysfs(psy);
1367 	if (rc)
1368 		goto add_hwmon_sysfs_failed;
1369 
1370 	/*
1371 	 * Update use_cnt after any uevents (most notably from device_add()).
1372 	 * We are here still during driver's probe but
1373 	 * the power_supply_uevent() calls back driver's get_property
1374 	 * method so:
1375 	 * 1. Driver did not assigned the returned struct power_supply,
1376 	 * 2. Driver could not finish initialization (anything in its probe
1377 	 *    after calling power_supply_register()).
1378 	 */
1379 	atomic_inc(&psy->use_cnt);
1380 	psy->initialized = true;
1381 
1382 	queue_delayed_work(system_power_efficient_wq,
1383 			   &psy->deferred_register_work,
1384 			   POWER_SUPPLY_DEFERRED_REGISTER_TIME);
1385 
1386 	return psy;
1387 
1388 add_hwmon_sysfs_failed:
1389 	power_supply_remove_triggers(psy);
1390 create_triggers_failed:
1391 	psy_unregister_cooler(psy);
1392 register_cooler_failed:
1393 	psy_unregister_thermal(psy);
1394 register_thermal_failed:
1395 wakeup_init_failed:
1396 	device_del(dev);
1397 device_add_failed:
1398 check_supplies_failed:
1399 dev_set_name_failed:
1400 	put_device(dev);
1401 	return ERR_PTR(rc);
1402 }
1403 
1404 /**
1405  * power_supply_register() - Register new power supply
1406  * @parent:	Device to be a parent of power supply's device, usually
1407  *		the device which probe function calls this
1408  * @desc:	Description of power supply, must be valid through whole
1409  *		lifetime of this power supply
1410  * @cfg:	Run-time specific configuration accessed during registering,
1411  *		may be NULL
1412  *
1413  * Return: A pointer to newly allocated power_supply on success
1414  * or ERR_PTR otherwise.
1415  * Use power_supply_unregister() on returned power_supply pointer to release
1416  * resources.
1417  */
power_supply_register(struct device * parent,const struct power_supply_desc * desc,const struct power_supply_config * cfg)1418 struct power_supply *__must_check power_supply_register(struct device *parent,
1419 		const struct power_supply_desc *desc,
1420 		const struct power_supply_config *cfg)
1421 {
1422 	return __power_supply_register(parent, desc, cfg, true);
1423 }
1424 EXPORT_SYMBOL_GPL(power_supply_register);
1425 
1426 /**
1427  * power_supply_register_no_ws() - Register new non-waking-source power supply
1428  * @parent:	Device to be a parent of power supply's device, usually
1429  *		the device which probe function calls this
1430  * @desc:	Description of power supply, must be valid through whole
1431  *		lifetime of this power supply
1432  * @cfg:	Run-time specific configuration accessed during registering,
1433  *		may be NULL
1434  *
1435  * Return: A pointer to newly allocated power_supply on success
1436  * or ERR_PTR otherwise.
1437  * Use power_supply_unregister() on returned power_supply pointer to release
1438  * resources.
1439  */
1440 struct power_supply *__must_check
power_supply_register_no_ws(struct device * parent,const struct power_supply_desc * desc,const struct power_supply_config * cfg)1441 power_supply_register_no_ws(struct device *parent,
1442 		const struct power_supply_desc *desc,
1443 		const struct power_supply_config *cfg)
1444 {
1445 	return __power_supply_register(parent, desc, cfg, false);
1446 }
1447 EXPORT_SYMBOL_GPL(power_supply_register_no_ws);
1448 
devm_power_supply_release(struct device * dev,void * res)1449 static void devm_power_supply_release(struct device *dev, void *res)
1450 {
1451 	struct power_supply **psy = res;
1452 
1453 	power_supply_unregister(*psy);
1454 }
1455 
1456 /**
1457  * devm_power_supply_register() - Register managed power supply
1458  * @parent:	Device to be a parent of power supply's device, usually
1459  *		the device which probe function calls this
1460  * @desc:	Description of power supply, must be valid through whole
1461  *		lifetime of this power supply
1462  * @cfg:	Run-time specific configuration accessed during registering,
1463  *		may be NULL
1464  *
1465  * Return: A pointer to newly allocated power_supply on success
1466  * or ERR_PTR otherwise.
1467  * The returned power_supply pointer will be automatically unregistered
1468  * on driver detach.
1469  */
1470 struct power_supply *__must_check
devm_power_supply_register(struct device * parent,const struct power_supply_desc * desc,const struct power_supply_config * cfg)1471 devm_power_supply_register(struct device *parent,
1472 		const struct power_supply_desc *desc,
1473 		const struct power_supply_config *cfg)
1474 {
1475 	struct power_supply **ptr, *psy;
1476 
1477 	ptr = devres_alloc(devm_power_supply_release, sizeof(*ptr), GFP_KERNEL);
1478 
1479 	if (!ptr)
1480 		return ERR_PTR(-ENOMEM);
1481 	psy = __power_supply_register(parent, desc, cfg, true);
1482 	if (IS_ERR(psy)) {
1483 		devres_free(ptr);
1484 	} else {
1485 		*ptr = psy;
1486 		devres_add(parent, ptr);
1487 	}
1488 	return psy;
1489 }
1490 EXPORT_SYMBOL_GPL(devm_power_supply_register);
1491 
1492 /**
1493  * devm_power_supply_register_no_ws() - Register managed non-waking-source power supply
1494  * @parent:	Device to be a parent of power supply's device, usually
1495  *		the device which probe function calls this
1496  * @desc:	Description of power supply, must be valid through whole
1497  *		lifetime of this power supply
1498  * @cfg:	Run-time specific configuration accessed during registering,
1499  *		may be NULL
1500  *
1501  * Return: A pointer to newly allocated power_supply on success
1502  * or ERR_PTR otherwise.
1503  * The returned power_supply pointer will be automatically unregistered
1504  * on driver detach.
1505  */
1506 struct power_supply *__must_check
devm_power_supply_register_no_ws(struct device * parent,const struct power_supply_desc * desc,const struct power_supply_config * cfg)1507 devm_power_supply_register_no_ws(struct device *parent,
1508 		const struct power_supply_desc *desc,
1509 		const struct power_supply_config *cfg)
1510 {
1511 	struct power_supply **ptr, *psy;
1512 
1513 	ptr = devres_alloc(devm_power_supply_release, sizeof(*ptr), GFP_KERNEL);
1514 
1515 	if (!ptr)
1516 		return ERR_PTR(-ENOMEM);
1517 	psy = __power_supply_register(parent, desc, cfg, false);
1518 	if (IS_ERR(psy)) {
1519 		devres_free(ptr);
1520 	} else {
1521 		*ptr = psy;
1522 		devres_add(parent, ptr);
1523 	}
1524 	return psy;
1525 }
1526 EXPORT_SYMBOL_GPL(devm_power_supply_register_no_ws);
1527 
1528 /**
1529  * power_supply_unregister() - Remove this power supply from system
1530  * @psy:	Pointer to power supply to unregister
1531  *
1532  * Remove this power supply from the system. The resources of power supply
1533  * will be freed here or on last power_supply_put() call.
1534  */
power_supply_unregister(struct power_supply * psy)1535 void power_supply_unregister(struct power_supply *psy)
1536 {
1537 	WARN_ON(atomic_dec_return(&psy->use_cnt));
1538 	psy->removing = true;
1539 	cancel_work_sync(&psy->changed_work);
1540 	cancel_delayed_work_sync(&psy->deferred_register_work);
1541 	sysfs_remove_link(&psy->dev.kobj, "powers");
1542 	power_supply_remove_hwmon_sysfs(psy);
1543 	power_supply_remove_triggers(psy);
1544 	psy_unregister_cooler(psy);
1545 	psy_unregister_thermal(psy);
1546 	device_init_wakeup(&psy->dev, false);
1547 	device_unregister(&psy->dev);
1548 }
1549 EXPORT_SYMBOL_GPL(power_supply_unregister);
1550 
power_supply_get_drvdata(struct power_supply * psy)1551 void *power_supply_get_drvdata(struct power_supply *psy)
1552 {
1553 	return psy->drv_data;
1554 }
1555 EXPORT_SYMBOL_GPL(power_supply_get_drvdata);
1556 
power_supply_class_init(void)1557 static int __init power_supply_class_init(void)
1558 {
1559 	power_supply_class = class_create(THIS_MODULE, "power_supply");
1560 
1561 	if (IS_ERR(power_supply_class))
1562 		return PTR_ERR(power_supply_class);
1563 
1564 	power_supply_class->dev_uevent = power_supply_uevent;
1565 	power_supply_init_attrs(&power_supply_dev_type);
1566 
1567 	return 0;
1568 }
1569 
power_supply_class_exit(void)1570 static void __exit power_supply_class_exit(void)
1571 {
1572 	class_destroy(power_supply_class);
1573 }
1574 
1575 subsys_initcall(power_supply_class_init);
1576 module_exit(power_supply_class_exit);
1577 
1578 MODULE_DESCRIPTION("Universal power supply monitor class");
1579 MODULE_AUTHOR("Ian Molton <spyro@f2s.com>, "
1580 	      "Szabolcs Gyurko, "
1581 	      "Anton Vorontsov <cbou@mail.ru>");
1582 MODULE_LICENSE("GPL");
1583