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