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