power_supply_core.c 33.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 *  Universal power supply monitor class
 *
 *  Copyright © 2007  Anton Vorontsov <cbou@mail.ru>
 *  Copyright © 2004  Szabolcs Gyurko
 *  Copyright © 2003  Ian Molton <spyro@f2s.com>
 *
 *  Modified: 2004, Oct     Szabolcs Gyurko
 *
 *  You may use this code as per GPL version 2
 */

#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
16
#include <linux/slab.h>
17
#include <linux/delay.h>
18
#include <linux/device.h>
19
#include <linux/notifier.h>
20
#include <linux/err.h>
21
#include <linux/of.h>
22
#include <linux/power_supply.h>
23
#include <linux/property.h>
24
#include <linux/thermal.h>
25 26
#include "power_supply.h"

27
/* exported for the APM Power driver, APM emulation */
28
struct class *power_supply_class;
29
EXPORT_SYMBOL_GPL(power_supply_class);
30

31 32 33
ATOMIC_NOTIFIER_HEAD(power_supply_notifier);
EXPORT_SYMBOL_GPL(power_supply_notifier);

34 35
static struct device_type power_supply_dev_type;

36 37
#define POWER_SUPPLY_DEFERRED_REGISTER_TIME	msecs_to_jiffies(10)

38 39 40 41 42 43 44 45 46 47
static bool __power_supply_is_supplied_by(struct power_supply *supplier,
					 struct power_supply *supply)
{
	int i;

	if (!supply->supplied_from && !supplier->supplied_to)
		return false;

	/* Support both supplied_to and supplied_from modes */
	if (supply->supplied_from) {
48
		if (!supplier->desc->name)
49 50
			return false;
		for (i = 0; i < supply->num_supplies; i++)
51
			if (!strcmp(supplier->desc->name, supply->supplied_from[i]))
52 53
				return true;
	} else {
54
		if (!supply->desc->name)
55 56
			return false;
		for (i = 0; i < supplier->num_supplicants; i++)
57
			if (!strcmp(supplier->supplied_to[i], supply->desc->name))
58 59 60 61 62 63
				return true;
	}

	return false;
}

64 65
static int __power_supply_changed_work(struct device *dev, void *data)
{
66
	struct power_supply *psy = data;
67 68
	struct power_supply *pst = dev_get_drvdata(dev);

69
	if (__power_supply_is_supplied_by(psy, pst)) {
70 71
		if (pst->desc->external_power_changed)
			pst->desc->external_power_changed(pst);
72 73
	}

74 75 76
	return 0;
}

77 78
static void power_supply_changed_work(struct work_struct *work)
{
79
	unsigned long flags;
80 81 82
	struct power_supply *psy = container_of(work, struct power_supply,
						changed_work);

83
	dev_dbg(&psy->dev, "%s\n", __func__);
84

85
	spin_lock_irqsave(&psy->changed_lock, flags);
86 87 88 89 90 91 92 93
	/*
	 * Check 'changed' here to avoid issues due to race between
	 * power_supply_changed() and this routine. In worst case
	 * power_supply_changed() can be called again just before we take above
	 * lock. During the first call of this routine we will mark 'changed' as
	 * false and it will stay false for the next call as well.
	 */
	if (likely(psy->changed)) {
94 95 96 97 98
		psy->changed = false;
		spin_unlock_irqrestore(&psy->changed_lock, flags);
		class_for_each_device(power_supply_class, NULL, psy,
				      __power_supply_changed_work);
		power_supply_update_leds(psy);
99 100
		atomic_notifier_call_chain(&power_supply_notifier,
				PSY_EVENT_PROP_CHANGED, psy);
101
		kobject_uevent(&psy->dev.kobj, KOBJ_CHANGE);
102 103
		spin_lock_irqsave(&psy->changed_lock, flags);
	}
104

105
	/*
106 107 108
	 * Hold the wakeup_source until all events are processed.
	 * power_supply_changed() might have called again and have set 'changed'
	 * to true.
109
	 */
110
	if (likely(!psy->changed))
111
		pm_relax(&psy->dev);
112
	spin_unlock_irqrestore(&psy->changed_lock, flags);
113 114 115 116
}

void power_supply_changed(struct power_supply *psy)
{
117 118
	unsigned long flags;

119
	dev_dbg(&psy->dev, "%s\n", __func__);
120

121 122
	spin_lock_irqsave(&psy->changed_lock, flags);
	psy->changed = true;
123
	pm_stay_awake(&psy->dev);
124
	spin_unlock_irqrestore(&psy->changed_lock, flags);
125 126
	schedule_work(&psy->changed_work);
}
127
EXPORT_SYMBOL_GPL(power_supply_changed);
128

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
/*
 * Notify that power supply was registered after parent finished the probing.
 *
 * Often power supply is registered from driver's probe function. However
 * calling power_supply_changed() directly from power_supply_register()
 * would lead to execution of get_property() function provided by the driver
 * too early - before the probe ends.
 *
 * Avoid that by waiting on parent's mutex.
 */
static void power_supply_deferred_register_work(struct work_struct *work)
{
	struct power_supply *psy = container_of(work, struct power_supply,
						deferred_register_work.work);

144 145 146 147 148 149 150
	if (psy->dev.parent) {
		while (!mutex_trylock(&psy->dev.parent->mutex)) {
			if (psy->removing)
				return;
			msleep(10);
		}
	}
151 152 153 154 155 156 157

	power_supply_changed(psy);

	if (psy->dev.parent)
		mutex_unlock(&psy->dev.parent->mutex);
}

