File Index
Files and directories
Sign in
FILE

charger-manager.c

File preview with syntax highlighting.

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