usb: phy: rcar-gen2-usb: always use 'dev' variable in probe() method
[platform/adaptation/renesas_rcar/renesas_kernel.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         bool present = false;
101         int i, ret;
102
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;
123                         }
124                 }
125                 break;
126         }
127
128         return present;
129 }
130
131 /**
132  * is_ext_pwr_online - See if an external power source is attached to charge
133  * @cm: the Charger Manager representing the battery.
134  *
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.
138  */
139 static bool is_ext_pwr_online(struct charger_manager *cm)
140 {
141         union power_supply_propval val;
142         bool online = false;
143         int i, ret;
144
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;
153                 }
154         }
155
156         return online;
157 }
158
159 /**
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.
163  *
164  * Returns 0 if there is no error.
165  * Returns a negative value on error.
166  */
167 static int get_batt_uV(struct charger_manager *cm, int *uV)
168 {
169         union power_supply_propval val;
170         int ret;
171
172         if (!cm->fuel_gauge)
173                 return -ENODEV;
174
175         ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
176                                 POWER_SUPPLY_PROP_VOLTAGE_NOW, &val);
177         if (ret)
178                 return ret;
179
180         *uV = val.intval;
181         return 0;
182 }
183
184 /**
185  * is_charging - Returns true if the battery is being charged.
186  * @cm: the Charger Manager representing the battery.
187  */
188 static bool is_charging(struct charger_manager *cm)
189 {
190         int i, ret;
191         bool charging = false;
192         union power_supply_propval val;
193
194         /* If there is no battery, it cannot be charged */
195         if (!is_batt_present(cm))
196                 return false;
197
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;
205
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;
214                 }
215                 if (val.intval == 0)
216                         continue;
217
218                 /*
219                  * 3. The charger should not be FULL, DISCHARGING,
220                  * or NOT_CHARGING.
221                  */
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;
229                 }
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;
234
235                 /* Then, this is charging. */
236                 charging = true;
237                 break;
238         }
239
240         return charging;
241 }
242
243 /**
244  * is_full_charged - Returns true if the battery is fully charged.
245  * @cm: the Charger Manager representing the battery.
246  */
247 static bool is_full_charged(struct charger_manager *cm)
248 {
249         struct charger_desc *desc = cm->desc;
250         union power_supply_propval val;
251         int ret = 0;
252         int uV;
253
254         /* If there is no battery, it cannot be charged */
255         if (!is_batt_present(cm))
256                 return false;
257
258         if (cm->fuel_gauge && desc->fullbatt_full_capacity > 0) {
259                 val.intval = 0;
260
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;
266         }
267
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;
273         }
274
275         /* Full, if the capacity is more than fullbatt_soc */
276         if (cm->fuel_gauge && desc->fullbatt_soc > 0) {
277                 val.intval = 0;
278
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;
283         }
284
285         return false;
286 }
287
288 /**
289  * is_polling_required - Return true if need to continue polling for this CM.
290  * @cm: the Charger Manager representing the battery.
291  */
292 static bool is_polling_required(struct charger_manager *cm)
293 {
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);
306         }
307
308         return false;
309 }
310
311 /**
312  * try_charger_enable - Enable/Disable chargers altogether
313  * @cm: the Charger Manager representing the battery.
314  * @enable: true: enable / false: disable
315  *
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.
320  */
321 static int try_charger_enable(struct charger_manager *cm, bool enable)
322 {
323         int err = 0, i;
324         struct charger_desc *desc = cm->desc;
325
326         /* Ignore if it's redundent command */
327         if (enable == cm->charger_enabled)
328                 return 0;
329
330         if (enable) {
331                 if (cm->emergency_stop)
332                         return -EAGAIN;
333
334                 /*
335                  * Save start time of charging to limit
336                  * maximum possible charging time.
337                  */
338                 cm->charging_start_time = ktime_to_ms(ktime_get());
339                 cm->charging_end_time = 0;
340
341                 for (i = 0 ; i < desc->num_charger_regulators ; i++) {
342                         if (desc->charger_regulators[i].externally_control)
343                                 continue;
344
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);
349                         }
350                 }
351         } else {
352                 /*
353                  * Save end time of charging to maintain fully charged state
354                  * of battery after full-batt.
355                  */
356                 cm->charging_start_time = 0;
357                 cm->charging_end_time = ktime_to_ms(ktime_get());
358
359                 for (i = 0 ; i < desc->num_charger_regulators ; i++) {
360                         if (desc->charger_regulators[i].externally_control)
361                                 continue;
362
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);
367                         }
368                 }
369
370                 /*
371                  * Abnormal battery state - Stop charging forcibly,
372                  * even if charger was enabled at the other places
373                  */
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);
381                         }
382                 }
383         }
384
385         if (!err)
386                 cm->charger_enabled = enable;
387
388         return err;
389 }
390
391 /**
392  * try_charger_restart - Restart charging.
393  * @cm: the Charger Manager representing the battery.
394  *
395  * Restart charging by turning off and on the charger.
396  */
397 static int try_charger_restart(struct charger_manager *cm)
398 {
399         int err;
400
401         if (cm->emergency_stop)
402                 return -EAGAIN;
403
404         err = try_charger_enable(cm, false);
405         if (err)
406                 return err;
407
408         return try_charger_enable(cm, true);
409 }
410
411 /**
412  * uevent_notify - Let users know something has changed.
413  * @cm: the Charger Manager representing the battery.
414  * @event: the event string.
415  *
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.
422  */
423 static void uevent_notify(struct charger_manager *cm, const char *event)
424 {
425         static char env_str[UEVENT_BUF_SIZE + 1] = "";
426         static char env_str_save[UEVENT_BUF_SIZE + 1] = "";
427
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;
435                 }
436
437                 if (!strncmp(env_str_save, event, UEVENT_BUF_SIZE))
438                         return; /* Duplicated. */
439                 strncpy(env_str_save, event, UEVENT_BUF_SIZE);
440                 return;
441         }
442
443         if (event == NULL) {
444                 /* No messages pending */
445                 if (!env_str_save[0])
446                         return;
447
448                 strncpy(env_str, env_str_save, UEVENT_BUF_SIZE);
449                 kobject_uevent(&cm->dev->kobj, KOBJ_CHANGE);
450                 env_str_save[0] = 0;
451
452                 return;
453         }
454
455         /* status not changed */
456         if (!strncmp(env_str, event, UEVENT_BUF_SIZE))
457                 return;
458
459         /* save the status and notify the update */
460         strncpy(env_str, event, UEVENT_BUF_SIZE);
461         kobject_uevent(&cm->dev->kobj, KOBJ_CHANGE);
462
463         dev_info(cm->dev, "%s\n", event);
464 }
465
466 /**
467  * fullbatt_vchk - Check voltage drop some times after "FULL" event.
468  * @work: the work_struct appointing the function
469  *
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.
474  */
475 static void fullbatt_vchk(struct work_struct *work)
476 {
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;
482
483         /* remove the appointment for fullbatt_vchk */
484         cm->fullbatt_vchk_jiffies_at = 0;
485
486         if (!desc->fullbatt_vchkdrop_uV || !desc->fullbatt_vchkdrop_ms)
487                 return;
488
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;
493         }
494
495         diff = desc->fullbatt_uV - batt_uV;
496         if (diff < 0)
497                 return;
498
499         dev_info(cm->dev, "VBATT dropped %duV after full-batt\n", diff);
500
501         if (diff > desc->fullbatt_vchkdrop_uV) {
502                 try_charger_restart(cm);
503                 uevent_notify(cm, "Recharging");
504         }
505 }
506
507 /**
508  * check_charging_duration - Monitor charging/discharging duration
509  * @cm: the Charger Manager representing the battery.
510  *
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.
516  */
517 static int check_charging_duration(struct charger_manager *cm)
518 {
519         struct charger_desc *desc = cm->desc;
520         u64 curr = ktime_to_ms(ktime_get());
521         u64 duration;
522         int ret = false;
523
524         if (!desc->charging_max_duration_ms &&
525                         !desc->discharging_max_duration_ms)
526                 return ret;
527
528         if (cm->charger_enabled) {
529                 duration = curr - cm->charging_start_time;
530
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;
537                 }
538         } else if (is_ext_pwr_online(cm) && !cm->charger_enabled) {
539                 duration = curr - cm->charging_end_time;
540
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;
548                 }
549         }
550
551         return ret;
552 }
553
554 static int cm_get_battery_temperature(struct charger_manager *cm,
555                                         int *temp)
556 {
557         int ret;
558
559         if (!cm->desc->measure_battery_temp)
560                 return -ENODEV;
561
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;
573 }
574
575 static int cm_check_thermal_status(struct charger_manager *cm)
576 {
577         struct charger_desc *desc = cm->desc;
578         int temp, upper_limit, lower_limit;
579         int ret = 0;
580
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.
587                  */
588                 dev_err(cm->dev, "Failed to get battery temperature\n");
589                 return 0;
590         }
591
592         upper_limit = desc->temp_max;
593         lower_limit = desc->temp_min;
594
595         if (cm->emergency_stop) {
596                 upper_limit -= desc->temp_diff;
597                 lower_limit += desc->temp_diff;
598         }
599
600         if (temp > upper_limit)
601                 ret = CM_EVENT_BATT_OVERHEAT;
602         else if (temp < lower_limit)
603                 ret = CM_EVENT_BATT_COLD;
604
605         return ret;
606 }
607
608 /**
609  * _cm_monitor - Monitor the temperature and return true for exceptions.
610  * @cm: the Charger Manager representing the battery.
611  *
612  * Returns true if there is an event to notify for the battery.
613  * (True if the status of "emergency_stop" changes)
614  */
615 static bool _cm_monitor(struct charger_manager *cm)
616 {
617         int temp_alrt;
618
619         temp_alrt = cm_check_thermal_status(cm);
620
621         /* It has been stopped already */
622         if (temp_alrt && cm->emergency_stop)
623                 return false;
624
625         /*
626          * Check temperature whether overheat or cold.
627          * If temperature is out of range normal state, stop charging.
628          */
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]);
633
634         /*
635          * Check whole charging duration and discharing duration
636          * after full-batt.
637          */
638         } else if (!cm->emergency_stop && check_charging_duration(cm)) {
639                 dev_dbg(cm->dev,
640                         "Charging/Discharging duration is out of range\n");
641         /*
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.
645          */
646         } else if (!cm->emergency_stop && is_ext_pwr_online(cm) &&
647                         !cm->charger_enabled) {
648                 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
649
650         /*
651          * Check whether fully charged state to protect overcharge
652          * if charger-manager is charging for battery.
653          */
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]);
658
659                 try_charger_enable(cm, false);
660
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");
667                 }
668         }
669
670         return true;
671 }
672
673 /**
674  * cm_monitor - Monitor every battery.
675  *
676  * Returns true if there is an event to notify from any of the batteries.
677  * (True if the status of "emergency_stop" changes)
678  */
679 static bool cm_monitor(void)
680 {
681         bool stop = false;
682         struct charger_manager *cm;
683
684         mutex_lock(&cm_list_mtx);
685
686         list_for_each_entry(cm, &cm_list, entry) {
687                 if (_cm_monitor(cm))
688                         stop = true;
689         }
690
691         mutex_unlock(&cm_list_mtx);
692
693         return stop;
694 }
695
696 /**
697  * _setup_polling - Setup the next instance of polling.
698  * @work: work_struct of the function _setup_polling.
699  */
700 static void _setup_polling(struct work_struct *work)
701 {
702         unsigned long min = ULONG_MAX;
703         struct charger_manager *cm;
704         bool keep_polling = false;
705         unsigned long _next_polling;
706
707         mutex_lock(&cm_list_mtx);
708
709         list_for_each_entry(cm, &cm_list, entry) {
710                 if (is_polling_required(cm) && cm->desc->polling_interval_ms) {
711                         keep_polling = true;
712
713                         if (min > cm->desc->polling_interval_ms)
714                                 min = cm->desc->polling_interval_ms;
715                 }
716         }
717
718         polling_jiffy = msecs_to_jiffies(min);
719         if (polling_jiffy <= CM_JIFFIES_SMALL)
720                 polling_jiffy = CM_JIFFIES_SMALL + 1;
721
722         if (!keep_polling)
723                 polling_jiffy = ULONG_MAX;
724         if (polling_jiffy == ULONG_MAX)
725                 goto out;
726
727         WARN(cm_wq == NULL, "charger-manager: workqueue not initialized"
728                             ". try it later. %s\n", __func__);
729
730         /*
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.
735          */
736         _next_polling = jiffies + polling_jiffy;
737
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;
744         }
745 out:
746         mutex_unlock(&cm_list_mtx);
747 }
748 static DECLARE_WORK(setup_polling, _setup_polling);
749
750 /**
751  * cm_monitor_poller - The Monitor / Poller.
752  * @work: work_struct of the function cm_monitor_poller
753  *
754  * During non-suspended state, cm_monitor_poller is used to poll and monitor
755  * the batteries.
756  */
757 static void cm_monitor_poller(struct work_struct *work)
758 {
759         cm_monitor();
760         schedule_work(&setup_polling);
761 }
762
763 /**
764  * fullbatt_handler - Event handler for CM_EVENT_BATT_FULL
765  * @cm: the Charger Manager representing the battery.
766  */
767 static void fullbatt_handler(struct charger_manager *cm)
768 {
769         struct charger_desc *desc = cm->desc;
770
771         if (!desc->fullbatt_vchkdrop_uV || !desc->fullbatt_vchkdrop_ms)
772                 goto out;
773
774         if (cm_suspended)
775                 device_set_wakeup_capable(cm->dev, true);
776
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);
781
782         if (cm->fullbatt_vchk_jiffies_at == 0)
783                 cm->fullbatt_vchk_jiffies_at = 1;
784
785 out:
786         dev_info(cm->dev, "EVENT_HANDLE: Battery Fully Charged\n");
787         uevent_notify(cm, default_event_names[CM_EVENT_BATT_FULL]);
788 }
789
790 /**
791  * battout_handler - Event handler for CM_EVENT_BATT_OUT
792  * @cm: the Charger Manager representing the battery.
793  */
794 static void battout_handler(struct charger_manager *cm)
795 {
796         if (cm_suspended)
797                 device_set_wakeup_capable(cm->dev, true);
798
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?");
804         }
805 }
806
807 /**
808  * misc_event_handler - Handler for other evnets
809  * @cm: the Charger Manager representing the battery.
810  * @type: the Charger Manager representing the battery.
811  */
812 static void misc_event_handler(struct charger_manager *cm,
813                         enum cm_event_types type)
814 {
815         if (cm_suspended)
816                 device_set_wakeup_capable(cm->dev, true);
817
818         if (is_polling_required(cm) && cm->desc->polling_interval_ms)
819                 schedule_work(&setup_polling);
820         uevent_notify(cm, default_event_names[type]);
821 }
822
823 static int charger_get_property(struct power_supply *psy,
824                 enum power_supply_property psp,
825                 union power_supply_propval *val)
826 {
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;
832
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;
870                 }
871
872                 if (!is_batt_present(cm)) {
873                         /* There is no battery. Assume 100% */
874                         val->intval = 100;
875                         break;
876                 }
877
878                 ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
879                                         POWER_SUPPLY_PROP_CAPACITY, val);
880                 if (ret)
881                         break;
882
883                 if (val->intval > 100) {
884                         val->intval = 100;
885                         break;
886                 }
887                 if (val->intval < 0)
888                         val->intval = 0;
889
890                 /* Do not adjust SOC when charging: voltage is overrated */
891                 if (is_charging(cm))
892                         break;
893
894                 /*
895                  * If the capacity value is inconsistent, calibrate it base on
896                  * the battery voltage values and the thresholds given as desc
897                  */
898                 ret = get_batt_uV(cm, &uV);
899                 if (ret) {
900                         /* Voltage information not available. No calibration */
901                         ret = 0;
902                         break;
903                 }
904
905                 if (desc->fullbatt_uV > 0 && uV >= desc->fullbatt_uV &&
906                     !is_charging(cm)) {
907                         val->intval = 100;
908                         break;
909                 }
910
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;
937                         }
938                 } else {
939                         val->intval = 0;
940                 }
941                 break;
942         default:
943                 return -EINVAL;
944         }
945         return ret;
946 }
947
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,
958         /*
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,
964          */
965 };
966
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,
973 };
974
975 /**
976  * cm_setup_timer - For in-suspend monitoring setup wakeup alarm
977  *                  for suspend_again.
978  *
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.
984  */
985 static bool cm_setup_timer(void)
986 {
987         struct charger_manager *cm;
988         unsigned int wakeup_ms = UINT_MAX;
989         bool ret = false;
990
991         mutex_lock(&cm_list_mtx);
992
993         list_for_each_entry(cm, &cm_list, entry) {
994                 unsigned int fbchk_ms = 0;
995
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;
1005                         }
1006                 }
1007                 CM_MIN_VALID(wakeup_ms, fbchk_ms);
1008
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);
1015         }
1016
1017         mutex_unlock(&cm_list_mtx);
1018
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);
1025
1026                         /*
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.
1031                          */
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;
1038
1039                         ret = true;
1040
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;
1048
1049                                 /* The timer is not appointed by CM */
1050                                 ret = false;
1051                         }
1052
1053                         pr_info("Waking up after %lu secs\n", time - now);
1054
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;
1059                 }
1060         }
1061
1062         if (rtc_dev)
1063                 rtc_set_alarm(rtc_dev, &rtc_wkalarm_save);
1064         return false;
1065 }
1066
1067 static void _cm_fbchk_in_suspend(struct charger_manager *cm)
1068 {
1069         unsigned long jiffy_now = jiffies;
1070
1071         if (!cm->fullbatt_vchk_jiffies_at)
1072                 return;
1073
1074         if (g_desc && g_desc->assume_timer_stops_in_suspend)
1075                 jiffy_now += msecs_to_jiffies(cm_suspend_duration_ms);
1076
1077         /* Execute now if it's going to be executed not too long after */
1078         jiffy_now += CM_JIFFIES_SMALL;
1079
1080         if (time_after_eq(jiffy_now, cm->fullbatt_vchk_jiffies_at))
1081                 fullbatt_vchk(&cm->fullbatt_vchk_work.work);
1082 }
1083
1084 /**
1085  * cm_suspend_again - Determine whether suspend again or not
1086  *
1087  * Returns true if the system should be suspended again
1088  * Returns false if the system should be woken up
1089  */
1090 bool cm_suspend_again(void)
1091 {
1092         struct charger_manager *cm;
1093         bool ret = false;
1094
1095         if (!g_desc || !g_desc->rtc_only_wakeup || !g_desc->rtc_only_wakeup() ||
1096             !cm_rtc_set)
1097                 return false;
1098
1099         if (cm_monitor())
1100                 goto out;
1101
1102         ret = true;
1103         mutex_lock(&cm_list_mtx);
1104         list_for_each_entry(cm, &cm_list, entry) {
1105                 _cm_fbchk_in_suspend(cm);
1106
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;
1111                 }
1112         }
1113         mutex_unlock(&cm_list_mtx);
1114
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;
1121
1122                 rtc_read_time(rtc_dev, &tmp);
1123                 rtc_tm_to_time(&tmp, &now);
1124
1125                 if (rtc_wkalarm_save_time &&
1126                     now + CM_RTC_SMALL >= rtc_wkalarm_save_time)
1127                         return false;
1128         }
1129         return ret;
1130 }
1131 EXPORT_SYMBOL_GPL(cm_suspend_again);
1132
1133 /**
1134  * setup_charger_manager - initialize charger_global_desc data
1135  * @gd: pointer to instance of charger_global_desc
1136  */
1137 int setup_charger_manager(struct charger_global_desc *gd)
1138 {
1139         if (!gd)
1140                 return -EINVAL;
1141
1142         if (rtc_dev)
1143                 rtc_class_close(rtc_dev);
1144         rtc_dev = NULL;
1145         g_desc = NULL;
1146
1147         if (!gd->rtc_only_wakeup) {
1148                 pr_err("The callback rtc_only_wakeup is not given\n");
1149                 return -EINVAL;
1150         }
1151
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 */
1157                 }
1158         } else {
1159                 pr_warn("No wakeup timer is given for charger manager.  "
1160                         "In-suspend monitoring won't work.\n");
1161         }
1162
1163         g_desc = gd;
1164         return 0;
1165 }
1166 EXPORT_SYMBOL_GPL(setup_charger_manager);
1167
1168 /**
1169  * charger_extcon_work - enable/diable charger according to the state
1170  *                      of charger cable
1171  *
1172  * @work: work_struct of the function charger_extcon_work.
1173  */
1174 static void charger_extcon_work(struct work_struct *work)
1175 {
1176         struct charger_cable *cable =
1177                         container_of(work, struct charger_cable, wq);
1178         int ret;
1179
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;
1187                 }
1188
1189                 pr_info("Set current limit of %s : %duA ~ %duA\n",
1190                         cable->charger->regulator_name,
1191                         cable->min_uA, cable->max_uA);
1192         }
1193
1194         try_charger_enable(cable->cm, cable->attached);
1195 }
1196
1197 /**
1198  * charger_extcon_notifier - receive the state of charger cable
1199  *                      when registered cable is attached or detached.
1200  *
1201  * @self: the notifier block of the charger_extcon_notifier.
1202  * @event: the cable state.
1203  * @ptr: the data pointer of notifier block.
1204  */
1205 static int charger_extcon_notifier(struct notifier_block *self,
1206                         unsigned long event, void *ptr)
1207 {
1208         struct charger_cable *cable =
1209                 container_of(self, struct charger_cable, nb);
1210
1211         /*
1212          * The newly state of charger cable.
1213          * If cable is attached, cable->attached is true.
1214          */
1215         cable->attached = event;
1216
1217         /*
1218          * Setup monitoring to check battery state
1219          * when charger cable is attached.
1220          */
1221         if (cable->attached && is_polling_required(cable->cm)) {
1222                 cancel_work_sync(&setup_polling);
1223                 schedule_work(&setup_polling);
1224         }
1225
1226         /*
1227          * Setup work for controlling charger(regulator)
1228          * according to charger cable.
1229          */
1230         schedule_work(&cable->wq);
1231
1232         return NOTIFY_DONE;
1233 }
1234
1235 /**
1236  * charger_extcon_init - register external connector to use it
1237  *                      as the charger cable
1238  *
1239  * @cm: the Charger Manager representing the battery.
1240  * @cable: the Charger cable representing the external connector.
1241  */
1242 static int charger_extcon_init(struct charger_manager *cm,
1243                 struct charger_cable *cable)
1244 {
1245         int ret = 0;
1246
1247         /*
1248          * Charger manager use Extcon framework to identify
1249          * the charger cable among various external connector
1250          * cable (e.g., TA, USB, MHL, Dock).
1251          */
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;
1260         }
1261
1262         return ret;
1263 }
1264
1265 /**
1266  * charger_manager_register_extcon - Register extcon device to recevie state
1267  *                                   of charger cable.
1268  * @cm: the Charger Manager representing the battery.
1269  *
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.
1274  */
1275 static int charger_manager_register_extcon(struct charger_manager *cm)
1276 {
1277         struct charger_desc *desc = cm->desc;
1278         struct charger_regulator *charger;
1279         int ret = 0;
1280         int i;
1281         int j;
1282
1283         for (i = 0; i < desc->num_charger_regulators; i++) {
1284                 charger = &desc->charger_regulators[i];
1285
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);
1292                 }
1293                 charger->cm = cm;
1294
1295                 for (j = 0; j < charger->num_cables; j++) {
1296                         struct charger_cable *cable = &charger->cables[j];
1297
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;
1303                         }
1304                         cable->charger = charger;
1305                         cable->cm = cm;
1306                 }
1307         }
1308
1309 err:
1310         return ret;
1311 }
1312
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)
1316 {
1317         struct charger_regulator *charger
1318                 = container_of(attr, struct charger_regulator, attr_name);
1319
1320         return sprintf(buf, "%s\n", charger->regulator_name);
1321 }
1322
1323 static ssize_t charger_state_show(struct device *dev,
1324                                 struct device_attribute *attr, char *buf)
1325 {
1326         struct charger_regulator *charger
1327                 = container_of(attr, struct charger_regulator, attr_state);
1328         int state = 0;
1329
1330         if (!charger->externally_control)
1331                 state = regulator_is_enabled(charger->consumer);
1332
1333         return sprintf(buf, "%s\n", state ? "enabled" : "disabled");
1334 }
1335
1336 static ssize_t charger_externally_control_show(struct device *dev,
1337                                 struct device_attribute *attr, char *buf)
1338 {
1339         struct charger_regulator *charger = container_of(attr,
1340                         struct charger_regulator, attr_externally_control);
1341
1342         return sprintf(buf, "%d\n", charger->externally_control);
1343 }
1344
1345 static ssize_t charger_externally_control_store(struct device *dev,
1346                                 struct device_attribute *attr, const char *buf,
1347                                 size_t count)
1348 {
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;
1358
1359         ret = sscanf(buf, "%d", &externally_control);
1360         if (ret == 0) {
1361                 ret = -EINVAL;
1362                 return ret;
1363         }
1364
1365         if (!externally_control) {
1366                 charger->externally_control = 0;
1367                 return count;
1368         }
1369
1370         for (i = 0; i < desc->num_charger_regulators; i++) {
1371                 if (&desc->charger_regulators[i] != charger &&
1372                         !desc->charger_regulators[i].externally_control) {
1373                         /*
1374                          * At least, one charger is controlled by
1375                          * charger-manager
1376                          */
1377                         chargers_externally_control = 0;
1378                         break;
1379                 }
1380         }
1381
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;
1389                 }
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);
1394         }
1395
1396         return count;
1397 }
1398
1399 /**
1400  * charger_manager_register_sysfs - Register sysfs entry for each charger
1401  * @cm: the Charger Manager representing the battery.
1402  *
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.
1411  */
1412 static int charger_manager_register_sysfs(struct charger_manager *cm)
1413 {
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;
1421
1422         /* Create sysfs entry to control charger(regulator) */
1423         for (i = 0; i < desc->num_charger_regulators; i++) {
1424                 charger = &desc->charger_regulators[i];
1425
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;
1432                 }
1433                 strcpy(str, buf);
1434
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;
1441
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;
1446
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;
1451
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;
1460
1461                 if (!desc->charger_regulators[i].externally_control ||
1462                                 !chargers_externally_control)
1463                         chargers_externally_control = 0;
1464
1465                 dev_info(cm->dev, "'%s' regulator's externally_control is %d\n",
1466                          charger->regulator_name, charger->externally_control);
1467
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;
1475                 }
1476         }
1477
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;
1482         }
1483
1484 err:
1485         return ret;
1486 }
1487
1488 static int cm_init_thermal_data(struct charger_manager *cm)
1489 {
1490         struct charger_desc *desc = cm->desc;
1491         union power_supply_propval val;
1492         int ret;
1493
1494         /* Verify whether fuel gauge provides battery temperature */
1495         ret = cm->fuel_gauge->get_property(cm->fuel_gauge,
1496                                         POWER_SUPPLY_PROP_TEMP, &val);
1497
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;
1503         }
1504 #ifdef CONFIG_THERMAL
1505         cm->tzd_batt = cm->fuel_gauge->tzd;
1506
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);
1512
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;
1519         }
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;
1527         }
1528
1529         return ret;
1530 }
1531
1532 static struct of_device_id charger_manager_match[] = {
1533         {
1534                 .compatible = "charger-manager",
1535         },
1536         {},
1537 };
1538
1539 static struct charger_desc *of_cm_parse_desc(struct device *dev)
1540 {
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;
1546
1547         desc = devm_kzalloc(dev, sizeof(*desc), GFP_KERNEL);
1548         if (!desc)
1549                 return ERR_PTR(-ENOMEM);
1550
1551         of_property_read_string(np, "cm-name", &desc->psy_name);
1552
1553         of_property_read_u32(np, "cm-poll-mode", &poll_mode);
1554         desc->polling_mode = poll_mode;
1555
1556         of_property_read_u32(np, "cm-poll-interval",
1557                                 &desc->polling_interval_ms);
1558
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);
1567
1568         of_property_read_u32(np, "cm-battery-stat", &battery_stat);
1569         desc->battery_present = battery_stat;
1570
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);
1584                 }
1585         }
1586
1587         of_property_read_string(np, "cm-fuel-gauge", &desc->psy_fuel_gauge);
1588
1589         of_property_read_string(np, "cm-thermal-zone", &desc->thermal_zone);
1590
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);
1596
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);
1601
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;
1607
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);
1613
1614                 desc->charger_regulators = chg_regs;
1615
1616                 for_each_child_of_node(np, child) {
1617                         struct charger_cable *cables;
1618                         struct device_node *_child;
1619
1620                         of_property_read_string(child, "cm-regulator-name",
1621                                         &chg_regs->regulator_name);
1622
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);
1631
1632                                 chg_regs->cables = cables;
1633
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++;
1647                                 }
1648                         }
1649                         chg_regs++;
1650                 }
1651         }
1652         return desc;
1653 }
1654
1655 static inline struct charger_desc *cm_get_drv_data(struct platform_device *pdev)
1656 {
1657         if (pdev->dev.of_node)
1658                 return of_cm_parse_desc(&pdev->dev);
1659         return (struct charger_desc *)dev_get_platdata(&pdev->dev);
1660 }
1661
1662 static int charger_manager_probe(struct platform_device *pdev)
1663 {
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;
1669
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;
1677                 }
1678         }
1679
1680         if (!desc) {
1681                 dev_err(&pdev->dev, "No platform data (desc) found\n");
1682                 return -ENODEV;
1683         }
1684
1685         cm = devm_kzalloc(&pdev->dev,
1686                         sizeof(struct charger_manager), GFP_KERNEL);
1687         if (!cm)
1688                 return -ENOMEM;
1689
1690         /* Basic Values. Unspecified are Null or 0 */
1691         cm->dev = &pdev->dev;
1692         cm->desc = desc;
1693
1694         /*
1695          * The following two do not need to be errors.
1696          * Users may intentionally ignore those two features.
1697          */
1698         if (desc->fullbatt_uV == 0) {
1699                 dev_info(&pdev->dev, "Ignoring full-battery voltage threshold as it is not supplied\n");
1700         }
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;
1705         }
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");
1708         }
1709         if (desc->fullbatt_full_capacity == 0) {
1710                 dev_info(&pdev->dev, "Ignoring full-battery full capacity threshold as it is not supplied\n");
1711         }
1712
1713         if (!desc->charger_regulators || desc->num_charger_regulators < 1) {
1714                 dev_err(&pdev->dev, "charger_regulators undefined\n");
1715                 return -EINVAL;
1716         }
1717
1718         if (!desc->psy_charger_stat || !desc->psy_charger_stat[0]) {
1719                 dev_err(&pdev->dev, "No power supply defined\n");
1720                 return -EINVAL;
1721         }
1722
1723         if (!desc->psy_fuel_gauge) {
1724                 dev_err(&pdev->dev, "No fuel gauge power supply defined\n");
1725                 return -EINVAL;
1726         }
1727
1728         /* Counting index only */
1729         while (desc->psy_charger_stat[i])
1730                 i++;
1731
1732         cm->charger_stat = devm_kzalloc(&pdev->dev,
1733                                 sizeof(struct power_supply *) * i, GFP_KERNEL);
1734         if (!cm->charger_stat)
1735                 return -ENOMEM;
1736
1737         for (i = 0; desc->psy_charger_stat[i]; i++) {
1738                 cm->charger_stat[i] = power_supply_get_by_name(
1739                                         desc->psy_charger_stat[i]);
1740                 if (!cm->charger_stat[i]) {
1741                         dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1742                                 desc->psy_charger_stat[i]);
1743                         return -ENODEV;
1744                 }
1745         }
1746
1747         cm->fuel_gauge = power_supply_get_by_name(desc->psy_fuel_gauge);
1748         if (!cm->fuel_gauge) {
1749                 dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1750                         desc->psy_fuel_gauge);
1751                 return -ENODEV;
1752         }
1753
1754         if (desc->polling_interval_ms == 0 ||
1755             msecs_to_jiffies(desc->polling_interval_ms) <= CM_JIFFIES_SMALL) {
1756                 dev_err(&pdev->dev, "polling_interval_ms is too small\n");
1757                 return -EINVAL;
1758         }
1759
1760         if (!desc->charging_max_duration_ms ||
1761                         !desc->discharging_max_duration_ms) {
1762                 dev_info(&pdev->dev, "Cannot limit charging duration checking mechanism to prevent overcharge/overheat and control discharging duration\n");
1763                 desc->charging_max_duration_ms = 0;
1764                 desc->discharging_max_duration_ms = 0;
1765         }
1766
1767         platform_set_drvdata(pdev, cm);
1768
1769         memcpy(&cm->charger_psy, &psy_default, sizeof(psy_default));
1770
1771         if (!desc->psy_name)
1772                 strncpy(cm->psy_name_buf, psy_default.name, PSY_NAME_MAX);
1773         else
1774                 strncpy(cm->psy_name_buf, desc->psy_name, PSY_NAME_MAX);
1775         cm->charger_psy.name = cm->psy_name_buf;
1776
1777         /* Allocate for psy properties because they may vary */
1778         cm->charger_psy.properties = devm_kzalloc(&pdev->dev,
1779                                 sizeof(enum power_supply_property)
1780                                 * (ARRAY_SIZE(default_charger_props) +
1781                                 NUM_CHARGER_PSY_OPTIONAL), GFP_KERNEL);
1782         if (!cm->charger_psy.properties)
1783                 return -ENOMEM;
1784
1785         memcpy(cm->charger_psy.properties, default_charger_props,
1786                 sizeof(enum power_supply_property) *
1787                 ARRAY_SIZE(default_charger_props));
1788         cm->charger_psy.num_properties = psy_default.num_properties;
1789
1790         /* Find which optional psy-properties are available */
1791         if (!cm->fuel_gauge->get_property(cm->fuel_gauge,
1792                                           POWER_SUPPLY_PROP_CHARGE_NOW, &val)) {
1793                 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1794                                 POWER_SUPPLY_PROP_CHARGE_NOW;
1795                 cm->charger_psy.num_properties++;
1796         }
1797         if (!cm->fuel_gauge->get_property(cm->fuel_gauge,
1798                                           POWER_SUPPLY_PROP_CURRENT_NOW,
1799                                           &val)) {
1800                 cm->charger_psy.properties[cm->charger_psy.num_properties] =
1801                                 POWER_SUPPLY_PROP_CURRENT_NOW;
1802                 cm->charger_psy.num_properties++;
1803         }
1804
1805         ret = cm_init_thermal_data(cm);
1806         if (ret) {
1807                 dev_err(&pdev->dev, "Failed to initialize thermal data\n");
1808                 cm->desc->measure_battery_temp = false;
1809         }
1810
1811         INIT_DELAYED_WORK(&cm->fullbatt_vchk_work, fullbatt_vchk);
1812
1813         ret = power_supply_register(NULL, &cm->charger_psy);
1814         if (ret) {
1815                 dev_err(&pdev->dev, "Cannot register charger-manager with name \"%s\"\n",
1816                         cm->charger_psy.name);
1817                 return ret;
1818         }
1819
1820         /* Register extcon device for charger cable */
1821         ret = charger_manager_register_extcon(cm);
1822         if (ret < 0) {
1823                 dev_err(&pdev->dev, "Cannot initialize extcon device\n");
1824                 goto err_reg_extcon;
1825         }
1826
1827         /* Register sysfs entry for charger(regulator) */
1828         ret = charger_manager_register_sysfs(cm);
1829         if (ret < 0) {
1830                 dev_err(&pdev->dev,
1831                         "Cannot initialize sysfs entry of regulator\n");
1832                 goto err_reg_sysfs;
1833         }
1834
1835         /* Add to the list */
1836         mutex_lock(&cm_list_mtx);
1837         list_add(&cm->entry, &cm_list);
1838         mutex_unlock(&cm_list_mtx);
1839
1840         /*
1841          * Charger-manager is capable of waking up the systme from sleep
1842          * when event is happend through cm_notify_event()
1843          */
1844         device_init_wakeup(&pdev->dev, true);
1845         device_set_wakeup_capable(&pdev->dev, false);
1846
1847         schedule_work(&setup_polling);
1848
1849         return 0;
1850
1851 err_reg_sysfs:
1852         for (i = 0; i < desc->num_charger_regulators; i++) {
1853                 struct charger_regulator *charger;
1854
1855                 charger = &desc->charger_regulators[i];
1856                 sysfs_remove_group(&cm->charger_psy.dev->kobj,
1857                                 &charger->attr_g);
1858         }
1859 err_reg_extcon:
1860         for (i = 0; i < desc->num_charger_regulators; i++) {
1861                 struct charger_regulator *charger;
1862
1863                 charger = &desc->charger_regulators[i];
1864                 for (j = 0; j < charger->num_cables; j++) {
1865                         struct charger_cable *cable = &charger->cables[j];
1866                         /* Remove notifier block if only edev exists */
1867                         if (cable->extcon_dev.edev)
1868                                 extcon_unregister_interest(&cable->extcon_dev);
1869                 }
1870
1871                 regulator_put(desc->charger_regulators[i].consumer);
1872         }
1873
1874         power_supply_unregister(&cm->charger_psy);
1875
1876         return ret;
1877 }
1878
1879 static int charger_manager_remove(struct platform_device *pdev)
1880 {
1881         struct charger_manager *cm = platform_get_drvdata(pdev);
1882         struct charger_desc *desc = cm->desc;
1883         int i = 0;
1884         int j = 0;
1885
1886         /* Remove from the list */
1887         mutex_lock(&cm_list_mtx);
1888         list_del(&cm->entry);
1889         mutex_unlock(&cm_list_mtx);
1890
1891         cancel_work_sync(&setup_polling);
1892         cancel_delayed_work_sync(&cm_monitor_work);
1893
1894         for (i = 0 ; i < desc->num_charger_regulators ; i++) {
1895                 struct charger_regulator *charger
1896                                 = &desc->charger_regulators[i];
1897                 for (j = 0 ; j < charger->num_cables ; j++) {
1898                         struct charger_cable *cable = &charger->cables[j];
1899                         extcon_unregister_interest(&cable->extcon_dev);
1900                 }
1901         }
1902
1903         for (i = 0 ; i < desc->num_charger_regulators ; i++)
1904                 regulator_put(desc->charger_regulators[i].consumer);
1905
1906         power_supply_unregister(&cm->charger_psy);
1907
1908         try_charger_enable(cm, false);
1909
1910         return 0;
1911 }
1912
1913 static const struct platform_device_id charger_manager_id[] = {
1914         { "charger-manager", 0 },
1915         { },
1916 };
1917 MODULE_DEVICE_TABLE(platform, charger_manager_id);
1918
1919 static int cm_suspend_noirq(struct device *dev)
1920 {
1921         int ret = 0;
1922
1923         if (device_may_wakeup(dev)) {
1924                 device_set_wakeup_capable(dev, false);
1925                 ret = -EAGAIN;
1926         }
1927
1928         return ret;
1929 }
1930
1931 static int cm_suspend_prepare(struct device *dev)
1932 {
1933         struct charger_manager *cm = dev_get_drvdata(dev);
1934
1935         if (!cm_suspended) {
1936                 if (rtc_dev) {
1937                         struct rtc_time tmp;
1938                         unsigned long now;
1939
1940                         rtc_read_alarm(rtc_dev, &rtc_wkalarm_save);
1941                         rtc_read_time(rtc_dev, &tmp);
1942
1943                         if (rtc_wkalarm_save.enabled) {
1944                                 rtc_tm_to_time(&rtc_wkalarm_save.time,
1945                                                &rtc_wkalarm_save_time);
1946                                 rtc_tm_to_time(&tmp, &now);
1947                                 if (now > rtc_wkalarm_save_time)
1948                                         rtc_wkalarm_save_time = 0;
1949                         } else {
1950                                 rtc_wkalarm_save_time = 0;
1951                         }
1952                 }
1953                 cm_suspended = true;
1954         }
1955
1956         cancel_delayed_work(&cm->fullbatt_vchk_work);
1957         cm->status_save_ext_pwr_inserted = is_ext_pwr_online(cm);
1958         cm->status_save_batt = is_batt_present(cm);
1959
1960         if (!cm_rtc_set) {
1961                 cm_suspend_duration_ms = 0;
1962                 cm_rtc_set = cm_setup_timer();
1963         }
1964
1965         return 0;
1966 }
1967
1968 static void cm_suspend_complete(struct device *dev)
1969 {
1970         struct charger_manager *cm = dev_get_drvdata(dev);
1971
1972         if (cm_suspended) {
1973                 if (rtc_dev) {
1974                         struct rtc_wkalrm tmp;
1975
1976                         rtc_read_alarm(rtc_dev, &tmp);
1977                         rtc_wkalarm_save.pending = tmp.pending;
1978                         rtc_set_alarm(rtc_dev, &rtc_wkalarm_save);
1979                 }
1980                 cm_suspended = false;
1981                 cm_rtc_set = false;
1982         }
1983
1984         /* Re-enqueue delayed work (fullbatt_vchk_work) */
1985         if (cm->fullbatt_vchk_jiffies_at) {
1986                 unsigned long delay = 0;
1987                 unsigned long now = jiffies + CM_JIFFIES_SMALL;
1988
1989                 if (time_after_eq(now, cm->fullbatt_vchk_jiffies_at)) {
1990                         delay = (unsigned long)((long)now
1991                                 - (long)(cm->fullbatt_vchk_jiffies_at));
1992                         delay = jiffies_to_msecs(delay);
1993                 } else {
1994                         delay = 0;
1995                 }
1996
1997                 /*
1998                  * Account for cm_suspend_duration_ms if
1999                  * assume_timer_stops_in_suspend is active
2000                  */
2001                 if (g_desc && g_desc->assume_timer_stops_in_suspend) {
2002                         if (delay > cm_suspend_duration_ms)
2003                                 delay -= cm_suspend_duration_ms;
2004                         else
2005                                 delay = 0;
2006                 }
2007
2008                 queue_delayed_work(cm_wq, &cm->fullbatt_vchk_work,
2009                                    msecs_to_jiffies(delay));
2010         }
2011         device_set_wakeup_capable(cm->dev, false);
2012         uevent_notify(cm, NULL);
2013 }
2014
2015 static const struct dev_pm_ops charger_manager_pm = {
2016         .prepare        = cm_suspend_prepare,
2017         .suspend_noirq  = cm_suspend_noirq,
2018         .complete       = cm_suspend_complete,
2019 };
2020
2021 static struct platform_driver charger_manager_driver = {
2022         .driver = {
2023                 .name = "charger-manager",
2024                 .owner = THIS_MODULE,
2025                 .pm = &charger_manager_pm,
2026                 .of_match_table = charger_manager_match,
2027         },
2028         .probe = charger_manager_probe,
2029         .remove = charger_manager_remove,
2030         .id_table = charger_manager_id,
2031 };
2032
2033 static int __init charger_manager_init(void)
2034 {
2035         cm_wq = create_freezable_workqueue("charger_manager");
2036         INIT_DELAYED_WORK(&cm_monitor_work, cm_monitor_poller);
2037
2038         return platform_driver_register(&charger_manager_driver);
2039 }
2040 late_initcall(charger_manager_init);
2041
2042 static void __exit charger_manager_cleanup(void)
2043 {
2044         destroy_workqueue(cm_wq);
2045         cm_wq = NULL;
2046
2047         platform_driver_unregister(&charger_manager_driver);
2048 }
2049 module_exit(charger_manager_cleanup);
2050
2051 /**
2052  * find_power_supply - find the associated power_supply of charger
2053  * @cm: the Charger Manager representing the battery
2054  * @psy: pointer to instance of charger's power_supply
2055  */
2056 static bool find_power_supply(struct charger_manager *cm,
2057                         struct power_supply *psy)
2058 {
2059         int i;
2060         bool found = false;
2061
2062         for (i = 0; cm->charger_stat[i]; i++) {
2063                 if (psy == cm->charger_stat[i]) {
2064                         found = true;
2065                         break;
2066                 }
2067         }
2068
2069         return found;
2070 }
2071
2072 /**
2073  * cm_notify_event - charger driver notify Charger Manager of charger event
2074  * @psy: pointer to instance of charger's power_supply
2075  * @type: type of charger event
2076  * @msg: optional message passed to uevent_notify fuction
2077  */
2078 void cm_notify_event(struct power_supply *psy, enum cm_event_types type,
2079                      char *msg)
2080 {
2081         struct charger_manager *cm;
2082         bool found_power_supply = false;
2083
2084         if (psy == NULL)
2085                 return;
2086
2087         mutex_lock(&cm_list_mtx);
2088         list_for_each_entry(cm, &cm_list, entry) {
2089                 found_power_supply = find_power_supply(cm, psy);
2090                 if (found_power_supply)
2091                         break;
2092         }
2093         mutex_unlock(&cm_list_mtx);
2094
2095         if (!found_power_supply)
2096                 return;
2097
2098         switch (type) {
2099         case CM_EVENT_BATT_FULL:
2100                 fullbatt_handler(cm);
2101                 break;
2102         case CM_EVENT_BATT_OUT:
2103                 battout_handler(cm);
2104                 break;
2105         case CM_EVENT_BATT_IN:
2106         case CM_EVENT_EXT_PWR_IN_OUT ... CM_EVENT_CHG_START_STOP:
2107                 misc_event_handler(cm, type);
2108                 break;
2109         case CM_EVENT_UNKNOWN:
2110         case CM_EVENT_OTHERS:
2111                 uevent_notify(cm, msg ? msg : default_event_names[type]);
2112                 break;
2113         default:
2114                 dev_err(cm->dev, "%s: type not specified\n", __func__);
2115                 break;
2116         }
2117 }
2118 EXPORT_SYMBOL_GPL(cm_notify_event);
2119
2120 MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
2121 MODULE_DESCRIPTION("Charger Manager");
2122 MODULE_LICENSE("GPL");