158 159 160 161
#ifdef CONFIG_OF
static int __power_supply_populate_supplied_from(struct device *dev,
						 void *data)
{
162
	struct power_supply *psy = data;
163 164 165 166 167 168 169
	struct power_supply *epsy = dev_get_drvdata(dev);
	struct device_node *np;
	int i = 0;

	do {
		np = of_parse_phandle(psy->of_node, "power-supplies", i++);
		if (!np)
170
			break;
171 172

		if (np == epsy->of_node) {
173 174 175
			dev_info(&psy->dev, "%s: Found supply : %s\n",
				psy->desc->name, epsy->desc->name);
			psy->supplied_from[i-1] = (char *)epsy->desc->name;
176
			psy->num_supplies++;
177
			of_node_put(np);
178 179
			break;
		}
180
		of_node_put(np);
181 182 183 184 185 186 187 188 189 190 191 192
	} while (np);

	return 0;
}

static int power_supply_populate_supplied_from(struct power_supply *psy)
{
	int error;

	error = class_for_each_device(power_supply_class, NULL, psy,
				      __power_supply_populate_supplied_from);

193
	dev_dbg(&psy->dev, "%s %d\n", __func__, error);
194 195 196 197 198 199 200

	return error;
}

static int  __power_supply_find_supply_from_node(struct device *dev,
						 void *data)
{
201
	struct device_node *np = data;
202 203
	struct power_supply *epsy = dev_get_drvdata(dev);

204
	/* returning non-zero breaks out of class_for_each_device loop */
205
	if (epsy->of_node == np)
206
		return 1;
207 208 209 210 211 212 213 214 215

	return 0;
}

static int power_supply_find_supply_from_node(struct device_node *supply_node)
{
	int error;

	/*
216 217 218 219 220 221 222 223
	 * class_for_each_device() either returns its own errors or values
	 * returned by __power_supply_find_supply_from_node().
	 *
	 * __power_supply_find_supply_from_node() will return 0 (no match)
	 * or 1 (match).
	 *
	 * We return 0 if class_for_each_device() returned 1, -EPROBE_DEFER if
	 * it returned 0, or error as returned by it.
224 225 226 227
	 */
	error = class_for_each_device(power_supply_class, NULL, supply_node,
				       __power_supply_find_supply_from_node);

228
	return error ? (error == 1 ? 0 : error) : -EPROBE_DEFER;
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
}

static int power_supply_check_supplies(struct power_supply *psy)
{
	struct device_node *np;
	int cnt = 0;

	/* If there is already a list honor it */
	if (psy->supplied_from && psy->num_supplies > 0)
		return 0;

	/* No device node found, nothing to do */
	if (!psy->of_node)
		return 0;

	do {
		int ret;

		np = of_parse_phandle(psy->of_node, "power-supplies", cnt++);
		if (!np)
249
			break;
250 251

		ret = power_supply_find_supply_from_node(np);
252 253
		of_node_put(np);

254
		if (ret) {
255
			dev_dbg(&psy->dev, "Failed to find supply!\n");
256
			return ret;
257 258 259
		}
	} while (np);

260 261 262 263
	/* Missing valid "power-supplies" entries */
	if (cnt == 1)
		return 0;

264
	/* All supplies found, allocate char ** array for filling */
265
	psy->supplied_from = devm_kzalloc(&psy->dev, sizeof(psy->supplied_from),
266
					  GFP_KERNEL);
267
	if (!psy->supplied_from)
268 269
		return -ENOMEM;

270 271
	*psy->supplied_from = devm_kcalloc(&psy->dev,
					   cnt - 1, sizeof(char *),
272
					   GFP_KERNEL);
273
	if (!*psy->supplied_from)
274 275 276 277 278
		return -ENOMEM;

	return power_supply_populate_supplied_from(psy);
}
#else
279
static int power_supply_check_supplies(struct power_supply *psy)
280
{
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	int nval, ret;

	if (!psy->dev.parent)
		return 0;

	nval = device_property_read_string_array(psy->dev.parent,
						 "supplied-from", NULL, 0);
	if (nval <= 0)
		return 0;

	psy->supplied_from = devm_kmalloc_array(&psy->dev, nval,
						sizeof(char *), GFP_KERNEL);
	if (!psy->supplied_from)
		return -ENOMEM;

	ret = device_property_read_string_array(psy->dev.parent,
		"supplied-from", (const char **)psy->supplied_from, nval);
	if (ret < 0)
		return ret;

	psy->num_supplies = nval;

303 304 305 306
	return 0;
}
#endif

307 308 309 310 311 312
struct psy_am_i_supplied_data {
	struct power_supply *psy;
	unsigned int count;
};

static int __power_supply_am_i_supplied(struct device *dev, void *_data)
313 314
{
	union power_supply_propval ret = {0,};
315
	struct power_supply *epsy = dev_get_drvdata(dev);
316
	struct psy_am_i_supplied_data *data = _data;
317

318 319
	if (__power_supply_is_supplied_by(epsy, data->psy)) {
		data->count++;
320 321
		if (!epsy->desc->get_property(epsy, POWER_SUPPLY_PROP_ONLINE,
					&ret))
322
			return ret.intval;
323
	}
324

325 326 327 328 329
	return 0;
}

int power_supply_am_i_supplied(struct power_supply *psy)
{
330
	struct psy_am_i_supplied_data data = { psy, 0 };
331 332
	int error;

333
	error = class_for_each_device(power_supply_class, NULL, &data,
334
				      __power_supply_am_i_supplied);
335

336 337 338 339
	dev_dbg(&psy->dev, "%s count %u err %d\n", __func__, data.count, error);

	if (data.count == 0)
		return -ENODEV;
340

341
	return error;
342
}
343
EXPORT_SYMBOL_GPL(power_supply_am_i_supplied);
344

