Merge remote-tracking branch 'regulator/topic/core' into regulator-next
[cascardo/linux.git] / drivers / power / charger-manager.c
1 /*
2  * Copyright (C) 2011 Samsung Electronics Co., Ltd.
3  * MyungJoo Ham <myungjoo.ham@samsung.com>
4  *
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.
9  *
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 **/
14
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16
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>
30
31 /*
32  * Default termperature threshold for charging.
33  * Every temperature units are in tenth of centigrade.
34  */
35 #define CM_DEFAULT_RECHARGE_TEMP_DIFF   50
36 #define CM_DEFAULT_CHARGE_TEMP_MAX      500
37
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"
48 };
49
50 /*
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.
54  */
55 #define CM_JIFFIES_SMALL        (2)
56
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))
59
60 /*
61  * Regard CM_RTC_SMALL (sec) is small enough to ignore error in invoking
62  * rtc alarm. It should be 2 or larger
63  */
64 #define CM_RTC_SMALL            (2)
65
66 #define UEVENT_BUF_SIZE         32
67
68 static LIST_HEAD(cm_list);
69 static DEFINE_MUTEX(cm_list_mtx);
70
71 /* About in-suspend (suspend-again) monitoring */
72 static struct rtc_device *rtc_dev;
73 /*
74  * Backup RTC alarm
75  * Save the wakeup alarm before entering suspend-to-RAM
76  */
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;
83
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 */
89
90 /* Global charger-manager description */
91 static struct charger_global_desc *g_desc; /* init with setup_charger_manager */
92
93 /**
94  * is_batt_present - See if the battery presents in place.
95  * @cm: the Charger Manager representing the battery.
96  */
97 static bool is_batt_present(struct charger_manager *cm)
98 {
99         union power_supply_propval val;
100         struct power_supply *psy;
101         bool present = false;
102         int i, ret;
103
104         switch (cm->desc->battery_present) {
105         case CM_BATTERY_PRESENT:
106                 present = true;
107                 break;
108         case CM_NO_BATTERY:
109                 break;
110         case CM_FUEL_GAUGE:
111                 psy = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
112                 if (!psy)
113                         break;
114
115                 ret = psy->get_property(psy,
116                                 POWER_SUPPLY_PROP_PRESENT, &val);
117                 if (ret == 0 && val.intval)
118                         present = true;
119                 break;
120         case CM_CHARGER_STAT:
121                 for (i = 0; cm->desc->psy_charger_stat[i]; i++) {
122                         psy = power_supply_get_by_name(
123                                         cm->desc->psy_charger_stat[i]);
124                         if (!psy) {
125                                 dev_err(cm->dev, "Cannot find power supply \"%s\"\n",
126                                         cm->desc->psy_charger_stat[i]);
127                                 continue;
128                         }
129
130                         ret = psy->get_property(psy, POWER_SUPPLY_PROP_PRESENT,
131                                         &val);
132                         if (ret == 0 && val.intval) {
133                                 present = true;
134                                 break;
135                         }
136                 }
137                 break;
138         }
139
140         return present;
141 }
142
143 /**
144  * is_ext_pwr_online - See if an external power source is attached to charge
145  * @cm: the Charger Manager representing the battery.
146  *
147  * Returns true if at least one of the chargers of the battery has an external
148  * power source attached to charge the battery regardless of whether it is
149  * actually charging or not.
150  */
151 static bool is_ext_pwr_online(struct charger_manager *cm)
152 {
153         union power_supply_propval val;
154         struct power_supply *psy;
155         bool online = false;
156         int i, ret;
157
158         /* If at least one of them has one, it's yes. */
159         for (i = 0; cm->desc->psy_charger_stat[i]; i++) {
160                 psy = power_supply_get_by_name(cm->desc->psy_charger_stat[i]);
161                 if (!psy) {
162                         dev_err(cm->dev, "Cannot find power supply \"%s\"\n",
163                                         cm->desc->psy_charger_stat[i]);
164                         continue;
165                 }
166
167                 ret = psy->get_property(psy, POWER_SUPPLY_PROP_ONLINE, &val);
168                 if (ret == 0 && val.intval) {
169                         online = true;
170                         break;
171                 }
172         }
173
174         return online;
175 }
176
177 /**
178  * get_batt_uV - Get the voltage level of the battery
179  * @cm: the Charger Manager representing the battery.
180  * @uV: the voltage level returned.
181  *
182  * Returns 0 if there is no error.
183  * Returns a negative value on error.
184  */
185 static int get_batt_uV(struct charger_manager *cm, int *uV)
186 {
187         union power_supply_propval val;
188         struct power_supply *fuel_gauge;
189         int ret;
190
191         fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
192         if (!fuel_gauge)
193                 return -ENODEV;
194
195         ret = fuel_gauge->get_property(fuel_gauge,
196                                 POWER_SUPPLY_PROP_VOLTAGE_NOW, &val);
197         if (ret)
198                 return ret;
199
200         *uV = val.intval;
201         return 0;
202 }
203
204 /**
205  * is_charging - Returns true if the battery is being charged.
206  * @cm: the Charger Manager representing the battery.
207  */
208 static bool is_charging(struct charger_manager *cm)
209 {
210         int i, ret;
211         bool charging = false;
212         struct power_supply *psy;
213         union power_supply_propval val;
214
215         /* If there is no battery, it cannot be charged */
216         if (!is_batt_present(cm))
217                 return false;
218
219         /* If at least one of the charger is charging, return yes */
220         for (i = 0; cm->desc->psy_charger_stat[i]; i++) {
221                 /* 1. The charger sholuld not be DISABLED */
222                 if (cm->emergency_stop)
223                         continue;
224                 if (!cm->charger_enabled)
225                         continue;
226
227                 psy = power_supply_get_by_name(cm->desc->psy_charger_stat[i]);
228                 if (!psy) {
229                         dev_err(cm->dev, "Cannot find power supply \"%s\"\n",
230                                         cm->desc->psy_charger_stat[i]);
231                         continue;
232                 }
233
234                 /* 2. The charger should be online (ext-power) */
235                 ret = psy->get_property(psy, POWER_SUPPLY_PROP_ONLINE, &val);
236                 if (ret) {
237                         dev_warn(cm->dev, "Cannot read ONLINE value from %s\n",
238                                  cm->desc->psy_charger_stat[i]);
239                         continue;
240                 }
241                 if (val.intval == 0)
242                         continue;
243
244                 /*
245                  * 3. The charger should not be FULL, DISCHARGING,
246                  * or NOT_CHARGING.
247                  */
248                 ret = psy->get_property(psy, POWER_SUPPLY_PROP_STATUS, &val);
249                 if (ret) {
250                         dev_warn(cm->dev, "Cannot read STATUS value from %s\n",
251                                  cm->desc->psy_charger_stat[i]);
252                         continue;
253                 }
254                 if (val.intval == POWER_SUPPLY_STATUS_FULL ||
255                                 val.intval == POWER_SUPPLY_STATUS_DISCHARGING ||
256                                 val.intval == POWER_SUPPLY_STATUS_NOT_CHARGING)
257                         continue;
258
259                 /* Then, this is charging. */
260                 charging = true;
261                 break;
262         }
263
264         return charging;
265 }
266
267 /**
268  * is_full_charged - Returns true if the battery is fully charged.
269  * @cm: the Charger Manager representing the battery.
270  */
271 static bool is_full_charged(struct charger_manager *cm)
272 {
273         struct charger_desc *desc = cm->desc;
274         union power_supply_propval val;
275         struct power_supply *fuel_gauge;
276         int ret = 0;
277         int uV;
278
279         /* If there is no battery, it cannot be charged */
280         if (!is_batt_present(cm))
281                 return false;
282
283         fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
284         if (!fuel_gauge)
285                 return false;
286
287         if (desc->fullbatt_full_capacity > 0) {
288                 val.intval = 0;
289
290                 /* Not full if capacity of fuel gauge isn't full */
291                 ret = fuel_gauge->get_property(fuel_gauge,
292                                 POWER_SUPPLY_PROP_CHARGE_FULL, &val);
293                 if (!ret && val.intval > desc->fullbatt_full_capacity)
294                         return true;
295         }
296
297         /* Full, if it's over the fullbatt voltage */
298         if (desc->fullbatt_uV > 0) {
299                 ret = get_batt_uV(cm, &uV);
300                 if (!ret && uV >= desc->fullbatt_uV)
301                         return true;
302         }
303
304         /* Full, if the capacity is more than fullbatt_soc */
305         if (desc->fullbatt_soc > 0) {
306                 val.intval = 0;
307
308                 ret = fuel_gauge->get_property(fuel_gauge,
309                                 POWER_SUPPLY_PROP_CAPACITY, &val);
310                 if (!ret && val.intval >= desc->fullbatt_soc)
311                         return true;
312         }
313
314         return false;
315 }
316
317 /**
318  * is_polling_required - Return true if need to continue polling for this CM.
319  * @cm: the Charger Manager representing the battery.
320  */
321 static bool is_polling_required(struct charger_manager *cm)
322 {
323         switch (cm->desc->polling_mode) {
324         case CM_POLL_DISABLE:
325                 return false;
326         case CM_POLL_ALWAYS:
327                 return true;
328         case CM_POLL_EXTERNAL_POWER_ONLY:
329                 return is_ext_pwr_online(cm);
330         case CM_POLL_CHARGING_ONLY:
331                 return is_charging(cm);
332         default:
333                 dev_warn(cm->dev, "Incorrect polling_mode (%d)\n",
334                          cm->desc->polling_mode);
335         }
336
337         return false;
338 }
339
340 /**
341  * try_charger_enable - Enable/Disable chargers altogether
342  * @cm: the Charger Manager representing the battery.
343  * @enable: true: enable / false: disable
344  *
345  * Note that Charger Manager keeps the charger enabled regardless whether
346  * the charger is charging or not (because battery is full or no external
347  * power source exists) except when CM needs to disable chargers forcibly
348  * bacause of emergency causes; when the battery is overheated or too cold.
349  */
350 static int try_charger_enable(struct charger_manager *cm, bool enable)
351 {
352         int err = 0, i;
353         struct charger_desc *desc = cm->desc;
354
355         /* Ignore if it's redundent command */
356         if (enable == cm->charger_enabled)
357                 return 0;
358
359         if (enable) {
360                 if (cm->emergency_stop)
361                         return -EAGAIN;
362
363                 /*
364                  * Save start time of charging to limit
365                  * maximum possible charging time.
366                  */
367                 cm->charging_start_time = ktime_to_ms(ktime_get());
368                 cm->charging_end_time = 0;
369
370                 for (i = 0 ; i < desc->num_charger_regulators ; i++) {
371                         if (desc->charger_regulators[i].externally_control)
372                                 continue;
373
374                         err = regulator_enable(desc->charger_regulators[i].consumer);
375                         if (err < 0) {
376                                 dev_warn(cm->dev, "Cannot enable %s regulator\n",
377                                          desc->charger_regulators[i].regulator_name);
378                         }
379                 }
380         } else {
381                 /*
382                  * Save end time of charging to maintain fully charged state
383                  * of battery after full-batt.
384                  */
385                 cm->charging_start_time = 0;
386                 cm->charging_end_time = ktime_to_ms(ktime_get());
387
388                 for (i = 0 ; i < desc->num_charger_regulators ; i++) {
389                         if (desc->charger_regulators[i].externally_control)
390                                 continue;
391
392                         err = regulator_disable(desc->charger_regulators[i].consumer);
393                         if (err < 0) {
394                                 dev_warn(cm->dev, "Cannot disable %s regulator\n",
395                                          desc->charger_regulators[i].regulator_name);
396                         }
397                 }
398
399                 /*
400                  * Abnormal battery state - Stop charging forcibly,
401                  * even if charger was enabled at the other places
402                  */
403                 for (i = 0; i < desc->num_charger_regulators; i++) {
404                         if (regulator_is_enabled(
405                                     desc->charger_regulators[i].consumer)) {
406                                 regulator_force_disable(
407                                         desc->charger_regulators[i].consumer);
408                                 dev_warn(cm->dev, "Disable regulator(%s) forcibly\n",
409                                          desc->charger_regulators[i].regulator_name);
410                         }
411                 }
412         }
413
414         if (!err)
415                 cm->charger_enabled = enable;
416
417         return err;
418 }
419
420 /**
421  * try_charger_restart - Restart charging.
422  * @cm: the Charger Manager representing the battery.
423  *
424  * Restart charging by turning off and on the charger.
425  */
426 static int try_charger_restart(struct charger_manager *cm)
427 {
428         int err;
429
430         if (cm->emergency_stop)
431                 return -EAGAIN;
432
433         err = try_charger_enable(cm, false);
434         if (err)
435                 return err;
436
437         return try_charger_enable(cm, true);
438 }
439
440 /**
441  * uevent_notify - Let users know something has changed.
442  * @cm: the Charger Manager representing the battery.
443  * @event: the event string.
444  *
445  * If @event is null, it implies that uevent_notify is called
446  * by resume function. When called in the resume function, cm_suspended
447  * should be already reset to false in order to let uevent_notify
448  * notify the recent event during the suspend to users. While
449  * suspended, uevent_notify does not notify users, but tracks
450  * events so that uevent_notify can notify users later after resumed.
451  */
452 static void uevent_notify(struct charger_manager *cm, const char *event)
453 {
454         static char env_str[UEVENT_BUF_SIZE + 1] = "";
455         static char env_str_save[UEVENT_BUF_SIZE + 1] = "";
456
457         if (cm_suspended) {
458                 /* Nothing in suspended-event buffer */
459                 if (env_str_save[0] == 0) {
460                         if (!strncmp(env_str, event, UEVENT_BUF_SIZE))
461                                 return; /* status not changed */
462                         strncpy(env_str_save, event, UEVENT_BUF_SIZE);
463                         return;
464                 }
465
466                 if (!strncmp(env_str_save, event, UEVENT_BUF_SIZE))
467                         return; /* Duplicated. */
468                 strncpy(env_str_save, event, UEVENT_BUF_SIZE);
469                 return;
470         }
471
472         if (event == NULL) {
473                 /* No messages pending */
474                 if (!env_str_save[0])
475                         return;
476
477                 strncpy(env_str, env_str_save, UEVENT_BUF_SIZE);
478                 kobject_uevent(&cm->dev->kobj, KOBJ_CHANGE);
479                 env_str_save[0] = 0;
480
481                 return;
482         }
483
484         /* status not changed */
485         if (!strncmp(env_str, event, UEVENT_BUF_SIZE))
486                 return;
487
488         /* save the status and notify the update */
489         strncpy(env_str, event, UEVENT_BUF_SIZE);
490         kobject_uevent(&cm->dev->kobj, KOBJ_CHANGE);
491
492         dev_info(cm->dev, "%s\n", event);
493 }
494
495 /**
496  * fullbatt_vchk - Check voltage drop some times after "FULL" event.
497  * @work: the work_struct appointing the function
498  *
499  * If a user has designated "fullbatt_vchkdrop_ms/uV" values with
500  * charger_desc, Charger Manager checks voltage drop after the battery
501  * "FULL" event. It checks whether the voltage has dropped more than
502  * fullbatt_vchkdrop_uV by calling this function after fullbatt_vchkrop_ms.
503  */
504 static void fullbatt_vchk(struct work_struct *work)
505 {
506         struct delayed_work *dwork = to_delayed_work(work);
507         struct charger_manager *cm = container_of(dwork,
508                         struct charger_manager, fullbatt_vchk_work);
509         struct charger_desc *desc = cm->desc;
510         int batt_uV, err, diff;
511
512         /* remove the appointment for fullbatt_vchk */
513         cm->fullbatt_vchk_jiffies_at = 0;
514
515         if (!desc->fullbatt_vchkdrop_uV || !desc->fullbatt_vchkdrop_ms)
516                 return;
517
518         err = get_batt_uV(cm, &batt_uV);
519         if (err) {
520                 dev_err(cm->dev, "%s: get_batt_uV error(%d)\n", __func__, err);
521                 return;
522         }
523
524         diff = desc->fullbatt_uV - batt_uV;
525         if (diff < 0)
526                 return;
527
528         dev_info(cm->dev, "VBATT dropped %duV after full-batt\n", diff);
529
530         if (diff > desc->fullbatt_vchkdrop_uV) {
531                 try_charger_restart(cm);
532                 uevent_notify(cm, "Recharging");
533         }
534 }
535
536 /**
537  * check_charging_duration - Monitor charging/discharging duration
538  * @cm: the Charger Manager representing the battery.
539  *
540  * If whole charging duration exceed 'charging_max_duration_ms',
541  * cm stop charging to prevent overcharge/overheat. If discharging
542  * duration exceed 'discharging _max_duration_ms', charger cable is
543  * attached, after full-batt, cm start charging to maintain fully
544  * charged state for battery.
545  */
546 static int check_charging_duration(struct charger_manager *cm)
547 {
548         struct charger_desc *desc = cm->desc;
549         u64 curr = ktime_to_ms(ktime_get());
550         u64 duration;
551         int ret = false;
552
553         if (!desc->charging_max_duration_ms &&
554                         !desc->discharging_max_duration_ms)
555                 return ret;
556
557         if (cm->charger_enabled) {
558                 duration = curr - cm->charging_start_time;
559
560                 if (duration > desc->charging_max_duration_ms) {
561                         dev_info(cm->dev, "Charging duration exceed %ums\n",
562                                  desc->charging_max_duration_ms);
563                         uevent_notify(cm, "Discharging");
564                         try_charger_enable(cm, false);
565                         ret = true;
566                 }
567         } else if (is_ext_pwr_online(cm) && !cm->charger_enabled) {
568                 duration = curr - cm->charging_end_time;
569
570                 if (duration > desc->charging_max_duration_ms &&
571                                 is_ext_pwr_online(cm)) {
572                         dev_info(cm->dev, "Discharging duration exceed %ums\n",
573                                  desc->discharging_max_duration_ms);
574                         uevent_notify(cm, "Recharging");
575                         try_charger_enable(cm, true);
576                         ret = true;
577                 }
578         }
579
580         return ret;
581 }
582
583 static int cm_get_battery_temperature_by_psy(struct charger_manager *cm,
584                                         int *temp)
585 {
586         struct power_supply *fuel_gauge;
587
588         fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
589         if (!fuel_gauge)
590                 return -ENODEV;
591
592         return fuel_gauge->get_property(fuel_gauge,
593                                 POWER_SUPPLY_PROP_TEMP,
594                                 (union power_supply_propval *)temp);
595 }
596
597 static int cm_get_battery_temperature(struct charger_manager *cm,
598                                         int *temp)
599 {
600         int ret;
601
602         if (!cm->desc->measure_battery_temp)
603                 return -ENODEV;
604
605 #ifdef CONFIG_THERMAL
606         if (cm->tzd_batt) {
607                 ret = thermal_zone_get_temp(cm->tzd_batt, (unsigned long *)temp);
608                 if (!ret)
609                         /* Calibrate temperature unit */
610                         *temp /= 100;
611         } else
612 #endif
613         {
614                 /* if-else continued from CONFIG_THERMAL */
615                 ret = cm_get_battery_temperature_by_psy(cm, temp);
616         }
617
618         return ret;
619 }
620
621 static int cm_check_thermal_status(struct charger_manager *cm)
622 {
623         struct charger_desc *desc = cm->desc;
624         int temp, upper_limit, lower_limit;
625         int ret = 0;
626
627         ret = cm_get_battery_temperature(cm, &temp);
628         if (ret) {
629                 /* FIXME:
630                  * No information of battery temperature might
631                  * occur hazadous result. We have to handle it
632                  * depending on battery type.
633                  */
634                 dev_err(cm->dev, "Failed to get battery temperature\n");
635                 return 0;
636         }
637
638         upper_limit = desc->temp_max;
639         lower_limit = desc->temp_min;
640
641         if (cm->emergency_stop) {
642                 upper_limit -= desc->temp_diff;
643                 lower_limit += desc->temp_diff;
644         }
645
646         if (temp > upper_limit)
647                 ret = CM_EVENT_BATT_OVERHEAT;
648         else if (temp < lower_limit)
649                 ret = CM_EVENT_BATT_COLD;
650
651         return ret;
652 }
653
654 /**
655  * _cm_monitor - Monitor the temperature and return true for exceptions.
656  * @cm: the Charger Manager representing the battery.
657  *
658  * Returns true if there is an event to notify for the battery.
659  * (True if the status of "emergency_stop" changes)
660  */
661 static bool _cm_monitor(struct charger_manager *cm)
662 {
663         int temp_alrt;
664
665         temp_alrt = cm_check_thermal_status(cm);
666
667         /* It has been stopped already */
668         if (temp_alrt && cm->emergency_stop)
669                 return false;
670
671         /*
672          * Check temperature whether overheat or cold.
673          * If temperature is out of range normal state, stop charging.
674          */
675         if (temp_alrt) {
676                 cm->emergency_stop = temp_alrt;
677                 if (!try_charger_enable(cm, false))
678                         uevent_notify(cm, default_event_names[temp_alrt]);
679
680         /*
681          * Check whole charging duration and discharing duration
682          * after full-batt.
683          */
684         } else if (!cm->emergency_stop && check_charging_duration(cm)) {
685                 dev_dbg(cm->dev,
686                         "Charging/Discharging duration is out of range\n");
687         /*
688          * Check dropped voltage of battery. If battery voltage is more
689          * dropped than fullbatt_vchkdrop_uV after fully charged state,
690          * charger-manager have to recharge battery.
691          */
692         } else if (!cm->emergency_stop && is_ext_pwr_online(cm) &&
693                         !cm->charger_enabled) {
694                 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
695
696         /*
697          * Check whether fully charged state to protect overcharge
698          * if charger-manager is charging for battery.
699          */
700         } else if (!cm->emergency_stop && is_full_charged(cm) &&
701                         cm->charger_enabled) {
702                 dev_info(cm->dev, "EVENT_HANDLE: Battery Fully Charged\n");
703                 uevent_notify(cm, default_event_names[CM_EVENT_BATT_FULL]);
704
705                 try_charger_enable(cm, false);
706
707                 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
708         } else {
709                 cm->emergency_stop = 0;
710                 if (is_ext_pwr_online(cm)) {
711                         if (!try_charger_enable(cm, true))
712                                 uevent_notify(cm, "CHARGING");
713                 }
714         }
715
716         return true;
717 }
718
719 /**
720  * cm_monitor - Monitor every battery.
721  *
722  * Returns true if there is an event to notify from any of the batteries.
723  * (True if the status of "emergency_stop" changes)
724  */
725 static bool cm_monitor(void)
726 {
727         bool stop = false;
728         struct charger_manager *cm;
729
730         mutex_lock(&cm_list_mtx);
731
732         list_for_each_entry(cm, &cm_list, entry) {
733                 if (_cm_monitor(cm))
734                         stop = true;
735         }
736
737         mutex_unlock(&cm_list_mtx);
738
739         return stop;
740 }
741
742 /**
743  * _setup_polling - Setup the next instance of polling.
744  * @work: work_struct of the function _setup_polling.
745  */
746 static void _setup_polling(struct work_struct *work)
747 {
748         unsigned long min = ULONG_MAX;
749         struct charger_manager *cm;
750         bool keep_polling = false;
751         unsigned long _next_polling;
752
753         mutex_lock(&cm_list_mtx);
754
755         list_for_each_entry(cm, &cm_list, entry) {
756                 if (is_polling_required(cm) && cm->desc->polling_interval_ms) {
757                         keep_polling = true;
758
759                         if (min > cm->desc->polling_interval_ms)
760                                 min = cm->desc->polling_interval_ms;
761                 }
762         }
763
764         polling_jiffy = msecs_to_jiffies(min);
765         if (polling_jiffy <= CM_JIFFIES_SMALL)
766                 polling_jiffy = CM_JIFFIES_SMALL + 1;
767
768         if (!keep_polling)
769                 polling_jiffy = ULONG_MAX;
770         if (polling_jiffy == ULONG_MAX)
771                 goto out;
772
773         WARN(cm_wq == NULL, "charger-manager: workqueue not initialized"
774                             ". try it later. %s\n", __func__);
775
776         /*
777          * Use mod_delayed_work() iff the next polling interval should
778          * occur before the currently scheduled one.  If @cm_monitor_work
779          * isn't active, the end result is the same, so no need to worry
780          * about stale @next_polling.
781          */
782         _next_polling = jiffies + polling_jiffy;
783
784         if (time_before(_next_polling, next_polling)) {
785                 mod_delayed_work(cm_wq, &cm_monitor_work, polling_jiffy);
786                 next_polling = _next_polling;
787         } else {
788                 if (queue_delayed_work(cm_wq, &cm_monitor_work, polling_jiffy))
789                         next_polling = _next_polling;
790         }
791 out:
792         mutex_unlock(&cm_list_mtx);
793 }
794 static DECLARE_WORK(setup_polling, _setup_polling);
795
796 /**
797  * cm_monitor_poller - The Monitor / Poller.
798  * @work: work_struct of the function cm_monitor_poller
799  *
800  * During non-suspended state, cm_monitor_poller is used to poll and monitor
801  * the batteries.
802  */
803 static void cm_monitor_poller(struct work_struct *work)
804 {
805         cm_monitor();
806         schedule_work(&setup_polling);
807 }
808
809 /**
810  * fullbatt_handler - Event handler for CM_EVENT_BATT_FULL
811  * @cm: the Charger Manager representing the battery.
812  */
813 static void fullbatt_handler(struct charger_manager *cm)
814 {
815         struct charger_desc *desc = cm->desc;
816
817         if (!desc->fullbatt_vchkdrop_uV || !desc->fullbatt_vchkdrop_ms)
818                 goto out;
819
820         if (cm_suspended)
821                 device_set_wakeup_capable(cm->dev, true);
822
823         mod_delayed_work(cm_wq, &cm->fullbatt_vchk_work,
824                          msecs_to_jiffies(desc->fullbatt_vchkdrop_ms));
825         cm->fullbatt_vchk_jiffies_at = jiffies + msecs_to_jiffies(
826                                        desc->fullbatt_vchkdrop_ms);
827
828         if (cm->fullbatt_vchk_jiffies_at == 0)
829                 cm->fullbatt_vchk_jiffies_at = 1;
830
831 out:
832         dev_info(cm->dev, "EVENT_HANDLE: Battery Fully Charged\n");
833         uevent_notify(cm, default_event_names[CM_EVENT_BATT_FULL]);
834 }
835
836 /**
837  * battout_handler - Event handler for CM_EVENT_BATT_OUT
838  * @cm: the Charger Manager representing the battery.
839  */
840 static void battout_handler(struct charger_manager *cm)
841 {
842         if (cm_suspended)
843                 device_set_wakeup_capable(cm->dev, true);
844
845         if (!is_batt_present(cm)) {
846                 dev_emerg(cm->dev, "Battery Pulled Out!\n");
847                 uevent_notify(cm, default_event_names[CM_EVENT_BATT_OUT]);
848         } else {
849                 uevent_notify(cm, "Battery Reinserted?");
850         }
851 }
852
853 /**
854  * misc_event_handler - Handler for other evnets
855  * @cm: the Charger Manager representing the battery.
856  * @type: the Charger Manager representing the battery.
857  */
858 static void misc_event_handler(struct charger_manager *cm,
859                         enum cm_event_types type)
860 {
861         if (cm_suspended)
862                 device_set_wakeup_capable(cm->dev, true);
863
864         if (is_polling_required(cm) && cm->desc->polling_interval_ms)
865                 schedule_work(&setup_polling);
866         uevent_notify(cm, default_event_names[type]);
867 }
868
869 static int charger_get_property(struct power_supply *psy,
870                 enum power_supply_property psp,
871                 union power_supply_propval *val)
872 {
873         struct charger_manager *cm = container_of(psy,
874                         struct charger_manager, charger_psy);
875         struct charger_desc *desc = cm->desc;
876         struct power_supply *fuel_gauge;
877         int ret = 0;
878         int uV;
879
880         switch (psp) {
881         case POWER_SUPPLY_PROP_STATUS:
882                 if (is_charging(cm))
883                         val->intval = POWER_SUPPLY_STATUS_CHARGING;
884                 else if (is_ext_pwr_online(cm))
885                         val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
886                 else
887                         val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
888                 break;
889         case POWER_SUPPLY_PROP_HEALTH:
890                 if (cm->emergency_stop > 0)
891                         val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
892                 else if (cm->emergency_stop < 0)
893                         val->intval = POWER_SUPPLY_HEALTH_COLD;
894                 else
895                         val->intval = POWER_SUPPLY_HEALTH_GOOD;
896                 break;
897         case POWER_SUPPLY_PROP_PRESENT:
898                 if (is_batt_present(cm))
899                         val->intval = 1;
900                 else
901                         val->intval = 0;
902                 break;
903         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
904                 ret = get_batt_uV(cm, &val->intval);
905                 break;
906         case POWER_SUPPLY_PROP_CURRENT_NOW:
907                 fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
908                 if (!fuel_gauge) {
909                         ret = -ENODEV;
910                         break;
911                 }
912                 ret = fuel_gauge->get_property(fuel_gauge,
913                                 POWER_SUPPLY_PROP_CURRENT_NOW, val);
914                 break;
915         case POWER_SUPPLY_PROP_TEMP:
916         case POWER_SUPPLY_PROP_TEMP_AMBIENT:
917                 return cm_get_battery_temperature(cm, &val->intval);
918         case POWER_SUPPLY_PROP_CAPACITY:
919                 fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
920                 if (!fuel_gauge) {
921                         ret = -ENODEV;
922                         break;
923                 }
924
925                 if (!is_batt_present(cm)) {
926                         /* There is no battery. Assume 100% */
927                         val->intval = 100;
928                         break;
929                 }
930
931                 ret = fuel_gauge->get_property(fuel_gauge,
932                                         POWER_SUPPLY_PROP_CAPACITY, val);
933                 if (ret)
934                         break;
935
936                 if (val->intval > 100) {
937                         val->intval = 100;
938                         break;
939                 }
940                 if (val->intval < 0)
941                         val->intval = 0;
942
943                 /* Do not adjust SOC when charging: voltage is overrated */
944                 if (is_charging(cm))
945                         break;
946
947                 /*
948                  * If the capacity value is inconsistent, calibrate it base on
949                  * the battery voltage values and the thresholds given as desc
950                  */
951                 ret = get_batt_uV(cm, &uV);
952                 if (ret) {
953                         /* Voltage information not available. No calibration */
954                         ret = 0;
955                         break;
956                 }
957
958                 if (desc->fullbatt_uV > 0 && uV >= desc->fullbatt_uV &&
959                     !is_charging(cm)) {
960                         val->intval = 100;
961                         break;
962                 }
963
964                 break;
965         case POWER_SUPPLY_PROP_ONLINE:
966                 if (is_ext_pwr_online(cm))
967                         val->intval = 1;
968                 else
969                         val->intval = 0;
970                 break;
971         case POWER_SUPPLY_PROP_CHARGE_FULL:
972                 if (is_full_charged(cm))
973                         val->intval = 1;
974                 else
975                         val->intval = 0;
976                 ret = 0;
977                 break;
978         case POWER_SUPPLY_PROP_CHARGE_NOW:
979                 if (is_charging(cm)) {
980                         fuel_gauge = power_supply_get_by_name(
981                                         cm->desc->psy_fuel_gauge);
982                         if (!fuel_gauge) {
983                                 ret = -ENODEV;
984                                 break;
985                         }
986
987                         ret = fuel_gauge->get_property(fuel_gauge,
988                                                 POWER_SUPPLY_PROP_CHARGE_NOW,
989                                                 val);
990                         if (ret) {
991                                 val->intval = 1;
992                                 ret = 0;
993                         } else {
994                                 /* If CHARGE_NOW is supplied, use it */
995                                 val->intval = (val->intval > 0) ?
996                                                 val->intval : 1;
997                         }
998                 } else {
999                         val->intval = 0;
1000                 }
1001                 break;
1002         default:
1003                 return -EINVAL;
1004         }
1005         return ret;
1006 }
1007
1008 #define NUM_CHARGER_PSY_OPTIONAL        (4)
1009 static enum power_supply_property default_charger_props[] = {
1010         /* Guaranteed to provide */
1011         POWER_SUPPLY_PROP_STATUS,
1012         POWER_SUPPLY_PROP_HEALTH,
1013         POWER_SUPPLY_PROP_PRESENT,
1014         POWER_SUPPLY_PROP_VOLTAGE_NOW,
1015         POWER_SUPPLY_PROP_CAPACITY,
1016         POWER_SUPPLY_PROP_ONLINE,
1017         POWER_SUPPLY_PROP_CHARGE_FULL,
1018         /*
1019          * Optional properties are:
1020          * POWER_SUPPLY_PROP_CHARGE_NOW,
1021          * POWER_SUPPLY_PROP_CURRENT_NOW,
1022          * POWER_SUPPLY_PROP_TEMP, and
1023          * POWER_SUPPLY_PROP_TEMP_AMBIENT,
1024          */
1025 };
1026
1027 static struct power_supply psy_default = {
1028         .name = "battery",
1029         .type = POWER_SUPPLY_TYPE_BATTERY,
1030         .properties = default_charger_props,
1031         .num_properties = ARRAY_SIZE(default_charger_props),
1032         .get_property = charger_get_property,
1033         .no_thermal = true,
1034 };
1035
1036 /**
1037  * cm_setup_timer - For in-suspend monitoring setup wakeup alarm
1038  *                  for suspend_again.
1039  *
1040  * Returns true if the alarm is set for Charger Manager to use.
1041  * Returns false if
1042  *      cm_setup_timer fails to set an alarm,
1043  *      cm_setup_timer does not need to set an alarm for Charger Manager,
1044  *      or an alarm previously configured is to be used.
1045  */
1046 static bool cm_setup_timer(void)
1047 {
1048         struct charger_manager *cm;
1049         unsigned int wakeup_ms = UINT_MAX;
1050         bool ret = false;
1051
1052         mutex_lock(&cm_list_mtx);
1053
1054         list_for_each_entry(cm, &cm_list, entry) {
1055                 unsigned int fbchk_ms = 0;
1056
1057                 /* fullbatt_vchk is required. setup timer for that */
1058                 if (cm->fullbatt_vchk_jiffies_at) {
1059                         fbchk_ms = jiffies_to_msecs(cm->fullbatt_vchk_jiffies_at
1060                                                     - jiffies);
1061                         if (time_is_before_eq_jiffies(
1062                                 cm->fullbatt_vchk_jiffies_at) ||
1063                                 msecs_to_jiffies(fbchk_ms) < CM_JIFFIES_SMALL) {
1064                                 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
1065                                 fbchk_ms = 0;
1066                         }
1067                 }
1068                 CM_MIN_VALID(wakeup_ms, fbchk_ms);
1069
1070                 /* Skip if polling is not required for this CM */
1071                 if (!is_polling_required(cm) && !cm->emergency_stop)
1072                         continue;
1073                 if (cm->desc->polling_interval_ms == 0)
1074                         continue;
1075                 CM_MIN_VALID(wakeup_ms, cm->desc->polling_interval_ms);
1076         }
1077
1078         mutex_unlock(&cm_list_mtx);
1079
1080         if (wakeup_ms < UINT_MAX && wakeup_ms > 0) {
1081                 pr_info("Charger Manager wakeup timer: %u ms\n", wakeup_ms);
1082                 if (rtc_dev) {
1083                         struct rtc_wkalrm tmp;
1084                         unsigned long time, now;
1085                         unsigned long add = DIV_ROUND_UP(wakeup_ms, 1000);
1086
1087                         /*
1088                          * Set alarm with the polling interval (wakeup_ms)
1089                          * except when rtc_wkalarm_save comes first.
1090                          * However, the alarm time should be NOW +
1091                          * CM_RTC_SMALL or later.
1092                          */
1093                         tmp.enabled = 1;
1094                         rtc_read_time(rtc_dev, &tmp.time);
1095                         rtc_tm_to_time(&tmp.time, &now);
1096                         if (add < CM_RTC_SMALL)
1097                                 add = CM_RTC_SMALL;
1098                         time = now + add;
1099
1100                         ret = true;
1101
1102                         if (rtc_wkalarm_save.enabled &&
1103                             rtc_wkalarm_save_time &&
1104                             rtc_wkalarm_save_time < time) {
1105                                 if (rtc_wkalarm_save_time < now + CM_RTC_SMALL)
1106                                         time = now + CM_RTC_SMALL;
1107                                 else
1108                                         time = rtc_wkalarm_save_time;
1109
1110                                 /* The timer is not appointed by CM */
1111                                 ret = false;
1112                         }
1113
1114                         pr_info("Waking up after %lu secs\n", time - now);
1115
1116                         rtc_time_to_tm(time, &tmp.time);
1117                         rtc_set_alarm(rtc_dev, &tmp);
1118                         cm_suspend_duration_ms += wakeup_ms;
1119                         return ret;
1120                 }
1121         }
1122
1123         if (rtc_dev)
1124                 rtc_set_alarm(rtc_dev, &rtc_wkalarm_save);
1125         return false;
1126 }
1127
1128 static void _cm_fbchk_in_suspend(struct charger_manager *cm)
1129 {
1130         unsigned long jiffy_now = jiffies;
1131
1132         if (!cm->fullbatt_vchk_jiffies_at)
1133                 return;
1134
1135         if (g_desc && g_desc->assume_timer_stops_in_suspend)
1136                 jiffy_now += msecs_to_jiffies(cm_suspend_duration_ms);
1137
1138         /* Execute now if it's going to be executed not too long after */
1139         jiffy_now += CM_JIFFIES_SMALL;
1140
1141         if (time_after_eq(jiffy_now, cm->fullbatt_vchk_jiffies_at))
1142                 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
1143 }
1144
1145 /**
1146  * cm_suspend_again - Determine whether suspend again or not
1147  *
1148  * Returns true if the system should be suspended again
1149  * Returns false if the system should be woken up
1150  */
1151 bool cm_suspend_again(void)
1152 {
1153         struct charger_manager *cm;
1154         bool ret = false;
1155
1156         if (!g_desc || !g_desc->rtc_only_wakeup || !g_desc->rtc_only_wakeup() ||
1157             !cm_rtc_set)
1158                 return false;
1159
1160         if (cm_monitor())
1161                 goto out;
1162
1163         ret = true;
1164         mutex_lock(&cm_list_mtx);
1165         list_for_each_entry(cm, &cm_list, entry) {
1166                 _cm_fbchk_in_suspend(cm);
1167
1168                 if (cm->status_save_ext_pwr_inserted != is_ext_pwr_online(cm) ||
1169                     cm->status_save_batt != is_batt_present(cm)) {
1170                         ret = false;
1171                         break;
1172                 }
1173         }
1174         mutex_unlock(&cm_list_mtx);
1175
1176         cm_rtc_set = cm_setup_timer();
1177 out:
1178         /* It's about the time when the non-CM appointed timer goes off */
1179         if (rtc_wkalarm_save.enabled) {
1180                 unsigned long now;
1181                 struct rtc_time tmp;
1182
1183                 rtc_read_time(rtc_dev, &tmp);
1184                 rtc_tm_to_time(&tmp, &now);
1185
1186                 if (rtc_wkalarm_save_time &&
1187                     now + CM_RTC_SMALL >= rtc_wkalarm_save_time)
1188                         return false;
1189         }
1190         return ret;
1191 }
1192 EXPORT_SYMBOL_GPL(cm_suspend_again);
1193
1194 /**
1195  * setup_charger_manager - initialize charger_global_desc data
1196  * @gd: pointer to instance of charger_global_desc
1197  */
1198 int setup_charger_manager(struct charger_global_desc *gd)
1199 {
1200         if (!gd)
1201                 return -EINVAL;
1202
1203         if (rtc_dev)
1204                 rtc_class_close(rtc_dev);
1205         rtc_dev = NULL;
1206         g_desc = NULL;
1207
1208         if (!gd->rtc_only_wakeup) {
1209                 pr_err("The callback rtc_only_wakeup is not given\n");
1210                 return -EINVAL;
1211         }
1212
1213         if (gd->rtc_name) {
1214                 rtc_dev = rtc_class_open(gd->rtc_name);
1215                 if (IS_ERR_OR_NULL(rtc_dev)) {
1216                         rtc_dev = NULL;
1217                         /* Retry at probe. RTC may be not registered yet */
1218                 }
1219         } else {
1220                 pr_warn("No wakeup timer is given for charger manager.  "
1221                         "In-suspend monitoring won't work.\n");
1222         }
1223
1224         g_desc = gd;
1225         return 0;
1226 }
1227 EXPORT_SYMBOL_GPL(setup_charger_manager);
1228
1229 /**
1230  * charger_extcon_work - enable/diable charger according to the state
1231  *                      of charger cable
1232  *
1233  * @work: work_struct of the function charger_extcon_work.
1234  */
1235 static void charger_extcon_work(struct work_struct *work)
1236 {
1237         struct charger_cable *cable =
1238                         container_of(work, struct charger_cable, wq);
1239         int ret;
1240
1241         if (cable->attached && cable->min_uA != 0 && cable->max_uA != 0) {
1242                 ret = regulator_set_current_limit(cable->charger->consumer,
1243                                         cable->min_uA, cable->max_uA);
1244                 if (ret < 0) {
1245                         pr_err("Cannot set current limit of %s (%s)\n",
1246                                cable->charger->regulator_name, cable->name);
1247                         return;
1248                 }
1249
1250                 pr_info("Set current limit of %s : %duA ~ %duA\n",
1251                         cable->charger->regulator_name,
1252                         cable->min_uA, cable->max_uA);
1253         }
1254
1255         try_charger_enable(cable->cm, cable->attached);
1256 }
1257
1258 /**
1259  * charger_extcon_notifier - receive the state of charger cable
1260  *                      when registered cable is attached or detached.
1261  *
1262  * @self: the notifier block of the charger_extcon_notifier.
1263  * @event: the cable state.
1264  * @ptr: the data pointer of notifier block.
1265  */
1266 static int charger_extcon_notifier(struct notifier_block *self,
1267                         unsigned long event, void *ptr)
1268 {
1269         struct charger_cable *cable =
1270                 container_of(self, struct charger_cable, nb);
1271
1272         /*
1273          * The newly state of charger cable.
1274          * If cable is attached, cable->attached is true.
1275          */
1276         cable->attached = event;
1277
1278         /*
1279          * Setup monitoring to check battery state
1280          * when charger cable is attached.
1281          */
1282         if (cable->attached && is_polling_required(cable->cm)) {
1283                 cancel_work_sync(&setup_polling);
1284                 schedule_work(&setup_polling);
1285         }
1286
1287         /*
1288          * Setup work for controlling charger(regulator)
1289          * according to charger cable.
1290          */
1291         schedule_work(&cable->wq);
1292
1293         return NOTIFY_DONE;
1294 }
1295
1296 /**
1297  * charger_extcon_init - register external connector to use it
1298  *                      as the charger cable
1299  *
1300  * @cm: the Charger Manager representing the battery.
1301  * @cable: the Charger cable representing the external connector.
1302  */
1303 static int charger_extcon_init(struct charger_manager *cm,
1304                 struct charger_cable *cable)
1305 {
1306         int ret = 0;
1307
1308         /*
1309          * Charger manager use Extcon framework to identify
1310          * the charger cable among various external connector
1311          * cable (e.g., TA, USB, MHL, Dock).
1312          */
1313         INIT_WORK(&cable->wq, charger_extcon_work);
1314         cable->nb.notifier_call = charger_extcon_notifier;
1315         ret = extcon_register_interest(&cable->extcon_dev,
1316                         cable->extcon_name, cable->name, &cable->nb);
1317         if (ret < 0) {
1318                 pr_info("Cannot register extcon_dev for %s(cable: %s)\n",
1319                         cable->extcon_name, cable->name);
1320                 ret = -EINVAL;
1321         }
1322
1323         return ret;
1324 }
1325
1326 /**
1327  * charger_manager_register_extcon - Register extcon device to recevie state
1328  *                                   of charger cable.
1329  * @cm: the Charger Manager representing the battery.
1330  *
1331  * This function support EXTCON(External Connector) subsystem to detect the
1332  * state of charger cables for enabling or disabling charger(regulator) and
1333  * select the charger cable for charging among a number of external cable
1334  * according to policy of H/W board.
1335  */
1336 static int charger_manager_register_extcon(struct charger_manager *cm)
1337 {
1338         struct charger_desc *desc = cm->desc;
1339         struct charger_regulator *charger;
1340         int ret = 0;
1341         int i;
1342         int j;
1343
1344         for (i = 0; i < desc->num_charger_regulators; i++) {
1345                 charger = &desc->charger_regulators[i];
1346
1347                 charger->consumer = regulator_get(cm->dev,
1348                                         charger->regulator_name);
1349                 if (IS_ERR(charger->consumer)) {
1350                         dev_err(cm->dev, "Cannot find charger(%s)\n",
1351                                 charger->regulator_name);
1352                         return PTR_ERR(charger->consumer);
1353                 }
1354                 charger->cm = cm;
1355
1356                 for (j = 0; j < charger->num_cables; j++) {
1357                         struct charger_cable *cable = &charger->cables[j];
1358
1359                         ret = charger_extcon_init(cm, cable);
1360                         if (ret < 0) {
1361                                 dev_err(cm->dev, "Cannot initialize charger(%s)\n",
1362                                         charger->regulator_name);
1363                                 goto err;
1364                         }
1365                         cable->charger = charger;
1366                         cable->cm = cm;
1367                 }
1368         }
1369
1370 err:
1371         return ret;
1372 }
1373
1374 /* help function of sysfs node to control charger(regulator) */
1375 static ssize_t charger_name_show(struct device *dev,
1376                                 struct device_attribute *attr, char *buf)
1377 {
1378         struct charger_regulator *charger
1379                 = container_of(attr, struct charger_regulator, attr_name);
1380
1381         return sprintf(buf, "%s\n", charger->regulator_name);
1382 }
1383
1384 static ssize_t charger_state_show(struct device *dev,
1385                                 struct device_attribute *attr, char *buf)
1386 {
1387         struct charger_regulator *charger
1388                 = container_of(attr, struct charger_regulator, attr_state);
1389         int state = 0;
1390
1391         if (!charger->externally_control)
1392                 state = regulator_is_enabled(charger->consumer);
1393
1394         return sprintf(buf, "%s\n", state ? "enabled" : "disabled");
1395 }
1396
1397 static ssize_t charger_externally_control_show(struct device *dev,
1398                                 struct device_attribute *attr, char *buf)
1399 {
1400         struct charger_regulator *charger = container_of(attr,
1401                         struct charger_regulator, attr_externally_control);
1402
1403         return sprintf(buf, "%d\n", charger->externally_control);
1404 }
1405
1406 static ssize_t charger_externally_control_store(struct device *dev,
1407                                 struct device_attribute *attr, const char *buf,
1408                                 size_t count)
1409 {
1410         struct charger_regulator *charger
1411                 = container_of(attr, struct charger_regulator,
1412                                         attr_externally_control);
1413         struct charger_manager *cm = charger->cm;
1414         struct charger_desc *desc = cm->desc;
1415         int i;
1416         int ret;
1417         int externally_control;
1418         int chargers_externally_control = 1;
1419
1420         ret = sscanf(buf, "%d", &externally_control);
1421         if (ret == 0) {
1422                 ret = -EINVAL;
1423                 return ret;
1424         }
1425
1426         if (!externally_control) {
1427                 charger->externally_control = 0;
1428                 return count;
1429         }
1430
1431         for (i = 0; i < desc->num_charger_regulators; i++) {
1432                 if (&desc->charger_regulators[i] != charger &&
1433                         !desc->charger_regulators[i].externally_control) {
1434                         /*
1435                          * At least, one charger is controlled by
1436                          * charger-manager
1437                          */
1438                         chargers_externally_control = 0;
1439                         break;
1440                 }
1441         }
1442
1443         if (!chargers_externally_control) {
1444                 if (cm->charger_enabled) {
1445                         try_charger_enable(charger->cm, false);
1446                         charger->externally_control = externally_control;
1447                         try_charger_enable(charger->cm, true);
1448                 } else {
1449                         charger->externally_control = externally_control;
1450                 }
1451         } else {
1452                 dev_warn(cm->dev,
1453                          "'%s' regulator should be controlled in charger-manager because charger-manager must need at least one charger for charging\n",
1454                          charger->regulator_name);
1455         }
1456
1457         return count;
1458 }
1459
1460 /**
1461  * charger_manager_register_sysfs - Register sysfs entry for each charger
1462  * @cm: the Charger Manager representing the battery.
1463  *
1464  * This function add sysfs entry for charger(regulator) to control charger from
1465  * user-space. If some development board use one more chargers for charging
1466  * but only need one charger on specific case which is dependent on user
1467  * scenario or hardware restrictions, the user enter 1 or 0(zero) to '/sys/
1468  * class/power_supply/battery/charger.[index]/externally_control'. For example,
1469  * if user enter 1 to 'sys/class/power_supply/battery/charger.[index]/
1470  * externally_control, this charger isn't controlled from charger-manager and
1471  * always stay off state of regulator.
1472  */
1473 static int charger_manager_register_sysfs(struct charger_manager *cm)
1474 {
1475         struct charger_desc *desc = cm->desc;
1476         struct charger_regulator *charger;
1477         int chargers_externally_control = 1;
1478         char buf[11];
1479         char *str;
1480         int ret = 0;
1481         int i;
1482
1483         /* Create sysfs entry to control charger(regulator) */
1484         for (i = 0; i < desc->num_charger_regulators; i++) {
1485                 charger = &desc->charger_regulators[i];
1486
1487                 snprintf(buf, 10, "charger.%d", i);
1488                 str = devm_kzalloc(cm->dev,
1489                                 sizeof(char) * (strlen(buf) + 1), GFP_KERNEL);
1490                 if (!str) {
1491                         ret = -ENOMEM;
1492                         goto err;
1493                 }
1494                 strcpy(str, buf);
1495
1496                 charger->attrs[0] = &charger->attr_name.attr;
1497                 charger->attrs[1] = &charger->attr_state.attr;
1498                 charger->attrs[2] = &charger->attr_externally_control.attr;
1499                 charger->attrs[3] = NULL;
1500                 charger->attr_g.name = str;
1501                 charger->attr_g.attrs = charger->attrs;
1502
1503                 sysfs_attr_init(&charger->attr_name.attr);
1504                 charger->attr_name.attr.name = "name";
1505                 charger->attr_name.attr.mode = 0444;
1506                 charger->attr_name.show = charger_name_show;
1507
1508                 sysfs_attr_init(&charger->attr_state.attr);
1509                 charger->attr_state.attr.name = "state";
1510                 charger->attr_state.attr.mode = 0444;
1511                 charger->attr_state.show = charger_state_show;
1512
1513                 sysfs_attr_init(&charger->attr_externally_control.attr);
1514                 charger->attr_externally_control.attr.name
1515                                 = "externally_control";
1516                 charger->attr_externally_control.attr.mode = 0644;
1517                 charger->attr_externally_control.show
1518                                 = charger_externally_control_show;
1519                 charger->attr_externally_control.store
1520                                 = charger_externally_control_store;
1521
1522                 if (!desc->charger_regulators[i].externally_control ||
1523                                 !chargers_externally_control)
1524                         chargers_externally_control = 0;
1525
1526                 dev_info(cm->dev, "'%s' regulator's externally_control is %d\n",
1527                          charger->regulator_name, charger->externally_control);
1528
1529                 ret = sysfs_create_group(&cm->charger_psy.dev->kobj,
1530                                         &charger->attr_g);
1531                 if (ret < 0) {
1532                         dev_err(cm->dev, "Cannot create sysfs entry of %s regulator\n",
1533                                 charger->regulator_name);
1534                         ret = -EINVAL;
1535                         goto err;
1536                 }
1537         }
1538
1539         if (chargers_externally_control) {
1540                 dev_err(cm->dev, "Cannot register regulator because charger-manager must need at least one charger for charging battery\n");
1541                 ret = -EINVAL;
1542                 goto err;
1543         }
1544
1545 err:
1546         return ret;
1547 }
1548
1549 static int cm_init_thermal_data(struct charger_manager *cm,
1550                 struct power_supply *fuel_gauge)
1551 {
1552         struct charger_desc *desc = cm->desc;
1553         union power_supply_propval val;
1554         int ret;
1555
1556         /* Verify whether fuel gauge provides battery temperature */
1557         ret = fuel_gauge->get_property(fuel_gauge,
1558                                         POWER_SUPPLY_PROP_TEMP, &val);
1559
1560         if (!ret) {
1561                 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1562                                 POWER_SUPPLY_PROP_TEMP;
1563                 cm->charger_psy.num_properties++;
1564                 cm->desc->measure_battery_temp = true;
1565         }
1566 #ifdef CONFIG_THERMAL
1567         if (ret && desc->thermal_zone) {
1568                 cm->tzd_batt =
1569                         thermal_zone_get_zone_by_name(desc->thermal_zone);
1570                 if (IS_ERR(cm->tzd_batt))
1571                         return PTR_ERR(cm->tzd_batt);
1572
1573                 /* Use external thermometer */
1574                 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1575                                 POWER_SUPPLY_PROP_TEMP_AMBIENT;
1576                 cm->charger_psy.num_properties++;
1577                 cm->desc->measure_battery_temp = true;
1578                 ret = 0;
1579         }
1580 #endif
1581         if (cm->desc->measure_battery_temp) {
1582                 /* NOTICE : Default allowable minimum charge temperature is 0 */
1583                 if (!desc->temp_max)
1584                         desc->temp_max = CM_DEFAULT_CHARGE_TEMP_MAX;
1585                 if (!desc->temp_diff)
1586                         desc->temp_diff = CM_DEFAULT_RECHARGE_TEMP_DIFF;
1587         }
1588
1589         return ret;
1590 }
1591
1592 static struct of_device_id charger_manager_match[] = {
1593         {
1594                 .compatible = "charger-manager",
1595         },
1596         {},
1597 };
1598
1599 static struct charger_desc *of_cm_parse_desc(struct device *dev)
1600 {
1601         struct charger_desc *desc;
1602         struct device_node *np = dev->of_node;
1603         u32 poll_mode = CM_POLL_DISABLE;
1604         u32 battery_stat = CM_NO_BATTERY;
1605         int num_chgs = 0;
1606
1607         desc = devm_kzalloc(dev, sizeof(*desc), GFP_KERNEL);
1608         if (!desc)
1609                 return ERR_PTR(-ENOMEM);
1610
1611         of_property_read_string(np, "cm-name", &desc->psy_name);
1612
1613         of_property_read_u32(np, "cm-poll-mode", &poll_mode);
1614         desc->polling_mode = poll_mode;
1615
1616         of_property_read_u32(np, "cm-poll-interval",
1617                                 &desc->polling_interval_ms);
1618
1619         of_property_read_u32(np, "cm-fullbatt-vchkdrop-ms",
1620                                         &desc->fullbatt_vchkdrop_ms);
1621         of_property_read_u32(np, "cm-fullbatt-vchkdrop-volt",
1622                                         &desc->fullbatt_vchkdrop_uV);
1623         of_property_read_u32(np, "cm-fullbatt-voltage", &desc->fullbatt_uV);
1624         of_property_read_u32(np, "cm-fullbatt-soc", &desc->fullbatt_soc);
1625         of_property_read_u32(np, "cm-fullbatt-capacity",
1626                                         &desc->fullbatt_full_capacity);
1627
1628         of_property_read_u32(np, "cm-battery-stat", &battery_stat);
1629         desc->battery_present = battery_stat;
1630
1631         /* chargers */
1632         of_property_read_u32(np, "cm-num-chargers", &num_chgs);
1633         if (num_chgs) {
1634                 /* Allocate empty bin at the tail of array */
1635                 desc->psy_charger_stat = devm_kzalloc(dev, sizeof(char *)
1636                                                 * (num_chgs + 1), GFP_KERNEL);
1637                 if (desc->psy_charger_stat) {
1638                         int i;
1639                         for (i = 0; i < num_chgs; i++)
1640                                 of_property_read_string_index(np, "cm-chargers",
1641                                                 i, &desc->psy_charger_stat[i]);
1642                 } else {
1643                         return ERR_PTR(-ENOMEM);
1644                 }
1645         }
1646
1647         of_property_read_string(np, "cm-fuel-gauge", &desc->psy_fuel_gauge);
1648
1649         of_property_read_string(np, "cm-thermal-zone", &desc->thermal_zone);
1650
1651         of_property_read_u32(np, "cm-battery-cold", &desc->temp_min);
1652         if (of_get_property(np, "cm-battery-cold-in-minus", NULL))
1653                 desc->temp_min *= -1;
1654         of_property_read_u32(np, "cm-battery-hot", &desc->temp_max);
1655         of_property_read_u32(np, "cm-battery-temp-diff", &desc->temp_diff);
1656
1657         of_property_read_u32(np, "cm-charging-max",
1658                                 &desc->charging_max_duration_ms);
1659         of_property_read_u32(np, "cm-discharging-max",
1660                                 &desc->discharging_max_duration_ms);
1661
1662         /* battery charger regualtors */
1663         desc->num_charger_regulators = of_get_child_count(np);
1664         if (desc->num_charger_regulators) {
1665                 struct charger_regulator *chg_regs;
1666                 struct device_node *child;
1667
1668                 chg_regs = devm_kzalloc(dev, sizeof(*chg_regs)
1669                                         * desc->num_charger_regulators,
1670                                         GFP_KERNEL);
1671                 if (!chg_regs)
1672                         return ERR_PTR(-ENOMEM);
1673
1674                 desc->charger_regulators = chg_regs;
1675
1676                 for_each_child_of_node(np, child) {
1677                         struct charger_cable *cables;
1678                         struct device_node *_child;
1679
1680                         of_property_read_string(child, "cm-regulator-name",
1681                                         &chg_regs->regulator_name);
1682
1683                         /* charger cables */
1684                         chg_regs->num_cables = of_get_child_count(child);
1685                         if (chg_regs->num_cables) {
1686                                 cables = devm_kzalloc(dev, sizeof(*cables)
1687                                                 * chg_regs->num_cables,
1688                                                 GFP_KERNEL);
1689                                 if (!cables)
1690                                         return ERR_PTR(-ENOMEM);
1691
1692                                 chg_regs->cables = cables;
1693
1694                                 for_each_child_of_node(child, _child) {
1695                                         of_property_read_string(_child,
1696                                         "cm-cable-name", &cables->name);
1697                                         of_property_read_string(_child,
1698                                         "cm-cable-extcon",
1699                                         &cables->extcon_name);
1700                                         of_property_read_u32(_child,
1701                                         "cm-cable-min",
1702                                         &cables->min_uA);
1703                                         of_property_read_u32(_child,
1704                                         "cm-cable-max",
1705                                         &cables->max_uA);
1706                                         cables++;
1707                                 }
1708                         }
1709                         chg_regs++;
1710                 }
1711         }
1712         return desc;
1713 }
1714
1715 static inline struct charger_desc *cm_get_drv_data(struct platform_device *pdev)
1716 {
1717         if (pdev->dev.of_node)
1718                 return of_cm_parse_desc(&pdev->dev);
1719         return dev_get_platdata(&pdev->dev);
1720 }
1721
1722 static int charger_manager_probe(struct platform_device *pdev)
1723 {
1724         struct charger_desc *desc = cm_get_drv_data(pdev);
1725         struct charger_manager *cm;
1726         int ret = 0, i = 0;
1727         int j = 0;
1728         union power_supply_propval val;
1729         struct power_supply *fuel_gauge;
1730
1731         if (g_desc && !rtc_dev && g_desc->rtc_name) {
1732                 rtc_dev = rtc_class_open(g_desc->rtc_name);
1733                 if (IS_ERR_OR_NULL(rtc_dev)) {
1734                         rtc_dev = NULL;
1735                         dev_err(&pdev->dev, "Cannot get RTC %s\n",
1736                                 g_desc->rtc_name);
1737                         return -ENODEV;
1738                 }
1739         }
1740
1741         if (IS_ERR(desc)) {
1742                 dev_err(&pdev->dev, "No platform data (desc) found\n");
1743                 return -ENODEV;
1744         }
1745
1746         cm = devm_kzalloc(&pdev->dev,
1747                         sizeof(struct charger_manager), GFP_KERNEL);
1748         if (!cm)
1749                 return -ENOMEM;
1750
1751         /* Basic Values. Unspecified are Null or 0 */
1752         cm->dev = &pdev->dev;
1753         cm->desc = desc;
1754
1755         /*
1756          * The following two do not need to be errors.
1757          * Users may intentionally ignore those two features.
1758          */
1759         if (desc->fullbatt_uV == 0) {
1760                 dev_info(&pdev->dev, "Ignoring full-battery voltage threshold as it is not supplied\n");
1761         }
1762         if (!desc->fullbatt_vchkdrop_ms || !desc->fullbatt_vchkdrop_uV) {
1763                 dev_info(&pdev->dev, "Disabling full-battery voltage drop checking mechanism as it is not supplied\n");
1764                 desc->fullbatt_vchkdrop_ms = 0;
1765                 desc->fullbatt_vchkdrop_uV = 0;
1766         }
1767         if (desc->fullbatt_soc == 0) {
1768                 dev_info(&pdev->dev, "Ignoring full-battery soc(state of charge) threshold as it is not supplied\n");
1769         }
1770         if (desc->fullbatt_full_capacity == 0) {
1771                 dev_info(&pdev->dev, "Ignoring full-battery full capacity threshold as it is not supplied\n");
1772         }
1773
1774         if (!desc->charger_regulators || desc->num_charger_regulators < 1) {
1775                 dev_err(&pdev->dev, "charger_regulators undefined\n");
1776                 return -EINVAL;
1777         }
1778
1779         if (!desc->psy_charger_stat || !desc->psy_charger_stat[0]) {
1780                 dev_err(&pdev->dev, "No power supply defined\n");
1781                 return -EINVAL;
1782         }
1783
1784         if (!desc->psy_fuel_gauge) {
1785                 dev_err(&pdev->dev, "No fuel gauge power supply defined\n");
1786                 return -EINVAL;
1787         }
1788
1789         /* Counting index only */
1790         while (desc->psy_charger_stat[i])
1791                 i++;
1792
1793         /* Check if charger's supplies are present at probe */
1794         for (i = 0; desc->psy_charger_stat[i]; i++) {
1795                 struct power_supply *psy;
1796
1797                 psy = power_supply_get_by_name(desc->psy_charger_stat[i]);
1798                 if (!psy) {
1799                         dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1800                                 desc->psy_charger_stat[i]);
1801                         return -ENODEV;
1802                 }
1803         }
1804
1805         fuel_gauge = power_supply_get_by_name(desc->psy_fuel_gauge);
1806         if (!fuel_gauge) {
1807                 dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1808                         desc->psy_fuel_gauge);
1809                 return -ENODEV;
1810         }
1811
1812         if (desc->polling_interval_ms == 0 ||
1813             msecs_to_jiffies(desc->polling_interval_ms) <= CM_JIFFIES_SMALL) {
1814                 dev_err(&pdev->dev, "polling_interval_ms is too small\n");
1815                 return -EINVAL;
1816         }
1817
1818         if (!desc->charging_max_duration_ms ||
1819                         !desc->discharging_max_duration_ms) {
1820                 dev_info(&pdev->dev, "Cannot limit charging duration checking mechanism to prevent overcharge/overheat and control discharging duration\n");
1821                 desc->charging_max_duration_ms = 0;
1822                 desc->discharging_max_duration_ms = 0;
1823         }
1824
1825         platform_set_drvdata(pdev, cm);
1826
1827         memcpy(&cm->charger_psy, &psy_default, sizeof(psy_default));
1828
1829         if (!desc->psy_name)
1830                 strncpy(cm->psy_name_buf, psy_default.name, PSY_NAME_MAX);
1831         else
1832                 strncpy(cm->psy_name_buf, desc->psy_name, PSY_NAME_MAX);
1833         cm->charger_psy.name = cm->psy_name_buf;
1834
1835         /* Allocate for psy properties because they may vary */
1836         cm->charger_psy.properties = devm_kzalloc(&pdev->dev,
1837                                 sizeof(enum power_supply_property)
1838                                 * (ARRAY_SIZE(default_charger_props) +
1839                                 NUM_CHARGER_PSY_OPTIONAL), GFP_KERNEL);
1840         if (!cm->charger_psy.properties)
1841                 return -ENOMEM;
1842
1843         memcpy(cm->charger_psy.properties, default_charger_props,
1844                 sizeof(enum power_supply_property) *
1845                 ARRAY_SIZE(default_charger_props));
1846         cm->charger_psy.num_properties = psy_default.num_properties;
1847
1848         /* Find which optional psy-properties are available */
1849         if (!fuel_gauge->get_property(fuel_gauge,
1850                                           POWER_SUPPLY_PROP_CHARGE_NOW, &val)) {
1851                 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1852                                 POWER_SUPPLY_PROP_CHARGE_NOW;
1853                 cm->charger_psy.num_properties++;
1854         }
1855         if (!fuel_gauge->get_property(fuel_gauge,
1856                                           POWER_SUPPLY_PROP_CURRENT_NOW,
1857                                           &val)) {
1858                 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1859                                 POWER_SUPPLY_PROP_CURRENT_NOW;
1860                 cm->charger_psy.num_properties++;
1861         }
1862
1863         ret = cm_init_thermal_data(cm, fuel_gauge);
1864         if (ret) {
1865                 dev_err(&pdev->dev, "Failed to initialize thermal data\n");
1866                 cm->desc->measure_battery_temp = false;
1867         }
1868
1869         INIT_DELAYED_WORK(&cm->fullbatt_vchk_work, fullbatt_vchk);
1870
1871         ret = power_supply_register(NULL, &cm->charger_psy);
1872         if (ret) {
1873                 dev_err(&pdev->dev, "Cannot register charger-manager with name \"%s\"\n",
1874                         cm->charger_psy.name);
1875                 return ret;
1876         }
1877
1878         /* Register extcon device for charger cable */
1879         ret = charger_manager_register_extcon(cm);
1880         if (ret < 0) {
1881                 dev_err(&pdev->dev, "Cannot initialize extcon device\n");
1882                 goto err_reg_extcon;
1883         }
1884
1885         /* Register sysfs entry for charger(regulator) */
1886         ret = charger_manager_register_sysfs(cm);
1887         if (ret < 0) {
1888                 dev_err(&pdev->dev,
1889                         "Cannot initialize sysfs entry of regulator\n");
1890                 goto err_reg_sysfs;
1891         }
1892
1893         /* Add to the list */
1894         mutex_lock(&cm_list_mtx);
1895         list_add(&cm->entry, &cm_list);
1896         mutex_unlock(&cm_list_mtx);
1897
1898         /*
1899          * Charger-manager is capable of waking up the systme from sleep
1900          * when event is happend through cm_notify_event()
1901          */
1902         device_init_wakeup(&pdev->dev, true);
1903         device_set_wakeup_capable(&pdev->dev, false);
1904
1905         /*
1906          * Charger-manager have to check the charging state right after
1907          * tialization of charger-manager and then update current charging
1908          * state.
1909          */
1910         cm_monitor();
1911
1912         schedule_work(&setup_polling);
1913
1914         return 0;
1915
1916 err_reg_sysfs:
1917         for (i = 0; i < desc->num_charger_regulators; i++) {
1918                 struct charger_regulator *charger;
1919
1920                 charger = &desc->charger_regulators[i];
1921                 sysfs_remove_group(&cm->charger_psy.dev->kobj,
1922                                 &charger->attr_g);
1923         }
1924 err_reg_extcon:
1925         for (i = 0; i < desc->num_charger_regulators; i++) {
1926                 struct charger_regulator *charger;
1927
1928                 charger = &desc->charger_regulators[i];
1929                 for (j = 0; j < charger->num_cables; j++) {
1930                         struct charger_cable *cable = &charger->cables[j];
1931                         /* Remove notifier block if only edev exists */
1932                         if (cable->extcon_dev.edev)
1933                                 extcon_unregister_interest(&cable->extcon_dev);
1934                 }
1935
1936                 regulator_put(desc->charger_regulators[i].consumer);
1937         }
1938
1939         power_supply_unregister(&cm->charger_psy);
1940
1941         return ret;
1942 }
1943
1944 static int charger_manager_remove(struct platform_device *pdev)
1945 {
1946         struct charger_manager *cm = platform_get_drvdata(pdev);
1947         struct charger_desc *desc = cm->desc;
1948         int i = 0;
1949         int j = 0;
1950
1951         /* Remove from the list */
1952         mutex_lock(&cm_list_mtx);
1953         list_del(&cm->entry);
1954         mutex_unlock(&cm_list_mtx);
1955
1956         cancel_work_sync(&setup_polling);
1957         cancel_delayed_work_sync(&cm_monitor_work);
1958
1959         for (i = 0 ; i < desc->num_charger_regulators ; i++) {
1960                 struct charger_regulator *charger
1961                                 = &desc->charger_regulators[i];
1962                 for (j = 0 ; j < charger->num_cables ; j++) {
1963                         struct charger_cable *cable = &charger->cables[j];
1964                         extcon_unregister_interest(&cable->extcon_dev);
1965                 }
1966         }
1967
1968         for (i = 0 ; i < desc->num_charger_regulators ; i++)
1969                 regulator_put(desc->charger_regulators[i].consumer);
1970
1971         power_supply_unregister(&cm->charger_psy);
1972
1973         try_charger_enable(cm, false);
1974
1975         return 0;
1976 }
1977
1978 static const struct platform_device_id charger_manager_id[] = {
1979         { "charger-manager", 0 },
1980         { },
1981 };
1982 MODULE_DEVICE_TABLE(platform, charger_manager_id);
1983
1984 static int cm_suspend_noirq(struct device *dev)
1985 {
1986         int ret = 0;
1987
1988         if (device_may_wakeup(dev)) {
1989                 device_set_wakeup_capable(dev, false);
1990                 ret = -EAGAIN;
1991         }
1992
1993         return ret;
1994 }
1995
1996 static int cm_suspend_prepare(struct device *dev)
1997 {
1998         struct charger_manager *cm = dev_get_drvdata(dev);
1999
2000         if (!cm_suspended) {
2001                 if (rtc_dev) {
2002                         struct rtc_time tmp;
2003                         unsigned long now;
2004
2005                         rtc_read_alarm(rtc_dev, &rtc_wkalarm_save);
2006                         rtc_read_time(rtc_dev, &tmp);
2007
2008                         if (rtc_wkalarm_save.enabled) {
2009                                 rtc_tm_to_time(&rtc_wkalarm_save.time,
2010                                                &rtc_wkalarm_save_time);
2011                                 rtc_tm_to_time(&tmp, &now);
2012                                 if (now > rtc_wkalarm_save_time)
2013                                         rtc_wkalarm_save_time = 0;
2014                         } else {
2015                                 rtc_wkalarm_save_time = 0;
2016                         }
2017                 }
2018                 cm_suspended = true;
2019         }
2020
2021         cancel_delayed_work(&cm->fullbatt_vchk_work);
2022         cm->status_save_ext_pwr_inserted = is_ext_pwr_online(cm);
2023         cm->status_save_batt = is_batt_present(cm);
2024
2025         if (!cm_rtc_set) {
2026                 cm_suspend_duration_ms = 0;
2027                 cm_rtc_set = cm_setup_timer();
2028         }
2029
2030         return 0;
2031 }
2032
2033 static void cm_suspend_complete(struct device *dev)
2034 {
2035         struct charger_manager *cm = dev_get_drvdata(dev);
2036
2037         if (cm_suspended) {
2038                 if (rtc_dev) {
2039                         struct rtc_wkalrm tmp;
2040
2041                         rtc_read_alarm(rtc_dev, &tmp);
2042                         rtc_wkalarm_save.pending = tmp.pending;
2043                         rtc_set_alarm(rtc_dev, &rtc_wkalarm_save);
2044                 }
2045                 cm_suspended = false;
2046                 cm_rtc_set = false;
2047         }
2048
2049         /* Re-enqueue delayed work (fullbatt_vchk_work) */
2050         if (cm->fullbatt_vchk_jiffies_at) {
2051                 unsigned long delay = 0;
2052                 unsigned long now = jiffies + CM_JIFFIES_SMALL;
2053
2054                 if (time_after_eq(now, cm->fullbatt_vchk_jiffies_at)) {
2055                         delay = (unsigned long)((long)now
2056                                 - (long)(cm->fullbatt_vchk_jiffies_at));
2057                         delay = jiffies_to_msecs(delay);
2058                 } else {
2059                         delay = 0;
2060                 }
2061
2062                 /*
2063                  * Account for cm_suspend_duration_ms if
2064                  * assume_timer_stops_in_suspend is active
2065                  */
2066                 if (g_desc && g_desc->assume_timer_stops_in_suspend) {
2067                         if (delay > cm_suspend_duration_ms)
2068                                 delay -= cm_suspend_duration_ms;
2069                         else
2070                                 delay = 0;
2071                 }
2072
2073                 queue_delayed_work(cm_wq, &cm->fullbatt_vchk_work,
2074                                    msecs_to_jiffies(delay));
2075         }
2076         device_set_wakeup_capable(cm->dev, false);
2077         uevent_notify(cm, NULL);
2078 }
2079
2080 static const struct dev_pm_ops charger_manager_pm = {
2081         .prepare        = cm_suspend_prepare,
2082         .suspend_noirq  = cm_suspend_noirq,
2083         .complete       = cm_suspend_complete,
2084 };
2085
2086 static struct platform_driver charger_manager_driver = {
2087         .driver = {
2088                 .name = "charger-manager",
2089                 .owner = THIS_MODULE,
2090                 .pm = &charger_manager_pm,
2091                 .of_match_table = charger_manager_match,
2092         },
2093         .probe = charger_manager_probe,
2094         .remove = charger_manager_remove,
2095         .id_table = charger_manager_id,
2096 };
2097
2098 static int __init charger_manager_init(void)
2099 {
2100         cm_wq = create_freezable_workqueue("charger_manager");
2101         INIT_DELAYED_WORK(&cm_monitor_work, cm_monitor_poller);
2102
2103         return platform_driver_register(&charger_manager_driver);
2104 }
2105 late_initcall(charger_manager_init);
2106
2107 static void __exit charger_manager_cleanup(void)
2108 {
2109         destroy_workqueue(cm_wq);
2110         cm_wq = NULL;
2111
2112         platform_driver_unregister(&charger_manager_driver);
2113 }
2114 module_exit(charger_manager_cleanup);
2115
2116 /**
2117  * find_power_supply - find the associated power_supply of charger
2118  * @cm: the Charger Manager representing the battery
2119  * @psy: pointer to instance of charger's power_supply
2120  */
2121 static bool find_power_supply(struct charger_manager *cm,
2122                         struct power_supply *psy)
2123 {
2124         int i;
2125         bool found = false;
2126
2127         for (i = 0; cm->desc->psy_charger_stat[i]; i++) {
2128                 if (!strcmp(psy->name, cm->desc->psy_charger_stat[i])) {
2129                         found = true;
2130                         break;
2131                 }
2132         }
2133
2134         return found;
2135 }
2136
2137 /**
2138  * cm_notify_event - charger driver notify Charger Manager of charger event
2139  * @psy: pointer to instance of charger's power_supply
2140  * @type: type of charger event
2141  * @msg: optional message passed to uevent_notify fuction
2142  */
2143 void cm_notify_event(struct power_supply *psy, enum cm_event_types type,
2144                      char *msg)
2145 {
2146         struct charger_manager *cm;
2147         bool found_power_supply = false;
2148
2149         if (psy == NULL)
2150                 return;
2151
2152         mutex_lock(&cm_list_mtx);
2153         list_for_each_entry(cm, &cm_list, entry) {
2154                 found_power_supply = find_power_supply(cm, psy);
2155                 if (found_power_supply)
2156                         break;
2157         }
2158         mutex_unlock(&cm_list_mtx);
2159
2160         if (!found_power_supply)
2161                 return;
2162
2163         switch (type) {
2164         case CM_EVENT_BATT_FULL:
2165                 fullbatt_handler(cm);
2166                 break;
2167         case CM_EVENT_BATT_OUT:
2168                 battout_handler(cm);
2169                 break;
2170         case CM_EVENT_BATT_IN:
2171         case CM_EVENT_EXT_PWR_IN_OUT ... CM_EVENT_CHG_START_STOP:
2172                 misc_event_handler(cm, type);
2173                 break;
2174         case CM_EVENT_UNKNOWN:
2175         case CM_EVENT_OTHERS:
2176                 uevent_notify(cm, msg ? msg : default_event_names[type]);
2177                 break;
2178         default:
2179                 dev_err(cm->dev, "%s: type not specified\n", __func__);
2180                 break;
2181         }
2182 }
2183 EXPORT_SYMBOL_GPL(cm_notify_event);
2184
2185 MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
2186 MODULE_DESCRIPTION("Charger Manager");
2187 MODULE_LICENSE("GPL");