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