345 346 347 348
static int __power_supply_is_system_supplied(struct device *dev, void *data)
{
	union power_supply_propval ret = {0,};
	struct power_supply *psy = dev_get_drvdata(dev);
349
	unsigned int *count = data;
350

351
	(*count)++;
352 353 354
	if (psy->desc->type != POWER_SUPPLY_TYPE_BATTERY)
		if (!psy->desc->get_property(psy, POWER_SUPPLY_PROP_ONLINE,
					&ret))
355
			return ret.intval;
356

357 358 359 360 361 362
	return 0;
}

int power_supply_is_system_supplied(void)
{
	int error;
363
	unsigned int count = 0;
364

365
	error = class_for_each_device(power_supply_class, NULL, &count,
366 367
				      __power_supply_is_system_supplied);

368 369 370 371 372 373 374
	/*
	 * If no power class device was found at all, most probably we are
	 * running on a desktop system, so assume we are on mains power.
	 */
	if (count == 0)
		return 1;

375 376
	return error;
}
377
EXPORT_SYMBOL_GPL(power_supply_is_system_supplied);
378

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
static int __power_supply_get_supplier_max_current(struct device *dev,
						   void *data)
{
	union power_supply_propval ret = {0,};
	struct power_supply *epsy = dev_get_drvdata(dev);
	struct power_supply *psy = data;

	if (__power_supply_is_supplied_by(epsy, psy))
		if (!epsy->desc->get_property(epsy,
					      POWER_SUPPLY_PROP_CURRENT_MAX,
					      &ret))
			return ret.intval;

	return 0;
}

int power_supply_set_input_current_limit_from_supplier(struct power_supply *psy)
{
	union power_supply_propval val = {0,};
	int curr;

	if (!psy->desc->set_property)
		return -EINVAL;

	/*
	 * This function is not intended for use with a supply with multiple
	 * suppliers, we simply pick the first supply to report a non 0
	 * max-current.
	 */
	curr = class_for_each_device(power_supply_class, NULL, psy,
				      __power_supply_get_supplier_max_current);
	if (curr <= 0)
		return (curr == 0) ? -ENODEV : curr;

	val.intval = curr;

	return psy->desc->set_property(psy,
				POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &val);
}
EXPORT_SYMBOL_GPL(power_supply_set_input_current_limit_from_supplier);

420 421
int power_supply_set_battery_charged(struct power_supply *psy)
{
422
	if (atomic_read(&psy->use_cnt) >= 0 &&
423 424 425
			psy->desc->type == POWER_SUPPLY_TYPE_BATTERY &&
			psy->desc->set_charged) {
		psy->desc->set_charged(psy);
426 427 428 429 430 431 432
		return 0;
	}

	return -EINVAL;
}
EXPORT_SYMBOL_GPL(power_supply_set_battery_charged);

433
static int power_supply_match_device_by_name(struct device *dev, const void *data)
434 435 436 437
{
	const char *name = data;
	struct power_supply *psy = dev_get_drvdata(dev);

438
	return strcmp(psy->desc->name, name) == 0;
439 440
}

441 442 443 444 445 446 447 448 449 450 451
/**
 * power_supply_get_by_name() - Search for a power supply and returns its ref
 * @name: Power supply name to fetch
 *
 * If power supply was found, it increases reference count for the
 * internal power supply's device. The user should power_supply_put()
 * after usage.
 *
 * Return: On success returns a reference to a power supply with
 * matching name equals to @name, a NULL otherwise.
 */
452
struct power_supply *power_supply_get_by_name(const char *name)
453
{
454
	struct power_supply *psy = NULL;
455 456 457
	struct device *dev = class_find_device(power_supply_class, NULL, name,
					power_supply_match_device_by_name);

458 459 460 461 462 463
	if (dev) {
		psy = dev_get_drvdata(dev);
		atomic_inc(&psy->use_cnt);
	}

	return psy;
464 465 466
}
EXPORT_SYMBOL_GPL(power_supply_get_by_name);

467 468 469 470 471 472 473 474 475 476 477
/**
 * power_supply_put() - Drop reference obtained with power_supply_get_by_name
 * @psy: Reference to put
 *
 * The reference to power supply should be put before unregistering
 * the power supply.
 */
void power_supply_put(struct power_supply *psy)
{
	might_sleep();

478
	atomic_dec(&psy->use_cnt);
479 480 481 482
	put_device(&psy->dev);
}
EXPORT_SYMBOL_GPL(power_supply_put);

483 484 485 486 487 488
#ifdef CONFIG_OF
static int power_supply_match_device_node(struct device *dev, const void *data)
{
	return dev->parent && dev->parent->of_node == data;
}

489 490 491
/**
 * power_supply_get_by_phandle() - Search for a power supply and returns its ref
 * @np: Pointer to device node holding phandle property
492
 * @property: Name of property holding a power supply name
493 494 495 496 497 498 499 500
 *
 * If power supply was found, it increases reference count for the
 * internal power supply's device. The user should power_supply_put()
 * after usage.
 *
 * Return: On success returns a reference to a power supply with
 * matching name equals to value under @property, NULL or ERR_PTR otherwise.
 */
