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 
29 static 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 
75 static LIST_HEAD(cm_list);
76 static DEFINE_MUTEX(cm_list_mtx);
77 
78 /* About in-suspend (suspend-again) monitoring */
79 static struct alarm *cm_timer;
80 
81 static bool cm_suspended;
82 static bool cm_timer_set;
83 static unsigned long cm_suspend_duration_ms;
84 
85 /* About normal (not suspended) monitoring */
86 static unsigned long polling_jiffy = ULONG_MAX; /* ULONG_MAX: no polling */
87 static unsigned long next_polling; /* Next appointed polling time */
88 static struct workqueue_struct *cm_wq; /* init at driver add */
89 static 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  */
95 static 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  */
151 static 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  */
187 static 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  */
211 static 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  */
280 static 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 
334 out:
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  */
343 static 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  */
372 static 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  */
452 static 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 
484 static 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 
502 static 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 
526 static 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  */
567 static 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 
593 charging_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  */
605 static 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  */
627 static bool cm_monitor(void)
628 {
629 	bool stop = false;
630 	struct charger_manager *cm;
631 
632 	mutex_lock(&cm_list_mtx);
633 
634 	list_for_each_entry(cm, &cm_list, entry) {
635 		if (_cm_monitor(cm))
636 			stop = true;
637 	}
638 
639 	mutex_unlock(&cm_list_mtx);
640 
641 	return stop;
642 }
643 
644 /**
645  * _setup_polling - Setup the next instance of polling.
646  * @work: work_struct of the function _setup_polling.
647  */
648 static void _setup_polling(struct work_struct *work)
649 {
650 	unsigned long min = ULONG_MAX;
651 	struct charger_manager *cm;
652 	bool keep_polling = false;
653 	unsigned long _next_polling;
654 
655 	mutex_lock(&cm_list_mtx);
656 
657 	list_for_each_entry(cm, &cm_list, entry) {
658 		if (is_polling_required(cm) && cm->desc->polling_interval_ms) {
659 			keep_polling = true;
660 
661 			if (min > cm->desc->polling_interval_ms)
662 				min = cm->desc->polling_interval_ms;
663 		}
664 	}
665 
666 	polling_jiffy = msecs_to_jiffies(min);
667 	if (polling_jiffy <= CM_JIFFIES_SMALL)
668 		polling_jiffy = CM_JIFFIES_SMALL + 1;
669 
670 	if (!keep_polling)
671 		polling_jiffy = ULONG_MAX;
672 	if (polling_jiffy == ULONG_MAX)
673 		goto out;
674 
675 	WARN(cm_wq == NULL, "charger-manager: workqueue not initialized"
676 			    ". try it later. %s\n", __func__);
677 
678 	/*
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 	}
693 out:
694 	mutex_unlock(&cm_list_mtx);
695 }
696 static 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  */
705 static void cm_monitor_poller(struct work_struct *work)
706 {
707 	cm_monitor();
708 	schedule_work(&setup_polling);
709 }
710 
711 static 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)
824 static 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 
841 static 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  */
860 static 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  */
913 static 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  */
945 static 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  */
973 static 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(cable->extcon_dev)) {
989 		pr_err("Cannot find extcon_dev for %s (cable: %s)\n",
990 			cable->extcon_name, cable->name);
991 		return PTR_ERR(cable->extcon_dev);
992 	}
993 
994 	for (i = 0; i < ARRAY_SIZE(extcon_mapping); i++) {
995 		if (!strcmp(cable->name, extcon_mapping[i].name)) {
996 			extcon_type = extcon_mapping[i].extcon_type;
997 			break;
998 		}
999 	}
1000 	if (extcon_type == EXTCON_NONE) {
1001 		pr_err("Cannot find cable for type %s", cable->name);
1002 		return -EINVAL;
1003 	}
1004 
1005 	cable->extcon_type = extcon_type;
1006 
1007 	ret = devm_extcon_register_notifier(cm->dev, cable->extcon_dev,
1008 		cable->extcon_type, &cable->nb);
1009 	if (ret < 0) {
1010 		pr_err("Cannot register extcon_dev for %s (cable: %s)\n",
1011 			cable->extcon_name, cable->name);
1012 		return ret;
1013 	}
1014 
1015 	return 0;
1016 }
1017 
1018 /**
1019  * charger_manager_register_extcon - Register extcon device to receive state
1020  *				     of charger cable.
1021  * @cm: the Charger Manager representing the battery.
1022  *
1023  * This function support EXTCON(External Connector) subsystem to detect the
1024  * state of charger cables for enabling or disabling charger(regulator) and
1025  * select the charger cable for charging among a number of external cable
1026  * according to policy of H/W board.
1027  */
1028 static int charger_manager_register_extcon(struct charger_manager *cm)
1029 {
1030 	struct charger_desc *desc = cm->desc;
1031 	struct charger_regulator *charger;
1032 	unsigned long event;
1033 	int ret;
1034 	int i;
1035 	int j;
1036 
1037 	for (i = 0; i < desc->num_charger_regulators; i++) {
1038 		charger = &desc->charger_regulators[i];
1039 
1040 		charger->consumer = regulator_get(cm->dev,
1041 					charger->regulator_name);
1042 		if (IS_ERR(charger->consumer)) {
1043 			dev_err(cm->dev, "Cannot find charger(%s)\n",
1044 				charger->regulator_name);
1045 			return PTR_ERR(charger->consumer);
1046 		}
1047 		charger->cm = cm;
1048 
1049 		for (j = 0; j < charger->num_cables; j++) {
1050 			struct charger_cable *cable = &charger->cables[j];
1051 
1052 			ret = charger_extcon_init(cm, cable);
1053 			if (ret < 0) {
1054 				dev_err(cm->dev, "Cannot initialize charger(%s)\n",
1055 					charger->regulator_name);
1056 				return ret;
1057 			}
1058 			cable->charger = charger;
1059 			cable->cm = cm;
1060 
1061 			event = extcon_get_state(cable->extcon_dev,
1062 				cable->extcon_type);
1063 			charger_extcon_notifier(&cable->nb,
1064 				event, NULL);
1065 		}
1066 	}
1067 
1068 	return 0;
1069 }
1070 
1071 /* help function of sysfs node to control charger(regulator) */
1072 static ssize_t charger_name_show(struct device *dev,
1073 				struct device_attribute *attr, char *buf)
1074 {
1075 	struct charger_regulator *charger
1076 		= container_of(attr, struct charger_regulator, attr_name);
1077 
1078 	return sprintf(buf, "%s\n", charger->regulator_name);
1079 }
1080 
1081 static ssize_t charger_state_show(struct device *dev,
1082 				struct device_attribute *attr, char *buf)
1083 {
1084 	struct charger_regulator *charger
1085 		= container_of(attr, struct charger_regulator, attr_state);
1086 	int state = 0;
1087 
1088 	if (!charger->externally_control)
1089 		state = regulator_is_enabled(charger->consumer);
1090 
1091 	return sprintf(buf, "%s\n", state ? "enabled" : "disabled");
1092 }
1093 
1094 static ssize_t charger_externally_control_show(struct device *dev,
1095 				struct device_attribute *attr, char *buf)
1096 {
1097 	struct charger_regulator *charger = container_of(attr,
1098 			struct charger_regulator, attr_externally_control);
1099 
1100 	return sprintf(buf, "%d\n", charger->externally_control);
1101 }
1102 
1103 static ssize_t charger_externally_control_store(struct device *dev,
1104 				struct device_attribute *attr, const char *buf,
1105 				size_t count)
1106 {
1107 	struct charger_regulator *charger
1108 		= container_of(attr, struct charger_regulator,
1109 					attr_externally_control);
1110 	struct charger_manager *cm = charger->cm;
1111 	struct charger_desc *desc = cm->desc;
1112 	int i;
1113 	int ret;
1114 	int externally_control;
1115 	int chargers_externally_control = 1;
1116 
1117 	ret = sscanf(buf, "%d", &externally_control);
1118 	if (ret == 0) {
1119 		ret = -EINVAL;
1120 		return ret;
1121 	}
1122 
1123 	if (!externally_control) {
1124 		charger->externally_control = 0;
1125 		return count;
1126 	}
1127 
1128 	for (i = 0; i < desc->num_charger_regulators; i++) {
1129 		if (&desc->charger_regulators[i] != charger &&
1130 			!desc->charger_regulators[i].externally_control) {
1131 			/*
1132 			 * At least, one charger is controlled by
1133 			 * charger-manager
1134 			 */
1135 			chargers_externally_control = 0;
1136 			break;
1137 		}
1138 	}
1139 
1140 	if (!chargers_externally_control) {
1141 		if (cm->charger_enabled) {
1142 			try_charger_enable(charger->cm, false);
1143 			charger->externally_control = externally_control;
1144 			try_charger_enable(charger->cm, true);
1145 		} else {
1146 			charger->externally_control = externally_control;
1147 		}
1148 	} else {
1149 		dev_warn(cm->dev,
1150 			 "'%s' regulator should be controlled in charger-manager because charger-manager must need at least one charger for charging\n",
1151 			 charger->regulator_name);
1152 	}
1153 
1154 	return count;
1155 }
1156 
1157 /**
1158  * charger_manager_prepare_sysfs - Prepare sysfs entry for each charger
1159  * @cm: the Charger Manager representing the battery.
1160  *
1161  * This function add sysfs entry for charger(regulator) to control charger from
1162  * user-space. If some development board use one more chargers for charging
1163  * but only need one charger on specific case which is dependent on user
1164  * scenario or hardware restrictions, the user enter 1 or 0(zero) to '/sys/
1165  * class/power_supply/battery/charger.[index]/externally_control'. For example,
1166  * if user enter 1 to 'sys/class/power_supply/battery/charger.[index]/
1167  * externally_control, this charger isn't controlled from charger-manager and
1168  * always stay off state of regulator.
1169  */
1170 static int charger_manager_prepare_sysfs(struct charger_manager *cm)
1171 {
1172 	struct charger_desc *desc = cm->desc;
1173 	struct charger_regulator *charger;
1174 	int chargers_externally_control = 1;
1175 	char *name;
1176 	int i;
1177 
1178 	/* Create sysfs entry to control charger(regulator) */
1179 	for (i = 0; i < desc->num_charger_regulators; i++) {
1180 		charger = &desc->charger_regulators[i];
1181 
1182 		name = devm_kasprintf(cm->dev, GFP_KERNEL, "charger.%d", i);
1183 		if (!name)
1184 			return -ENOMEM;
1185 
1186 		charger->attrs[0] = &charger->attr_name.attr;
1187 		charger->attrs[1] = &charger->attr_state.attr;
1188 		charger->attrs[2] = &charger->attr_externally_control.attr;
1189 		charger->attrs[3] = NULL;
1190 
1191 		charger->attr_grp.name = name;
1192 		charger->attr_grp.attrs = charger->attrs;
1193 		desc->sysfs_groups[i] = &charger->attr_grp;
1194 
1195 		sysfs_attr_init(&charger->attr_name.attr);
1196 		charger->attr_name.attr.name = "name";
1197 		charger->attr_name.attr.mode = 0444;
1198 		charger->attr_name.show = charger_name_show;
1199 
1200 		sysfs_attr_init(&charger->attr_state.attr);
1201 		charger->attr_state.attr.name = "state";
1202 		charger->attr_state.attr.mode = 0444;
1203 		charger->attr_state.show = charger_state_show;
1204 
1205 		sysfs_attr_init(&charger->attr_externally_control.attr);
1206 		charger->attr_externally_control.attr.name
1207 				= "externally_control";
1208 		charger->attr_externally_control.attr.mode = 0644;
1209 		charger->attr_externally_control.show
1210 				= charger_externally_control_show;
1211 		charger->attr_externally_control.store
1212 				= charger_externally_control_store;
1213 
1214 		if (!desc->charger_regulators[i].externally_control ||
1215 				!chargers_externally_control)
1216 			chargers_externally_control = 0;
1217 
1218 		dev_info(cm->dev, "'%s' regulator's externally_control is %d\n",
1219 			 charger->regulator_name, charger->externally_control);
1220 	}
1221 
1222 	if (chargers_externally_control) {
1223 		dev_err(cm->dev, "Cannot register regulator because charger-manager must need at least one charger for charging battery\n");
1224 		return -EINVAL;
1225 	}
1226 
1227 	return 0;
1228 }
1229 
1230 static int cm_init_thermal_data(struct charger_manager *cm,
1231 		struct power_supply *fuel_gauge,
1232 		enum power_supply_property *properties,
1233 		size_t *num_properties)
1234 {
1235 	struct charger_desc *desc = cm->desc;
1236 	union power_supply_propval val;
1237 	int ret;
1238 
1239 	/* Verify whether fuel gauge provides battery temperature */
1240 	ret = power_supply_get_property(fuel_gauge,
1241 					POWER_SUPPLY_PROP_TEMP, &val);
1242 
1243 	if (!ret) {
1244 		properties[*num_properties] = POWER_SUPPLY_PROP_TEMP;
1245 		(*num_properties)++;
1246 		cm->desc->measure_battery_temp = true;
1247 	}
1248 #ifdef CONFIG_THERMAL
1249 	if (ret && desc->thermal_zone) {
1250 		cm->tzd_batt =
1251 			thermal_zone_get_zone_by_name(desc->thermal_zone);
1252 		if (IS_ERR(cm->tzd_batt))
1253 			return PTR_ERR(cm->tzd_batt);
1254 
1255 		/* Use external thermometer */
1256 		properties[*num_properties] = POWER_SUPPLY_PROP_TEMP;
1257 		(*num_properties)++;
1258 		cm->desc->measure_battery_temp = true;
1259 		ret = 0;
1260 	}
1261 #endif
1262 	if (cm->desc->measure_battery_temp) {
1263 		/* NOTICE : Default allowable minimum charge temperature is 0 */
1264 		if (!desc->temp_max)
1265 			desc->temp_max = CM_DEFAULT_CHARGE_TEMP_MAX;
1266 		if (!desc->temp_diff)
1267 			desc->temp_diff = CM_DEFAULT_RECHARGE_TEMP_DIFF;
1268 	}
1269 
1270 	return ret;
1271 }
1272 
1273 static const struct of_device_id charger_manager_match[] = {
1274 	{
1275 		.compatible = "charger-manager",
1276 	},
1277 	{},
1278 };
1279 MODULE_DEVICE_TABLE(of, charger_manager_match);
1280 
1281 static struct charger_desc *of_cm_parse_desc(struct device *dev)
1282 {
1283 	struct charger_desc *desc;
1284 	struct device_node *np = dev->of_node;
1285 	u32 poll_mode = CM_POLL_DISABLE;
1286 	u32 battery_stat = CM_NO_BATTERY;
1287 	int num_chgs = 0;
1288 
1289 	desc = devm_kzalloc(dev, sizeof(*desc), GFP_KERNEL);
1290 	if (!desc)
1291 		return ERR_PTR(-ENOMEM);
1292 
1293 	of_property_read_string(np, "cm-name", &desc->psy_name);
1294 
1295 	of_property_read_u32(np, "cm-poll-mode", &poll_mode);
1296 	desc->polling_mode = poll_mode;
1297 
1298 	of_property_read_u32(np, "cm-poll-interval",
1299 				&desc->polling_interval_ms);
1300 
1301 	of_property_read_u32(np, "cm-fullbatt-vchkdrop-volt",
1302 					&desc->fullbatt_vchkdrop_uV);
1303 	of_property_read_u32(np, "cm-fullbatt-voltage", &desc->fullbatt_uV);
1304 	of_property_read_u32(np, "cm-fullbatt-soc", &desc->fullbatt_soc);
1305 	of_property_read_u32(np, "cm-fullbatt-capacity",
1306 					&desc->fullbatt_full_capacity);
1307 
1308 	of_property_read_u32(np, "cm-battery-stat", &battery_stat);
1309 	desc->battery_present = battery_stat;
1310 
1311 	/* chargers */
1312 	num_chgs = of_property_count_strings(np, "cm-chargers");
1313 	if (num_chgs > 0) {
1314 		int i;
1315 
1316 		/* Allocate empty bin at the tail of array */
1317 		desc->psy_charger_stat = devm_kcalloc(dev,
1318 						      num_chgs + 1,
1319 						      sizeof(char *),
1320 						      GFP_KERNEL);
1321 		if (!desc->psy_charger_stat)
1322 			return ERR_PTR(-ENOMEM);
1323 
1324 		for (i = 0; i < num_chgs; i++)
1325 			of_property_read_string_index(np, "cm-chargers",
1326 						      i, &desc->psy_charger_stat[i]);
1327 	}
1328 
1329 	of_property_read_string(np, "cm-fuel-gauge", &desc->psy_fuel_gauge);
1330 
1331 	of_property_read_string(np, "cm-thermal-zone", &desc->thermal_zone);
1332 
1333 	of_property_read_u32(np, "cm-battery-cold", &desc->temp_min);
1334 	if (of_get_property(np, "cm-battery-cold-in-minus", NULL))
1335 		desc->temp_min *= -1;
1336 	of_property_read_u32(np, "cm-battery-hot", &desc->temp_max);
1337 	of_property_read_u32(np, "cm-battery-temp-diff", &desc->temp_diff);
1338 
1339 	of_property_read_u32(np, "cm-charging-max",
1340 				&desc->charging_max_duration_ms);
1341 	of_property_read_u32(np, "cm-discharging-max",
1342 				&desc->discharging_max_duration_ms);
1343 
1344 	/* battery charger regulators */
1345 	desc->num_charger_regulators = of_get_child_count(np);
1346 	if (desc->num_charger_regulators) {
1347 		struct charger_regulator *chg_regs;
1348 		struct device_node *child;
1349 
1350 		chg_regs = devm_kcalloc(dev,
1351 					desc->num_charger_regulators,
1352 					sizeof(*chg_regs),
1353 					GFP_KERNEL);
1354 		if (!chg_regs)
1355 			return ERR_PTR(-ENOMEM);
1356 
1357 		desc->charger_regulators = chg_regs;
1358 
1359 		desc->sysfs_groups = devm_kcalloc(dev,
1360 					desc->num_charger_regulators + 1,
1361 					sizeof(*desc->sysfs_groups),
1362 					GFP_KERNEL);
1363 		if (!desc->sysfs_groups)
1364 			return ERR_PTR(-ENOMEM);
1365 
1366 		for_each_child_of_node(np, child) {
1367 			struct charger_cable *cables;
1368 			struct device_node *_child;
1369 
1370 			of_property_read_string(child, "cm-regulator-name",
1371 					&chg_regs->regulator_name);
1372 
1373 			/* charger cables */
1374 			chg_regs->num_cables = of_get_child_count(child);
1375 			if (chg_regs->num_cables) {
1376 				cables = devm_kcalloc(dev,
1377 						      chg_regs->num_cables,
1378 						      sizeof(*cables),
1379 						      GFP_KERNEL);
1380 				if (!cables) {
1381 					of_node_put(child);
1382 					return ERR_PTR(-ENOMEM);
1383 				}
1384 
1385 				chg_regs->cables = cables;
1386 
1387 				for_each_child_of_node(child, _child) {
1388 					of_property_read_string(_child,
1389 					"cm-cable-name", &cables->name);
1390 					of_property_read_string(_child,
1391 					"cm-cable-extcon",
1392 					&cables->extcon_name);
1393 					of_property_read_u32(_child,
1394 					"cm-cable-min",
1395 					&cables->min_uA);
1396 					of_property_read_u32(_child,
1397 					"cm-cable-max",
1398 					&cables->max_uA);
1399 					cables++;
1400 				}
1401 			}
1402 			chg_regs++;
1403 		}
1404 	}
1405 	return desc;
1406 }
1407 
1408 static inline struct charger_desc *cm_get_drv_data(struct platform_device *pdev)
1409 {
1410 	if (pdev->dev.of_node)
1411 		return of_cm_parse_desc(&pdev->dev);
1412 	return dev_get_platdata(&pdev->dev);
1413 }
1414 
1415 static enum alarmtimer_restart cm_timer_func(struct alarm *alarm, ktime_t now)
1416 {
1417 	cm_timer_set = false;
1418 	return ALARMTIMER_NORESTART;
1419 }
1420 
1421 static 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 		strncpy(cm->psy_name_buf, psy_default.name, PSY_NAME_MAX);
1520 	else
1521 		strncpy(cm->psy_name_buf, desc->psy_name, PSY_NAME_MAX);
1522 	cm->charger_psy_desc.name = cm->psy_name_buf;
1523 
1524 	/* Allocate for psy properties because they may vary */
1525 	properties = devm_kcalloc(&pdev->dev,
1526 			     ARRAY_SIZE(default_charger_props) +
1527 				NUM_CHARGER_PSY_OPTIONAL,
1528 			     sizeof(*properties), GFP_KERNEL);
1529 	if (!properties)
1530 		return -ENOMEM;
1531 
1532 	memcpy(properties, default_charger_props,
1533 		sizeof(enum power_supply_property) *
1534 		ARRAY_SIZE(default_charger_props));
1535 	num_properties = ARRAY_SIZE(default_charger_props);
1536 
1537 	/* Find which optional psy-properties are available */
1538 	fuel_gauge = power_supply_get_by_name(desc->psy_fuel_gauge);
1539 	if (!fuel_gauge) {
1540 		dev_err(&pdev->dev, "Cannot find power supply \"%s\"\n",
1541 			desc->psy_fuel_gauge);
1542 		return -ENODEV;
1543 	}
1544 	if (!power_supply_get_property(fuel_gauge,
1545 					POWER_SUPPLY_PROP_CHARGE_FULL, &val)) {
1546 		properties[num_properties] =
1547 				POWER_SUPPLY_PROP_CHARGE_FULL;
1548 		num_properties++;
1549 	}
1550 	if (!power_supply_get_property(fuel_gauge,
1551 					  POWER_SUPPLY_PROP_CHARGE_NOW, &val)) {
1552 		properties[num_properties] =
1553 				POWER_SUPPLY_PROP_CHARGE_NOW;
1554 		num_properties++;
1555 	}
1556 	if (!power_supply_get_property(fuel_gauge,
1557 					  POWER_SUPPLY_PROP_CURRENT_NOW,
1558 					  &val)) {
1559 		properties[num_properties] =
1560 				POWER_SUPPLY_PROP_CURRENT_NOW;
1561 		num_properties++;
1562 	}
1563 
1564 	ret = cm_init_thermal_data(cm, fuel_gauge, properties, &num_properties);
1565 	if (ret) {
1566 		dev_err(&pdev->dev, "Failed to initialize thermal data\n");
1567 		cm->desc->measure_battery_temp = false;
1568 	}
1569 	power_supply_put(fuel_gauge);
1570 
1571 	cm->charger_psy_desc.properties = properties;
1572 	cm->charger_psy_desc.num_properties = num_properties;
1573 
1574 	/* Register sysfs entry for charger(regulator) */
1575 	ret = charger_manager_prepare_sysfs(cm);
1576 	if (ret < 0) {
1577 		dev_err(&pdev->dev,
1578 			"Cannot prepare sysfs entry of regulators\n");
1579 		return ret;
1580 	}
1581 	psy_cfg.attr_grp = desc->sysfs_groups;
1582 
1583 	cm->charger_psy = power_supply_register(&pdev->dev,
1584 						&cm->charger_psy_desc,
1585 						&psy_cfg);
1586 	if (IS_ERR(cm->charger_psy)) {
1587 		dev_err(&pdev->dev, "Cannot register charger-manager with name \"%s\"\n",
1588 			cm->charger_psy_desc.name);
1589 		return PTR_ERR(cm->charger_psy);
1590 	}
1591 
1592 	/* Register extcon device for charger cable */
1593 	ret = charger_manager_register_extcon(cm);
1594 	if (ret < 0) {
1595 		dev_err(&pdev->dev, "Cannot initialize extcon device\n");
1596 		goto err_reg_extcon;
1597 	}
1598 
1599 	/* Add to the list */
1600 	mutex_lock(&cm_list_mtx);
1601 	list_add(&cm->entry, &cm_list);
1602 	mutex_unlock(&cm_list_mtx);
1603 
1604 	/*
1605 	 * Charger-manager is capable of waking up the system from sleep
1606 	 * when event is happened through cm_notify_event()
1607 	 */
1608 	device_init_wakeup(&pdev->dev, true);
1609 	device_set_wakeup_capable(&pdev->dev, false);
1610 
1611 	/*
1612 	 * Charger-manager have to check the charging state right after
1613 	 * initialization of charger-manager and then update current charging
1614 	 * state.
1615 	 */
1616 	cm_monitor();
1617 
1618 	schedule_work(&setup_polling);
1619 
1620 	return 0;
1621 
1622 err_reg_extcon:
1623 	for (i = 0; i < desc->num_charger_regulators; i++)
1624 		regulator_put(desc->charger_regulators[i].consumer);
1625 
1626 	power_supply_unregister(cm->charger_psy);
1627 
1628 	return ret;
1629 }
1630 
1631 static int charger_manager_remove(struct platform_device *pdev)
1632 {
1633 	struct charger_manager *cm = platform_get_drvdata(pdev);
1634 	struct charger_desc *desc = cm->desc;
1635 	int i = 0;
1636 
1637 	/* Remove from the list */
1638 	mutex_lock(&cm_list_mtx);
1639 	list_del(&cm->entry);
1640 	mutex_unlock(&cm_list_mtx);
1641 
1642 	cancel_work_sync(&setup_polling);
1643 	cancel_delayed_work_sync(&cm_monitor_work);
1644 
1645 	for (i = 0 ; i < desc->num_charger_regulators ; i++)
1646 		regulator_put(desc->charger_regulators[i].consumer);
1647 
1648 	power_supply_unregister(cm->charger_psy);
1649 
1650 	try_charger_enable(cm, false);
1651 
1652 	return 0;
1653 }
1654 
1655 static const struct platform_device_id charger_manager_id[] = {
1656 	{ "charger-manager", 0 },
1657 	{ },
1658 };
1659 MODULE_DEVICE_TABLE(platform, charger_manager_id);
1660 
1661 static 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 
1671 static 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 
1690 static 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 
1708 static 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 
1730 static 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 
1736 static 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 
1747 static 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 }
1757 late_initcall(charger_manager_init);
1758 
1759 static 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 }
1766 module_exit(charger_manager_cleanup);
1767 
1768 MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
1769 MODULE_DESCRIPTION("Charger Manager");
1770 MODULE_LICENSE("GPL");
1771