PM / sleep: Asynchronous threads for suspend_noirq
[linux/fpc-iii.git] / drivers / power / charger-manager.c
blob9e4dab46eefd52d87c044ca9a8141da7309088d1
1 /*
2 * Copyright (C) 2011 Samsung Electronics Co., Ltd.
3 * MyungJoo Ham <myungjoo.ham@samsung.com>
5 * This driver enables to monitor battery health and control charger
6 * during suspend-to-mem.
7 * Charger manager depends on other devices. register this later than
8 * the depending devices.
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2 as
12 * published by the Free Software Foundation.
13 **/
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 #include <linux/io.h>
18 #include <linux/module.h>
19 #include <linux/irq.h>
20 #include <linux/interrupt.h>
21 #include <linux/rtc.h>
22 #include <linux/slab.h>
23 #include <linux/workqueue.h>
24 #include <linux/platform_device.h>
25 #include <linux/power/charger-manager.h>
26 #include <linux/regulator/consumer.h>
27 #include <linux/sysfs.h>
28 #include <linux/of.h>
29 #include <linux/thermal.h>
32 * Default termperature threshold for charging.
33 * Every temperature units are in tenth of centigrade.
35 #define CM_DEFAULT_RECHARGE_TEMP_DIFF 50
36 #define CM_DEFAULT_CHARGE_TEMP_MAX 500
38 static const char * const default_event_names[] = {
39 [CM_EVENT_UNKNOWN] = "Unknown",
40 [CM_EVENT_BATT_FULL] = "Battery Full",
41 [CM_EVENT_BATT_IN] = "Battery Inserted",
42 [CM_EVENT_BATT_OUT] = "Battery Pulled Out",
43 [CM_EVENT_BATT_OVERHEAT] = "Battery Overheat",
44 [CM_EVENT_BATT_COLD] = "Battery Cold",
45 [CM_EVENT_EXT_PWR_IN_OUT] = "External Power Attach/Detach",
46 [CM_EVENT_CHG_START_STOP] = "Charging Start/Stop",
47 [CM_EVENT_OTHERS] = "Other battery events"
51 * Regard CM_JIFFIES_SMALL jiffies is small enough to ignore for
52 * delayed works so that we can run delayed works with CM_JIFFIES_SMALL
53 * without any delays.
55 #define CM_JIFFIES_SMALL (2)
57 /* If y is valid (> 0) and smaller than x, do x = y */
58 #define CM_MIN_VALID(x, y) x = (((y > 0) && ((x) > (y))) ? (y) : (x))
61 * Regard CM_RTC_SMALL (sec) is small enough to ignore error in invoking
62 * rtc alarm. It should be 2 or larger
64 #define CM_RTC_SMALL (2)
66 #define UEVENT_BUF_SIZE 32
68 static LIST_HEAD(cm_list);
69 static DEFINE_MUTEX(cm_list_mtx);
71 /* About in-suspend (suspend-again) monitoring */
72 static struct rtc_device *rtc_dev;
74 * Backup RTC alarm
75 * Save the wakeup alarm before entering suspend-to-RAM
77 static struct rtc_wkalrm rtc_wkalarm_save;
78 /* Backup RTC alarm time in terms of seconds since 01-01-1970 00:00:00 */
79 static unsigned long rtc_wkalarm_save_time;
80 static bool cm_suspended;
81 static bool cm_rtc_set;
82 static unsigned long cm_suspend_duration_ms;
84 /* About normal (not suspended) monitoring */
85 static unsigned long polling_jiffy = ULONG_MAX; /* ULONG_MAX: no polling */
86 static unsigned long next_polling; /* Next appointed polling time */
87 static struct workqueue_struct *cm_wq; /* init at driver add */
88 static struct delayed_work cm_monitor_work; /* init at driver add */
90 /* Global charger-manager description */
91 static struct charger_global_desc *g_desc; /* init with setup_charger_manager */
93 /**
94 * is_batt_present - See if the battery presents in place.
95 * @cm: the Charger Manager representing the battery.
97 static bool is_batt_present(struct charger_manager *cm)
99 union power_supply_propval val;
100 bool present = false;
101 int i, ret;
103 switch (cm->desc->battery_present) {
104 case CM_BATTERY_PRESENT:
105 present = true;
106 break;
107 case CM_NO_BATTERY:
108 break;
109 case CM_FUEL_GAUGE:
110 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
111 POWER_SUPPLY_PROP_PRESENT, &val);
112 if (ret == 0 && val.intval)
113 present = true;
114 break;
115 case CM_CHARGER_STAT:
116 for (i = 0; cm->charger_stat[i]; i++) {
117 ret = cm->charger_stat[i]->get_property(
118 cm->charger_stat[i],
119 POWER_SUPPLY_PROP_PRESENT, &val);
120 if (ret == 0 && val.intval) {
121 present = true;
122 break;
125 break;
128 return present;
132 * is_ext_pwr_online - See if an external power source is attached to charge
133 * @cm: the Charger Manager representing the battery.
135 * Returns true if at least one of the chargers of the battery has an external
136 * power source attached to charge the battery regardless of whether it is
137 * actually charging or not.
139 static bool is_ext_pwr_online(struct charger_manager *cm)
141 union power_supply_propval val;
142 bool online = false;
143 int i, ret;
145 /* If at least one of them has one, it's yes. */
146 for (i = 0; cm->charger_stat[i]; i++) {
147 ret = cm->charger_stat[i]->get_property(
148 cm->charger_stat[i],
149 POWER_SUPPLY_PROP_ONLINE, &val);
150 if (ret == 0 && val.intval) {
151 online = true;
152 break;
156 return online;
160 * get_batt_uV - Get the voltage level of the battery
161 * @cm: the Charger Manager representing the battery.
162 * @uV: the voltage level returned.
164 * Returns 0 if there is no error.
165 * Returns a negative value on error.
167 static int get_batt_uV(struct charger_manager *cm, int *uV)
169 union power_supply_propval val;
170 int ret;
172 if (!cm->fuel_gauge)
173 return -ENODEV;
175 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
176 POWER_SUPPLY_PROP_VOLTAGE_NOW, &val);
177 if (ret)
178 return ret;
180 *uV = val.intval;
181 return 0;
185 * is_charging - Returns true if the battery is being charged.
186 * @cm: the Charger Manager representing the battery.
188 static bool is_charging(struct charger_manager *cm)
190 int i, ret;
191 bool charging = false;
192 union power_supply_propval val;
194 /* If there is no battery, it cannot be charged */
195 if (!is_batt_present(cm))
196 return false;
198 /* If at least one of the charger is charging, return yes */
199 for (i = 0; cm->charger_stat[i]; i++) {
200 /* 1. The charger sholuld not be DISABLED */
201 if (cm->emergency_stop)
202 continue;
203 if (!cm->charger_enabled)
204 continue;
206 /* 2. The charger should be online (ext-power) */
207 ret = cm->charger_stat[i]->get_property(
208 cm->charger_stat[i],
209 POWER_SUPPLY_PROP_ONLINE, &val);
210 if (ret) {
211 dev_warn(cm->dev, "Cannot read ONLINE value from %s\n",
212 cm->desc->psy_charger_stat[i]);
213 continue;
215 if (val.intval == 0)
216 continue;
219 * 3. The charger should not be FULL, DISCHARGING,
220 * or NOT_CHARGING.
222 ret = cm->charger_stat[i]->get_property(
223 cm->charger_stat[i],
224 POWER_SUPPLY_PROP_STATUS, &val);
225 if (ret) {
226 dev_warn(cm->dev, "Cannot read STATUS value from %s\n",
227 cm->desc->psy_charger_stat[i]);
228 continue;
230 if (val.intval == POWER_SUPPLY_STATUS_FULL ||
231 val.intval == POWER_SUPPLY_STATUS_DISCHARGING ||
232 val.intval == POWER_SUPPLY_STATUS_NOT_CHARGING)
233 continue;
235 /* Then, this is charging. */
236 charging = true;
237 break;
240 return charging;
244 * is_full_charged - Returns true if the battery is fully charged.
245 * @cm: the Charger Manager representing the battery.
247 static bool is_full_charged(struct charger_manager *cm)
249 struct charger_desc *desc = cm->desc;
250 union power_supply_propval val;
251 int ret = 0;
252 int uV;
254 /* If there is no battery, it cannot be charged */
255 if (!is_batt_present(cm))
256 return false;
258 if (cm->fuel_gauge && desc->fullbatt_full_capacity > 0) {
259 val.intval = 0;
261 /* Not full if capacity of fuel gauge isn't full */
262 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
263 POWER_SUPPLY_PROP_CHARGE_FULL, &val);
264 if (!ret && val.intval > desc->fullbatt_full_capacity)
265 return true;
268 /* Full, if it's over the fullbatt voltage */
269 if (desc->fullbatt_uV > 0) {
270 ret = get_batt_uV(cm, &uV);
271 if (!ret && uV >= desc->fullbatt_uV)
272 return true;
275 /* Full, if the capacity is more than fullbatt_soc */
276 if (cm->fuel_gauge && desc->fullbatt_soc > 0) {
277 val.intval = 0;
279 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
280 POWER_SUPPLY_PROP_CAPACITY, &val);
281 if (!ret && val.intval >= desc->fullbatt_soc)
282 return true;
285 return false;
289 * is_polling_required - Return true if need to continue polling for this CM.
290 * @cm: the Charger Manager representing the battery.
292 static bool is_polling_required(struct charger_manager *cm)
294 switch (cm->desc->polling_mode) {
295 case CM_POLL_DISABLE:
296 return false;
297 case CM_POLL_ALWAYS:
298 return true;
299 case CM_POLL_EXTERNAL_POWER_ONLY:
300 return is_ext_pwr_online(cm);
301 case CM_POLL_CHARGING_ONLY:
302 return is_charging(cm);
303 default:
304 dev_warn(cm->dev, "Incorrect polling_mode (%d)\n",
305 cm->desc->polling_mode);
308 return false;
312 * try_charger_enable - Enable/Disable chargers altogether
313 * @cm: the Charger Manager representing the battery.
314 * @enable: true: enable / false: disable
316 * Note that Charger Manager keeps the charger enabled regardless whether
317 * the charger is charging or not (because battery is full or no external
318 * power source exists) except when CM needs to disable chargers forcibly
319 * bacause of emergency causes; when the battery is overheated or too cold.
321 static int try_charger_enable(struct charger_manager *cm, bool enable)
323 int err = 0, i;
324 struct charger_desc *desc = cm->desc;
326 /* Ignore if it's redundent command */
327 if (enable == cm->charger_enabled)
328 return 0;
330 if (enable) {
331 if (cm->emergency_stop)
332 return -EAGAIN;
335 * Save start time of charging to limit
336 * maximum possible charging time.
338 cm->charging_start_time = ktime_to_ms(ktime_get());
339 cm->charging_end_time = 0;
341 for (i = 0 ; i < desc->num_charger_regulators ; i++) {
342 if (desc->charger_regulators[i].externally_control)
343 continue;
345 err = regulator_enable(desc->charger_regulators[i].consumer);
346 if (err < 0) {
347 dev_warn(cm->dev, "Cannot enable %s regulator\n",
348 desc->charger_regulators[i].regulator_name);
351 } else {
353 * Save end time of charging to maintain fully charged state
354 * of battery after full-batt.
356 cm->charging_start_time = 0;
357 cm->charging_end_time = ktime_to_ms(ktime_get());
359 for (i = 0 ; i < desc->num_charger_regulators ; i++) {
360 if (desc->charger_regulators[i].externally_control)
361 continue;
363 err = regulator_disable(desc->charger_regulators[i].consumer);
364 if (err < 0) {
365 dev_warn(cm->dev, "Cannot disable %s regulator\n",
366 desc->charger_regulators[i].regulator_name);
371 * Abnormal battery state - Stop charging forcibly,
372 * even if charger was enabled at the other places
374 for (i = 0; i < desc->num_charger_regulators; i++) {
375 if (regulator_is_enabled(
376 desc->charger_regulators[i].consumer)) {
377 regulator_force_disable(
378 desc->charger_regulators[i].consumer);
379 dev_warn(cm->dev, "Disable regulator(%s) forcibly\n",
380 desc->charger_regulators[i].regulator_name);
385 if (!err)
386 cm->charger_enabled = enable;
388 return err;
392 * try_charger_restart - Restart charging.
393 * @cm: the Charger Manager representing the battery.
395 * Restart charging by turning off and on the charger.
397 static int try_charger_restart(struct charger_manager *cm)
399 int err;
401 if (cm->emergency_stop)
402 return -EAGAIN;
404 err = try_charger_enable(cm, false);
405 if (err)
406 return err;
408 return try_charger_enable(cm, true);
412 * uevent_notify - Let users know something has changed.
413 * @cm: the Charger Manager representing the battery.
414 * @event: the event string.
416 * If @event is null, it implies that uevent_notify is called
417 * by resume function. When called in the resume function, cm_suspended
418 * should be already reset to false in order to let uevent_notify
419 * notify the recent event during the suspend to users. While
420 * suspended, uevent_notify does not notify users, but tracks
421 * events so that uevent_notify can notify users later after resumed.
423 static void uevent_notify(struct charger_manager *cm, const char *event)
425 static char env_str[UEVENT_BUF_SIZE + 1] = "";
426 static char env_str_save[UEVENT_BUF_SIZE + 1] = "";
428 if (cm_suspended) {
429 /* Nothing in suspended-event buffer */
430 if (env_str_save[0] == 0) {
431 if (!strncmp(env_str, event, UEVENT_BUF_SIZE))
432 return; /* status not changed */
433 strncpy(env_str_save, event, UEVENT_BUF_SIZE);
434 return;
437 if (!strncmp(env_str_save, event, UEVENT_BUF_SIZE))
438 return; /* Duplicated. */
439 strncpy(env_str_save, event, UEVENT_BUF_SIZE);
440 return;
443 if (event == NULL) {
444 /* No messages pending */
445 if (!env_str_save[0])
446 return;
448 strncpy(env_str, env_str_save, UEVENT_BUF_SIZE);
449 kobject_uevent(&cm->dev->kobj, KOBJ_CHANGE);
450 env_str_save[0] = 0;
452 return;
455 /* status not changed */
456 if (!strncmp(env_str, event, UEVENT_BUF_SIZE))
457 return;
459 /* save the status and notify the update */
460 strncpy(env_str, event, UEVENT_BUF_SIZE);
461 kobject_uevent(&cm->dev->kobj, KOBJ_CHANGE);
463 dev_info(cm->dev, "%s\n", event);
467 * fullbatt_vchk - Check voltage drop some times after "FULL" event.
468 * @work: the work_struct appointing the function
470 * If a user has designated "fullbatt_vchkdrop_ms/uV" values with
471 * charger_desc, Charger Manager checks voltage drop after the battery
472 * "FULL" event. It checks whether the voltage has dropped more than
473 * fullbatt_vchkdrop_uV by calling this function after fullbatt_vchkrop_ms.
475 static void fullbatt_vchk(struct work_struct *work)
477 struct delayed_work *dwork = to_delayed_work(work);
478 struct charger_manager *cm = container_of(dwork,
479 struct charger_manager, fullbatt_vchk_work);
480 struct charger_desc *desc = cm->desc;
481 int batt_uV, err, diff;
483 /* remove the appointment for fullbatt_vchk */
484 cm->fullbatt_vchk_jiffies_at = 0;
486 if (!desc->fullbatt_vchkdrop_uV || !desc->fullbatt_vchkdrop_ms)
487 return;
489 err = get_batt_uV(cm, &batt_uV);
490 if (err) {
491 dev_err(cm->dev, "%s: get_batt_uV error(%d)\n", __func__, err);
492 return;
495 diff = desc->fullbatt_uV - batt_uV;
496 if (diff < 0)
497 return;
499 dev_info(cm->dev, "VBATT dropped %duV after full-batt\n", diff);
501 if (diff > desc->fullbatt_vchkdrop_uV) {
502 try_charger_restart(cm);
503 uevent_notify(cm, "Recharging");
508 * check_charging_duration - Monitor charging/discharging duration
509 * @cm: the Charger Manager representing the battery.
511 * If whole charging duration exceed 'charging_max_duration_ms',
512 * cm stop charging to prevent overcharge/overheat. If discharging
513 * duration exceed 'discharging _max_duration_ms', charger cable is
514 * attached, after full-batt, cm start charging to maintain fully
515 * charged state for battery.
517 static int check_charging_duration(struct charger_manager *cm)
519 struct charger_desc *desc = cm->desc;
520 u64 curr = ktime_to_ms(ktime_get());
521 u64 duration;
522 int ret = false;
524 if (!desc->charging_max_duration_ms &&
525 !desc->discharging_max_duration_ms)
526 return ret;
528 if (cm->charger_enabled) {
529 duration = curr - cm->charging_start_time;
531 if (duration > desc->charging_max_duration_ms) {
532 dev_info(cm->dev, "Charging duration exceed %ums\n",
533 desc->charging_max_duration_ms);
534 uevent_notify(cm, "Discharging");
535 try_charger_enable(cm, false);
536 ret = true;
538 } else if (is_ext_pwr_online(cm) && !cm->charger_enabled) {
539 duration = curr - cm->charging_end_time;
541 if (duration > desc->charging_max_duration_ms &&
542 is_ext_pwr_online(cm)) {
543 dev_info(cm->dev, "Discharging duration exceed %ums\n",
544 desc->discharging_max_duration_ms);
545 uevent_notify(cm, "Recharging");
546 try_charger_enable(cm, true);
547 ret = true;
551 return ret;
554 static int cm_get_battery_temperature(struct charger_manager *cm,
555 int *temp)
557 int ret;
559 if (!cm->desc->measure_battery_temp)
560 return -ENODEV;
562 #ifdef CONFIG_THERMAL
563 ret = thermal_zone_get_temp(cm->tzd_batt, (unsigned long *)temp);
564 if (!ret)
565 /* Calibrate temperature unit */
566 *temp /= 100;
567 #else
568 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
569 POWER_SUPPLY_PROP_TEMP,
570 (union power_supply_propval *)temp);
571 #endif
572 return ret;
575 static int cm_check_thermal_status(struct charger_manager *cm)
577 struct charger_desc *desc = cm->desc;
578 int temp, upper_limit, lower_limit;
579 int ret = 0;
581 ret = cm_get_battery_temperature(cm, &temp);
582 if (ret) {
583 /* FIXME:
584 * No information of battery temperature might
585 * occur hazadous result. We have to handle it
586 * depending on battery type.
588 dev_err(cm->dev, "Failed to get battery temperature\n");
589 return 0;
592 upper_limit = desc->temp_max;
593 lower_limit = desc->temp_min;
595 if (cm->emergency_stop) {
596 upper_limit -= desc->temp_diff;
597 lower_limit += desc->temp_diff;
600 if (temp > upper_limit)
601 ret = CM_EVENT_BATT_OVERHEAT;
602 else if (temp < lower_limit)
603 ret = CM_EVENT_BATT_COLD;
605 return ret;
609 * _cm_monitor - Monitor the temperature and return true for exceptions.
610 * @cm: the Charger Manager representing the battery.
612 * Returns true if there is an event to notify for the battery.
613 * (True if the status of "emergency_stop" changes)
615 static bool _cm_monitor(struct charger_manager *cm)
617 int temp_alrt;
619 temp_alrt = cm_check_thermal_status(cm);
621 /* It has been stopped already */
622 if (temp_alrt && cm->emergency_stop)
623 return false;
626 * Check temperature whether overheat or cold.
627 * If temperature is out of range normal state, stop charging.
629 if (temp_alrt) {
630 cm->emergency_stop = temp_alrt;
631 if (!try_charger_enable(cm, false))
632 uevent_notify(cm, default_event_names[temp_alrt]);
635 * Check whole charging duration and discharing duration
636 * after full-batt.
638 } else if (!cm->emergency_stop && check_charging_duration(cm)) {
639 dev_dbg(cm->dev,
640 "Charging/Discharging duration is out of range\n");
642 * Check dropped voltage of battery. If battery voltage is more
643 * dropped than fullbatt_vchkdrop_uV after fully charged state,
644 * charger-manager have to recharge battery.
646 } else if (!cm->emergency_stop && is_ext_pwr_online(cm) &&
647 !cm->charger_enabled) {
648 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
651 * Check whether fully charged state to protect overcharge
652 * if charger-manager is charging for battery.
654 } else if (!cm->emergency_stop && is_full_charged(cm) &&
655 cm->charger_enabled) {
656 dev_info(cm->dev, "EVENT_HANDLE: Battery Fully Charged\n");
657 uevent_notify(cm, default_event_names[CM_EVENT_BATT_FULL]);
659 try_charger_enable(cm, false);
661 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
662 } else {
663 cm->emergency_stop = 0;
664 if (is_ext_pwr_online(cm)) {
665 if (!try_charger_enable(cm, true))
666 uevent_notify(cm, "CHARGING");
670 return true;
674 * cm_monitor - Monitor every battery.
676 * Returns true if there is an event to notify from any of the batteries.
677 * (True if the status of "emergency_stop" changes)
679 static bool cm_monitor(void)
681 bool stop = false;
682 struct charger_manager *cm;
684 mutex_lock(&cm_list_mtx);
686 list_for_each_entry(cm, &cm_list, entry) {
687 if (_cm_monitor(cm))
688 stop = true;
691 mutex_unlock(&cm_list_mtx);
693 return stop;
697 * _setup_polling - Setup the next instance of polling.
698 * @work: work_struct of the function _setup_polling.
700 static void _setup_polling(struct work_struct *work)
702 unsigned long min = ULONG_MAX;
703 struct charger_manager *cm;
704 bool keep_polling = false;
705 unsigned long _next_polling;
707 mutex_lock(&cm_list_mtx);
709 list_for_each_entry(cm, &cm_list, entry) {
710 if (is_polling_required(cm) && cm->desc->polling_interval_ms) {
711 keep_polling = true;
713 if (min > cm->desc->polling_interval_ms)
714 min = cm->desc->polling_interval_ms;
718 polling_jiffy = msecs_to_jiffies(min);
719 if (polling_jiffy <= CM_JIFFIES_SMALL)
720 polling_jiffy = CM_JIFFIES_SMALL + 1;
722 if (!keep_polling)
723 polling_jiffy = ULONG_MAX;
724 if (polling_jiffy == ULONG_MAX)
725 goto out;
727 WARN(cm_wq == NULL, "charger-manager: workqueue not initialized"
728 ". try it later. %s\n", __func__);
731 * Use mod_delayed_work() iff the next polling interval should
732 * occur before the currently scheduled one. If @cm_monitor_work
733 * isn't active, the end result is the same, so no need to worry
734 * about stale @next_polling.
736 _next_polling = jiffies + polling_jiffy;
738 if (time_before(_next_polling, next_polling)) {
739 mod_delayed_work(cm_wq, &cm_monitor_work, polling_jiffy);
740 next_polling = _next_polling;
741 } else {
742 if (queue_delayed_work(cm_wq, &cm_monitor_work, polling_jiffy))
743 next_polling = _next_polling;
745 out:
746 mutex_unlock(&cm_list_mtx);
748 static DECLARE_WORK(setup_polling, _setup_polling);
751 * cm_monitor_poller - The Monitor / Poller.
752 * @work: work_struct of the function cm_monitor_poller
754 * During non-suspended state, cm_monitor_poller is used to poll and monitor
755 * the batteries.
757 static void cm_monitor_poller(struct work_struct *work)
759 cm_monitor();
760 schedule_work(&setup_polling);
764 * fullbatt_handler - Event handler for CM_EVENT_BATT_FULL
765 * @cm: the Charger Manager representing the battery.
767 static void fullbatt_handler(struct charger_manager *cm)
769 struct charger_desc *desc = cm->desc;
771 if (!desc->fullbatt_vchkdrop_uV || !desc->fullbatt_vchkdrop_ms)
772 goto out;
774 if (cm_suspended)
775 device_set_wakeup_capable(cm->dev, true);
777 mod_delayed_work(cm_wq, &cm->fullbatt_vchk_work,
778 msecs_to_jiffies(desc->fullbatt_vchkdrop_ms));
779 cm->fullbatt_vchk_jiffies_at = jiffies + msecs_to_jiffies(
780 desc->fullbatt_vchkdrop_ms);
782 if (cm->fullbatt_vchk_jiffies_at == 0)
783 cm->fullbatt_vchk_jiffies_at = 1;
785 out:
786 dev_info(cm->dev, "EVENT_HANDLE: Battery Fully Charged\n");
787 uevent_notify(cm, default_event_names[CM_EVENT_BATT_FULL]);
791 * battout_handler - Event handler for CM_EVENT_BATT_OUT
792 * @cm: the Charger Manager representing the battery.
794 static void battout_handler(struct charger_manager *cm)
796 if (cm_suspended)
797 device_set_wakeup_capable(cm->dev, true);
799 if (!is_batt_present(cm)) {
800 dev_emerg(cm->dev, "Battery Pulled Out!\n");
801 uevent_notify(cm, default_event_names[CM_EVENT_BATT_OUT]);
802 } else {
803 uevent_notify(cm, "Battery Reinserted?");
808 * misc_event_handler - Handler for other evnets
809 * @cm: the Charger Manager representing the battery.
810 * @type: the Charger Manager representing the battery.
812 static void misc_event_handler(struct charger_manager *cm,
813 enum cm_event_types type)
815 if (cm_suspended)
816 device_set_wakeup_capable(cm->dev, true);
818 if (is_polling_required(cm) && cm->desc->polling_interval_ms)
819 schedule_work(&setup_polling);
820 uevent_notify(cm, default_event_names[type]);
823 static int charger_get_property(struct power_supply *psy,
824 enum power_supply_property psp,
825 union power_supply_propval *val)
827 struct charger_manager *cm = container_of(psy,
828 struct charger_manager, charger_psy);
829 struct charger_desc *desc = cm->desc;
830 int ret = 0;
831 int uV;
833 switch (psp) {
834 case POWER_SUPPLY_PROP_STATUS:
835 if (is_charging(cm))
836 val->intval = POWER_SUPPLY_STATUS_CHARGING;
837 else if (is_ext_pwr_online(cm))
838 val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
839 else
840 val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
841 break;
842 case POWER_SUPPLY_PROP_HEALTH:
843 if (cm->emergency_stop > 0)
844 val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
845 else if (cm->emergency_stop < 0)
846 val->intval = POWER_SUPPLY_HEALTH_COLD;
847 else
848 val->intval = POWER_SUPPLY_HEALTH_GOOD;
849 break;
850 case POWER_SUPPLY_PROP_PRESENT:
851 if (is_batt_present(cm))
852 val->intval = 1;
853 else
854 val->intval = 0;
855 break;
856 case POWER_SUPPLY_PROP_VOLTAGE_NOW:
857 ret = get_batt_uV(cm, &val->intval);
858 break;
859 case POWER_SUPPLY_PROP_CURRENT_NOW:
860 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
861 POWER_SUPPLY_PROP_CURRENT_NOW, val);
862 break;
863 case POWER_SUPPLY_PROP_TEMP:
864 case POWER_SUPPLY_PROP_TEMP_AMBIENT:
865 return cm_get_battery_temperature(cm, &val->intval);
866 case POWER_SUPPLY_PROP_CAPACITY:
867 if (!cm->fuel_gauge) {
868 ret = -ENODEV;
869 break;
872 if (!is_batt_present(cm)) {
873 /* There is no battery. Assume 100% */
874 val->intval = 100;
875 break;
878 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
879 POWER_SUPPLY_PROP_CAPACITY, val);
880 if (ret)
881 break;
883 if (val->intval > 100) {
884 val->intval = 100;
885 break;
887 if (val->intval < 0)
888 val->intval = 0;
890 /* Do not adjust SOC when charging: voltage is overrated */
891 if (is_charging(cm))
892 break;
895 * If the capacity value is inconsistent, calibrate it base on
896 * the battery voltage values and the thresholds given as desc
898 ret = get_batt_uV(cm, &uV);
899 if (ret) {
900 /* Voltage information not available. No calibration */
901 ret = 0;
902 break;
905 if (desc->fullbatt_uV > 0 && uV >= desc->fullbatt_uV &&
906 !is_charging(cm)) {
907 val->intval = 100;
908 break;
911 break;
912 case POWER_SUPPLY_PROP_ONLINE:
913 if (is_ext_pwr_online(cm))
914 val->intval = 1;
915 else
916 val->intval = 0;
917 break;
918 case POWER_SUPPLY_PROP_CHARGE_FULL:
919 if (is_full_charged(cm))
920 val->intval = 1;
921 else
922 val->intval = 0;
923 ret = 0;
924 break;
925 case POWER_SUPPLY_PROP_CHARGE_NOW:
926 if (is_charging(cm)) {
927 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
928 POWER_SUPPLY_PROP_CHARGE_NOW,
929 val);
930 if (ret) {
931 val->intval = 1;
932 ret = 0;
933 } else {
934 /* If CHARGE_NOW is supplied, use it */
935 val->intval = (val->intval > 0) ?
936 val->intval : 1;
938 } else {
939 val->intval = 0;
941 break;
942 default:
943 return -EINVAL;
945 return ret;
948 #define NUM_CHARGER_PSY_OPTIONAL (4)
949 static enum power_supply_property default_charger_props[] = {
950 /* Guaranteed to provide */
951 POWER_SUPPLY_PROP_STATUS,
952 POWER_SUPPLY_PROP_HEALTH,
953 POWER_SUPPLY_PROP_PRESENT,
954 POWER_SUPPLY_PROP_VOLTAGE_NOW,
955 POWER_SUPPLY_PROP_CAPACITY,
956 POWER_SUPPLY_PROP_ONLINE,
957 POWER_SUPPLY_PROP_CHARGE_FULL,
959 * Optional properties are:
960 * POWER_SUPPLY_PROP_CHARGE_NOW,
961 * POWER_SUPPLY_PROP_CURRENT_NOW,
962 * POWER_SUPPLY_PROP_TEMP, and
963 * POWER_SUPPLY_PROP_TEMP_AMBIENT,
967 static struct power_supply psy_default = {
968 .name = "battery",
969 .type = POWER_SUPPLY_TYPE_BATTERY,
970 .properties = default_charger_props,
971 .num_properties = ARRAY_SIZE(default_charger_props),
972 .get_property = charger_get_property,
976 * cm_setup_timer - For in-suspend monitoring setup wakeup alarm
977 * for suspend_again.
979 * Returns true if the alarm is set for Charger Manager to use.
980 * Returns false if
981 * cm_setup_timer fails to set an alarm,
982 * cm_setup_timer does not need to set an alarm for Charger Manager,
983 * or an alarm previously configured is to be used.
985 static bool cm_setup_timer(void)
987 struct charger_manager *cm;
988 unsigned int wakeup_ms = UINT_MAX;
989 bool ret = false;
991 mutex_lock(&cm_list_mtx);
993 list_for_each_entry(cm, &cm_list, entry) {
994 unsigned int fbchk_ms = 0;
996 /* fullbatt_vchk is required. setup timer for that */
997 if (cm->fullbatt_vchk_jiffies_at) {
998 fbchk_ms = jiffies_to_msecs(cm->fullbatt_vchk_jiffies_at
999 - jiffies);
1000 if (time_is_before_eq_jiffies(
1001 cm->fullbatt_vchk_jiffies_at) ||
1002 msecs_to_jiffies(fbchk_ms) < CM_JIFFIES_SMALL) {
1003 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
1004 fbchk_ms = 0;
1007 CM_MIN_VALID(wakeup_ms, fbchk_ms);
1009 /* Skip if polling is not required for this CM */
1010 if (!is_polling_required(cm) && !cm->emergency_stop)
1011 continue;
1012 if (cm->desc->polling_interval_ms == 0)
1013 continue;
1014 CM_MIN_VALID(wakeup_ms, cm->desc->polling_interval_ms);
1017 mutex_unlock(&cm_list_mtx);
1019 if (wakeup_ms < UINT_MAX && wakeup_ms > 0) {
1020 pr_info("Charger Manager wakeup timer: %u ms\n", wakeup_ms);
1021 if (rtc_dev) {
1022 struct rtc_wkalrm tmp;
1023 unsigned long time, now;
1024 unsigned long add = DIV_ROUND_UP(wakeup_ms, 1000);
1027 * Set alarm with the polling interval (wakeup_ms)
1028 * except when rtc_wkalarm_save comes first.
1029 * However, the alarm time should be NOW +
1030 * CM_RTC_SMALL or later.
1032 tmp.enabled = 1;
1033 rtc_read_time(rtc_dev, &tmp.time);
1034 rtc_tm_to_time(&tmp.time, &now);
1035 if (add < CM_RTC_SMALL)
1036 add = CM_RTC_SMALL;
1037 time = now + add;
1039 ret = true;
1041 if (rtc_wkalarm_save.enabled &&
1042 rtc_wkalarm_save_time &&
1043 rtc_wkalarm_save_time < time) {
1044 if (rtc_wkalarm_save_time < now + CM_RTC_SMALL)
1045 time = now + CM_RTC_SMALL;
1046 else
1047 time = rtc_wkalarm_save_time;
1049 /* The timer is not appointed by CM */
1050 ret = false;
1053 pr_info("Waking up after %lu secs\n", time - now);
1055 rtc_time_to_tm(time, &tmp.time);
1056 rtc_set_alarm(rtc_dev, &tmp);
1057 cm_suspend_duration_ms += wakeup_ms;
1058 return ret;
1062 if (rtc_dev)
1063 rtc_set_alarm(rtc_dev, &rtc_wkalarm_save);
1064 return false;
1067 static void _cm_fbchk_in_suspend(struct charger_manager *cm)
1069 unsigned long jiffy_now = jiffies;
1071 if (!cm->fullbatt_vchk_jiffies_at)
1072 return;
1074 if (g_desc && g_desc->assume_timer_stops_in_suspend)
1075 jiffy_now += msecs_to_jiffies(cm_suspend_duration_ms);
1077 /* Execute now if it's going to be executed not too long after */
1078 jiffy_now += CM_JIFFIES_SMALL;
1080 if (time_after_eq(jiffy_now, cm->fullbatt_vchk_jiffies_at))
1081 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
1085 * cm_suspend_again - Determine whether suspend again or not
1087 * Returns true if the system should be suspended again
1088 * Returns false if the system should be woken up
1090 bool cm_suspend_again(void)
1092 struct charger_manager *cm;
1093 bool ret = false;
1095 if (!g_desc || !g_desc->rtc_only_wakeup || !g_desc->rtc_only_wakeup() ||
1096 !cm_rtc_set)
1097 return false;
1099 if (cm_monitor())
1100 goto out;
1102 ret = true;
1103 mutex_lock(&cm_list_mtx);
1104 list_for_each_entry(cm, &cm_list, entry) {
1105 _cm_fbchk_in_suspend(cm);
1107 if (cm->status_save_ext_pwr_inserted != is_ext_pwr_online(cm) ||
1108 cm->status_save_batt != is_batt_present(cm)) {
1109 ret = false;
1110 break;
1113 mutex_unlock(&cm_list_mtx);
1115 cm_rtc_set = cm_setup_timer();
1116 out:
1117 /* It's about the time when the non-CM appointed timer goes off */
1118 if (rtc_wkalarm_save.enabled) {
1119 unsigned long now;
1120 struct rtc_time tmp;
1122 rtc_read_time(rtc_dev, &tmp);
1123 rtc_tm_to_time(&tmp, &now);
1125 if (rtc_wkalarm_save_time &&
1126 now + CM_RTC_SMALL >= rtc_wkalarm_save_time)
1127 return false;
1129 return ret;
1131 EXPORT_SYMBOL_GPL(cm_suspend_again);
1134 * setup_charger_manager - initialize charger_global_desc data
1135 * @gd: pointer to instance of charger_global_desc
1137 int setup_charger_manager(struct charger_global_desc *gd)
1139 if (!gd)
1140 return -EINVAL;
1142 if (rtc_dev)
1143 rtc_class_close(rtc_dev);
1144 rtc_dev = NULL;
1145 g_desc = NULL;
1147 if (!gd->rtc_only_wakeup) {
1148 pr_err("The callback rtc_only_wakeup is not given\n");
1149 return -EINVAL;
1152 if (gd->rtc_name) {
1153 rtc_dev = rtc_class_open(gd->rtc_name);
1154 if (IS_ERR_OR_NULL(rtc_dev)) {
1155 rtc_dev = NULL;
1156 /* Retry at probe. RTC may be not registered yet */
1158 } else {
1159 pr_warn("No wakeup timer is given for charger manager. "
1160 "In-suspend monitoring won't work.\n");
1163 g_desc = gd;
1164 return 0;
1166 EXPORT_SYMBOL_GPL(setup_charger_manager);
1169 * charger_extcon_work - enable/diable charger according to the state
1170 * of charger cable
1172 * @work: work_struct of the function charger_extcon_work.
1174 static void charger_extcon_work(struct work_struct *work)
1176 struct charger_cable *cable =
1177 container_of(work, struct charger_cable, wq);
1178 int ret;
1180 if (cable->attached && cable->min_uA != 0 && cable->max_uA != 0) {
1181 ret = regulator_set_current_limit(cable->charger->consumer,
1182 cable->min_uA, cable->max_uA);
1183 if (ret < 0) {
1184 pr_err("Cannot set current limit of %s (%s)\n",
1185 cable->charger->regulator_name, cable->name);
1186 return;
1189 pr_info("Set current limit of %s : %duA ~ %duA\n",
1190 cable->charger->regulator_name,
1191 cable->min_uA, cable->max_uA);
1194 try_charger_enable(cable->cm, cable->attached);
1198 * charger_extcon_notifier - receive the state of charger cable
1199 * when registered cable is attached or detached.
1201 * @self: the notifier block of the charger_extcon_notifier.
1202 * @event: the cable state.
1203 * @ptr: the data pointer of notifier block.
1205 static int charger_extcon_notifier(struct notifier_block *self,
1206 unsigned long event, void *ptr)
1208 struct charger_cable *cable =
1209 container_of(self, struct charger_cable, nb);
1212 * The newly state of charger cable.
1213 * If cable is attached, cable->attached is true.
1215 cable->attached = event;
1218 * Setup monitoring to check battery state
1219 * when charger cable is attached.
1221 if (cable->attached && is_polling_required(cable->cm)) {
1222 cancel_work_sync(&setup_polling);
1223 schedule_work(&setup_polling);
1227 * Setup work for controlling charger(regulator)
1228 * according to charger cable.
1230 schedule_work(&cable->wq);
1232 return NOTIFY_DONE;
1236 * charger_extcon_init - register external connector to use it
1237 * as the charger cable
1239 * @cm: the Charger Manager representing the battery.
1240 * @cable: the Charger cable representing the external connector.
1242 static int charger_extcon_init(struct charger_manager *cm,
1243 struct charger_cable *cable)
1245 int ret = 0;
1248 * Charger manager use Extcon framework to identify
1249 * the charger cable among various external connector
1250 * cable (e.g., TA, USB, MHL, Dock).
1252 INIT_WORK(&cable->wq, charger_extcon_work);
1253 cable->nb.notifier_call = charger_extcon_notifier;
1254 ret = extcon_register_interest(&cable->extcon_dev,
1255 cable->extcon_name, cable->name, &cable->nb);
1256 if (ret < 0) {
1257 pr_info("Cannot register extcon_dev for %s(cable: %s)\n",
1258 cable->extcon_name, cable->name);
1259 ret = -EINVAL;
1262 return ret;
1266 * charger_manager_register_extcon - Register extcon device to recevie state
1267 * of charger cable.
1268 * @cm: the Charger Manager representing the battery.
1270 * This function support EXTCON(External Connector) subsystem to detect the
1271 * state of charger cables for enabling or disabling charger(regulator) and
1272 * select the charger cable for charging among a number of external cable
1273 * according to policy of H/W board.
1275 static int charger_manager_register_extcon(struct charger_manager *cm)
1277 struct charger_desc *desc = cm->desc;
1278 struct charger_regulator *charger;
1279 int ret = 0;
1280 int i;
1281 int j;
1283 for (i = 0; i < desc->num_charger_regulators; i++) {
1284 charger = &desc->charger_regulators[i];
1286 charger->consumer = regulator_get(cm->dev,
1287 charger->regulator_name);
1288 if (IS_ERR(charger->consumer)) {
1289 dev_err(cm->dev, "Cannot find charger(%s)\n",
1290 charger->regulator_name);
1291 return PTR_ERR(charger->consumer);
1293 charger->cm = cm;
1295 for (j = 0; j < charger->num_cables; j++) {
1296 struct charger_cable *cable = &charger->cables[j];
1298 ret = charger_extcon_init(cm, cable);
1299 if (ret < 0) {
1300 dev_err(cm->dev, "Cannot initialize charger(%s)\n",
1301 charger->regulator_name);
1302 goto err;
1304 cable->charger = charger;
1305 cable->cm = cm;
1309 err:
1310 return ret;
1313 /* help function of sysfs node to control charger(regulator) */
1314 static ssize_t charger_name_show(struct device *dev,
1315 struct device_attribute *attr, char *buf)
1317 struct charger_regulator *charger
1318 = container_of(attr, struct charger_regulator, attr_name);
1320 return sprintf(buf, "%s\n", charger->regulator_name);
1323 static ssize_t charger_state_show(struct device *dev,
1324 struct device_attribute *attr, char *buf)
1326 struct charger_regulator *charger
1327 = container_of(attr, struct charger_regulator, attr_state);
1328 int state = 0;
1330 if (!charger->externally_control)
1331 state = regulator_is_enabled(charger->consumer);
1333 return sprintf(buf, "%s\n", state ? "enabled" : "disabled");
1336 static ssize_t charger_externally_control_show(struct device *dev,
1337 struct device_attribute *attr, char *buf)
1339 struct charger_regulator *charger = container_of(attr,
1340 struct charger_regulator, attr_externally_control);
1342 return sprintf(buf, "%d\n", charger->externally_control);
1345 static ssize_t charger_externally_control_store(struct device *dev,
1346 struct device_attribute *attr, const char *buf,
1347 size_t count)
1349 struct charger_regulator *charger
1350 = container_of(attr, struct charger_regulator,
1351 attr_externally_control);
1352 struct charger_manager *cm = charger->cm;
1353 struct charger_desc *desc = cm->desc;
1354 int i;
1355 int ret;
1356 int externally_control;
1357 int chargers_externally_control = 1;
1359 ret = sscanf(buf, "%d", &externally_control);
1360 if (ret == 0) {
1361 ret = -EINVAL;
1362 return ret;
1365 if (!externally_control) {
1366 charger->externally_control = 0;
1367 return count;
1370 for (i = 0; i < desc->num_charger_regulators; i++) {
1371 if (&desc->charger_regulators[i] != charger &&
1372 !desc->charger_regulators[i].externally_control) {
1374 * At least, one charger is controlled by
1375 * charger-manager
1377 chargers_externally_control = 0;
1378 break;
1382 if (!chargers_externally_control) {
1383 if (cm->charger_enabled) {
1384 try_charger_enable(charger->cm, false);
1385 charger->externally_control = externally_control;
1386 try_charger_enable(charger->cm, true);
1387 } else {
1388 charger->externally_control = externally_control;
1390 } else {
1391 dev_warn(cm->dev,
1392 "'%s' regulator should be controlled in charger-manager because charger-manager must need at least one charger for charging\n",
1393 charger->regulator_name);
1396 return count;
1400 * charger_manager_register_sysfs - Register sysfs entry for each charger
1401 * @cm: the Charger Manager representing the battery.
1403 * This function add sysfs entry for charger(regulator) to control charger from
1404 * user-space. If some development board use one more chargers for charging
1405 * but only need one charger on specific case which is dependent on user
1406 * scenario or hardware restrictions, the user enter 1 or 0(zero) to '/sys/
1407 * class/power_supply/battery/charger.[index]/externally_control'. For example,
1408 * if user enter 1 to 'sys/class/power_supply/battery/charger.[index]/
1409 * externally_control, this charger isn't controlled from charger-manager and
1410 * always stay off state of regulator.
1412 static int charger_manager_register_sysfs(struct charger_manager *cm)
1414 struct charger_desc *desc = cm->desc;
1415 struct charger_regulator *charger;
1416 int chargers_externally_control = 1;
1417 char buf[11];
1418 char *str;
1419 int ret = 0;
1420 int i;
1422 /* Create sysfs entry to control charger(regulator) */
1423 for (i = 0; i < desc->num_charger_regulators; i++) {
1424 charger = &desc->charger_regulators[i];
1426 snprintf(buf, 10, "charger.%d", i);
1427 str = devm_kzalloc(cm->dev,
1428 sizeof(char) * (strlen(buf) + 1), GFP_KERNEL);
1429 if (!str) {
1430 ret = -ENOMEM;
1431 goto err;
1433 strcpy(str, buf);
1435 charger->attrs[0] = &charger->attr_name.attr;
1436 charger->attrs[1] = &charger->attr_state.attr;
1437 charger->attrs[2] = &charger->attr_externally_control.attr;
1438 charger->attrs[3] = NULL;
1439 charger->attr_g.name = str;
1440 charger->attr_g.attrs = charger->attrs;
1442 sysfs_attr_init(&charger->attr_name.attr);
1443 charger->attr_name.attr.name = "name";
1444 charger->attr_name.attr.mode = 0444;
1445 charger->attr_name.show = charger_name_show;
1447 sysfs_attr_init(&charger->attr_state.attr);
1448 charger->attr_state.attr.name = "state";
1449 charger->attr_state.attr.mode = 0444;
1450 charger->attr_state.show = charger_state_show;
1452 sysfs_attr_init(&charger->attr_externally_control.attr);
1453 charger->attr_externally_control.attr.name
1454 = "externally_control";
1455 charger->attr_externally_control.attr.mode = 0644;
1456 charger->attr_externally_control.show
1457 = charger_externally_control_show;
1458 charger->attr_externally_control.store
1459 = charger_externally_control_store;
1461 if (!desc->charger_regulators[i].externally_control ||
1462 !chargers_externally_control)
1463 chargers_externally_control = 0;
1465 dev_info(cm->dev, "'%s' regulator's externally_control is %d\n",
1466 charger->regulator_name, charger->externally_control);
1468 ret = sysfs_create_group(&cm->charger_psy.dev->kobj,
1469 &charger->attr_g);
1470 if (ret < 0) {
1471 dev_err(cm->dev, "Cannot create sysfs entry of %s regulator\n",
1472 charger->regulator_name);
1473 ret = -EINVAL;
1474 goto err;
1478 if (chargers_externally_control) {
1479 dev_err(cm->dev, "Cannot register regulator because charger-manager must need at least one charger for charging battery\n");
1480 ret = -EINVAL;
1481 goto err;
1484 err:
1485 return ret;
1488 static int cm_init_thermal_data(struct charger_manager *cm)
1490 struct charger_desc *desc = cm->desc;
1491 union power_supply_propval val;
1492 int ret;
1494 /* Verify whether fuel gauge provides battery temperature */
1495 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
1496 POWER_SUPPLY_PROP_TEMP, &val);
1498 if (!ret) {
1499 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1500 POWER_SUPPLY_PROP_TEMP;
1501 cm->charger_psy.num_properties++;
1502 cm->desc->measure_battery_temp = true;
1504 #ifdef CONFIG_THERMAL
1505 cm->tzd_batt = cm->fuel_gauge->tzd;
1507 if (ret && desc->thermal_zone) {
1508 cm->tzd_batt =
1509 thermal_zone_get_zone_by_name(desc->thermal_zone);
1510 if (IS_ERR(cm->tzd_batt))
1511 return PTR_ERR(cm->tzd_batt);
1513 /* Use external thermometer */
1514 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1515 POWER_SUPPLY_PROP_TEMP_AMBIENT;
1516 cm->charger_psy.num_properties++;
1517 cm->desc->measure_battery_temp = true;
1518 ret = 0;
1520 #endif
1521 if (cm->desc->measure_battery_temp) {
1522 /* NOTICE : Default allowable minimum charge temperature is 0 */
1523 if (!desc->temp_max)
1524 desc->temp_max = CM_DEFAULT_CHARGE_TEMP_MAX;
1525 if (!desc->temp_diff)
1526 desc->temp_diff = CM_DEFAULT_RECHARGE_TEMP_DIFF;
1529 return ret;
1532 static struct of_device_id charger_manager_match[] = {
1534 .compatible = "charger-manager",
1539 static struct charger_desc *of_cm_parse_desc(struct device *dev)
1541 struct charger_desc *desc;
1542 struct device_node *np = dev->of_node;
1543 u32 poll_mode = CM_POLL_DISABLE;
1544 u32 battery_stat = CM_NO_BATTERY;
1545 int num_chgs = 0;
1547 desc = devm_kzalloc(dev, sizeof(*desc), GFP_KERNEL);
1548 if (!desc)
1549 return ERR_PTR(-ENOMEM);
1551 of_property_read_string(np, "cm-name", &desc->psy_name);
1553 of_property_read_u32(np, "cm-poll-mode", &poll_mode);
1554 desc->polling_mode = poll_mode;
1556 of_property_read_u32(np, "cm-poll-interval",
1557 &desc->polling_interval_ms);
1559 of_property_read_u32(np, "cm-fullbatt-vchkdrop-ms",
1560 &desc->fullbatt_vchkdrop_ms);
1561 of_property_read_u32(np, "cm-fullbatt-vchkdrop-volt",
1562 &desc->fullbatt_vchkdrop_uV);
1563 of_property_read_u32(np, "cm-fullbatt-voltage", &desc->fullbatt_uV);
1564 of_property_read_u32(np, "cm-fullbatt-soc", &desc->fullbatt_soc);
1565 of_property_read_u32(np, "cm-fullbatt-capacity",
1566 &desc->fullbatt_full_capacity);
1568 of_property_read_u32(np, "cm-battery-stat", &battery_stat);
1569 desc->battery_present = battery_stat;
1571 /* chargers */
1572 of_property_read_u32(np, "cm-num-chargers", &num_chgs);
1573 if (num_chgs) {
1574 /* Allocate empty bin at the tail of array */
1575 desc->psy_charger_stat = devm_kzalloc(dev, sizeof(char *)
1576 * (num_chgs + 1), GFP_KERNEL);
1577 if (desc->psy_charger_stat) {
1578 int i;
1579 for (i = 0; i < num_chgs; i++)
1580 of_property_read_string_index(np, "cm-chargers",
1581 i, &desc->psy_charger_stat[i]);
1582 } else {
1583 return ERR_PTR(-ENOMEM);
1587 of_property_read_string(np, "cm-fuel-gauge", &desc->psy_fuel_gauge);
1589 of_property_read_string(np, "cm-thermal-zone", &desc->thermal_zone);
1591 of_property_read_u32(np, "cm-battery-cold", &desc->temp_min);
1592 if (of_get_property(np, "cm-battery-cold-in-minus", NULL))
1593 desc->temp_min *= -1;
1594 of_property_read_u32(np, "cm-battery-hot", &desc->temp_max);
1595 of_property_read_u32(np, "cm-battery-temp-diff", &desc->temp_diff);
1597 of_property_read_u32(np, "cm-charging-max",
1598 &desc->charging_max_duration_ms);
1599 of_property_read_u32(np, "cm-discharging-max",
1600 &desc->discharging_max_duration_ms);
1602 /* battery charger regualtors */
1603 desc->num_charger_regulators = of_get_child_count(np);
1604 if (desc->num_charger_regulators) {
1605 struct charger_regulator *chg_regs;
1606 struct device_node *child;
1608 chg_regs = devm_kzalloc(dev, sizeof(*chg_regs)
1609 * desc->num_charger_regulators,
1610 GFP_KERNEL);
1611 if (!chg_regs)
1612 return ERR_PTR(-ENOMEM);
1614 desc->charger_regulators = chg_regs;
1616 for_each_child_of_node(np, child) {
1617 struct charger_cable *cables;
1618 struct device_node *_child;
1620 of_property_read_string(child, "cm-regulator-name",
1621 &chg_regs->regulator_name);
1623 /* charger cables */
1624 chg_regs->num_cables = of_get_child_count(child);
1625 if (chg_regs->num_cables) {
1626 cables = devm_kzalloc(dev, sizeof(*cables)
1627 * chg_regs->num_cables,
1628 GFP_KERNEL);
1629 if (!cables)
1630 return ERR_PTR(-ENOMEM);
1632 chg_regs->cables = cables;
1634 for_each_child_of_node(child, _child) {
1635 of_property_read_string(_child,
1636 "cm-cable-name", &cables->name);
1637 of_property_read_string(_child,
1638 "cm-cable-extcon",
1639 &cables->extcon_name);
1640 of_property_read_u32(_child,
1641 "cm-cable-min",
1642 &cables->min_uA);
1643 of_property_read_u32(_child,
1644 "cm-cable-max",
1645 &cables->max_uA);
1646 cables++;
1649 chg_regs++;
1652 return desc;
1655 static inline struct charger_desc *cm_get_drv_data(struct platform_device *pdev)
1657 if (pdev->dev.of_node)
1658 return of_cm_parse_desc(&pdev->dev);
1659 return (struct charger_desc *)dev_get_platdata(&pdev->dev);
1662 static int charger_manager_probe(struct platform_device *pdev)
1664 struct charger_desc *desc = cm_get_drv_data(pdev);
1665 struct charger_manager *cm;
1666 int ret = 0, i = 0;
1667 int j = 0;
1668 union power_supply_propval val;
1670 if (g_desc && !rtc_dev && g_desc->rtc_name) {
1671 rtc_dev = rtc_class_open(g_desc->rtc_name);
1672 if (IS_ERR_OR_NULL(rtc_dev)) {
1673 rtc_dev = NULL;
1674 dev_err(&pdev->dev, "Cannot get RTC %s\n",
1675 g_desc->rtc_name);
1676 return -ENODEV;
1680 if (!desc) {
1681 dev_err(&pdev->dev, "No platform data (desc) found\n");
1682 return -ENODEV;
1685 cm = devm_kzalloc(&pdev->dev,
1686 sizeof(struct charger_manager), GFP_KERNEL);
1687 if (!cm)
1688 return -ENOMEM;
1690 /* Basic Values. Unspecified are Null or 0 */
1691 cm->dev = &pdev->dev;
1692 cm->desc = desc;
1695 * The following two do not need to be errors.
1696 * Users may intentionally ignore those two features.
1698 if (desc->fullbatt_uV == 0) {
1699 dev_info(&pdev->dev, "Ignoring full-battery voltage threshold as it is not supplied\n");
1701 if (!desc->fullbatt_vchkdrop_ms || !desc->fullbatt_vchkdrop_uV) {
1702 dev_info(&pdev->dev, "Disabling full-battery voltage drop checking mechanism as it is not supplied\n");
1703 desc->fullbatt_vchkdrop_ms = 0;
1704 desc->fullbatt_vchkdrop_uV = 0;
1706 if (desc->fullbatt_soc == 0) {
1707 dev_info(&pdev->dev, "Ignoring full-battery soc(state of charge) threshold as it is not supplied\n");
1709 if (desc->fullbatt_full_capacity == 0) {
1710 dev_info(&pdev->dev, "Ignoring full-battery full capacity threshold as it is not supplied\n");
1713 if (!desc->charger_regulators || desc->num_charger_regulators < 1) {
1714 dev_err(&pdev->dev, "charger_regulators undefined\n");
1715 return -EINVAL;
1718 if (!desc->psy_charger_stat || !desc->psy_charger_stat[0]) {
1719 dev_err(&pdev->dev, "No power supply defined\n");
1720 return -EINVAL;
1723 /* Counting index only */
1724 while (desc->psy_charger_stat[i])
1725 i++;
1727 cm->charger_stat = devm_kzalloc(&pdev->dev,
1728 sizeof(struct power_supply *) * i, GFP_KERNEL);
1729 if (!cm->charger_stat)
1730 return -ENOMEM;
1732 for (i = 0; desc->psy_charger_stat[i]; i++) {
1733 cm->charger_stat[i] = power_supply_get_by_name(
1734 desc->psy_charger_stat[i]);
1735 if (!cm->charger_stat[i]) {
1736 dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1737 desc->psy_charger_stat[i]);
1738 return -ENODEV;
1742 cm->fuel_gauge = power_supply_get_by_name(desc->psy_fuel_gauge);
1743 if (!cm->fuel_gauge) {
1744 dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1745 desc->psy_fuel_gauge);
1746 return -ENODEV;
1749 if (desc->polling_interval_ms == 0 ||
1750 msecs_to_jiffies(desc->polling_interval_ms) <= CM_JIFFIES_SMALL) {
1751 dev_err(&pdev->dev, "polling_interval_ms is too small\n");
1752 return -EINVAL;
1755 if (!desc->charging_max_duration_ms ||
1756 !desc->discharging_max_duration_ms) {
1757 dev_info(&pdev->dev, "Cannot limit charging duration checking mechanism to prevent overcharge/overheat and control discharging duration\n");
1758 desc->charging_max_duration_ms = 0;
1759 desc->discharging_max_duration_ms = 0;
1762 platform_set_drvdata(pdev, cm);
1764 memcpy(&cm->charger_psy, &psy_default, sizeof(psy_default));
1766 if (!desc->psy_name)
1767 strncpy(cm->psy_name_buf, psy_default.name, PSY_NAME_MAX);
1768 else
1769 strncpy(cm->psy_name_buf, desc->psy_name, PSY_NAME_MAX);
1770 cm->charger_psy.name = cm->psy_name_buf;
1772 /* Allocate for psy properties because they may vary */
1773 cm->charger_psy.properties = devm_kzalloc(&pdev->dev,
1774 sizeof(enum power_supply_property)
1775 * (ARRAY_SIZE(default_charger_props) +
1776 NUM_CHARGER_PSY_OPTIONAL), GFP_KERNEL);
1777 if (!cm->charger_psy.properties)
1778 return -ENOMEM;
1780 memcpy(cm->charger_psy.properties, default_charger_props,
1781 sizeof(enum power_supply_property) *
1782 ARRAY_SIZE(default_charger_props));
1783 cm->charger_psy.num_properties = psy_default.num_properties;
1785 /* Find which optional psy-properties are available */
1786 if (!cm->fuel_gauge->get_property(cm->fuel_gauge,
1787 POWER_SUPPLY_PROP_CHARGE_NOW, &val)) {
1788 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1789 POWER_SUPPLY_PROP_CHARGE_NOW;
1790 cm->charger_psy.num_properties++;
1792 if (!cm->fuel_gauge->get_property(cm->fuel_gauge,
1793 POWER_SUPPLY_PROP_CURRENT_NOW,
1794 &val)) {
1795 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1796 POWER_SUPPLY_PROP_CURRENT_NOW;
1797 cm->charger_psy.num_properties++;
1800 ret = cm_init_thermal_data(cm);
1801 if (ret) {
1802 dev_err(&pdev->dev, "Failed to initialize thermal data\n");
1803 cm->desc->measure_battery_temp = false;
1806 INIT_DELAYED_WORK(&cm->fullbatt_vchk_work, fullbatt_vchk);
1808 ret = power_supply_register(NULL, &cm->charger_psy);
1809 if (ret) {
1810 dev_err(&pdev->dev, "Cannot register charger-manager with name \"%s\"\n",
1811 cm->charger_psy.name);
1812 return ret;
1815 /* Register extcon device for charger cable */
1816 ret = charger_manager_register_extcon(cm);
1817 if (ret < 0) {
1818 dev_err(&pdev->dev, "Cannot initialize extcon device\n");
1819 goto err_reg_extcon;
1822 /* Register sysfs entry for charger(regulator) */
1823 ret = charger_manager_register_sysfs(cm);
1824 if (ret < 0) {
1825 dev_err(&pdev->dev,
1826 "Cannot initialize sysfs entry of regulator\n");
1827 goto err_reg_sysfs;
1830 /* Add to the list */
1831 mutex_lock(&cm_list_mtx);
1832 list_add(&cm->entry, &cm_list);
1833 mutex_unlock(&cm_list_mtx);
1836 * Charger-manager is capable of waking up the systme from sleep
1837 * when event is happend through cm_notify_event()
1839 device_init_wakeup(&pdev->dev, true);
1840 device_set_wakeup_capable(&pdev->dev, false);
1842 schedule_work(&setup_polling);
1844 return 0;
1846 err_reg_sysfs:
1847 for (i = 0; i < desc->num_charger_regulators; i++) {
1848 struct charger_regulator *charger;
1850 charger = &desc->charger_regulators[i];
1851 sysfs_remove_group(&cm->charger_psy.dev->kobj,
1852 &charger->attr_g);
1854 err_reg_extcon:
1855 for (i = 0; i < desc->num_charger_regulators; i++) {
1856 struct charger_regulator *charger;
1858 charger = &desc->charger_regulators[i];
1859 for (j = 0; j < charger->num_cables; j++) {
1860 struct charger_cable *cable = &charger->cables[j];
1861 /* Remove notifier block if only edev exists */
1862 if (cable->extcon_dev.edev)
1863 extcon_unregister_interest(&cable->extcon_dev);
1866 regulator_put(desc->charger_regulators[i].consumer);
1869 power_supply_unregister(&cm->charger_psy);
1871 return ret;
1874 static int charger_manager_remove(struct platform_device *pdev)
1876 struct charger_manager *cm = platform_get_drvdata(pdev);
1877 struct charger_desc *desc = cm->desc;
1878 int i = 0;
1879 int j = 0;
1881 /* Remove from the list */
1882 mutex_lock(&cm_list_mtx);
1883 list_del(&cm->entry);
1884 mutex_unlock(&cm_list_mtx);
1886 cancel_work_sync(&setup_polling);
1887 cancel_delayed_work_sync(&cm_monitor_work);
1889 for (i = 0 ; i < desc->num_charger_regulators ; i++) {
1890 struct charger_regulator *charger
1891 = &desc->charger_regulators[i];
1892 for (j = 0 ; j < charger->num_cables ; j++) {
1893 struct charger_cable *cable = &charger->cables[j];
1894 extcon_unregister_interest(&cable->extcon_dev);
1898 for (i = 0 ; i < desc->num_charger_regulators ; i++)
1899 regulator_put(desc->charger_regulators[i].consumer);
1901 power_supply_unregister(&cm->charger_psy);
1903 try_charger_enable(cm, false);
1905 return 0;
1908 static const struct platform_device_id charger_manager_id[] = {
1909 { "charger-manager", 0 },
1910 { },
1912 MODULE_DEVICE_TABLE(platform, charger_manager_id);
1914 static int cm_suspend_noirq(struct device *dev)
1916 int ret = 0;
1918 if (device_may_wakeup(dev)) {
1919 device_set_wakeup_capable(dev, false);
1920 ret = -EAGAIN;
1923 return ret;
1926 static int cm_suspend_prepare(struct device *dev)
1928 struct charger_manager *cm = dev_get_drvdata(dev);
1930 if (!cm_suspended) {
1931 if (rtc_dev) {
1932 struct rtc_time tmp;
1933 unsigned long now;
1935 rtc_read_alarm(rtc_dev, &rtc_wkalarm_save);
1936 rtc_read_time(rtc_dev, &tmp);
1938 if (rtc_wkalarm_save.enabled) {
1939 rtc_tm_to_time(&rtc_wkalarm_save.time,
1940 &rtc_wkalarm_save_time);
1941 rtc_tm_to_time(&tmp, &now);
1942 if (now > rtc_wkalarm_save_time)
1943 rtc_wkalarm_save_time = 0;
1944 } else {
1945 rtc_wkalarm_save_time = 0;
1948 cm_suspended = true;
1951 cancel_delayed_work(&cm->fullbatt_vchk_work);
1952 cm->status_save_ext_pwr_inserted = is_ext_pwr_online(cm);
1953 cm->status_save_batt = is_batt_present(cm);
1955 if (!cm_rtc_set) {
1956 cm_suspend_duration_ms = 0;
1957 cm_rtc_set = cm_setup_timer();
1960 return 0;
1963 static void cm_suspend_complete(struct device *dev)
1965 struct charger_manager *cm = dev_get_drvdata(dev);
1967 if (cm_suspended) {
1968 if (rtc_dev) {
1969 struct rtc_wkalrm tmp;
1971 rtc_read_alarm(rtc_dev, &tmp);
1972 rtc_wkalarm_save.pending = tmp.pending;
1973 rtc_set_alarm(rtc_dev, &rtc_wkalarm_save);
1975 cm_suspended = false;
1976 cm_rtc_set = false;
1979 /* Re-enqueue delayed work (fullbatt_vchk_work) */
1980 if (cm->fullbatt_vchk_jiffies_at) {
1981 unsigned long delay = 0;
1982 unsigned long now = jiffies + CM_JIFFIES_SMALL;
1984 if (time_after_eq(now, cm->fullbatt_vchk_jiffies_at)) {
1985 delay = (unsigned long)((long)now
1986 - (long)(cm->fullbatt_vchk_jiffies_at));
1987 delay = jiffies_to_msecs(delay);
1988 } else {
1989 delay = 0;
1993 * Account for cm_suspend_duration_ms if
1994 * assume_timer_stops_in_suspend is active
1996 if (g_desc && g_desc->assume_timer_stops_in_suspend) {
1997 if (delay > cm_suspend_duration_ms)
1998 delay -= cm_suspend_duration_ms;
1999 else
2000 delay = 0;
2003 queue_delayed_work(cm_wq, &cm->fullbatt_vchk_work,
2004 msecs_to_jiffies(delay));
2006 device_set_wakeup_capable(cm->dev, false);
2007 uevent_notify(cm, NULL);
2010 static const struct dev_pm_ops charger_manager_pm = {
2011 .prepare = cm_suspend_prepare,
2012 .suspend_noirq = cm_suspend_noirq,
2013 .complete = cm_suspend_complete,
2016 static struct platform_driver charger_manager_driver = {
2017 .driver = {
2018 .name = "charger-manager",
2019 .owner = THIS_MODULE,
2020 .pm = &charger_manager_pm,
2021 .of_match_table = charger_manager_match,
2023 .probe = charger_manager_probe,
2024 .remove = charger_manager_remove,
2025 .id_table = charger_manager_id,
2028 static int __init charger_manager_init(void)
2030 cm_wq = create_freezable_workqueue("charger_manager");
2031 INIT_DELAYED_WORK(&cm_monitor_work, cm_monitor_poller);
2033 return platform_driver_register(&charger_manager_driver);
2035 late_initcall(charger_manager_init);
2037 static void __exit charger_manager_cleanup(void)
2039 destroy_workqueue(cm_wq);
2040 cm_wq = NULL;
2042 platform_driver_unregister(&charger_manager_driver);
2044 module_exit(charger_manager_cleanup);
2047 * find_power_supply - find the associated power_supply of charger
2048 * @cm: the Charger Manager representing the battery
2049 * @psy: pointer to instance of charger's power_supply
2051 static bool find_power_supply(struct charger_manager *cm,
2052 struct power_supply *psy)
2054 int i;
2055 bool found = false;
2057 for (i = 0; cm->charger_stat[i]; i++) {
2058 if (psy == cm->charger_stat[i]) {
2059 found = true;
2060 break;
2064 return found;
2068 * cm_notify_event - charger driver notify Charger Manager of charger event
2069 * @psy: pointer to instance of charger's power_supply
2070 * @type: type of charger event
2071 * @msg: optional message passed to uevent_notify fuction
2073 void cm_notify_event(struct power_supply *psy, enum cm_event_types type,
2074 char *msg)
2076 struct charger_manager *cm;
2077 bool found_power_supply = false;
2079 if (psy == NULL)
2080 return;
2082 mutex_lock(&cm_list_mtx);
2083 list_for_each_entry(cm, &cm_list, entry) {
2084 found_power_supply = find_power_supply(cm, psy);
2085 if (found_power_supply)
2086 break;
2088 mutex_unlock(&cm_list_mtx);
2090 if (!found_power_supply)
2091 return;
2093 switch (type) {
2094 case CM_EVENT_BATT_FULL:
2095 fullbatt_handler(cm);
2096 break;
2097 case CM_EVENT_BATT_OUT:
2098 battout_handler(cm);
2099 break;
2100 case CM_EVENT_BATT_IN:
2101 case CM_EVENT_EXT_PWR_IN_OUT ... CM_EVENT_CHG_START_STOP:
2102 misc_event_handler(cm, type);
2103 break;
2104 case CM_EVENT_UNKNOWN:
2105 case CM_EVENT_OTHERS:
2106 uevent_notify(cm, msg ? msg : default_event_names[type]);
2107 break;
2108 default:
2109 dev_err(cm->dev, "%s: type not specified\n", __func__);
2110 break;
2113 EXPORT_SYMBOL_GPL(cm_notify_event);
2115 MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
2116 MODULE_DESCRIPTION("Charger Manager");
2117 MODULE_LICENSE("GPL");