501 502 503 504
struct power_supply *power_supply_get_by_phandle(struct device_node *np,
							const char *property)
{
	struct device_node *power_supply_np;
505
	struct power_supply *psy = NULL;
506 507 508 509 510 511 512 513 514 515 516
	struct device *dev;

	power_supply_np = of_parse_phandle(np, property, 0);
	if (!power_supply_np)
		return ERR_PTR(-ENODEV);

	dev = class_find_device(power_supply_class, NULL, power_supply_np,
						power_supply_match_device_node);

	of_node_put(power_supply_np);

517 518 519 520 521 522
	if (dev) {
		psy = dev_get_drvdata(dev);
		atomic_inc(&psy->use_cnt);
	}

	return psy;
523 524
}
EXPORT_SYMBOL_GPL(power_supply_get_by_phandle);
525 526 527 528 529 530 531 532 533 534 535 536

static void devm_power_supply_put(struct device *dev, void *res)
{
	struct power_supply **psy = res;

	power_supply_put(*psy);
}

/**
 * devm_power_supply_get_by_phandle() - Resource managed version of
 *  power_supply_get_by_phandle()
 * @dev: Pointer to device holding phandle property
537
 * @property: Name of property holding a power supply phandle
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
 *
 * Return: On success returns a reference to a power supply with
 * matching name equals to value under @property, NULL or ERR_PTR otherwise.
 */
struct power_supply *devm_power_supply_get_by_phandle(struct device *dev,
						      const char *property)
{
	struct power_supply **ptr, *psy;

	if (!dev->of_node)
		return ERR_PTR(-ENODEV);

	ptr = devres_alloc(devm_power_supply_put, sizeof(*ptr), GFP_KERNEL);
	if (!ptr)
		return ERR_PTR(-ENOMEM);

	psy = power_supply_get_by_phandle(dev->of_node, property);
	if (IS_ERR_OR_NULL(psy)) {
		devres_free(ptr);
	} else {
		*ptr = psy;
		devres_add(dev, ptr);
	}
	return psy;
}
EXPORT_SYMBOL_GPL(devm_power_supply_get_by_phandle);
564 565
#endif /* CONFIG_OF */

566 567 568 569 570
int power_supply_get_battery_info(struct power_supply *psy,
				  struct power_supply_battery_info *info)
{
	struct device_node *battery_np;
	const char *value;
571
	int err, len, index;
572 573 574 575

	info->energy_full_design_uwh         = -EINVAL;
	info->charge_full_design_uah         = -EINVAL;
	info->voltage_min_design_uv          = -EINVAL;
576
	info->voltage_max_design_uv          = -EINVAL;
577 578 579 580
	info->precharge_current_ua           = -EINVAL;
	info->charge_term_current_ua         = -EINVAL;
	info->constant_charge_current_max_ua = -EINVAL;
	info->constant_charge_voltage_max_uv = -EINVAL;
581
	info->factory_internal_resistance_uohm  = -EINVAL;
582

583 584 585 586 587 588
	for (index = 0; index < POWER_SUPPLY_OCV_TEMP_MAX; index++) {
		info->ocv_table[index]       = NULL;
		info->ocv_temp[index]        = -EINVAL;
		info->ocv_table_size[index]  = -EINVAL;
	}

589 590 591 592 593 594 595 596 597 598 599 600
	if (!psy->of_node) {
		dev_warn(&psy->dev, "%s currently only supports devicetree\n",
			 __func__);
		return -ENXIO;
	}

	battery_np = of_parse_phandle(psy->of_node, "monitored-battery", 0);
	if (!battery_np)
		return -ENODEV;

	err = of_property_read_string(battery_np, "compatible", &value);
	if (err)
601
		goto out_put_node;
602

603 604 605 606
	if (strcmp("simple-battery", value)) {
		err = -ENODEV;
		goto out_put_node;
	}
607 608 609 610 611 612 613 614 615 616 617 618

	/* The property and field names below must correspond to elements
	 * in enum power_supply_property. For reasoning, see
	 * Documentation/power/power_supply_class.txt.
	 */

	of_property_read_u32(battery_np, "energy-full-design-microwatt-hours",
			     &info->energy_full_design_uwh);
	of_property_read_u32(battery_np, "charge-full-design-microamp-hours",
			     &info->charge_full_design_uah);
	of_property_read_u32(battery_np, "voltage-min-design-microvolt",
			     &info->voltage_min_design_uv);
619 620
	of_property_read_u32(battery_np, "voltage-max-design-microvolt",
			     &info->voltage_max_design_uv);
621 622 623 624
	of_property_read_u32(battery_np, "precharge-current-microamp",
			     &info->precharge_current_ua);
	of_property_read_u32(battery_np, "charge-term-current-microamp",
			     &info->charge_term_current_ua);
625
	of_property_read_u32(battery_np, "constant-charge-current-max-microamp",
626
			     &info->constant_charge_current_max_ua);
627
	of_property_read_u32(battery_np, "constant-charge-voltage-max-microvolt",
628
			     &info->constant_charge_voltage_max_uv);
629 630
	of_property_read_u32(battery_np, "factory-internal-resistance-micro-ohms",
			     &info->factory_internal_resistance_uohm);
631

632 633
	len = of_property_count_u32_elems(battery_np, "ocv-capacity-celsius");
	if (len < 0 && len != -EINVAL) {
634 635
		err = len;
		goto out_put_node;
636 637
	} else if (len > POWER_SUPPLY_OCV_TEMP_MAX) {
		dev_err(&psy->dev, "Too many temperature values\n");
638 639
		err = -EINVAL;
		goto out_put_node;
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
	} else if (len > 0) {
		of_property_read_u32_array(battery_np, "ocv-capacity-celsius",
					   info->ocv_temp, len);
	}

