linux/drivers/power/supply/charger-manager.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Copyright (C) 2011 Samsung Electronics Co., Ltd.
   4 * MyungJoo Ham <myungjoo.ham@samsung.com>
   5 *
   6 * This driver enables to monitor battery health and control charger
   7 * during suspend-to-mem.
   8 * Charger manager depends on other devices. Register this later than
   9 * the depending devices.
  10 *
  11**/
  12
  13#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  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#include <linux/of.h>
  27#include <linux/thermal.h>
  28
  29static struct {
  30        const char *name;
  31        u64 extcon_type;
  32} extcon_mapping[] = {
  33        /* Current textual representations */
  34        { "USB", EXTCON_USB },
  35        { "USB-HOST", EXTCON_USB_HOST },
  36        { "SDP", EXTCON_CHG_USB_SDP },
  37        { "DCP", EXTCON_CHG_USB_DCP },
  38        { "CDP", EXTCON_CHG_USB_CDP },
  39        { "ACA", EXTCON_CHG_USB_ACA },
  40        { "FAST-CHARGER", EXTCON_CHG_USB_FAST },
  41        { "SLOW-CHARGER", EXTCON_CHG_USB_SLOW },
  42        { "WPT", EXTCON_CHG_WPT },
  43        { "PD", EXTCON_CHG_USB_PD },
  44        { "DOCK", EXTCON_DOCK },
  45        { "JIG", EXTCON_JIG },
  46        { "MECHANICAL", EXTCON_MECHANICAL },
  47        /* Deprecated textual representations */
  48        { "TA", EXTCON_CHG_USB_SDP },
  49        { "CHARGE-DOWNSTREAM", EXTCON_CHG_USB_CDP },
  50};
  51
  52/*
  53 * Default temperature threshold for charging.
  54 * Every temperature units are in tenth of centigrade.
  55 */
  56#define CM_DEFAULT_RECHARGE_TEMP_DIFF   50
  57#define CM_DEFAULT_CHARGE_TEMP_MAX      500
  58
  59/*
  60 * Regard CM_JIFFIES_SMALL jiffies is small enough to ignore for
  61 * delayed works so that we can run delayed works with CM_JIFFIES_SMALL
  62 * without any delays.
  63 */
  64#define CM_JIFFIES_SMALL        (2)
  65
  66/* If y is valid (> 0) and smaller than x, do x = y */
  67#define CM_MIN_VALID(x, y)      x = (((y > 0) && ((x) > (y))) ? (y) : (x))
  68
  69/*
  70 * Regard CM_RTC_SMALL (sec) is small enough to ignore error in invoking
  71 * rtc alarm. It should be 2 or larger
  72 */
  73#define CM_RTC_SMALL            (2)
  74
  75static LIST_HEAD(cm_list);
  76static DEFINE_MUTEX(cm_list_mtx);
  77
  78/* About in-suspend (suspend-again) monitoring */
  79static struct alarm *cm_timer;
  80
  81static bool cm_suspended;
  82static bool cm_timer_set;
  83static unsigned long cm_suspend_duration_ms;
  84
  85/* About normal (not suspended) monitoring */
  86static unsigned long polling_jiffy = ULONG_MAX; /* ULONG_MAX: no polling */
  87static unsigned long next_polling; /* Next appointed polling time */
  88static struct workqueue_struct *cm_wq; /* init at driver add */
  89static struct delayed_work cm_monitor_work; /* init at driver add */
  90
  91/**
  92 * is_batt_present - See if the battery presents in place.
  93 * @cm: the Charger Manager representing the battery.
  94 */
  95static bool is_batt_present(struct charger_manager *cm)
  96{
  97        union power_supply_propval val;
  98        struct power_supply *psy;
  99        bool present = false;
 100        int i, ret;
 101
 102        switch (cm->desc->battery_present) {
 103        case CM_BATTERY_PRESENT:
 104                present = true;
 105                break;
 106        case CM_NO_BATTERY:
 107                break;
 108        case CM_FUEL_GAUGE:
 109                psy = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
 110                if (!psy)
 111                        break;
 112
 113                ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_PRESENT,
 114                                &val);
 115                if (ret == 0 && val.intval)
 116                        present = true;
 117                power_supply_put(psy);
 118                break;
 119        case CM_CHARGER_STAT:
 120                for (i = 0; cm->desc->psy_charger_stat[i]; i++) {
 121                        psy = power_supply_get_by_name(
 122                                        cm->desc->psy_charger_stat[i]);
 123                        if (!psy) {
 124                                dev_err(cm->dev, "Cannot find power supply \"%s\"\n",
 125                                        cm->desc->psy_charger_stat[i]);
 126                                continue;
 127                        }
 128
 129                        ret = power_supply_get_property(psy,
 130                                POWER_SUPPLY_PROP_PRESENT, &val);
 131                        power_supply_put(psy);
 132                        if (ret == 0 && val.intval) {
 133                                present = true;
 134                                break;
 135                        }
 136                }
 137                break;
 138        }
 139
 140        return present;
 141}
 142
 143/**
 144 * is_ext_pwr_online - See if an external power source is attached to charge
 145 * @cm: the Charger Manager representing the battery.
 146 *
 147 * Returns true if at least one of the chargers of the battery has an external
 148 * power source attached to charge the battery regardless of whether it is
 149 * actually charging or not.
 150 */
 151static bool is_ext_pwr_online(struct charger_manager *cm)
 152{
 153        union power_supply_propval val;
 154        struct power_supply *psy;
 155        bool online = false;
 156        int i, ret;
 157
 158        /* If at least one of them has one, it's yes. */
 159        for (i = 0; cm->desc->psy_charger_stat[i]; i++) {
 160                psy = power_supply_get_by_name(cm->desc->psy_charger_stat[i]);
 161                if (!psy) {
 162                        dev_err(cm->dev, "Cannot find power supply \"%s\"\n",
 163                                        cm->desc->psy_charger_stat[i]);
 164                        continue;
 165                }
 166
 167                ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_ONLINE,
 168                                &val);
 169                power_supply_put(psy);
 170                if (ret == 0 && val.intval) {
 171                        online = true;
 172                        break;
 173                }
 174        }
 175
 176        return online;
 177}
 178
 179/**
 180 * get_batt_uV - Get the voltage level of the battery
 181 * @cm: the Charger Manager representing the battery.
 182 * @uV: the voltage level returned.
 183 *
 184 * Returns 0 if there is no error.
 185 * Returns a negative value on error.
 186 */
 187static int get_batt_uV(struct charger_manager *cm, int *uV)
 188{
 189        union power_supply_propval val;
 190        struct power_supply *fuel_gauge;
 191        int ret;
 192
 193        fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
 194        if (!fuel_gauge)
 195                return -ENODEV;
 196
 197        ret = power_supply_get_property(fuel_gauge,
 198                                POWER_SUPPLY_PROP_VOLTAGE_NOW, &val);
 199        power_supply_put(fuel_gauge);
 200        if (ret)
 201                return ret;
 202
 203        *uV = val.intval;
 204        return 0;
 205}
 206
 207/**
 208 * is_charging - Returns true if the battery is being charged.
 209 * @cm: the Charger Manager representing the battery.
 210 */
 211static bool is_charging(struct charger_manager *cm)
 212{
 213        int i, ret;
 214        bool charging = false;
 215        struct power_supply *psy;
 216        union power_supply_propval val;
 217
 218        /* If there is no battery, it cannot be charged */
 219        if (!is_batt_present(cm))
 220                return false;
 221
 222        /* If at least one of the charger is charging, return yes */
 223        for (i = 0; cm->desc->psy_charger_stat[i]; i++) {
 224                /* 1. The charger sholuld not be DISABLED */
 225                if (cm->emergency_stop)
 226                        continue;
 227                if (!cm->charger_enabled)
 228                        continue;
 229
 230                psy = power_supply_get_by_name(cm->desc->psy_charger_stat[i]);
 231                if (!psy) {
 232                        dev_err(cm->dev, "Cannot find power supply \"%s\"\n",
 233                                        cm->desc->psy_charger_stat[i]);
 234                        continue;
 235                }
 236
 237                /* 2. The charger should be online (ext-power) */
 238                ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_ONLINE,
 239                                &val);
 240                if (ret) {
 241                        dev_warn(cm->dev, "Cannot read ONLINE value from %s\n",
 242                                 cm->desc->psy_charger_stat[i]);
 243                        power_supply_put(psy);
 244                        continue;
 245                }
 246                if (val.intval == 0) {
 247                        power_supply_put(psy);
 248                        continue;
 249                }
 250
 251                /*
 252                 * 3. The charger should not be FULL, DISCHARGING,
 253                 * or NOT_CHARGING.
 254                 */
 255                ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_STATUS,
 256                                &val);
 257                power_supply_put(psy);
 258                if (ret) {
 259                        dev_warn(cm->dev, "Cannot read STATUS value from %s\n",
 260                                 cm->desc->psy_charger_stat[i]);
 261                        continue;
 262                }
 263                if (val.intval == POWER_SUPPLY_STATUS_FULL ||
 264                                val.intval == POWER_SUPPLY_STATUS_DISCHARGING ||
 265                                val.intval == POWER_SUPPLY_STATUS_NOT_CHARGING)
 266                        continue;
 267
 268                /* Then, this is charging. */
 269                charging = true;
 270                break;
 271        }
 272
 273        return charging;
 274}
 275
 276/**
 277 * is_full_charged - Returns true if the battery is fully charged.
 278 * @cm: the Charger Manager representing the battery.
 279 */
 280static bool is_full_charged(struct charger_manager *cm)
 281{
 282        struct charger_desc *desc = cm->desc;
 283        union power_supply_propval val;
 284        struct power_supply *fuel_gauge;
 285        bool is_full = false;
 286        int ret = 0;
 287        int uV;
 288
 289        /* If there is no battery, it cannot be charged */
 290        if (!is_batt_present(cm))
 291                return false;
 292
 293        fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
 294        if (!fuel_gauge)
 295                return false;
 296
 297        /* Full, if it's over the fullbatt voltage */
 298        if (desc->fullbatt_uV > 0) {
 299                ret = get_batt_uV(cm, &uV);
 300                if (!ret) {
 301                        /* Battery is already full, checks voltage drop. */
 302                        if (cm->battery_status == POWER_SUPPLY_STATUS_FULL
 303                                        && desc->fullbatt_vchkdrop_uV)
 304                                uV += desc->fullbatt_vchkdrop_uV;
 305                        if (uV >= desc->fullbatt_uV)
 306                                return true;
 307                }
 308        }
 309
 310        if (desc->fullbatt_full_capacity > 0) {
 311                val.intval = 0;
 312
 313                /* Not full if capacity of fuel gauge isn't full */
 314                ret = power_supply_get_property(fuel_gauge,
 315                                POWER_SUPPLY_PROP_CHARGE_FULL, &val);
 316                if (!ret && val.intval > desc->fullbatt_full_capacity) {
 317                        is_full = true;
 318                        goto out;
 319                }
 320        }
 321
 322        /* Full, if the capacity is more than fullbatt_soc */
 323        if (desc->fullbatt_soc > 0) {
 324                val.intval = 0;
 325
 326                ret = power_supply_get_property(fuel_gauge,
 327                                POWER_SUPPLY_PROP_CAPACITY, &val);
 328                if (!ret && val.intval >= desc->fullbatt_soc) {
 329                        is_full = true;
 330                        goto out;
 331                }
 332        }
 333
 334out:
 335        power_supply_put(fuel_gauge);
 336        return is_full;
 337}
 338
 339/**
 340 * is_polling_required - Return true if need to continue polling for this CM.
 341 * @cm: the Charger Manager representing the battery.
 342 */
 343static bool is_polling_required(struct charger_manager *cm)
 344{
 345        switch (cm->desc->polling_mode) {
 346        case CM_POLL_DISABLE:
 347                return false;
 348        case CM_POLL_ALWAYS:
 349                return true;
 350        case CM_POLL_EXTERNAL_POWER_ONLY:
 351                return is_ext_pwr_online(cm);
 352        case CM_POLL_CHARGING_ONLY:
 353                return is_charging(cm);
 354        default:
 355                dev_warn(cm->dev, "Incorrect polling_mode (%d)\n",
 356                         cm->desc->polling_mode);
 357        }
 358
 359        return false;
 360}
 361
 362/**
 363 * try_charger_enable - Enable/Disable chargers altogether
 364 * @cm: the Charger Manager representing the battery.
 365 * @enable: true: enable / false: disable
 366 *
 367 * Note that Charger Manager keeps the charger enabled regardless whether
 368 * the charger is charging or not (because battery is full or no external
 369 * power source exists) except when CM needs to disable chargers forcibly
 370 * because of emergency causes; when the battery is overheated or too cold.
 371 */
 372static int try_charger_enable(struct charger_manager *cm, bool enable)
 373{
 374        int err = 0, i;
 375        struct charger_desc *desc = cm->desc;
 376
 377        /* Ignore if it's redundant command */
 378        if (enable == cm->charger_enabled)
 379                return 0;
 380
 381        if (enable) {
 382                if (cm->emergency_stop)
 383                        return -EAGAIN;
 384
 385                /*
 386                 * Save start time of charging to limit
 387                 * maximum possible charging time.
 388                 */
 389                cm->charging_start_time = ktime_to_ms(ktime_get());
 390                cm->charging_end_time = 0;
 391
 392                for (i = 0 ; i < desc->num_charger_regulators ; i++) {
 393                        if (desc->charger_regulators[i].externally_control)
 394                                continue;
 395
 396                        err = regulator_enable(desc->charger_regulators[i].consumer);
 397                        if (err < 0) {
 398                                dev_warn(cm->dev, "Cannot enable %s regulator\n",
 399                                         desc->charger_regulators[i].regulator_name);
 400                        }
 401                }
 402        } else {
 403                /*
 404                 * Save end time of charging to maintain fully charged state
 405                 * of battery after full-batt.
 406                 */
 407                cm->charging_start_time = 0;
 408                cm->charging_end_time = ktime_to_ms(ktime_get());
 409
 410                for (i = 0 ; i < desc->num_charger_regulators ; i++) {
 411                        if (desc->charger_regulators[i].externally_control)
 412                                continue;
 413
 414                        err = regulator_disable(desc->charger_regulators[i].consumer);
 415                        if (err < 0) {
 416                                dev_warn(cm->dev, "Cannot disable %s regulator\n",
 417                                         desc->charger_regulators[i].regulator_name);
 418                        }
 419                }
 420
 421                /*
 422                 * Abnormal battery state - Stop charging forcibly,
 423                 * even if charger was enabled at the other places
 424                 */
 425                for (i = 0; i < desc->num_charger_regulators; i++) {
 426                        if (regulator_is_enabled(
 427                                    desc->charger_regulators[i].consumer)) {
 428                                regulator_force_disable(
 429                                        desc->charger_regulators[i].consumer);
 430                                dev_warn(cm->dev, "Disable regulator(%s) forcibly\n",
 431                                         desc->charger_regulators[i].regulator_name);
 432                        }
 433                }
 434        }
 435
 436        if (!err)
 437                cm->charger_enabled = enable;
 438
 439        return err;
 440}
 441
 442/**
 443 * check_charging_duration - Monitor charging/discharging duration
 444 * @cm: the Charger Manager representing the battery.
 445 *
 446 * If whole charging duration exceed 'charging_max_duration_ms',
 447 * cm stop charging to prevent overcharge/overheat. If discharging
 448 * duration exceed 'discharging _max_duration_ms', charger cable is
 449 * attached, after full-batt, cm start charging to maintain fully
 450 * charged state for battery.
 451 */
 452static int check_charging_duration(struct charger_manager *cm)
 453{
 454        struct charger_desc *desc = cm->desc;
 455        u64 curr = ktime_to_ms(ktime_get());
 456        u64 duration;
 457        int ret = false;
 458
 459        if (!desc->charging_max_duration_ms &&
 460                        !desc->discharging_max_duration_ms)
 461                return ret;
 462
 463        if (cm->charger_enabled) {
 464                duration = curr - cm->charging_start_time;
 465
 466                if (duration > desc->charging_max_duration_ms) {
 467                        dev_info(cm->dev, "Charging duration exceed %ums\n",
 468                                 desc->charging_max_duration_ms);
 469                        ret = true;
 470                }
 471        } else if (cm->battery_status == POWER_SUPPLY_STATUS_NOT_CHARGING) {
 472                duration = curr - cm->charging_end_time;
 473
 474                if (duration > desc->discharging_max_duration_ms) {
 475                        dev_info(cm->dev, "Discharging duration exceed %ums\n",
 476                                 desc->discharging_max_duration_ms);
 477                        ret = true;
 478                }
 479        }
 480
 481        return ret;
 482}
 483
 484static int cm_get_battery_temperature_by_psy(struct charger_manager *cm,
 485                                        int *temp)
 486{
 487        struct power_supply *fuel_gauge;
 488        int ret;
 489
 490        fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
 491        if (!fuel_gauge)
 492                return -ENODEV;
 493
 494        ret = power_supply_get_property(fuel_gauge,
 495                                POWER_SUPPLY_PROP_TEMP,
 496                                (union power_supply_propval *)temp);
 497        power_supply_put(fuel_gauge);
 498
 499        return ret;
 500}
 501
 502static int cm_get_battery_temperature(struct charger_manager *cm,
 503                                        int *temp)
 504{
 505        int ret;
 506
 507        if (!cm->desc->measure_battery_temp)
 508                return -ENODEV;
 509
 510#ifdef CONFIG_THERMAL
 511        if (cm->tzd_batt) {
 512                ret = thermal_zone_get_temp(cm->tzd_batt, temp);
 513                if (!ret)
 514                        /* Calibrate temperature unit */
 515                        *temp /= 100;
 516        } else
 517#endif
 518        {
 519                /* if-else continued from CONFIG_THERMAL */
 520                ret = cm_get_battery_temperature_by_psy(cm, temp);
 521        }
 522
 523        return ret;
 524}
 525
 526static int cm_check_thermal_status(struct charger_manager *cm)
 527{
 528        struct charger_desc *desc = cm->desc;
 529        int temp, upper_limit, lower_limit;
 530        int ret = 0;
 531
 532        ret = cm_get_battery_temperature(cm, &temp);
 533        if (ret) {
 534                /* FIXME:
 535                 * No information of battery temperature might
 536                 * occur hazardous result. We have to handle it
 537                 * depending on battery type.
 538                 */
 539                dev_err(cm->dev, "Failed to get battery temperature\n");
 540                return 0;
 541        }
 542
 543        upper_limit = desc->temp_max;
 544        lower_limit = desc->temp_min;
 545
 546        if (cm->emergency_stop) {
 547                upper_limit -= desc->temp_diff;
 548                lower_limit += desc->temp_diff;
 549        }
 550
 551        if (temp > upper_limit)
 552                ret = CM_BATT_OVERHEAT;
 553        else if (temp < lower_limit)
 554                ret = CM_BATT_COLD;
 555        else
 556                ret = CM_BATT_OK;
 557
 558        cm->emergency_stop = ret;
 559
 560        return ret;
 561}
 562
 563/**
 564 * cm_get_target_status - Check current status and get next target status.
 565 * @cm: the Charger Manager representing the battery.
 566 */
 567static int cm_get_target_status(struct charger_manager *cm)
 568{
 569        if (!is_ext_pwr_online(cm))
 570                return POWER_SUPPLY_STATUS_DISCHARGING;
 571
 572        if (cm_check_thermal_status(cm)) {
 573                /* Check if discharging duration exceeds limit. */
 574                if (check_charging_duration(cm))
 575                        goto charging_ok;
 576                return POWER_SUPPLY_STATUS_NOT_CHARGING;
 577        }
 578
 579        switch (cm->battery_status) {
 580        case POWER_SUPPLY_STATUS_CHARGING:
 581                /* Check if charging duration exceeds limit. */
 582                if (check_charging_duration(cm))
 583                        return POWER_SUPPLY_STATUS_FULL;
 584                fallthrough;
 585        case POWER_SUPPLY_STATUS_FULL:
 586                if (is_full_charged(cm))
 587                        return POWER_SUPPLY_STATUS_FULL;
 588                fallthrough;
 589        default:
 590                break;
 591        }
 592
 593charging_ok:
 594        /* Charging is allowed. */
 595        return POWER_SUPPLY_STATUS_CHARGING;
 596}
 597
 598/**
 599 * _cm_monitor - Monitor the temperature and return true for exceptions.
 600 * @cm: the Charger Manager representing the battery.
 601 *
 602 * Returns true if there is an event to notify for the battery.
 603 * (True if the status of "emergency_stop" changes)
 604 */
 605static bool _cm_monitor(struct charger_manager *cm)
 606{
 607        int target;
 608
 609        target = cm_get_target_status(cm);
 610
 611        try_charger_enable(cm, (target == POWER_SUPPLY_STATUS_CHARGING));
 612
 613        if (cm->battery_status != target) {
 614                cm->battery_status = target;
 615                power_supply_changed(cm->charger_psy);
 616        }
 617
 618        return (cm->battery_status == POWER_SUPPLY_STATUS_NOT_CHARGING);
 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 */
 627static 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 */
 648static 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        /*
 679         * Use mod_delayed_work() iff the next polling interval should
 680         * occur before the currently scheduled one.  If @cm_monitor_work
 681         * isn't active, the end result is the same, so no need to worry
 682         * about stale @next_polling.
 683         */
 684        _next_polling = jiffies + polling_jiffy;
 685
 686        if (time_before(_next_polling, next_polling)) {
 687                mod_delayed_work(cm_wq, &cm_monitor_work, polling_jiffy);
 688                next_polling = _next_polling;
 689        } else {
 690                if (queue_delayed_work(cm_wq, &cm_monitor_work, polling_jiffy))
 691                        next_polling = _next_polling;
 692        }
 693out:
 694        mutex_unlock(&cm_list_mtx);
 695}
 696static DECLARE_WORK(setup_polling, _setup_polling);
 697
 698/**
 699 * cm_monitor_poller - The Monitor / Poller.
 700 * @work: work_struct of the function cm_monitor_poller
 701 *
 702 * During non-suspended state, cm_monitor_poller is used to poll and monitor
 703 * the batteries.
 704 */
 705static void cm_monitor_poller(struct work_struct *work)
 706{
 707        cm_monitor();
 708        schedule_work(&setup_polling);
 709}
 710
 711static int charger_get_property(struct power_supply *psy,
 712                enum power_supply_property psp,
 713                union power_supply_propval *val)
 714{
 715        struct charger_manager *cm = power_supply_get_drvdata(psy);
 716        struct charger_desc *desc = cm->desc;
 717        struct power_supply *fuel_gauge = NULL;
 718        int ret = 0;
 719        int uV;
 720
 721        switch (psp) {
 722        case POWER_SUPPLY_PROP_STATUS:
 723                val->intval = cm->battery_status;
 724                break;
 725        case POWER_SUPPLY_PROP_HEALTH:
 726                if (cm->emergency_stop == CM_BATT_OVERHEAT)
 727                        val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
 728                else if (cm->emergency_stop == CM_BATT_COLD)
 729                        val->intval = POWER_SUPPLY_HEALTH_COLD;
 730                else
 731                        val->intval = POWER_SUPPLY_HEALTH_GOOD;
 732                break;
 733        case POWER_SUPPLY_PROP_PRESENT:
 734                if (is_batt_present(cm))
 735                        val->intval = 1;
 736                else
 737                        val->intval = 0;
 738                break;
 739        case POWER_SUPPLY_PROP_VOLTAGE_NOW:
 740                ret = get_batt_uV(cm, &val->intval);
 741                break;
 742        case POWER_SUPPLY_PROP_CURRENT_NOW:
 743                fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
 744                if (!fuel_gauge) {
 745                        ret = -ENODEV;
 746                        break;
 747                }
 748                ret = power_supply_get_property(fuel_gauge,
 749                                POWER_SUPPLY_PROP_CURRENT_NOW, val);
 750                break;
 751        case POWER_SUPPLY_PROP_TEMP:
 752                return cm_get_battery_temperature(cm, &val->intval);
 753        case POWER_SUPPLY_PROP_CAPACITY:
 754                if (!is_batt_present(cm)) {
 755                        /* There is no battery. Assume 100% */
 756                        val->intval = 100;
 757                        break;
 758                }
 759
 760                fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
 761                if (!fuel_gauge) {
 762                        ret = -ENODEV;
 763                        break;
 764                }
 765
 766                ret = power_supply_get_property(fuel_gauge,
 767                                        POWER_SUPPLY_PROP_CAPACITY, val);
 768                if (ret)
 769                        break;
 770
 771                if (val->intval > 100) {
 772                        val->intval = 100;
 773                        break;
 774                }
 775                if (val->intval < 0)
 776                        val->intval = 0;
 777
 778                /* Do not adjust SOC when charging: voltage is overrated */
 779                if (is_charging(cm))
 780                        break;
 781
 782                /*
 783                 * If the capacity value is inconsistent, calibrate it base on
 784                 * the battery voltage values and the thresholds given as desc
 785                 */
 786                ret = get_batt_uV(cm, &uV);
 787                if (ret) {
 788                        /* Voltage information not available. No calibration */
 789                        ret = 0;
 790                        break;
 791                }
 792
 793                if (desc->fullbatt_uV > 0 && uV >= desc->fullbatt_uV &&
 794                    !is_charging(cm)) {
 795                        val->intval = 100;
 796                        break;
 797                }
 798
 799                break;
 800        case POWER_SUPPLY_PROP_ONLINE:
 801                if (is_ext_pwr_online(cm))
 802                        val->intval = 1;
 803                else
 804                        val->intval = 0;
 805                break;
 806        case POWER_SUPPLY_PROP_CHARGE_FULL:
 807        case POWER_SUPPLY_PROP_CHARGE_NOW:
 808                fuel_gauge = power_supply_get_by_name(cm->desc->psy_fuel_gauge);
 809                if (!fuel_gauge) {
 810                        ret = -ENODEV;
 811                        break;
 812                }
 813                ret = power_supply_get_property(fuel_gauge, psp, val);
 814                break;
 815        default:
 816                return -EINVAL;
 817        }
 818        if (fuel_gauge)
 819                power_supply_put(fuel_gauge);
 820        return ret;
 821}
 822
 823#define NUM_CHARGER_PSY_OPTIONAL        (4)
 824static enum power_supply_property default_charger_props[] = {
 825        /* Guaranteed to provide */
 826        POWER_SUPPLY_PROP_STATUS,
 827        POWER_SUPPLY_PROP_HEALTH,
 828        POWER_SUPPLY_PROP_PRESENT,
 829        POWER_SUPPLY_PROP_VOLTAGE_NOW,
 830        POWER_SUPPLY_PROP_CAPACITY,
 831        POWER_SUPPLY_PROP_ONLINE,
 832        /*
 833         * Optional properties are:
 834         * POWER_SUPPLY_PROP_CHARGE_FULL,
 835         * POWER_SUPPLY_PROP_CHARGE_NOW,
 836         * POWER_SUPPLY_PROP_CURRENT_NOW,
 837         * POWER_SUPPLY_PROP_TEMP,
 838         */
 839};
 840
 841static const struct power_supply_desc psy_default = {
 842        .name = "battery",
 843        .type = POWER_SUPPLY_TYPE_BATTERY,
 844        .properties = default_charger_props,
 845        .num_properties = ARRAY_SIZE(default_charger_props),
 846        .get_property = charger_get_property,
 847        .no_thermal = true,
 848};
 849
 850/**
 851 * cm_setup_timer - For in-suspend monitoring setup wakeup alarm
 852 *                  for suspend_again.
 853 *
 854 * Returns true if the alarm is set for Charger Manager to use.
 855 * Returns false if
 856 *      cm_setup_timer fails to set an alarm,
 857 *      cm_setup_timer does not need to set an alarm for Charger Manager,
 858 *      or an alarm previously configured is to be used.
 859 */
 860static bool cm_setup_timer(void)
 861{
 862        struct charger_manager *cm;
 863        unsigned int wakeup_ms = UINT_MAX;
 864        int timer_req = 0;
 865
 866        if (time_after(next_polling, jiffies))
 867                CM_MIN_VALID(wakeup_ms,
 868                        jiffies_to_msecs(next_polling - jiffies));
 869
 870        mutex_lock(&cm_list_mtx);
 871        list_for_each_entry(cm, &cm_list, entry) {
 872                /* Skip if polling is not required for this CM */
 873                if (!is_polling_required(cm) && !cm->emergency_stop)
 874                        continue;
 875                timer_req++;
 876                if (cm->desc->polling_interval_ms == 0)
 877                        continue;
 878                CM_MIN_VALID(wakeup_ms, cm->desc->polling_interval_ms);
 879        }
 880        mutex_unlock(&cm_list_mtx);
 881
 882        if (timer_req && cm_timer) {
 883                ktime_t now, add;
 884
 885                /*
 886                 * Set alarm with the polling interval (wakeup_ms)
 887                 * The alarm time should be NOW + CM_RTC_SMALL or later.
 888                 */
 889                if (wakeup_ms == UINT_MAX ||
 890                        wakeup_ms < CM_RTC_SMALL * MSEC_PER_SEC)
 891                        wakeup_ms = 2 * CM_RTC_SMALL * MSEC_PER_SEC;
 892
 893                pr_info("Charger Manager wakeup timer: %u ms\n", wakeup_ms);
 894
 895                now = ktime_get_boottime();
 896                add = ktime_set(wakeup_ms / MSEC_PER_SEC,
 897                                (wakeup_ms % MSEC_PER_SEC) * NSEC_PER_MSEC);
 898                alarm_start(cm_timer, ktime_add(now, add));
 899
 900                cm_suspend_duration_ms = wakeup_ms;
 901
 902                return true;
 903        }
 904        return false;
 905}
 906
 907/**
 908 * charger_extcon_work - enable/diable charger according to the state
 909 *                      of charger cable
 910 *
 911 * @work: work_struct of the function charger_extcon_work.
 912 */
 913static void charger_extcon_work(struct work_struct *work)
 914{
 915        struct charger_cable *cable =
 916                        container_of(work, struct charger_cable, wq);
 917        int ret;
 918
 919        if (cable->attached && cable->min_uA != 0 && cable->max_uA != 0) {
 920                ret = regulator_set_current_limit(cable->charger->consumer,
 921                                        cable->min_uA, cable->max_uA);
 922                if (ret < 0) {
 923                        pr_err("Cannot set current limit of %s (%s)\n",
 924                               cable->charger->regulator_name, cable->name);
 925                        return;
 926                }
 927
 928                pr_info("Set current limit of %s : %duA ~ %duA\n",
 929                        cable->charger->regulator_name,
 930                        cable->min_uA, cable->max_uA);
 931        }
 932
 933        cancel_delayed_work(&cm_monitor_work);
 934        queue_delayed_work(cm_wq, &cm_monitor_work, 0);
 935}
 936
 937/**
 938 * charger_extcon_notifier - receive the state of charger cable
 939 *                      when registered cable is attached or detached.
 940 *
 941 * @self: the notifier block of the charger_extcon_notifier.
 942 * @event: the cable state.
 943 * @ptr: the data pointer of notifier block.
 944 */
 945static int charger_extcon_notifier(struct notifier_block *self,
 946                        unsigned long event, void *ptr)
 947{
 948        struct charger_cable *cable =
 949                container_of(self, struct charger_cable, nb);
 950
 951        /*
 952         * The newly state of charger cable.
 953         * If cable is attached, cable->attached is true.
 954         */
 955        cable->attached = event;
 956
 957        /*
 958         * Setup work for controlling charger(regulator)
 959         * according to charger cable.
 960         */
 961        schedule_work(&cable->wq);
 962
 963        return NOTIFY_DONE;
 964}
 965
 966/**
 967 * charger_extcon_init - register external connector to use it
 968 *                      as the charger cable
 969 *
 970 * @cm: the Charger Manager representing the battery.
 971 * @cable: the Charger cable representing the external connector.
 972 */
 973static int charger_extcon_init(struct charger_manager *cm,
 974                struct charger_cable *cable)
 975{
 976        int ret, i;
 977        u64 extcon_type = EXTCON_NONE;
 978
 979        /*
 980         * Charger manager use Extcon framework to identify
 981         * the charger cable among various external connector
 982         * cable (e.g., TA, USB, MHL, Dock).
 983         */
 984        INIT_WORK(&cable->wq, charger_extcon_work);
 985        cable->nb.notifier_call = charger_extcon_notifier;
 986
 987        cable->extcon_dev = extcon_get_extcon_dev(cable->extcon_name);
 988        if (IS_ERR_OR_NULL(cable->extcon_dev)) {
 989                pr_err("Cannot find extcon_dev for %s (cable: %s)\n",
 990                        cable->extcon_name, cable->name);
 991                if (cable->extcon_dev == NULL)
 992                        return -EPROBE_DEFER;
 993                else
 994                        return PTR_ERR(cable->extcon_dev);
 995        }
 996
 997        for (i = 0; i < ARRAY_SIZE(extcon_mapping); i++) {
 998                if (!strcmp(cable->name, extcon_mapping[i].name)) {
 999                        extcon_type = extcon_mapping[i].extcon_type;
1000                        break;
1001                }
1002        }
1003        if (extcon_type == EXTCON_NONE) {
1004                pr_err("Cannot find cable for type %s", cable->name);
1005                return -EINVAL;
1006        }
1007
1008        cable->extcon_type = extcon_type;
1009
1010        ret = devm_extcon_register_notifier(cm->dev, cable->extcon_dev,
1011                cable->extcon_type, &cable->nb);
1012        if (ret < 0) {
1013                pr_err("Cannot register extcon_dev for %s (cable: %s)\n",
1014                        cable->extcon_name, cable->name);
1015                return ret;
1016        }
1017
1018        return 0;
1019}
1020
1021/**
1022 * charger_manager_register_extcon - Register extcon device to receive state
1023 *                                   of charger cable.
1024 * @cm: the Charger Manager representing the battery.
1025 *
1026 * This function support EXTCON(External Connector) subsystem to detect the
1027 * state of charger cables for enabling or disabling charger(regulator) and
1028 * select the charger cable for charging among a number of external cable
1029 * according to policy of H/W board.
1030 */
1031static int charger_manager_register_extcon(struct charger_manager *cm)
1032{
1033        struct charger_desc *desc = cm->desc;
1034        struct charger_regulator *charger;
1035        unsigned long event;
1036        int ret;
1037        int i;
1038        int j;
1039
1040        for (i = 0; i < desc->num_charger_regulators; i++) {
1041                charger = &desc->charger_regulators[i];
1042
1043                charger->consumer = regulator_get(cm->dev,
1044                                        charger->regulator_name);
1045                if (IS_ERR(charger->consumer)) {
1046                        dev_err(cm->dev, "Cannot find charger(%s)\n",
1047                                charger->regulator_name);
1048                        return PTR_ERR(charger->consumer);
1049                }
1050                charger->cm = cm;
1051
1052                for (j = 0; j < charger->num_cables; j++) {
1053                        struct charger_cable *cable = &charger->cables[j];
1054
1055                        ret = charger_extcon_init(cm, cable);
1056                        if (ret < 0) {
1057                                dev_err(cm->dev, "Cannot initialize charger(%s)\n",
1058                                        charger->regulator_name);
1059                                return ret;
1060                        }
1061                        cable->charger = charger;
1062                        cable->cm = cm;
1063
1064                        event = extcon_get_state(cable->extcon_dev,
1065                                cable->extcon_type);
1066                        charger_extcon_notifier(&cable->nb,
1067                                event, NULL);
1068                }
1069        }
1070
1071        return 0;
1072}
1073
1074/* help function of sysfs node to control charger(regulator) */
1075static ssize_t charger_name_show(struct device *dev,
1076                                struct device_attribute *attr, char *buf)
1077{
1078        struct charger_regulator *charger
1079                = container_of(attr, struct charger_regulator, attr_name);
1080
1081        return sprintf(buf, "%s\n", charger->regulator_name);
1082}
1083
1084static ssize_t charger_state_show(struct device *dev,
1085                                struct device_attribute *attr, char *buf)
1086{
1087        struct charger_regulator *charger
1088                = container_of(attr, struct charger_regulator, attr_state);
1089        int state = 0;
1090
1091        if (!charger->externally_control)
1092                state = regulator_is_enabled(charger->consumer);
1093
1094        return sprintf(buf, "%s\n", state ? "enabled" : "disabled");
1095}
1096
1097static ssize_t charger_externally_control_show(struct device *dev,
1098                                struct device_attribute *attr, char *buf)
1099{
1100        struct charger_regulator *charger = container_of(attr,
1101                        struct charger_regulator, attr_externally_control);
1102
1103        return sprintf(buf, "%d\n", charger->externally_control);
1104}
1105
1106static ssize_t charger_externally_control_store(struct device *dev,
1107                                struct device_attribute *attr, const char *buf,
1108                                size_t count)
1109{
1110        struct charger_regulator *charger
1111                = container_of(attr, struct charger_regulator,
1112                                        attr_externally_control);
1113        struct charger_manager *cm = charger->cm;
1114        struct charger_desc *desc = cm->desc;
1115        int i;
1116        int ret;
1117        int externally_control;
1118        int chargers_externally_control = 1;
1119
1120        ret = sscanf(buf, "%d", &externally_control);
1121        if (ret == 0) {
1122                ret = -EINVAL;
1123                return ret;
1124        }
1125
1126        if (!externally_control) {
1127                charger->externally_control = 0;
1128                return count;
1129        }
1130
1131        for (i = 0; i < desc->num_charger_regulators; i++) {
1132                if (&desc->charger_regulators[i] != charger &&
1133                        !desc->charger_regulators[i].externally_control) {
1134                        /*
1135                         * At least, one charger is controlled by
1136                         * charger-manager
1137                         */
1138                        chargers_externally_control = 0;
1139                        break;
1140                }
1141        }
1142
1143        if (!chargers_externally_control) {
1144                if (cm->charger_enabled) {
1145                        try_charger_enable(charger->cm, false);
1146                        charger->externally_control = externally_control;
1147                        try_charger_enable(charger->cm, true);
1148                } else {
1149                        charger->externally_control = externally_control;
1150                }
1151        } else {
1152                dev_warn(cm->dev,
1153                         "'%s' regulator should be controlled in charger-manager because charger-manager must need at least one charger for charging\n",
1154                         charger->regulator_name);
1155        }
1156
1157        return count;
1158}
1159
1160/**
1161 * charger_manager_prepare_sysfs - Prepare sysfs entry for each charger
1162 * @cm: the Charger Manager representing the battery.
1163 *
1164 * This function add sysfs entry for charger(regulator) to control charger from
1165 * user-space. If some development board use one more chargers for charging
1166 * but only need one charger on specific case which is dependent on user
1167 * scenario or hardware restrictions, the user enter 1 or 0(zero) to '/sys/
1168 * class/power_supply/battery/charger.[index]/externally_control'. For example,
1169 * if user enter 1 to 'sys/class/power_supply/battery/charger.[index]/
1170 * externally_control, this charger isn't controlled from charger-manager and
1171 * always stay off state of regulator.
1172 */
1173static int charger_manager_prepare_sysfs(struct charger_manager *cm)
1174{
1175        struct charger_desc *desc = cm->desc;
1176        struct charger_regulator *charger;
1177        int chargers_externally_control = 1;
1178        char *name;
1179        int i;
1180
1181        /* Create sysfs entry to control charger(regulator) */
1182        for (i = 0; i < desc->num_charger_regulators; i++) {
1183                charger = &desc->charger_regulators[i];
1184
1185                name = devm_kasprintf(cm->dev, GFP_KERNEL, "charger.%d", i);
1186                if (!name)
1187                        return -ENOMEM;
1188
1189                charger->attrs[0] = &charger->attr_name.attr;
1190                charger->attrs[1] = &charger->attr_state.attr;
1191                charger->attrs[2] = &charger->attr_externally_control.attr;
1192                charger->attrs[3] = NULL;
1193
1194                charger->attr_grp.name = name;
1195                charger->attr_grp.attrs = charger->attrs;
1196                desc->sysfs_groups[i] = &charger->attr_grp;
1197
1198                sysfs_attr_init(&charger->attr_name.attr);
1199                charger->attr_name.attr.name = "name";
1200                charger->attr_name.attr.mode = 0444;
1201                charger->attr_name.show = charger_name_show;
1202
1203                sysfs_attr_init(&charger->attr_state.attr);
1204                charger->attr_state.attr.name = "state";
1205                charger->attr_state.attr.mode = 0444;
1206                charger->attr_state.show = charger_state_show;
1207
1208                sysfs_attr_init(&charger->attr_externally_control.attr);
1209                charger->attr_externally_control.attr.name
1210                                = "externally_control";
1211                charger->attr_externally_control.attr.mode = 0644;
1212                charger->attr_externally_control.show
1213                                = charger_externally_control_show;
1214                charger->attr_externally_control.store
1215                                = charger_externally_control_store;
1216
1217                if (!desc->charger_regulators[i].externally_control ||
1218                                !chargers_externally_control)
1219                        chargers_externally_control = 0;
1220
1221                dev_info(cm->dev, "'%s' regulator's externally_control is %d\n",
1222                         charger->regulator_name, charger->externally_control);
1223        }
1224
1225        if (chargers_externally_control) {
1226                dev_err(cm->dev, "Cannot register regulator because charger-manager must need at least one charger for charging battery\n");
1227                return -EINVAL;
1228        }
1229
1230        return 0;
1231}
1232
1233static int cm_init_thermal_data(struct charger_manager *cm,
1234                struct power_supply *fuel_gauge,
1235                enum power_supply_property *properties,
1236                size_t *num_properties)
1237{
1238        struct charger_desc *desc = cm->desc;
1239        union power_supply_propval val;
1240        int ret;
1241
1242        /* Verify whether fuel gauge provides battery temperature */
1243        ret = power_supply_get_property(fuel_gauge,
1244                                        POWER_SUPPLY_PROP_TEMP, &val);
1245
1246        if (!ret) {
1247                properties[*num_properties] = POWER_SUPPLY_PROP_TEMP;
1248                (*num_properties)++;
1249                cm->desc->measure_battery_temp = true;
1250        }
1251#ifdef CONFIG_THERMAL
1252        if (ret && desc->thermal_zone) {
1253                cm->tzd_batt =
1254                        thermal_zone_get_zone_by_name(desc->thermal_zone);
1255                if (IS_ERR(cm->tzd_batt))
1256                        return PTR_ERR(cm->tzd_batt);
1257
1258                /* Use external thermometer */
1259                properties[*num_properties] = POWER_SUPPLY_PROP_TEMP;
1260                (*num_properties)++;
1261                cm->desc->measure_battery_temp = true;
1262                ret = 0;
1263        }
1264#endif
1265        if (cm->desc->measure_battery_temp) {
1266                /* NOTICE : Default allowable minimum charge temperature is 0 */
1267                if (!desc->temp_max)
1268                        desc->temp_max = CM_DEFAULT_CHARGE_TEMP_MAX;
1269                if (!desc->temp_diff)
1270                        desc->temp_diff = CM_DEFAULT_RECHARGE_TEMP_DIFF;
1271        }
1272
1273        return ret;
1274}
1275
1276static const struct of_device_id charger_manager_match[] = {
1277        {
1278                .compatible = "charger-manager",
1279        },
1280        {},
1281};
1282MODULE_DEVICE_TABLE(of, charger_manager_match);
1283
1284static struct charger_desc *of_cm_parse_desc(struct device *dev)
1285{
1286        struct charger_desc *desc;
1287        struct device_node *np = dev->of_node;
1288        u32 poll_mode = CM_POLL_DISABLE;
1289        u32 battery_stat = CM_NO_BATTERY;
1290        int num_chgs = 0;
1291
1292        desc = devm_kzalloc(dev, sizeof(*desc), GFP_KERNEL);
1293        if (!desc)
1294                return ERR_PTR(-ENOMEM);
1295
1296        of_property_read_string(np, "cm-name", &desc->psy_name);
1297
1298        of_property_read_u32(np, "cm-poll-mode", &poll_mode);
1299        desc->polling_mode = poll_mode;
1300
1301        of_property_read_u32(np, "cm-poll-interval",
1302                                &desc->polling_interval_ms);
1303
1304        of_property_read_u32(np, "cm-fullbatt-vchkdrop-volt",
1305                                        &desc->fullbatt_vchkdrop_uV);
1306        of_property_read_u32(np, "cm-fullbatt-voltage", &desc->fullbatt_uV);
1307        of_property_read_u32(np, "cm-fullbatt-soc", &desc->fullbatt_soc);
1308        of_property_read_u32(np, "cm-fullbatt-capacity",
1309                                        &desc->fullbatt_full_capacity);
1310
1311        of_property_read_u32(np, "cm-battery-stat", &battery_stat);
1312        desc->battery_present = battery_stat;
1313
1314        /* chargers */
1315        num_chgs = of_property_count_strings(np, "cm-chargers");
1316        if (num_chgs > 0) {
1317                int i;
1318
1319                /* Allocate empty bin at the tail of array */
1320                desc->psy_charger_stat = devm_kcalloc(dev,
1321                                                      num_chgs + 1,
1322                                                      sizeof(char *),
1323                                                      GFP_KERNEL);
1324                if (!desc->psy_charger_stat)
1325                        return ERR_PTR(-ENOMEM);
1326
1327                for (i = 0; i < num_chgs; i++)
1328                        of_property_read_string_index(np, "cm-chargers",
1329                                                      i, &desc->psy_charger_stat[i]);
1330        }
1331
1332        of_property_read_string(np, "cm-fuel-gauge", &desc->psy_fuel_gauge);
1333
1334        of_property_read_string(np, "cm-thermal-zone", &desc->thermal_zone);
1335
1336        of_property_read_u32(np, "cm-battery-cold", &desc->temp_min);
1337        if (of_get_property(np, "cm-battery-cold-in-minus", NULL))
1338                desc->temp_min *= -1;
1339        of_property_read_u32(np, "cm-battery-hot", &desc->temp_max);
1340        of_property_read_u32(np, "cm-battery-temp-diff", &desc->temp_diff);
1341
1342        of_property_read_u32(np, "cm-charging-max",
1343                                &desc->charging_max_duration_ms);
1344        of_property_read_u32(np, "cm-discharging-max",
1345                                &desc->discharging_max_duration_ms);
1346
1347        /* battery charger regulators */
1348        desc->num_charger_regulators = of_get_child_count(np);
1349        if (desc->num_charger_regulators) {
1350                struct charger_regulator *chg_regs;
1351                struct device_node *child;
1352
1353                chg_regs = devm_kcalloc(dev,
1354                                        desc->num_charger_regulators,
1355                                        sizeof(*chg_regs),
1356                                        GFP_KERNEL);
1357                if (!chg_regs)
1358                        return ERR_PTR(-ENOMEM);
1359
1360                desc->charger_regulators = chg_regs;
1361
1362                desc->sysfs_groups = devm_kcalloc(dev,
1363                                        desc->num_charger_regulators + 1,
1364                                        sizeof(*desc->sysfs_groups),
1365                                        GFP_KERNEL);
1366                if (!desc->sysfs_groups)
1367                        return ERR_PTR(-ENOMEM);
1368
1369                for_each_child_of_node(np, child) {
1370                        struct charger_cable *cables;
1371                        struct device_node *_child;
1372
1373                        of_property_read_string(child, "cm-regulator-name",
1374                                        &chg_regs->regulator_name);
1375
1376                        /* charger cables */
1377                        chg_regs->num_cables = of_get_child_count(child);
1378                        if (chg_regs->num_cables) {
1379                                cables = devm_kcalloc(dev,
1380                                                      chg_regs->num_cables,
1381                                                      sizeof(*cables),
1382                                                      GFP_KERNEL);
1383                                if (!cables) {
1384                                        of_node_put(child);
1385                                        return ERR_PTR(-ENOMEM);
1386                                }
1387
1388                                chg_regs->cables = cables;
1389
1390                                for_each_child_of_node(child, _child) {
1391                                        of_property_read_string(_child,
1392                                        "cm-cable-name", &cables->name);
1393                                        of_property_read_string(_child,
1394                                        "cm-cable-extcon",
1395                                        &cables->extcon_name);
1396                                        of_property_read_u32(_child,
1397                                        "cm-cable-min",
1398                                        &cables->min_uA);
1399                                        of_property_read_u32(_child,
1400                                        "cm-cable-max",
1401                                        &cables->max_uA);
1402                                        cables++;
1403                                }
1404                        }
1405                        chg_regs++;
1406                }
1407        }
1408        return desc;
1409}
1410
1411static inline struct charger_desc *cm_get_drv_data(struct platform_device *pdev)
1412{
1413        if (pdev->dev.of_node)
1414                return of_cm_parse_desc(&pdev->dev);
1415        return dev_get_platdata(&pdev->dev);
1416}
1417
1418static enum alarmtimer_restart cm_timer_func(struct alarm *alarm, ktime_t now)
1419{
1420        cm_timer_set = false;
1421        return ALARMTIMER_NORESTART;
1422}
1423
1424static int charger_manager_probe(struct platform_device *pdev)
1425{
1426        struct charger_desc *desc = cm_get_drv_data(pdev);
1427        struct charger_manager *cm;
1428        int ret, i = 0;
1429        union power_supply_propval val;
1430        struct power_supply *fuel_gauge;
1431        enum power_supply_property *properties;
1432        size_t num_properties;
1433        struct power_supply_config psy_cfg = {};
1434
1435        if (IS_ERR(desc)) {
1436                dev_err(&pdev->dev, "No platform data (desc) found\n");
1437                return PTR_ERR(desc);
1438        }
1439
1440        cm = devm_kzalloc(&pdev->dev, sizeof(*cm), GFP_KERNEL);
1441        if (!cm)
1442                return -ENOMEM;
1443
1444        /* Basic Values. Unspecified are Null or 0 */
1445        cm->dev = &pdev->dev;
1446        cm->desc = desc;
1447        psy_cfg.drv_data = cm;
1448
1449        /* Initialize alarm timer */
1450        if (alarmtimer_get_rtcdev()) {
1451                cm_timer = devm_kzalloc(cm->dev, sizeof(*cm_timer), GFP_KERNEL);
1452                if (!cm_timer)
1453                        return -ENOMEM;
1454                alarm_init(cm_timer, ALARM_BOOTTIME, cm_timer_func);
1455        }
1456
1457        /*
1458         * Some of the following do not need to be errors.
1459         * Users may intentionally ignore those features.
1460         */
1461        if (desc->fullbatt_uV == 0) {
1462                dev_info(&pdev->dev, "Ignoring full-battery voltage threshold as it is not supplied\n");
1463        }
1464        if (!desc->fullbatt_vchkdrop_uV) {
1465                dev_info(&pdev->dev, "Disabling full-battery voltage drop checking mechanism as it is not supplied\n");
1466                desc->fullbatt_vchkdrop_uV = 0;
1467        }
1468        if (desc->fullbatt_soc == 0) {
1469                dev_info(&pdev->dev, "Ignoring full-battery soc(state of charge) threshold as it is not supplied\n");
1470        }
1471        if (desc->fullbatt_full_capacity == 0) {
1472                dev_info(&pdev->dev, "Ignoring full-battery full capacity threshold as it is not supplied\n");
1473        }
1474
1475        if (!desc->charger_regulators || desc->num_charger_regulators < 1) {
1476                dev_err(&pdev->dev, "charger_regulators undefined\n");
1477                return -EINVAL;
1478        }
1479
1480        if (!desc->psy_charger_stat || !desc->psy_charger_stat[0]) {
1481                dev_err(&pdev->dev, "No power supply defined\n");
1482                return -EINVAL;
1483        }
1484
1485        if (!desc->psy_fuel_gauge) {
1486                dev_err(&pdev->dev, "No fuel gauge power supply defined\n");
1487                return -EINVAL;
1488        }
1489
1490        /* Check if charger's supplies are present at probe */
1491        for (i = 0; desc->psy_charger_stat[i]; i++) {
1492                struct power_supply *psy;
1493
1494                psy = power_supply_get_by_name(desc->psy_charger_stat[i]);
1495                if (!psy) {
1496                        dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1497                                desc->psy_charger_stat[i]);
1498                        return -ENODEV;
1499                }
1500                power_supply_put(psy);
1501        }
1502
1503        if (cm->desc->polling_mode != CM_POLL_DISABLE &&
1504            (desc->polling_interval_ms == 0 ||
1505             msecs_to_jiffies(desc->polling_interval_ms) <= CM_JIFFIES_SMALL)) {
1506                dev_err(&pdev->dev, "polling_interval_ms is too small\n");
1507                return -EINVAL;
1508        }
1509
1510        if (!desc->charging_max_duration_ms ||
1511                        !desc->discharging_max_duration_ms) {
1512                dev_info(&pdev->dev, "Cannot limit charging duration checking mechanism to prevent overcharge/overheat and control discharging duration\n");
1513                desc->charging_max_duration_ms = 0;
1514                desc->discharging_max_duration_ms = 0;
1515        }
1516
1517        platform_set_drvdata(pdev, cm);
1518
1519        memcpy(&cm->charger_psy_desc, &psy_default, sizeof(psy_default));
1520
1521        if (!desc->psy_name)
1522                strncpy(cm->psy_name_buf, psy_default.name, PSY_NAME_MAX);
1523        else
1524                strncpy(cm->psy_name_buf, desc->psy_name, PSY_NAME_MAX);
1525        cm->charger_psy_desc.name = cm->psy_name_buf;
1526
1527        /* Allocate for psy properties because they may vary */
1528        properties = devm_kcalloc(&pdev->dev,
1529                             ARRAY_SIZE(default_charger_props) +
1530                                NUM_CHARGER_PSY_OPTIONAL,
1531                             sizeof(*properties), GFP_KERNEL);
1532        if (!properties)
1533                return -ENOMEM;
1534
1535        memcpy(properties, default_charger_props,
1536                sizeof(enum power_supply_property) *
1537                ARRAY_SIZE(default_charger_props));
1538        num_properties = ARRAY_SIZE(default_charger_props);
1539
1540        /* Find which optional psy-properties are available */
1541        fuel_gauge = power_supply_get_by_name(desc->psy_fuel_gauge);
1542        if (!fuel_gauge) {
1543                dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1544                        desc->psy_fuel_gauge);
1545                return -ENODEV;
1546        }
1547        if (!power_supply_get_property(fuel_gauge,
1548                                        POWER_SUPPLY_PROP_CHARGE_FULL, &val)) {
1549                properties[num_properties] =
1550                                POWER_SUPPLY_PROP_CHARGE_FULL;
1551                num_properties++;
1552        }
1553        if (!power_supply_get_property(fuel_gauge,
1554                                          POWER_SUPPLY_PROP_CHARGE_NOW, &val)) {
1555                properties[num_properties] =
1556                                POWER_SUPPLY_PROP_CHARGE_NOW;
1557                num_properties++;
1558        }
1559        if (!power_supply_get_property(fuel_gauge,
1560                                          POWER_SUPPLY_PROP_CURRENT_NOW,
1561                                          &val)) {
1562                properties[num_properties] =
1563                                POWER_SUPPLY_PROP_CURRENT_NOW;
1564                num_properties++;
1565        }
1566
1567        ret = cm_init_thermal_data(cm, fuel_gauge, properties, &num_properties);
1568        if (ret) {
1569                dev_err(&pdev->dev, "Failed to initialize thermal data\n");
1570                cm->desc->measure_battery_temp = false;
1571        }
1572        power_supply_put(fuel_gauge);
1573
1574        cm->charger_psy_desc.properties = properties;
1575        cm->charger_psy_desc.num_properties = num_properties;
1576
1577        /* Register sysfs entry for charger(regulator) */
1578        ret = charger_manager_prepare_sysfs(cm);
1579        if (ret < 0) {
1580                dev_err(&pdev->dev,
1581                        "Cannot prepare sysfs entry of regulators\n");
1582                return ret;
1583        }
1584        psy_cfg.attr_grp = desc->sysfs_groups;
1585
1586        cm->charger_psy = power_supply_register(&pdev->dev,
1587                                                &cm->charger_psy_desc,
1588                                                &psy_cfg);
1589        if (IS_ERR(cm->charger_psy)) {
1590                dev_err(&pdev->dev, "Cannot register charger-manager with name \"%s\"\n",
1591                        cm->charger_psy_desc.name);
1592                return PTR_ERR(cm->charger_psy);
1593        }
1594
1595        /* Register extcon device for charger cable */
1596        ret = charger_manager_register_extcon(cm);
1597        if (ret < 0) {
1598                dev_err(&pdev->dev, "Cannot initialize extcon device\n");
1599                goto err_reg_extcon;
1600        }
1601
1602        /* Add to the list */
1603        mutex_lock(&cm_list_mtx);
1604        list_add(&cm->entry, &cm_list);
1605        mutex_unlock(&cm_list_mtx);
1606
1607        /*
1608         * Charger-manager is capable of waking up the system from sleep
1609         * when event is happened through cm_notify_event()
1610         */
1611        device_init_wakeup(&pdev->dev, true);
1612        device_set_wakeup_capable(&pdev->dev, false);
1613
1614        /*
1615         * Charger-manager have to check the charging state right after
1616         * initialization of charger-manager and then update current charging
1617         * state.
1618         */
1619        cm_monitor();
1620
1621        schedule_work(&setup_polling);
1622
1623        return 0;
1624
1625err_reg_extcon:
1626        for (i = 0; i < desc->num_charger_regulators; i++)
1627                regulator_put(desc->charger_regulators[i].consumer);
1628
1629        power_supply_unregister(cm->charger_psy);
1630
1631        return ret;
1632}
1633
1634static int charger_manager_remove(struct platform_device *pdev)
1635{
1636        struct charger_manager *cm = platform_get_drvdata(pdev);
1637        struct charger_desc *desc = cm->desc;
1638        int i = 0;
1639
1640        /* Remove from the list */
1641        mutex_lock(&cm_list_mtx);
1642        list_del(&cm->entry);
1643        mutex_unlock(&cm_list_mtx);
1644
1645        cancel_work_sync(&setup_polling);
1646        cancel_delayed_work_sync(&cm_monitor_work);
1647
1648        for (i = 0 ; i < desc->num_charger_regulators ; i++)
1649                regulator_put(desc->charger_regulators[i].consumer);
1650
1651        power_supply_unregister(cm->charger_psy);
1652
1653        try_charger_enable(cm, false);
1654
1655        return 0;
1656}
1657
1658static const struct platform_device_id charger_manager_id[] = {
1659        { "charger-manager", 0 },
1660        { },
1661};
1662MODULE_DEVICE_TABLE(platform, charger_manager_id);
1663
1664static int cm_suspend_noirq(struct device *dev)
1665{
1666        if (device_may_wakeup(dev)) {
1667                device_set_wakeup_capable(dev, false);
1668                return -EAGAIN;
1669        }
1670
1671        return 0;
1672}
1673
1674static bool cm_need_to_awake(void)
1675{
1676        struct charger_manager *cm;
1677
1678        if (cm_timer)
1679                return false;
1680
1681        mutex_lock(&cm_list_mtx);
1682        list_for_each_entry(cm, &cm_list, entry) {
1683                if (is_charging(cm)) {
1684                        mutex_unlock(&cm_list_mtx);
1685                        return true;
1686                }
1687        }
1688        mutex_unlock(&cm_list_mtx);
1689
1690        return false;
1691}
1692
1693static int cm_suspend_prepare(struct device *dev)
1694{
1695        if (cm_need_to_awake())
1696                return -EBUSY;
1697
1698        if (!cm_suspended)
1699                cm_suspended = true;
1700
1701        cm_timer_set = cm_setup_timer();
1702
1703        if (cm_timer_set) {
1704                cancel_work_sync(&setup_polling);
1705                cancel_delayed_work_sync(&cm_monitor_work);
1706        }
1707
1708        return 0;
1709}
1710
1711static void cm_suspend_complete(struct device *dev)
1712{
1713        struct charger_manager *cm = dev_get_drvdata(dev);
1714
1715        if (cm_suspended)
1716                cm_suspended = false;
1717
1718        if (cm_timer_set) {
1719                ktime_t remain;
1720
1721                alarm_cancel(cm_timer);
1722                cm_timer_set = false;
1723                remain = alarm_expires_remaining(cm_timer);
1724                cm_suspend_duration_ms -= ktime_to_ms(remain);
1725                schedule_work(&setup_polling);
1726        }
1727
1728        _cm_monitor(cm);
1729
1730        device_set_wakeup_capable(cm->dev, false);
1731}
1732
1733static const struct dev_pm_ops charger_manager_pm = {
1734        .prepare        = cm_suspend_prepare,
1735        .suspend_noirq  = cm_suspend_noirq,
1736        .complete       = cm_suspend_complete,
1737};
1738
1739static struct platform_driver charger_manager_driver = {
1740        .driver = {
1741                .name = "charger-manager",
1742                .pm = &charger_manager_pm,
1743                .of_match_table = charger_manager_match,
1744        },
1745        .probe = charger_manager_probe,
1746        .remove = charger_manager_remove,
1747        .id_table = charger_manager_id,
1748};
1749
1750static int __init charger_manager_init(void)
1751{
1752        cm_wq = create_freezable_workqueue("charger_manager");
1753        if (unlikely(!cm_wq))
1754                return -ENOMEM;
1755
1756        INIT_DELAYED_WORK(&cm_monitor_work, cm_monitor_poller);
1757
1758        return platform_driver_register(&charger_manager_driver);
1759}
1760late_initcall(charger_manager_init);
1761
1762static void __exit charger_manager_cleanup(void)
1763{
1764        destroy_workqueue(cm_wq);
1765        cm_wq = NULL;
1766
1767        platform_driver_unregister(&charger_manager_driver);
1768}
1769module_exit(charger_manager_cleanup);
1770
1771MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
1772MODULE_DESCRIPTION("Charger Manager");
1773MODULE_LICENSE("GPL");
1774