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