	for (index = 0; index < len; index++) {
		struct power_supply_battery_ocv_table *table;
		char *propname;
		const __be32 *list;
		int i, tab_len, size;

		propname = kasprintf(GFP_KERNEL, "ocv-capacity-table-%d", index);
		list = of_get_property(battery_np, propname, &size);
		if (!list || !size) {
			dev_err(&psy->dev, "failed to get %s\n", propname);
			kfree(propname);
			power_supply_put_battery_info(psy, info);
657 658
			err = -EINVAL;
			goto out_put_node;
659 660 661 662 663 664 665 666 667 668
		}

		kfree(propname);
		tab_len = size / (2 * sizeof(__be32));
		info->ocv_table_size[index] = tab_len;

		table = info->ocv_table[index] =
			devm_kcalloc(&psy->dev, tab_len, sizeof(*table), GFP_KERNEL);
		if (!info->ocv_table[index]) {
			power_supply_put_battery_info(psy, info);
669 670
			err = -ENOMEM;
			goto out_put_node;
671 672 673 674 675 676 677 678
		}

		for (i = 0; i < tab_len; i++) {
			table[i].ocv = be32_to_cpu(*list++);
			table[i].capacity = be32_to_cpu(*list++);
		}
	}

679 680 681
out_put_node:
	of_node_put(battery_np);
	return err;
682 683 684
}
EXPORT_SYMBOL_GPL(power_supply_get_battery_info);

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
void power_supply_put_battery_info(struct power_supply *psy,
				   struct power_supply_battery_info *info)
{
	int i;

	for (i = 0; i < POWER_SUPPLY_OCV_TEMP_MAX; i++) {
		if (info->ocv_table[i])
			devm_kfree(&psy->dev, info->ocv_table[i]);
	}
}
EXPORT_SYMBOL_GPL(power_supply_put_battery_info);

/**
 * power_supply_ocv2cap_simple() - find the battery capacity
 * @table: Pointer to battery OCV lookup table
 * @table_len: OCV table length
 * @ocv: Current OCV value
 *
 * This helper function is used to look up battery capacity according to
 * current OCV value from one OCV table, and the OCV table must be ordered
 * descending.
 *
 * Return: the battery capacity.
 */
int power_supply_ocv2cap_simple(struct power_supply_battery_ocv_table *table,
				int table_len, int ocv)
{
	int i, cap, tmp;

	for (i = 0; i < table_len; i++)
		if (ocv > table[i].ocv)
			break;

	if (i > 0 && i < table_len) {
		tmp = (table[i - 1].capacity - table[i].capacity) *
			(ocv - table[i].ocv);
		tmp /= table[i - 1].ocv - table[i].ocv;
		cap = tmp + table[i].capacity;
	} else if (i == 0) {
		cap = table[0].capacity;
	} else {
		cap = table[table_len - 1].capacity;
	}

	return cap;
}
EXPORT_SYMBOL_GPL(power_supply_ocv2cap_simple);

struct power_supply_battery_ocv_table *
power_supply_find_ocv2cap_table(struct power_supply_battery_info *info,
				int temp, int *table_len)
{
	int best_temp_diff = INT_MAX, temp_diff;
	u8 i, best_index = 0;

	if (!info->ocv_table[0])
		return NULL;

	for (i = 0; i < POWER_SUPPLY_OCV_TEMP_MAX; i++) {
		temp_diff = abs(info->ocv_temp[i] - temp);

		if (temp_diff < best_temp_diff) {
			best_temp_diff = temp_diff;
			best_index = i;
		}
	}

	*table_len = info->ocv_table_size[best_index];
	return info->ocv_table[best_index];
}
EXPORT_SYMBOL_GPL(power_supply_find_ocv2cap_table);

int power_supply_batinfo_ocv2cap(struct power_supply_battery_info *info,
				 int ocv, int temp)
{
	struct power_supply_battery_ocv_table *table;
	int table_len;

	table = power_supply_find_ocv2cap_table(info, temp, &table_len);
	if (!table)
		return -EINVAL;

	return power_supply_ocv2cap_simple(table, table_len, ocv);
}
EXPORT_SYMBOL_GPL(power_supply_batinfo_ocv2cap);

771 772 773 774
int power_supply_get_property(struct power_supply *psy,
			    enum power_supply_property psp,
			    union power_supply_propval *val)
{
775 776 777
	if (atomic_read(&psy->use_cnt) <= 0) {
		if (!psy->initialized)
			return -EAGAIN;
778
		return -ENODEV;
779
	}
780

781
	return psy->desc->get_property(psy, psp, val);
782 783 784 785 786 787 788
}
EXPORT_SYMBOL_GPL(power_supply_get_property);

int power_supply_set_property(struct power_supply *psy,
			    enum power_supply_property psp,
			    const union power_supply_propval *val)
{
789
	if (atomic_read(&psy->use_cnt) <= 0 || !psy->desc->set_property)
790 791
		return -ENODEV;

792
	return psy->desc->set_property(psy, psp, val);
793 794 795 796 797 798
}
EXPORT_SYMBOL_GPL(power_supply_set_property);

int power_supply_property_is_writeable(struct power_supply *psy,
					enum power_supply_property psp)
{
799 800
	if (atomic_read(&psy->use_cnt) <= 0 ||
			!psy->desc->property_is_writeable)
801 802
		return -ENODEV;

803
	return psy->desc->property_is_writeable(psy, psp);
804 805 806 807 808
}
EXPORT_SYMBOL_GPL(power_supply_property_is_writeable);

void power_supply_external_power_changed(struct power_supply *psy)
{
809 810
	if (atomic_read(&psy->use_cnt) <= 0 ||
			!psy->desc->external_power_changed)
811 812
		return;

813
	psy->desc->external_power_changed(psy);
814 815 816
}
EXPORT_SYMBOL_GPL(power_supply_external_power_changed);

