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