• 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 (!power_supply_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 = NULL;
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 if (psy->dev.parent) {
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 	if (!fwnode)
681 		return -ENOENT;
682 
683 	err = fwnode_property_read_string(fwnode, "compatible", &value);
684 	if (err)
685 		goto out_put_node;
686 
687 
688 	/* Try static batteries first */
689 	err = samsung_sdi_battery_get_info(&psy->dev, value, &info);
690 	if (!err)
691 		goto out_ret_pointer;
692 	else if (err == -ENODEV)
693 		/*
694 		 * Device does not have a static battery.
695 		 * Proceed to look for a simple battery.
696 		 */
697 		err = 0;
698 
699 	if (strcmp("simple-battery", value)) {
700 		err = -ENODEV;
701 		goto out_put_node;
702 	}
703 
704 	info = devm_kzalloc(&psy->dev, sizeof(*info), GFP_KERNEL);
705 	if (!info) {
706 		err = -ENOMEM;
707 		goto out_put_node;
708 	}
709 
710 	info->technology                     = POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
711 	info->energy_full_design_uwh         = -EINVAL;
712 	info->charge_full_design_uah         = -EINVAL;
713 	info->voltage_min_design_uv          = -EINVAL;
714 	info->voltage_max_design_uv          = -EINVAL;
715 	info->precharge_current_ua           = -EINVAL;
716 	info->charge_term_current_ua         = -EINVAL;
717 	info->constant_charge_current_max_ua = -EINVAL;
718 	info->constant_charge_voltage_max_uv = -EINVAL;
719 	info->tricklecharge_current_ua       = -EINVAL;
720 	info->precharge_voltage_max_uv       = -EINVAL;
721 	info->charge_restart_voltage_uv      = -EINVAL;
722 	info->overvoltage_limit_uv           = -EINVAL;
723 	info->maintenance_charge             = NULL;
724 	info->alert_low_temp_charge_current_ua = -EINVAL;
725 	info->alert_low_temp_charge_voltage_uv = -EINVAL;
726 	info->alert_high_temp_charge_current_ua = -EINVAL;
727 	info->alert_high_temp_charge_voltage_uv = -EINVAL;
728 	info->temp_ambient_alert_min         = INT_MIN;
729 	info->temp_ambient_alert_max         = INT_MAX;
730 	info->temp_alert_min                 = INT_MIN;
731 	info->temp_alert_max                 = INT_MAX;
732 	info->temp_min                       = INT_MIN;
733 	info->temp_max                       = INT_MAX;
734 	info->factory_internal_resistance_uohm  = -EINVAL;
735 	info->resist_table                   = NULL;
736 	info->bti_resistance_ohm             = -EINVAL;
737 	info->bti_resistance_tolerance       = -EINVAL;
738 
739 	for (index = 0; index < POWER_SUPPLY_OCV_TEMP_MAX; index++) {
740 		info->ocv_table[index]       = NULL;
741 		info->ocv_temp[index]        = -EINVAL;
742 		info->ocv_table_size[index]  = -EINVAL;
743 	}
744 
745 	/* The property and field names below must correspond to elements
746 	 * in enum power_supply_property. For reasoning, see
747 	 * Documentation/power/power_supply_class.rst.
748 	 */
749 
750 	if (!fwnode_property_read_string(fwnode, "device-chemistry", &value)) {
751 		if (!strcmp("nickel-cadmium", value))
752 			info->technology = POWER_SUPPLY_TECHNOLOGY_NiCd;
753 		else if (!strcmp("nickel-metal-hydride", value))
754 			info->technology = POWER_SUPPLY_TECHNOLOGY_NiMH;
755 		else if (!strcmp("lithium-ion", value))
756 			/* Imprecise lithium-ion type */
757 			info->technology = POWER_SUPPLY_TECHNOLOGY_LION;
758 		else if (!strcmp("lithium-ion-polymer", value))
759 			info->technology = POWER_SUPPLY_TECHNOLOGY_LIPO;
760 		else if (!strcmp("lithium-ion-iron-phosphate", value))
761 			info->technology = POWER_SUPPLY_TECHNOLOGY_LiFe;
762 		else if (!strcmp("lithium-ion-manganese-oxide", value))
763 			info->technology = POWER_SUPPLY_TECHNOLOGY_LiMn;
764 		else
765 			dev_warn(&psy->dev, "%s unknown battery type\n", value);
766 	}
767 
768 	fwnode_property_read_u32(fwnode, "energy-full-design-microwatt-hours",
769 			     &info->energy_full_design_uwh);
770 	fwnode_property_read_u32(fwnode, "charge-full-design-microamp-hours",
771 			     &info->charge_full_design_uah);
772 	fwnode_property_read_u32(fwnode, "voltage-min-design-microvolt",
773 			     &info->voltage_min_design_uv);
774 	fwnode_property_read_u32(fwnode, "voltage-max-design-microvolt",
775 			     &info->voltage_max_design_uv);
776 	fwnode_property_read_u32(fwnode, "trickle-charge-current-microamp",
777 			     &info->tricklecharge_current_ua);
778 	fwnode_property_read_u32(fwnode, "precharge-current-microamp",
779 			     &info->precharge_current_ua);
780 	fwnode_property_read_u32(fwnode, "precharge-upper-limit-microvolt",
781 			     &info->precharge_voltage_max_uv);
782 	fwnode_property_read_u32(fwnode, "charge-term-current-microamp",
783 			     &info->charge_term_current_ua);
784 	fwnode_property_read_u32(fwnode, "re-charge-voltage-microvolt",
785 			     &info->charge_restart_voltage_uv);
786 	fwnode_property_read_u32(fwnode, "over-voltage-threshold-microvolt",
787 			     &info->overvoltage_limit_uv);
788 	fwnode_property_read_u32(fwnode, "constant-charge-current-max-microamp",
789 			     &info->constant_charge_current_max_ua);
790 	fwnode_property_read_u32(fwnode, "constant-charge-voltage-max-microvolt",
791 			     &info->constant_charge_voltage_max_uv);
792 	fwnode_property_read_u32(fwnode, "factory-internal-resistance-micro-ohms",
793 			     &info->factory_internal_resistance_uohm);
794 
795 	if (!fwnode_property_read_u32_array(fwnode, "ambient-celsius",
796 					    min_max, ARRAY_SIZE(min_max))) {
797 		info->temp_ambient_alert_min = min_max[0];
798 		info->temp_ambient_alert_max = min_max[1];
799 	}
800 	if (!fwnode_property_read_u32_array(fwnode, "alert-celsius",
801 					    min_max, ARRAY_SIZE(min_max))) {
802 		info->temp_alert_min = min_max[0];
803 		info->temp_alert_max = min_max[1];
804 	}
805 	if (!fwnode_property_read_u32_array(fwnode, "operating-range-celsius",
806 					    min_max, ARRAY_SIZE(min_max))) {
807 		info->temp_min = min_max[0];
808 		info->temp_max = min_max[1];
809 	}
810 
811 	/*
812 	 * The below code uses raw of-data parsing to parse
813 	 * /schemas/types.yaml#/definitions/uint32-matrix
814 	 * data, so for now this is only support with of.
815 	 */
816 	if (!battery_np)
817 		goto out_ret_pointer;
818 
819 	len = of_property_count_u32_elems(battery_np, "ocv-capacity-celsius");
820 	if (len < 0 && len != -EINVAL) {
821 		err = len;
822 		goto out_put_node;
823 	} else if (len > POWER_SUPPLY_OCV_TEMP_MAX) {
824 		dev_err(&psy->dev, "Too many temperature values\n");
825 		err = -EINVAL;
826 		goto out_put_node;
827 	} else if (len > 0) {
828 		of_property_read_u32_array(battery_np, "ocv-capacity-celsius",
829 					   info->ocv_temp, len);
830 	}
831 
832 	for (index = 0; index < len; index++) {
833 		struct power_supply_battery_ocv_table *table;
834 		char *propname;
835 		int i, tab_len, size;
836 
837 		propname = kasprintf(GFP_KERNEL, "ocv-capacity-table-%d", index);
838 		if (!propname) {
839 			power_supply_put_battery_info(psy, info);
840 			err = -ENOMEM;
841 			goto out_put_node;
842 		}
843 		list = of_get_property(battery_np, propname, &size);
844 		if (!list || !size) {
845 			dev_err(&psy->dev, "failed to get %s\n", propname);
846 			kfree(propname);
847 			power_supply_put_battery_info(psy, info);
848 			err = -EINVAL;
849 			goto out_put_node;
850 		}
851 
852 		kfree(propname);
853 		tab_len = size / (2 * sizeof(__be32));
854 		info->ocv_table_size[index] = tab_len;
855 
856 		table = info->ocv_table[index] =
857 			devm_kcalloc(&psy->dev, tab_len, sizeof(*table), GFP_KERNEL);
858 		if (!info->ocv_table[index]) {
859 			power_supply_put_battery_info(psy, info);
860 			err = -ENOMEM;
861 			goto out_put_node;
862 		}
863 
864 		for (i = 0; i < tab_len; i++) {
865 			table[i].ocv = be32_to_cpu(*list);
866 			list++;
867 			table[i].capacity = be32_to_cpu(*list);
868 			list++;
869 		}
870 	}
871 
872 	list = of_get_property(battery_np, "resistance-temp-table", &len);
873 	if (!list || !len)
874 		goto out_ret_pointer;
875 
876 	info->resist_table_size = len / (2 * sizeof(__be32));
877 	resist_table = info->resist_table = devm_kcalloc(&psy->dev,
878 							 info->resist_table_size,
879 							 sizeof(*resist_table),
880 							 GFP_KERNEL);
881 	if (!info->resist_table) {
882 		power_supply_put_battery_info(psy, info);
883 		err = -ENOMEM;
884 		goto out_put_node;
885 	}
886 
887 	for (index = 0; index < info->resist_table_size; index++) {
888 		resist_table[index].temp = be32_to_cpu(*list++);
889 		resist_table[index].resistance = be32_to_cpu(*list++);
890 	}
891 
892 out_ret_pointer:
893 	/* Finally return the whole thing */
894 	*info_out = info;
895 
896 out_put_node:
897 	fwnode_handle_put(fwnode);
898 	of_node_put(battery_np);
899 	return err;
900 }
901 EXPORT_SYMBOL_GPL(power_supply_get_battery_info);
902 
power_supply_put_battery_info(struct power_supply * psy,struct power_supply_battery_info * info)903 void power_supply_put_battery_info(struct power_supply *psy,
904 				   struct power_supply_battery_info *info)
905 {
906 	int i;
907 
908 	for (i = 0; i < POWER_SUPPLY_OCV_TEMP_MAX; i++) {
909 		if (info->ocv_table[i])
910 			devm_kfree(&psy->dev, info->ocv_table[i]);
911 	}
912 
913 	if (info->resist_table)
914 		devm_kfree(&psy->dev, info->resist_table);
915 
916 	devm_kfree(&psy->dev, info);
917 }
918 EXPORT_SYMBOL_GPL(power_supply_put_battery_info);
919 
920 const enum power_supply_property power_supply_battery_info_properties[] = {
921 	POWER_SUPPLY_PROP_TECHNOLOGY,
922 	POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
923 	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
924 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
925 	POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
926 	POWER_SUPPLY_PROP_PRECHARGE_CURRENT,
927 	POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT,
928 	POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX,
929 	POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX,
930 	POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN,
931 	POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX,
932 	POWER_SUPPLY_PROP_TEMP_ALERT_MIN,
933 	POWER_SUPPLY_PROP_TEMP_ALERT_MAX,
934 	POWER_SUPPLY_PROP_TEMP_MIN,
935 	POWER_SUPPLY_PROP_TEMP_MAX,
936 };
937 EXPORT_SYMBOL_GPL(power_supply_battery_info_properties);
938 
939 const size_t power_supply_battery_info_properties_size = ARRAY_SIZE(power_supply_battery_info_properties);
940 EXPORT_SYMBOL_GPL(power_supply_battery_info_properties_size);
941 
power_supply_battery_info_has_prop(struct power_supply_battery_info * info,enum power_supply_property psp)942 bool power_supply_battery_info_has_prop(struct power_supply_battery_info *info,
943 				        enum power_supply_property psp)
944 {
945 	if (!info)
946 		return false;
947 
948 	switch (psp) {
949 		case POWER_SUPPLY_PROP_TECHNOLOGY:
950 			return info->technology != POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
951 		case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
952 			return info->energy_full_design_uwh >= 0;
953 		case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
954 			return info->charge_full_design_uah >= 0;
955 		case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
956 			return info->voltage_min_design_uv >= 0;
957 		case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
958 			return info->voltage_max_design_uv >= 0;
959 		case POWER_SUPPLY_PROP_PRECHARGE_CURRENT:
960 			return info->precharge_current_ua >= 0;
961 		case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT:
962 			return info->charge_term_current_ua >= 0;
963 		case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
964 			return info->constant_charge_current_max_ua >= 0;
965 		case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
966 			return info->constant_charge_voltage_max_uv >= 0;
967 		case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN:
968 			return info->temp_ambient_alert_min > INT_MIN;
969 		case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX:
970 			return info->temp_ambient_alert_max < INT_MAX;
971 		case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
972 			return info->temp_alert_min > INT_MIN;
973 		case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
974 			return info->temp_alert_max < INT_MAX;
975 		case POWER_SUPPLY_PROP_TEMP_MIN:
976 			return info->temp_min > INT_MIN;
977 		case POWER_SUPPLY_PROP_TEMP_MAX:
978 			return info->temp_max < INT_MAX;
979 		default:
980 			return false;
981 	}
982 }
983 EXPORT_SYMBOL_GPL(power_supply_battery_info_has_prop);
984 
power_supply_battery_info_get_prop(struct power_supply_battery_info * info,enum power_supply_property psp,union power_supply_propval * val)985 int power_supply_battery_info_get_prop(struct power_supply_battery_info *info,
986 				       enum power_supply_property psp,
987 				       union power_supply_propval *val)
988 {
989 	if (!info)
990 		return -EINVAL;
991 
992 	if (!power_supply_battery_info_has_prop(info, psp))
993 		return -EINVAL;
994 
995 	switch (psp) {
996 		case POWER_SUPPLY_PROP_TECHNOLOGY:
997 			val->intval = info->technology;
998 			return 0;
999 		case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
1000 			val->intval = info->energy_full_design_uwh;
1001 			return 0;
1002 		case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
1003 			val->intval = info->charge_full_design_uah;
1004 			return 0;
1005 		case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
1006 			val->intval = info->voltage_min_design_uv;
1007 			return 0;
1008 		case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
1009 			val->intval = info->voltage_max_design_uv;
1010 			return 0;
1011 		case POWER_SUPPLY_PROP_PRECHARGE_CURRENT:
1012 			val->intval = info->precharge_current_ua;
1013 			return 0;
1014 		case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT:
1015 			val->intval = info->charge_term_current_ua;
1016 			return 0;
1017 		case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
1018 			val->intval = info->constant_charge_current_max_ua;
1019 			return 0;
1020 		case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
1021 			val->intval = info->constant_charge_voltage_max_uv;
1022 			return 0;
1023 		case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN:
1024 			val->intval = info->temp_ambient_alert_min;
1025 			return 0;
1026 		case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX:
1027 			val->intval = info->temp_ambient_alert_max;
1028 			return 0;
1029 		case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
1030 			val->intval = info->temp_alert_min;
1031 			return 0;
1032 		case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
1033 			val->intval = info->temp_alert_max;
1034 			return 0;
1035 		case POWER_SUPPLY_PROP_TEMP_MIN:
1036 			val->intval = info->temp_min;
1037 			return 0;
1038 		case POWER_SUPPLY_PROP_TEMP_MAX:
1039 			val->intval = info->temp_max;
1040 			return 0;
1041 		default:
1042 			return -EINVAL;
1043 	}
1044 }
1045 EXPORT_SYMBOL_GPL(power_supply_battery_info_get_prop);
1046 
1047 /**
1048  * power_supply_temp2resist_simple() - find the battery internal resistance
1049  * percent from temperature
1050  * @table: Pointer to battery resistance temperature table
1051  * @table_len: The table length
1052  * @temp: Current temperature
1053  *
1054  * This helper function is used to look up battery internal resistance percent
1055  * according to current temperature value from the resistance temperature table,
1056  * and the table must be ordered descending. Then the actual battery internal
1057  * resistance = the ideal battery internal resistance * percent / 100.
1058  *
1059  * Return: the battery internal resistance percent
1060  */
power_supply_temp2resist_simple(struct power_supply_resistance_temp_table * table,int table_len,int temp)1061 int power_supply_temp2resist_simple(struct power_supply_resistance_temp_table *table,
1062 				    int table_len, int temp)
1063 {
1064 	int i, high, low;
1065 
1066 	for (i = 0; i < table_len; i++)
1067 		if (temp > table[i].temp)
1068 			break;
1069 
1070 	/* The library function will deal with high == low */
1071 	if (i == 0)
1072 		high = low = i;
1073 	else if (i == table_len)
1074 		high = low = i - 1;
1075 	else
1076 		high = (low = i) - 1;
1077 
1078 	return fixp_linear_interpolate(table[low].temp,
1079 				       table[low].resistance,
1080 				       table[high].temp,
1081 				       table[high].resistance,
1082 				       temp);
1083 }
1084 EXPORT_SYMBOL_GPL(power_supply_temp2resist_simple);
1085 
1086 /**
1087  * power_supply_vbat2ri() - find the battery internal resistance
1088  * from the battery voltage
1089  * @info: The battery information container
1090  * @vbat_uv: The battery voltage in microvolt
1091  * @charging: If we are charging (true) or not (false)
1092  *
1093  * This helper function is used to look up battery internal resistance
1094  * according to current battery voltage. Depending on whether the battery
1095  * is currently charging or not, different resistance will be returned.
1096  *
1097  * Returns the internal resistance in microohm or negative error code.
1098  */
power_supply_vbat2ri(struct power_supply_battery_info * info,int vbat_uv,bool charging)1099 int power_supply_vbat2ri(struct power_supply_battery_info *info,
1100 			 int vbat_uv, bool charging)
1101 {
1102 	struct power_supply_vbat_ri_table *vbat2ri;
1103 	int table_len;
1104 	int i, high, low;
1105 
1106 	/*
1107 	 * If we are charging, and the battery supplies a separate table
1108 	 * for this state, we use that in order to compensate for the
1109 	 * charging voltage. Otherwise we use the main table.
1110 	 */
1111 	if (charging && info->vbat2ri_charging) {
1112 		vbat2ri = info->vbat2ri_charging;
1113 		table_len = info->vbat2ri_charging_size;
1114 	} else {
1115 		vbat2ri = info->vbat2ri_discharging;
1116 		table_len = info->vbat2ri_discharging_size;
1117 	}
1118 
1119 	/*
1120 	 * If no tables are specified, or if we are above the highest voltage in
1121 	 * the voltage table, just return the factory specified internal resistance.
1122 	 */
1123 	if (!vbat2ri || (table_len <= 0) || (vbat_uv > vbat2ri[0].vbat_uv)) {
1124 		if (charging && (info->factory_internal_resistance_charging_uohm > 0))
1125 			return info->factory_internal_resistance_charging_uohm;
1126 		else
1127 			return info->factory_internal_resistance_uohm;
1128 	}
1129 
1130 	/* Break loop at table_len - 1 because that is the highest index */
1131 	for (i = 0; i < table_len - 1; i++)
1132 		if (vbat_uv > vbat2ri[i].vbat_uv)
1133 			break;
1134 
1135 	/* The library function will deal with high == low */
1136 	if ((i == 0) || (i == (table_len - 1)))
1137 		high = i;
1138 	else
1139 		high = i - 1;
1140 	low = i;
1141 
1142 	return fixp_linear_interpolate(vbat2ri[low].vbat_uv,
1143 				       vbat2ri[low].ri_uohm,
1144 				       vbat2ri[high].vbat_uv,
1145 				       vbat2ri[high].ri_uohm,
1146 				       vbat_uv);
1147 }
1148 EXPORT_SYMBOL_GPL(power_supply_vbat2ri);
1149 
1150 struct power_supply_maintenance_charge_table *
power_supply_get_maintenance_charging_setting(struct power_supply_battery_info * info,int index)1151 power_supply_get_maintenance_charging_setting(struct power_supply_battery_info *info,
1152 					      int index)
1153 {
1154 	if (index >= info->maintenance_charge_size)
1155 		return NULL;
1156 	return &info->maintenance_charge[index];
1157 }
1158 EXPORT_SYMBOL_GPL(power_supply_get_maintenance_charging_setting);
1159 
1160 /**
1161  * power_supply_ocv2cap_simple() - find the battery capacity
1162  * @table: Pointer to battery OCV lookup table
1163  * @table_len: OCV table length
1164  * @ocv: Current OCV value
1165  *
1166  * This helper function is used to look up battery capacity according to
1167  * current OCV value from one OCV table, and the OCV table must be ordered
1168  * descending.
1169  *
1170  * Return: the battery capacity.
1171  */
power_supply_ocv2cap_simple(struct power_supply_battery_ocv_table * table,int table_len,int ocv)1172 int power_supply_ocv2cap_simple(struct power_supply_battery_ocv_table *table,
1173 				int table_len, int ocv)
1174 {
1175 	int i, high, low;
1176 
1177 	for (i = 0; i < table_len; i++)
1178 		if (ocv > table[i].ocv)
1179 			break;
1180 
1181 	/* The library function will deal with high == low */
1182 	if (i == 0)
1183 		high = low = i;
1184 	else if (i == table_len)
1185 		high = low = i - 1;
1186 	else
1187 		high = (low = i) - 1;
1188 
1189 	return fixp_linear_interpolate(table[low].ocv,
1190 				       table[low].capacity,
1191 				       table[high].ocv,
1192 				       table[high].capacity,
1193 				       ocv);
1194 }
1195 EXPORT_SYMBOL_GPL(power_supply_ocv2cap_simple);
1196 
1197 struct power_supply_battery_ocv_table *
power_supply_find_ocv2cap_table(struct power_supply_battery_info * info,int temp,int * table_len)1198 power_supply_find_ocv2cap_table(struct power_supply_battery_info *info,
1199 				int temp, int *table_len)
1200 {
1201 	int best_temp_diff = INT_MAX, temp_diff;
1202 	u8 i, best_index = 0;
1203 
1204 	if (!info->ocv_table[0])
1205 		return NULL;
1206 
1207 	for (i = 0; i < POWER_SUPPLY_OCV_TEMP_MAX; i++) {
1208 		/* Out of capacity tables */
1209 		if (!info->ocv_table[i])
1210 			break;
1211 
1212 		temp_diff = abs(info->ocv_temp[i] - temp);
1213 
1214 		if (temp_diff < best_temp_diff) {
1215 			best_temp_diff = temp_diff;
1216 			best_index = i;
1217 		}
1218 	}
1219 
1220 	*table_len = info->ocv_table_size[best_index];
1221 	return info->ocv_table[best_index];
1222 }
1223 EXPORT_SYMBOL_GPL(power_supply_find_ocv2cap_table);
1224 
power_supply_batinfo_ocv2cap(struct power_supply_battery_info * info,int ocv,int temp)1225 int power_supply_batinfo_ocv2cap(struct power_supply_battery_info *info,
1226 				 int ocv, int temp)
1227 {
1228 	struct power_supply_battery_ocv_table *table;
1229 	int table_len;
1230 
1231 	table = power_supply_find_ocv2cap_table(info, temp, &table_len);
1232 	if (!table)
1233 		return -EINVAL;
1234 
1235 	return power_supply_ocv2cap_simple(table, table_len, ocv);
1236 }
1237 EXPORT_SYMBOL_GPL(power_supply_batinfo_ocv2cap);
1238 
power_supply_battery_bti_in_range(struct power_supply_battery_info * info,int resistance)1239 bool power_supply_battery_bti_in_range(struct power_supply_battery_info *info,
1240 				       int resistance)
1241 {
1242 	int low, high;
1243 
1244 	/* Nothing like this can be checked */
1245 	if (info->bti_resistance_ohm <= 0)
1246 		return false;
1247 
1248 	/* This will be extremely strict and unlikely to work */
1249 	if (info->bti_resistance_tolerance <= 0)
1250 		return (info->bti_resistance_ohm == resistance);
1251 
1252 	low = info->bti_resistance_ohm -
1253 		(info->bti_resistance_ohm * info->bti_resistance_tolerance) / 100;
1254 	high = info->bti_resistance_ohm +
1255 		(info->bti_resistance_ohm * info->bti_resistance_tolerance) / 100;
1256 
1257 	return ((resistance >= low) && (resistance <= high));
1258 }
1259 EXPORT_SYMBOL_GPL(power_supply_battery_bti_in_range);
1260 
psy_has_property(const struct power_supply_desc * psy_desc,enum power_supply_property psp)1261 static bool psy_has_property(const struct power_supply_desc *psy_desc,
1262 			     enum power_supply_property psp)
1263 {
1264 	bool found = false;
1265 	int i;
1266 
1267 	for (i = 0; i < psy_desc->num_properties; i++) {
1268 		if (psy_desc->properties[i] == psp) {
1269 			found = true;
1270 			break;
1271 		}
1272 	}
1273 
1274 	return found;
1275 }
1276 
power_supply_get_property(struct power_supply * psy,enum power_supply_property psp,union power_supply_propval * val)1277 int power_supply_get_property(struct power_supply *psy,
1278 			    enum power_supply_property psp,
1279 			    union power_supply_propval *val)
1280 {
1281 	if (atomic_read(&psy->use_cnt) <= 0) {
1282 		if (!psy->initialized)
1283 			return -EAGAIN;
1284 		return -ENODEV;
1285 	}
1286 
1287 	if (psy_has_property(psy->desc, psp))
1288 		return psy->desc->get_property(psy, psp, val);
1289 	else if (power_supply_battery_info_has_prop(psy->battery_info, psp))
1290 		return power_supply_battery_info_get_prop(psy->battery_info, psp, val);
1291 	else
1292 		return -EINVAL;
1293 }
1294 EXPORT_SYMBOL_GPL(power_supply_get_property);
1295 
power_supply_set_property(struct power_supply * psy,enum power_supply_property psp,const union power_supply_propval * val)1296 int power_supply_set_property(struct power_supply *psy,
1297 			    enum power_supply_property psp,
1298 			    const union power_supply_propval *val)
1299 {
1300 	if (atomic_read(&psy->use_cnt) <= 0 || !psy->desc->set_property)
1301 		return -ENODEV;
1302 
1303 	return psy->desc->set_property(psy, psp, val);
1304 }
1305 EXPORT_SYMBOL_GPL(power_supply_set_property);
1306 
power_supply_property_is_writeable(struct power_supply * psy,enum power_supply_property psp)1307 int power_supply_property_is_writeable(struct power_supply *psy,
1308 					enum power_supply_property psp)
1309 {
1310 	if (atomic_read(&psy->use_cnt) <= 0 ||
1311 			!psy->desc->property_is_writeable)
1312 		return -ENODEV;
1313 
1314 	return psy->desc->property_is_writeable(psy, psp);
1315 }
1316 EXPORT_SYMBOL_GPL(power_supply_property_is_writeable);
1317 
power_supply_external_power_changed(struct power_supply * psy)1318 void power_supply_external_power_changed(struct power_supply *psy)
1319 {
1320 	if (atomic_read(&psy->use_cnt) <= 0 ||
1321 			!psy->desc->external_power_changed)
1322 		return;
1323 
1324 	psy->desc->external_power_changed(psy);
1325 }
1326 EXPORT_SYMBOL_GPL(power_supply_external_power_changed);
1327 
power_supply_powers(struct power_supply * psy,struct device * dev)1328 int power_supply_powers(struct power_supply *psy, struct device *dev)
1329 {
1330 	return sysfs_create_link(&psy->dev.kobj, &dev->kobj, "powers");
1331 }
1332 EXPORT_SYMBOL_GPL(power_supply_powers);
1333 
power_supply_dev_release(struct device * dev)1334 static void power_supply_dev_release(struct device *dev)
1335 {
1336 	struct power_supply *psy = to_power_supply(dev);
1337 	dev_dbg(dev, "%s\n", __func__);
1338 	kfree(psy);
1339 }
1340 
power_supply_reg_notifier(struct notifier_block * nb)1341 int power_supply_reg_notifier(struct notifier_block *nb)
1342 {
1343 	return blocking_notifier_chain_register(&power_supply_notifier, nb);
1344 }
1345 EXPORT_SYMBOL_GPL(power_supply_reg_notifier);
1346 
power_supply_unreg_notifier(struct notifier_block * nb)1347 void power_supply_unreg_notifier(struct notifier_block *nb)
1348 {
1349 	blocking_notifier_chain_unregister(&power_supply_notifier, nb);
1350 }
1351 EXPORT_SYMBOL_GPL(power_supply_unreg_notifier);
1352 
1353 #ifdef CONFIG_THERMAL
power_supply_read_temp(struct thermal_zone_device * tzd,int * temp)1354 static int power_supply_read_temp(struct thermal_zone_device *tzd,
1355 		int *temp)
1356 {
1357 	struct power_supply *psy;
1358 	union power_supply_propval val;
1359 	int ret;
1360 
1361 	WARN_ON(tzd == NULL);
1362 	psy = thermal_zone_device_priv(tzd);
1363 	ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_TEMP, &val);
1364 	if (ret)
1365 		return ret;
1366 
1367 	/* Convert tenths of degree Celsius to milli degree Celsius. */
1368 	*temp = val.intval * 100;
1369 
1370 	return ret;
1371 }
1372 
1373 static struct thermal_zone_device_ops psy_tzd_ops = {
1374 	.get_temp = power_supply_read_temp,
1375 };
1376 
psy_register_thermal(struct power_supply * psy)1377 static int psy_register_thermal(struct power_supply *psy)
1378 {
1379 	int ret;
1380 
1381 	if (psy->desc->no_thermal)
1382 		return 0;
1383 
1384 	/* Register battery zone device psy reports temperature */
1385 	if (psy_has_property(psy->desc, POWER_SUPPLY_PROP_TEMP)) {
1386 		/* Prefer our hwmon device and avoid duplicates */
1387 		struct thermal_zone_params tzp = {
1388 			.no_hwmon = IS_ENABLED(CONFIG_POWER_SUPPLY_HWMON)
1389 		};
1390 		psy->tzd = thermal_tripless_zone_device_register(psy->desc->name,
1391 				psy, &psy_tzd_ops, &tzp);
1392 		if (IS_ERR(psy->tzd))
1393 			return PTR_ERR(psy->tzd);
1394 		ret = thermal_zone_device_enable(psy->tzd);
1395 		if (ret)
1396 			thermal_zone_device_unregister(psy->tzd);
1397 		return ret;
1398 	}
1399 
1400 	return 0;
1401 }
1402 
psy_unregister_thermal(struct power_supply * psy)1403 static void psy_unregister_thermal(struct power_supply *psy)
1404 {
1405 	if (IS_ERR_OR_NULL(psy->tzd))
1406 		return;
1407 	thermal_zone_device_unregister(psy->tzd);
1408 }
1409 
1410 #else
psy_register_thermal(struct power_supply * psy)1411 static int psy_register_thermal(struct power_supply *psy)
1412 {
1413 	return 0;
1414 }
1415 
psy_unregister_thermal(struct power_supply * psy)1416 static void psy_unregister_thermal(struct power_supply *psy)
1417 {
1418 }
1419 #endif
1420 
1421 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)1422 __power_supply_register(struct device *parent,
1423 				   const struct power_supply_desc *desc,
1424 				   const struct power_supply_config *cfg,
1425 				   bool ws)
1426 {
1427 	struct device *dev;
1428 	struct power_supply *psy;
1429 	int rc;
1430 
1431 	if (!desc || !desc->name || !desc->properties || !desc->num_properties)
1432 		return ERR_PTR(-EINVAL);
1433 
1434 	if (!parent)
1435 		pr_warn("%s: Expected proper parent device for '%s'\n",
1436 			__func__, desc->name);
1437 
1438 	if (psy_has_property(desc, POWER_SUPPLY_PROP_USB_TYPE) &&
1439 	    (!desc->usb_types || !desc->num_usb_types))
1440 		return ERR_PTR(-EINVAL);
1441 
1442 	psy = kzalloc(sizeof(*psy), GFP_KERNEL);
1443 	if (!psy)
1444 		return ERR_PTR(-ENOMEM);
1445 
1446 	dev = &psy->dev;
1447 
1448 	device_initialize(dev);
1449 
1450 	dev->class = power_supply_class;
1451 	dev->type = &power_supply_dev_type;
1452 	dev->parent = parent;
1453 	dev->release = power_supply_dev_release;
1454 	dev_set_drvdata(dev, psy);
1455 	psy->desc = desc;
1456 	if (cfg) {
1457 		dev->groups = cfg->attr_grp;
1458 		psy->drv_data = cfg->drv_data;
1459 		psy->of_node =
1460 			cfg->fwnode ? to_of_node(cfg->fwnode) : cfg->of_node;
1461 		psy->supplied_to = cfg->supplied_to;
1462 		psy->num_supplicants = cfg->num_supplicants;
1463 	}
1464 
1465 	rc = dev_set_name(dev, "%s", desc->name);
1466 	if (rc)
1467 		goto dev_set_name_failed;
1468 
1469 	INIT_WORK(&psy->changed_work, power_supply_changed_work);
1470 	INIT_DELAYED_WORK(&psy->deferred_register_work,
1471 			  power_supply_deferred_register_work);
1472 
1473 	rc = power_supply_check_supplies(psy);
1474 	if (rc) {
1475 		dev_dbg(dev, "Not all required supplies found, defer probe\n");
1476 		goto check_supplies_failed;
1477 	}
1478 
1479 	/*
1480 	 * Expose constant battery info, if it is available. While there are
1481 	 * some chargers accessing constant battery data, we only want to
1482 	 * expose battery data to userspace for battery devices.
1483 	 */
1484 	if (desc->type == POWER_SUPPLY_TYPE_BATTERY) {
1485 		rc = power_supply_get_battery_info(psy, &psy->battery_info);
1486 		if (rc && rc != -ENODEV && rc != -ENOENT)
1487 			goto check_supplies_failed;
1488 	}
1489 
1490 	spin_lock_init(&psy->changed_lock);
1491 	rc = device_add(dev);
1492 	if (rc)
1493 		goto device_add_failed;
1494 
1495 	rc = device_init_wakeup(dev, ws);
1496 	if (rc)
1497 		goto wakeup_init_failed;
1498 
1499 	rc = psy_register_thermal(psy);
1500 	if (rc)
1501 		goto register_thermal_failed;
1502 
1503 	rc = power_supply_create_triggers(psy);
1504 	if (rc)
1505 		goto create_triggers_failed;
1506 
1507 	rc = power_supply_add_hwmon_sysfs(psy);
1508 	if (rc)
1509 		goto add_hwmon_sysfs_failed;
1510 
1511 	/*
1512 	 * Update use_cnt after any uevents (most notably from device_add()).
1513 	 * We are here still during driver's probe but
1514 	 * the power_supply_uevent() calls back driver's get_property
1515 	 * method so:
1516 	 * 1. Driver did not assigned the returned struct power_supply,
1517 	 * 2. Driver could not finish initialization (anything in its probe
1518 	 *    after calling power_supply_register()).
1519 	 */
1520 	atomic_inc(&psy->use_cnt);
1521 	psy->initialized = true;
1522 
1523 	queue_delayed_work(system_power_efficient_wq,
1524 			   &psy->deferred_register_work,
1525 			   POWER_SUPPLY_DEFERRED_REGISTER_TIME);
1526 
1527 	return psy;
1528 
1529 add_hwmon_sysfs_failed:
1530 	power_supply_remove_triggers(psy);
1531 create_triggers_failed:
1532 	psy_unregister_thermal(psy);
1533 register_thermal_failed:
1534 wakeup_init_failed:
1535 	device_del(dev);
1536 device_add_failed:
1537 check_supplies_failed:
1538 dev_set_name_failed:
1539 	put_device(dev);
1540 	return ERR_PTR(rc);
1541 }
1542 
1543 /**
1544  * power_supply_register() - Register new power supply
1545  * @parent:	Device to be a parent of power supply's device, usually
1546  *		the device which probe function calls this
1547  * @desc:	Description of power supply, must be valid through whole
1548  *		lifetime of this power supply
1549  * @cfg:	Run-time specific configuration accessed during registering,
1550  *		may be NULL
1551  *
1552  * Return: A pointer to newly allocated power_supply on success
1553  * or ERR_PTR otherwise.
1554  * Use power_supply_unregister() on returned power_supply pointer to release
1555  * resources.
1556  */
power_supply_register(struct device * parent,const struct power_supply_desc * desc,const struct power_supply_config * cfg)1557 struct power_supply *__must_check power_supply_register(struct device *parent,
1558 		const struct power_supply_desc *desc,
1559 		const struct power_supply_config *cfg)
1560 {
1561 	return __power_supply_register(parent, desc, cfg, true);
1562 }
1563 EXPORT_SYMBOL_GPL(power_supply_register);
1564 
1565 /**
1566  * power_supply_register_no_ws() - Register new non-waking-source power supply
1567  * @parent:	Device to be a parent of power supply's device, usually
1568  *		the device which probe function calls this
1569  * @desc:	Description of power supply, must be valid through whole
1570  *		lifetime of this power supply
1571  * @cfg:	Run-time specific configuration accessed during registering,
1572  *		may be NULL
1573  *
1574  * Return: A pointer to newly allocated power_supply on success
1575  * or ERR_PTR otherwise.
1576  * Use power_supply_unregister() on returned power_supply pointer to release
1577  * resources.
1578  */
1579 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)1580 power_supply_register_no_ws(struct device *parent,
1581 		const struct power_supply_desc *desc,
1582 		const struct power_supply_config *cfg)
1583 {
1584 	return __power_supply_register(parent, desc, cfg, false);
1585 }
1586 EXPORT_SYMBOL_GPL(power_supply_register_no_ws);
1587 
devm_power_supply_release(struct device * dev,void * res)1588 static void devm_power_supply_release(struct device *dev, void *res)
1589 {
1590 	struct power_supply **psy = res;
1591 
1592 	power_supply_unregister(*psy);
1593 }
1594 
1595 /**
1596  * devm_power_supply_register() - Register managed power supply
1597  * @parent:	Device to be a parent of power supply's device, usually
1598  *		the device which probe function calls this
1599  * @desc:	Description of power supply, must be valid through whole
1600  *		lifetime of this power supply
1601  * @cfg:	Run-time specific configuration accessed during registering,
1602  *		may be NULL
1603  *
1604  * Return: A pointer to newly allocated power_supply on success
1605  * or ERR_PTR otherwise.
1606  * The returned power_supply pointer will be automatically unregistered
1607  * on driver detach.
1608  */
1609 struct power_supply *__must_check
devm_power_supply_register(struct device * parent,const struct power_supply_desc * desc,const struct power_supply_config * cfg)1610 devm_power_supply_register(struct device *parent,
1611 		const struct power_supply_desc *desc,
1612 		const struct power_supply_config *cfg)
1613 {
1614 	struct power_supply **ptr, *psy;
1615 
1616 	ptr = devres_alloc(devm_power_supply_release, sizeof(*ptr), GFP_KERNEL);
1617 
1618 	if (!ptr)
1619 		return ERR_PTR(-ENOMEM);
1620 	psy = __power_supply_register(parent, desc, cfg, true);
1621 	if (IS_ERR(psy)) {
1622 		devres_free(ptr);
1623 	} else {
1624 		*ptr = psy;
1625 		devres_add(parent, ptr);
1626 	}
1627 	return psy;
1628 }
1629 EXPORT_SYMBOL_GPL(devm_power_supply_register);
1630 
1631 /**
1632  * devm_power_supply_register_no_ws() - Register managed non-waking-source power supply
1633  * @parent:	Device to be a parent of power supply's device, usually
1634  *		the device which probe function calls this
1635  * @desc:	Description of power supply, must be valid through whole
1636  *		lifetime of this power supply
1637  * @cfg:	Run-time specific configuration accessed during registering,
1638  *		may be NULL
1639  *
1640  * Return: A pointer to newly allocated power_supply on success
1641  * or ERR_PTR otherwise.
1642  * The returned power_supply pointer will be automatically unregistered
1643  * on driver detach.
1644  */
1645 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)1646 devm_power_supply_register_no_ws(struct device *parent,
1647 		const struct power_supply_desc *desc,
1648 		const struct power_supply_config *cfg)
1649 {
1650 	struct power_supply **ptr, *psy;
1651 
1652 	ptr = devres_alloc(devm_power_supply_release, sizeof(*ptr), GFP_KERNEL);
1653 
1654 	if (!ptr)
1655 		return ERR_PTR(-ENOMEM);
1656 	psy = __power_supply_register(parent, desc, cfg, false);
1657 	if (IS_ERR(psy)) {
1658 		devres_free(ptr);
1659 	} else {
1660 		*ptr = psy;
1661 		devres_add(parent, ptr);
1662 	}
1663 	return psy;
1664 }
1665 EXPORT_SYMBOL_GPL(devm_power_supply_register_no_ws);
1666 
1667 /**
1668  * power_supply_unregister() - Remove this power supply from system
1669  * @psy:	Pointer to power supply to unregister
1670  *
1671  * Remove this power supply from the system. The resources of power supply
1672  * will be freed here or on last power_supply_put() call.
1673  */
power_supply_unregister(struct power_supply * psy)1674 void power_supply_unregister(struct power_supply *psy)
1675 {
1676 	WARN_ON(atomic_dec_return(&psy->use_cnt));
1677 	psy->removing = true;
1678 	cancel_work_sync(&psy->changed_work);
1679 	cancel_delayed_work_sync(&psy->deferred_register_work);
1680 	sysfs_remove_link(&psy->dev.kobj, "powers");
1681 	power_supply_remove_hwmon_sysfs(psy);
1682 	power_supply_remove_triggers(psy);
1683 	psy_unregister_thermal(psy);
1684 	device_init_wakeup(&psy->dev, false);
1685 	device_unregister(&psy->dev);
1686 }
1687 EXPORT_SYMBOL_GPL(power_supply_unregister);
1688 
power_supply_get_drvdata(struct power_supply * psy)1689 void *power_supply_get_drvdata(struct power_supply *psy)
1690 {
1691 	return psy->drv_data;
1692 }
1693 EXPORT_SYMBOL_GPL(power_supply_get_drvdata);
1694 
power_supply_class_init(void)1695 static int __init power_supply_class_init(void)
1696 {
1697 	power_supply_class = class_create("power_supply");
1698 
1699 	if (IS_ERR(power_supply_class))
1700 		return PTR_ERR(power_supply_class);
1701 
1702 	power_supply_class->dev_uevent = power_supply_uevent;
1703 	power_supply_init_attrs(&power_supply_dev_type);
1704 
1705 	return 0;
1706 }
1707 
power_supply_class_exit(void)1708 static void __exit power_supply_class_exit(void)
1709 {
1710 	class_destroy(power_supply_class);
1711 }
1712 
1713 subsys_initcall(power_supply_class_init);
1714 module_exit(power_supply_class_exit);
1715 
1716 MODULE_DESCRIPTION("Universal power supply monitor class");
1717 MODULE_AUTHOR("Ian Molton <spyro@f2s.com>, "
1718 	      "Szabolcs Gyurko, "
1719 	      "Anton Vorontsov <cbou@mail.ru>");
1720