817 818
int power_supply_powers(struct power_supply *psy, struct device *dev)
{
819
	return sysfs_create_link(&psy->dev.kobj, &dev->kobj, "powers");
820 821 822
}
EXPORT_SYMBOL_GPL(power_supply_powers);

823 824
static void power_supply_dev_release(struct device *dev)
{
825
	struct power_supply *psy = to_power_supply(dev);
826
	dev_dbg(dev, "%s\n", __func__);
827
	kfree(psy);
828 829
}

830 831 832 833 834 835 836 837 838 839 840 841
int power_supply_reg_notifier(struct notifier_block *nb)
{
	return atomic_notifier_chain_register(&power_supply_notifier, nb);
}
EXPORT_SYMBOL_GPL(power_supply_reg_notifier);

void power_supply_unreg_notifier(struct notifier_block *nb)
{
	atomic_notifier_chain_unregister(&power_supply_notifier, nb);
}
EXPORT_SYMBOL_GPL(power_supply_unreg_notifier);

842 843
#ifdef CONFIG_THERMAL
static int power_supply_read_temp(struct thermal_zone_device *tzd,
844
		int *temp)
845 846 847 848 849 850 851
{
	struct power_supply *psy;
	union power_supply_propval val;
	int ret;

	WARN_ON(tzd == NULL);
	psy = tzd->devdata;
852 853 854
	ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_TEMP, &val);
	if (ret)
		return ret;
855 856

	/* Convert tenths of degree Celsius to milli degree Celsius. */
857
	*temp = val.intval * 100;
858 859 860 861 862 863 864 865 866 867 868 869

	return ret;
}

static struct thermal_zone_device_ops psy_tzd_ops = {
	.get_temp = power_supply_read_temp,
};

static int psy_register_thermal(struct power_supply *psy)
{
	int i;

870
	if (psy->desc->no_thermal)
871 872
		return 0;

873
	/* Register battery zone device psy reports temperature */
874 875 876 877
	for (i = 0; i < psy->desc->num_properties; i++) {
		if (psy->desc->properties[i] == POWER_SUPPLY_PROP_TEMP) {
			psy->tzd = thermal_zone_device_register(psy->desc->name,
					0, 0, psy, &psy_tzd_ops, NULL, 0, 0);
878
			return PTR_ERR_OR_ZERO(psy->tzd);
879 880 881 882 883 884 885 886 887 888 889
		}
	}
	return 0;
}

static void psy_unregister_thermal(struct power_supply *psy)
{
	if (IS_ERR_OR_NULL(psy->tzd))
		return;
	thermal_zone_device_unregister(psy->tzd);
}
890 891 892 893 894 895 896 897 898 899

/* thermal cooling device callbacks */
static int ps_get_max_charge_cntl_limit(struct thermal_cooling_device *tcd,
					unsigned long *state)
{
	struct power_supply *psy;
	union power_supply_propval val;
	int ret;

	psy = tcd->devdata;
900 901 902 903 904 905
	ret = power_supply_get_property(psy,
			POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT_MAX, &val);
	if (ret)
		return ret;

	*state = val.intval;
906 907 908 909

	return ret;
}

910
static int ps_get_cur_charge_cntl_limit(struct thermal_cooling_device *tcd,
911 912 913 914 915 916 917
					unsigned long *state)
{
	struct power_supply *psy;
	union power_supply_propval val;
	int ret;

	psy = tcd->devdata;
918 919 920 921 922 923
	ret = power_supply_get_property(psy,
			POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT, &val);
	if (ret)
		return ret;

	*state = val.intval;
924 925 926 927 928 929 930 931 932 933 934 935 936

	return ret;
}

static int ps_set_cur_charge_cntl_limit(struct thermal_cooling_device *tcd,
					unsigned long state)
{
	struct power_supply *psy;
	union power_supply_propval val;
	int ret;

	psy = tcd->devdata;
	val.intval = state;
937
	ret = psy->desc->set_property(psy,
938 939 940 941 942
		POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT, &val);

	return ret;
}

943
static const struct thermal_cooling_device_ops psy_tcd_ops = {
944
	.get_max_state = ps_get_max_charge_cntl_limit,
945
	.get_cur_state = ps_get_cur_charge_cntl_limit,
946 947 948 949 950 951 952 953
	.set_cur_state = ps_set_cur_charge_cntl_limit,
};

static int psy_register_cooler(struct power_supply *psy)
{
	int i;

	/* Register for cooling device if psy can control charging */
954 955
	for (i = 0; i < psy->desc->num_properties; i++) {
		if (psy->desc->properties[i] ==
956 957
				POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT) {
			psy->tcd = thermal_cooling_device_register(
958
							(char *)psy->desc->name,
959
							psy, &psy_tcd_ops);
960
			return PTR_ERR_OR_ZERO(psy->tcd);
961 962 963 964 965 966 967 968 969 970 971
		}
	}
	return 0;
}

static void psy_unregister_cooler(struct power_supply *psy)
{
	if (IS_ERR_OR_NULL(psy->tcd))
		return;
	thermal_cooling_device_unregister(psy->tcd);
}
972 973 974 975 976 977 978 979 980
#else
static int psy_register_thermal(struct power_supply *psy)
{
	return 0;
}

static void psy_unregister_thermal(struct power_supply *psy)
{
}
981 982 983 984 985 986 987 988 989

static int psy_register_cooler(struct power_supply *psy)
{
	return 0;
}

