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