static void psy_unregister_cooler(struct power_supply *psy)
{
}
990 991
#endif

992 993 994
static struct power_supply *__must_check
__power_supply_register(struct device *parent,
				   const struct power_supply_desc *desc,
995 996
				   const struct power_supply_config *cfg,
				   bool ws)
997
{
998
	struct device *dev;
999
	struct power_supply *psy;
1000
	int i, rc;
1001

1002 1003 1004 1005
	if (!parent)
		pr_warn("%s: Expected proper parent device for '%s'\n",
			__func__, desc->name);

1006 1007 1008
	if (!desc || !desc->name || !desc->properties || !desc->num_properties)
		return ERR_PTR(-EINVAL);

1009 1010 1011 1012 1013 1014
	for (i = 0; i < desc->num_properties; ++i) {
		if ((desc->properties[i] == POWER_SUPPLY_PROP_USB_TYPE) &&
		    (!desc->usb_types || !desc->num_usb_types))
			return ERR_PTR(-EINVAL);
	}

1015 1016 1017 1018 1019
	psy = kzalloc(sizeof(*psy), GFP_KERNEL);
	if (!psy)
		return ERR_PTR(-ENOMEM);

	dev = &psy->dev;
1020

1021
	device_initialize(dev);
1022

1023 1024 1025 1026 1027
	dev->class = power_supply_class;
	dev->type = &power_supply_dev_type;
	dev->parent = parent;
	dev->release = power_supply_dev_release;
	dev_set_drvdata(dev, psy);
1028
	psy->desc = desc;
1029
	if (cfg) {
1030
		dev->groups = cfg->attr_grp;
1031
		psy->drv_data = cfg->drv_data;
1032 1033
		psy->of_node =
			cfg->fwnode ? to_of_node(cfg->fwnode) : cfg->of_node;
1034 1035 1036
		psy->supplied_to = cfg->supplied_to;
		psy->num_supplicants = cfg->num_supplicants;
	}
1037

1038
	rc = dev_set_name(dev, "%s", desc->name);
1039 1040 1041
	if (rc)
		goto dev_set_name_failed;

1042
	INIT_WORK(&psy->changed_work, power_supply_changed_work);
1043 1044
	INIT_DELAYED_WORK(&psy->deferred_register_work,
			  power_supply_deferred_register_work);
1045

1046 1047 1048 1049 1050 1051
	rc = power_supply_check_supplies(psy);
	if (rc) {
		dev_info(dev, "Not all required supplies found, defer probe\n");
		goto check_supplies_failed;
	}

1052
	spin_lock_init(&psy->changed_lock);
1053
	rc = device_init_wakeup(dev, ws);
1054 1055 1056
	if (rc)
		goto wakeup_init_failed;

1057
	rc = device_add(dev);
1058
	if (rc)
1059 1060
		goto device_add_failed;

1061 1062 1063 1064
	rc = psy_register_thermal(psy);
	if (rc)
		goto register_thermal_failed;

1065 1066 1067 1068
	rc = psy_register_cooler(psy);
	if (rc)
		goto register_cooler_failed;

1069 1070 1071 1072
	rc = power_supply_create_triggers(psy);
	if (rc)
		goto create_triggers_failed;

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
	/*
	 * Update use_cnt after any uevents (most notably from device_add()).
	 * We are here still during driver's probe but
	 * the power_supply_uevent() calls back driver's get_property
	 * method so:
	 * 1. Driver did not assigned the returned struct power_supply,
	 * 2. Driver could not finish initialization (anything in its probe
	 *    after calling power_supply_register()).
	 */
	atomic_inc(&psy->use_cnt);
1083
	psy->initialized = true;
1084 1085 1086 1087

	queue_delayed_work(system_power_efficient_wq,
			   &psy->deferred_register_work,
			   POWER_SUPPLY_DEFERRED_REGISTER_TIME);
1088

1089
	return psy;
1090 1091

create_triggers_failed:
1092 1093
	psy_unregister_cooler(psy);
register_cooler_failed:
1094 1095
	psy_unregister_thermal(psy);
register_thermal_failed:
1096
	device_del(dev);
1097
device_add_failed:
1098
wakeup_init_failed:
1099
check_supplies_failed:
1100
dev_set_name_failed:
1101
	put_device(dev);
1102
	return ERR_PTR(rc);
1103
}
1104

1105 1106
/**
 * power_supply_register() - Register new power supply
1107 1108
 * @parent:	Device to be a parent of power supply's device, usually
 *		the device which probe function calls this
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
 * @desc:	Description of power supply, must be valid through whole
 *		lifetime of this power supply
 * @cfg:	Run-time specific configuration accessed during registering,
 *		may be NULL
 *
 * Return: A pointer to newly allocated power_supply on success
 * or ERR_PTR otherwise.
 * Use power_supply_unregister() on returned power_supply pointer to release
 * resources.
 */
struct power_supply *__must_check power_supply_register(struct device *parent,
		const struct power_supply_desc *desc,
1121
		const struct power_supply_config *cfg)
1122
{
1123
	return __power_supply_register(parent, desc, cfg, true);
1124
}
1125
EXPORT_SYMBOL_GPL(power_supply_register);
1126

1127
/**
1128
 * power_supply_register_no_ws() - Register new non-waking-source power supply
1129 1130
 * @parent:	Device to be a parent of power supply's device, usually
 *		the device which probe function calls this
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
 * @desc:	Description of power supply, must be valid through whole
 *		lifetime of this power supply
 * @cfg:	Run-time specific configuration accessed during registering,
 *		may be NULL
 *
 * Return: A pointer to newly allocated power_supply on success
 * or ERR_PTR otherwise.
 * Use power_supply_unregister() on returned power_supply pointer to release
 * resources.
 */
struct power_supply *__must_check
power_supply_register_no_ws(struct device *parent,
		const struct power_supply_desc *desc,
1144
		const struct power_supply_config *cfg)
1145
{
1146
	return __power_supply_register(parent, desc, cfg, false);
1147 1148 1149
}
EXPORT_SYMBOL_GPL(power_supply_register_no_ws);

1150 1151 1152 1153 1154 1155 1156
static void devm_power_supply_release(struct device *dev, void *res)
{
	struct power_supply **psy = res;

	power_supply_unregister(*psy);
}

1157
/**
1158
 * devm_power_supply_register() - Register managed power supply
1159 1160
 * @parent:	Device to be a parent of power supply's device, usually
 *		the device which probe function calls this
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
 * @desc:	Description of power supply, must be valid through whole
 *		lifetime of this power supply
 * @cfg:	Run-time specific configuration accessed during registering,
 *		may be NULL
 *
 * Return: A pointer to newly allocated power_supply on success
 * or ERR_PTR otherwise.
 * The returned power_supply pointer will be automatically unregistered
 * on driver detach.
 */
struct power_supply *__must_check
devm_power_supply_register(struct device *parent,
		const struct power_supply_desc *desc,
1174
		const struct power_supply_config *cfg)
1175
{
1176 1177 1178
	struct power_supply **ptr, *psy;

	ptr = devres_alloc(devm_power_supply_release, sizeof(*ptr), GFP_KERNEL);
1179 1180

	if (!ptr)
1181 1182 1183
		return ERR_PTR(-ENOMEM);
	psy = __power_supply_register(parent, desc, cfg, true);
	if (IS_ERR(psy)) {
1184
		devres_free(ptr);
1185
	} else {
1186 1187 1188
		*ptr = psy;
		devres_add(parent, ptr);
	}
1189
	return psy;
1190 1191 1192
}
EXPORT_SYMBOL_GPL(devm_power_supply_register);

1193
/**
1194
 * devm_power_supply_register_no_ws() - Register managed non-waking-source power supply
1195 1196
 * @parent:	Device to be a parent of power supply's device, usually
 *		the device which probe function calls this
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
 * @desc:	Description of power supply, must be valid through whole
 *		lifetime of this power supply
 * @cfg:	Run-time specific configuration accessed during registering,
 *		may be NULL
 *
 * Return: A pointer to newly allocated power_supply on success
 * or ERR_PTR otherwise.
 * The returned power_supply pointer will be automatically unregistered
 * on driver detach.
 */
struct power_supply *__must_check
devm_power_supply_register_no_ws(struct device *parent,
		const struct power_supply_desc *desc,
1210
		const struct power_supply_config *cfg)
1211
{
1212 1213 1214
	struct power_supply **ptr, *psy;

	ptr = devres_alloc(devm_power_supply_release, sizeof(*ptr), GFP_KERNEL);
1215 1216

	if (!ptr)
1217 1218 1219
		return ERR_PTR(-ENOMEM);
	psy = __power_supply_register(parent, desc, cfg, false);
	if (IS_ERR(psy)) {
1220
		devres_free(ptr);
1221
	} else {
1222 1223 1224
		*ptr = psy;
		devres_add(parent, ptr);
	}
1225
	return psy;
1226 1227 1228
}
EXPORT_SYMBOL_GPL(devm_power_supply_register_no_ws);

1229 1230 1231 1232 1233 1234 1235
/**
 * power_supply_unregister() - Remove this power supply from system
 * @psy:	Pointer to power supply to unregister
 *
 * Remove this power supply from the system. The resources of power supply
 * will be freed here or on last power_supply_put() call.
 */
1236 1237
void power_supply_unregister(struct power_supply *psy)
{
1238
	WARN_ON(atomic_dec_return(&psy->use_cnt));
1239
	psy->removing = true;
1240
	cancel_work_sync(&psy->changed_work);
1241
	cancel_delayed_work_sync(&psy->deferred_register_work);
1242
	sysfs_remove_link(&psy->dev.kobj, "powers");
1243
	power_supply_remove_triggers(psy);
1244
	psy_unregister_cooler(psy);
1245
	psy_unregister_thermal(psy);
1246 1247
	device_init_wakeup(&psy->dev, false);
	device_unregister(&psy->dev);
1248
}
1249
EXPORT_SYMBOL_GPL(power_supply_unregister);
1250

1251 1252 1253 1254 1255 1256
void *power_supply_get_drvdata(struct power_supply *psy)
{
	return psy->drv_data;
}
EXPORT_SYMBOL_GPL(power_supply_get_drvdata);

1257 1258 1259 1260 1261 1262 1263 1264
static int __init power_supply_class_init(void)
{
	power_supply_class = class_create(THIS_MODULE, "power_supply");

	if (IS_ERR(power_supply_class))
		return PTR_ERR(power_supply_class);

	power_supply_class->dev_uevent = power_supply_uevent;
1265
	power_supply_init_attrs(&power_supply_dev_type);
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282

	return 0;
}

static void __exit power_supply_class_exit(void)
{
	class_destroy(power_supply_class);
}

subsys_initcall(power_supply_class_init);
module_exit(power_supply_class_exit);

MODULE_DESCRIPTION("Universal power supply monitor class");
MODULE_AUTHOR("Ian Molton <spyro@f2s.com>, "
	      "Szabolcs Gyurko, "
	      "Anton Vorontsov <cbou@mail.ru>");
MODULE_LICENSE("GPL");