File Index
Files and directories
Sign in
FILE

ab8500_fg.c

File preview with syntax highlighting.

linux-6.19.14/drivers/power/supply/ab8500_fg.c C
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Copyright (C) ST-Ericsson AB 2012
   4 *
   5 * Main and Back-up battery management driver.
   6 *
   7 * Note: Backup battery management is required in case of Li-Ion battery and not
   8 * for capacitive battery. HREF boards have capacitive battery and hence backup
   9 * battery management is not used and the supported code is available in this
  10 * driver.
  11 *
  12 * Author:
  13 *	Johan Palsson <johan.palsson@stericsson.com>
  14 *	Karl Komierowski <karl.komierowski@stericsson.com>
  15 *	Arun R Murthy <arun.murthy@stericsson.com>
  16 */
  17
  18#include <linux/init.h>
  19#include <linux/module.h>
  20#include <linux/component.h>
  21#include <linux/device.h>
  22#include <linux/interrupt.h>
  23#include <linux/platform_device.h>
  24#include <linux/power_supply.h>
  25#include <linux/kobject.h>
  26#include <linux/slab.h>
  27#include <linux/delay.h>
  28#include <linux/time.h>
  29#include <linux/time64.h>
  30#include <linux/of.h>
  31#include <linux/completion.h>
  32#include <linux/mfd/core.h>
  33#include <linux/mfd/abx500.h>
  34#include <linux/mfd/abx500/ab8500.h>
  35#include <linux/iio/consumer.h>
  36#include <linux/kernel.h>
  37#include <linux/fixp-arith.h>
  38
  39#include "ab8500-bm.h"
  40
  41#define FG_LSB_IN_MA			1627
  42#define QLSB_NANO_AMP_HOURS_X10		1071
  43#define INS_CURR_TIMEOUT		(3 * HZ)
  44
  45#define SEC_TO_SAMPLE(S)		(S * 4)
  46
  47#define NBR_AVG_SAMPLES			20
  48#define WAIT_FOR_INST_CURRENT_MAX	70
  49/* Currents higher than -500mA (dissipating) will make compensation unstable */
  50#define IGNORE_VBAT_HIGHCUR		-500000
  51
  52#define LOW_BAT_CHECK_INTERVAL		(HZ / 16) /* 62.5 ms */
  53
  54#define VALID_CAPACITY_SEC		(45 * 60) /* 45 minutes */
  55#define BATT_OK_MIN			2360 /* mV */
  56#define BATT_OK_INCREMENT		50 /* mV */
  57#define BATT_OK_MAX_NR_INCREMENTS	0xE
  58
  59/* FG constants */
  60#define BATT_OVV			0x01
  61
  62/**
  63 * struct ab8500_fg_interrupts - ab8500 fg interrupts
  64 * @name:	name of the interrupt
  65 * @isr		function pointer to the isr
  66 */
  67struct ab8500_fg_interrupts {
  68	char *name;
  69	irqreturn_t (*isr)(int irq, void *data);
  70};
  71
  72enum ab8500_fg_discharge_state {
  73	AB8500_FG_DISCHARGE_INIT,
  74	AB8500_FG_DISCHARGE_INITMEASURING,
  75	AB8500_FG_DISCHARGE_INIT_RECOVERY,
  76	AB8500_FG_DISCHARGE_RECOVERY,
  77	AB8500_FG_DISCHARGE_READOUT_INIT,
  78	AB8500_FG_DISCHARGE_READOUT,
  79	AB8500_FG_DISCHARGE_WAKEUP,
  80};
  81
  82static char *discharge_state[] = {
  83	"DISCHARGE_INIT",
  84	"DISCHARGE_INITMEASURING",
  85	"DISCHARGE_INIT_RECOVERY",
  86	"DISCHARGE_RECOVERY",
  87	"DISCHARGE_READOUT_INIT",
  88	"DISCHARGE_READOUT",
  89	"DISCHARGE_WAKEUP",
  90};
  91
  92enum ab8500_fg_charge_state {
  93	AB8500_FG_CHARGE_INIT,
  94	AB8500_FG_CHARGE_READOUT,
  95};
  96
  97static char *charge_state[] = {
  98	"CHARGE_INIT",
  99	"CHARGE_READOUT",
 100};
 101
 102enum ab8500_fg_calibration_state {
 103	AB8500_FG_CALIB_INIT,
 104	AB8500_FG_CALIB_WAIT,
 105	AB8500_FG_CALIB_END,
 106};
 107
 108struct ab8500_fg_avg_cap {
 109	int avg;
 110	int samples[NBR_AVG_SAMPLES];
 111	time64_t time_stamps[NBR_AVG_SAMPLES];
 112	int pos;
 113	int nbr_samples;
 114	int sum;
 115};
 116
 117struct ab8500_fg_cap_scaling {
 118	bool enable;
 119	int cap_to_scale[2];
 120	int disable_cap_level;
 121	int scaled_cap;
 122};
 123
 124struct ab8500_fg_battery_capacity {
 125	int max_mah_design;
 126	int max_mah;
 127	int mah;
 128	int permille;
 129	int level;
 130	int prev_mah;
 131	int prev_percent;
 132	int prev_level;
 133	int user_mah;
 134	struct ab8500_fg_cap_scaling cap_scale;
 135};
 136
 137struct ab8500_fg_flags {
 138	bool fg_enabled;
 139	bool conv_done;
 140	bool charging;
 141	bool fully_charged;
 142	bool force_full;
 143	bool low_bat_delay;
 144	bool low_bat;
 145	bool bat_ovv;
 146	bool batt_unknown;
 147	bool calibrate;
 148	bool user_cap;
 149	bool batt_id_received;
 150};
 151
 152/**
 153 * struct ab8500_fg - ab8500 FG device information
 154 * @dev:		Pointer to the structure device
 155 * @node:		a list of AB8500 FGs, hence prepared for reentrance
 156 * @irq			holds the CCEOC interrupt number
 157 * @vbat_uv:		Battery voltage in uV
 158 * @vbat_nom_uv:	Nominal battery voltage in uV
 159 * @inst_curr_ua:	Instantenous battery current in uA
 160 * @avg_curr_ua:	Average battery current in uA
 161 * @bat_temp		battery temperature
 162 * @fg_samples:		Number of samples used in the FG accumulation
 163 * @accu_charge:	Accumulated charge from the last conversion
 164 * @recovery_cnt:	Counter for recovery mode
 165 * @high_curr_cnt:	Counter for high current mode
 166 * @init_cnt:		Counter for init mode
 167 * @low_bat_cnt		Counter for number of consecutive low battery measures
 168 * @nbr_cceoc_irq_cnt	Counter for number of CCEOC irqs received since enabled
 169 * @recovery_needed:	Indicate if recovery is needed
 170 * @high_curr_mode:	Indicate if we're in high current mode
 171 * @init_capacity:	Indicate if initial capacity measuring should be done
 172 * @turn_off_fg:	True if fg was off before current measurement
 173 * @calib_state		State during offset calibration
 174 * @discharge_state:	Current discharge state
 175 * @charge_state:	Current charge state
 176 * @ab8500_fg_started	Completion struct used for the instant current start
 177 * @ab8500_fg_complete	Completion struct used for the instant current reading
 178 * @flags:		Structure for information about events triggered
 179 * @bat_cap:		Structure for battery capacity specific parameters
 180 * @avg_cap:		Average capacity filter
 181 * @parent:		Pointer to the struct ab8500
 182 * @main_bat_v:		ADC channel for the main battery voltage
 183 * @bm:           	Platform specific battery management information
 184 * @fg_psy:		Structure that holds the FG specific battery properties
 185 * @fg_wq:		Work queue for running the FG algorithm
 186 * @fg_periodic_work:	Work to run the FG algorithm periodically
 187 * @fg_low_bat_work:	Work to check low bat condition
 188 * @fg_reinit_work	Work used to reset and reinitialise the FG algorithm
 189 * @fg_work:		Work to run the FG algorithm instantly
 190 * @fg_acc_cur_work:	Work to read the FG accumulator
 191 * @fg_check_hw_failure_work:	Work for checking HW state
 192 * @cc_lock:		Mutex for locking the CC
 193 * @fg_kobject:		Structure of type kobject
 194 */
 195struct ab8500_fg {
 196	struct device *dev;
 197	struct list_head node;
 198	int irq;
 199	int vbat_uv;
 200	int vbat_nom_uv;
 201	int inst_curr_ua;
 202	int avg_curr_ua;
 203	int bat_temp;
 204	int fg_samples;
 205	int accu_charge;
 206	int recovery_cnt;
 207	int high_curr_cnt;
 208	int init_cnt;
 209	int low_bat_cnt;
 210	int nbr_cceoc_irq_cnt;
 211	u32 line_impedance_uohm;
 212	bool recovery_needed;
 213	bool high_curr_mode;
 214	bool init_capacity;
 215	bool turn_off_fg;
 216	enum ab8500_fg_calibration_state calib_state;
 217	enum ab8500_fg_discharge_state discharge_state;
 218	enum ab8500_fg_charge_state charge_state;
 219	struct completion ab8500_fg_started;
 220	struct completion ab8500_fg_complete;
 221	struct ab8500_fg_flags flags;
 222	struct ab8500_fg_battery_capacity bat_cap;
 223	struct ab8500_fg_avg_cap avg_cap;
 224	struct ab8500 *parent;
 225	struct iio_channel *main_bat_v;
 226	struct ab8500_bm_data *bm;
 227	struct power_supply *fg_psy;
 228	struct workqueue_struct *fg_wq;
 229	struct delayed_work fg_periodic_work;
 230	struct delayed_work fg_low_bat_work;
 231	struct delayed_work fg_reinit_work;
 232	struct work_struct fg_work;
 233	struct work_struct fg_acc_cur_work;
 234	struct delayed_work fg_check_hw_failure_work;
 235	struct mutex cc_lock;
 236	struct kobject fg_kobject;
 237};
 238static LIST_HEAD(ab8500_fg_list);
 239
 240/**
 241 * ab8500_fg_get() - returns a reference to the primary AB8500 fuel gauge
 242 * (i.e. the first fuel gauge in the instance list)
 243 */
 244struct ab8500_fg *ab8500_fg_get(void)
 245{
 246	return list_first_entry_or_null(&ab8500_fg_list, struct ab8500_fg,
 247					node);
 248}
 249
 250/* Main battery properties */
 251static enum power_supply_property ab8500_fg_props[] = {
 252	POWER_SUPPLY_PROP_VOLTAGE_NOW,
 253	POWER_SUPPLY_PROP_CURRENT_NOW,
 254	POWER_SUPPLY_PROP_CURRENT_AVG,
 255	POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
 256	POWER_SUPPLY_PROP_ENERGY_FULL,
 257	POWER_SUPPLY_PROP_ENERGY_NOW,
 258	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
 259	POWER_SUPPLY_PROP_CHARGE_FULL,
 260	POWER_SUPPLY_PROP_CHARGE_NOW,
 261	POWER_SUPPLY_PROP_CAPACITY,
 262	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
 263};
 264
 265/*
 266 * This array maps the raw hex value to lowbat voltage used by the AB8500
 267 * Values taken from the UM0836, in microvolts.
 268 */
 269static int ab8500_fg_lowbat_voltage_map[] = {
 270	2300000,
 271	2325000,
 272	2350000,
 273	2375000,
 274	2400000,
 275	2425000,
 276	2450000,
 277	2475000,
 278	2500000,
 279	2525000,
 280	2550000,
 281	2575000,
 282	2600000,
 283	2625000,
 284	2650000,
 285	2675000,
 286	2700000,
 287	2725000,
 288	2750000,
 289	2775000,
 290	2800000,
 291	2825000,
 292	2850000,
 293	2875000,
 294	2900000,
 295	2925000,
 296	2950000,
 297	2975000,
 298	3000000,
 299	3025000,
 300	3050000,
 301	3075000,
 302	3100000,
 303	3125000,
 304	3150000,
 305	3175000,
 306	3200000,
 307	3225000,
 308	3250000,
 309	3275000,
 310	3300000,
 311	3325000,
 312	3350000,
 313	3375000,
 314	3400000,
 315	3425000,
 316	3450000,
 317	3475000,
 318	3500000,
 319	3525000,
 320	3550000,
 321	3575000,
 322	3600000,
 323	3625000,
 324	3650000,
 325	3675000,
 326	3700000,
 327	3725000,
 328	3750000,
 329	3775000,
 330	3800000,
 331	3825000,
 332	3850000,
 333	3850000,
 334};
 335
 336static u8 ab8500_volt_to_regval(int voltage_uv)
 337{
 338	int i;
 339
 340	if (voltage_uv < ab8500_fg_lowbat_voltage_map[0])
 341		return 0;
 342
 343	for (i = 0; i < ARRAY_SIZE(ab8500_fg_lowbat_voltage_map); i++) {
 344		if (voltage_uv < ab8500_fg_lowbat_voltage_map[i])
 345			return (u8) i - 1;
 346	}
 347
 348	/* If not captured above, return index of last element */
 349	return (u8) ARRAY_SIZE(ab8500_fg_lowbat_voltage_map) - 1;
 350}
 351
 352/**
 353 * ab8500_fg_is_low_curr() - Low or high current mode
 354 * @di:		pointer to the ab8500_fg structure
 355 * @curr_ua:	the current to base or our decision on in microampere
 356 *
 357 * Low current mode if the current consumption is below a certain threshold
 358 */
 359static int ab8500_fg_is_low_curr(struct ab8500_fg *di, int curr_ua)
 360{
 361	/*
 362	 * We want to know if we're in low current mode
 363	 */
 364	if (curr_ua > -di->bm->fg_params->high_curr_threshold_ua)
 365		return true;
 366	else
 367		return false;
 368}
 369
 370/**
 371 * ab8500_fg_add_cap_sample() - Add capacity to average filter
 372 * @di:		pointer to the ab8500_fg structure
 373 * @sample:	the capacity in mAh to add to the filter
 374 *
 375 * A capacity is added to the filter and a new mean capacity is calculated and
 376 * returned
 377 */
 378static int ab8500_fg_add_cap_sample(struct ab8500_fg *di, int sample)
 379{
 380	time64_t now = ktime_get_boottime_seconds();
 381	struct ab8500_fg_avg_cap *avg = &di->avg_cap;
 382
 383	do {
 384		avg->sum += sample - avg->samples[avg->pos];
 385		avg->samples[avg->pos] = sample;
 386		avg->time_stamps[avg->pos] = now;
 387		avg->pos++;
 388
 389		if (avg->pos == NBR_AVG_SAMPLES)
 390			avg->pos = 0;
 391
 392		if (avg->nbr_samples < NBR_AVG_SAMPLES)
 393			avg->nbr_samples++;
 394
 395		/*
 396		 * Check the time stamp for each sample. If too old,
 397		 * replace with latest sample
 398		 */
 399	} while (now - VALID_CAPACITY_SEC > avg->time_stamps[avg->pos]);
 400
 401	avg->avg = avg->sum / avg->nbr_samples;
 402
 403	return avg->avg;
 404}
 405
 406/**
 407 * ab8500_fg_clear_cap_samples() - Clear average filter
 408 * @di:		pointer to the ab8500_fg structure
 409 *
 410 * The capacity filter is reset to zero.
 411 */
 412static void ab8500_fg_clear_cap_samples(struct ab8500_fg *di)
 413{
 414	int i;
 415	struct ab8500_fg_avg_cap *avg = &di->avg_cap;
 416
 417	avg->pos = 0;
 418	avg->nbr_samples = 0;
 419	avg->sum = 0;
 420	avg->avg = 0;
 421
 422	for (i = 0; i < NBR_AVG_SAMPLES; i++) {
 423		avg->samples[i] = 0;
 424		avg->time_stamps[i] = 0;
 425	}
 426}
 427
 428/**
 429 * ab8500_fg_fill_cap_sample() - Fill average filter
 430 * @di:		pointer to the ab8500_fg structure
 431 * @sample:	the capacity in mAh to fill the filter with
 432 *
 433 * The capacity filter is filled with a capacity in mAh
 434 */
 435static void ab8500_fg_fill_cap_sample(struct ab8500_fg *di, int sample)
 436{
 437	int i;
 438	time64_t now;
 439	struct ab8500_fg_avg_cap *avg = &di->avg_cap;
 440
 441	now = ktime_get_boottime_seconds();
 442
 443	for (i = 0; i < NBR_AVG_SAMPLES; i++) {
 444		avg->samples[i] = sample;
 445		avg->time_stamps[i] = now;
 446	}
 447
 448	avg->pos = 0;
 449	avg->nbr_samples = NBR_AVG_SAMPLES;
 450	avg->sum = sample * NBR_AVG_SAMPLES;
 451	avg->avg = sample;
 452}
 453
 454/**
 455 * ab8500_fg_coulomb_counter() - enable coulomb counter
 456 * @di:		pointer to the ab8500_fg structure
 457 * @enable:	enable/disable
 458 *
 459 * Enable/Disable coulomb counter.
 460 * On failure returns negative value.
 461 */
 462static int ab8500_fg_coulomb_counter(struct ab8500_fg *di, bool enable)
 463{
 464	int ret = 0;
 465	mutex_lock(&di->cc_lock);
 466	if (enable) {
 467		/* To be able to reprogram the number of samples, we have to
 468		 * first stop the CC and then enable it again */
 469		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 470			AB8500_RTC_CC_CONF_REG, 0x00);
 471		if (ret)
 472			goto cc_err;
 473
 474		/* Program the samples */
 475		ret = abx500_set_register_interruptible(di->dev,
 476			AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
 477			di->fg_samples);
 478		if (ret)
 479			goto cc_err;
 480
 481		/* Start the CC */
 482		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 483			AB8500_RTC_CC_CONF_REG,
 484			(CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
 485		if (ret)
 486			goto cc_err;
 487
 488		di->flags.fg_enabled = true;
 489	} else {
 490		/* Clear any pending read requests */
 491		ret = abx500_mask_and_set_register_interruptible(di->dev,
 492			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
 493			(RESET_ACCU | READ_REQ), 0);
 494		if (ret)
 495			goto cc_err;
 496
 497		ret = abx500_set_register_interruptible(di->dev,
 498			AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU_CTRL, 0);
 499		if (ret)
 500			goto cc_err;
 501
 502		/* Stop the CC */
 503		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 504			AB8500_RTC_CC_CONF_REG, 0);
 505		if (ret)
 506			goto cc_err;
 507
 508		di->flags.fg_enabled = false;
 509
 510	}
 511	dev_dbg(di->dev, " CC enabled: %d Samples: %d\n",
 512		enable, di->fg_samples);
 513
 514	mutex_unlock(&di->cc_lock);
 515
 516	return ret;
 517cc_err:
 518	dev_err(di->dev, "%s Enabling coulomb counter failed\n", __func__);
 519	mutex_unlock(&di->cc_lock);
 520	return ret;
 521}
 522
 523/**
 524 * ab8500_fg_inst_curr_start() - start battery instantaneous current
 525 * @di:         pointer to the ab8500_fg structure
 526 *
 527 * Returns 0 or error code
 528 * Note: This is part "one" and has to be called before
 529 * ab8500_fg_inst_curr_finalize()
 530 */
 531int ab8500_fg_inst_curr_start(struct ab8500_fg *di)
 532{
 533	u8 reg_val;
 534	int ret;
 535
 536	mutex_lock(&di->cc_lock);
 537
 538	di->nbr_cceoc_irq_cnt = 0;
 539	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
 540		AB8500_RTC_CC_CONF_REG, &reg_val);
 541	if (ret < 0)
 542		goto fail;
 543
 544	if (!(reg_val & CC_PWR_UP_ENA)) {
 545		dev_dbg(di->dev, "%s Enable FG\n", __func__);
 546		di->turn_off_fg = true;
 547
 548		/* Program the samples */
 549		ret = abx500_set_register_interruptible(di->dev,
 550			AB8500_GAS_GAUGE, AB8500_GASG_CC_NCOV_ACCU,
 551			SEC_TO_SAMPLE(10));
 552		if (ret)
 553			goto fail;
 554
 555		/* Start the CC */
 556		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 557			AB8500_RTC_CC_CONF_REG,
 558			(CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA));
 559		if (ret)
 560			goto fail;
 561	} else {
 562		di->turn_off_fg = false;
 563	}
 564
 565	/* Return and WFI */
 566	reinit_completion(&di->ab8500_fg_started);
 567	reinit_completion(&di->ab8500_fg_complete);
 568	enable_irq(di->irq);
 569
 570	/* Note: cc_lock is still locked */
 571	return 0;
 572fail:
 573	mutex_unlock(&di->cc_lock);
 574	return ret;
 575}
 576
 577/**
 578 * ab8500_fg_inst_curr_started() - check if fg conversion has started
 579 * @di:         pointer to the ab8500_fg structure
 580 *
 581 * Returns 1 if conversion started, 0 if still waiting
 582 */
 583int ab8500_fg_inst_curr_started(struct ab8500_fg *di)
 584{
 585	return completion_done(&di->ab8500_fg_started);
 586}
 587
 588/**
 589 * ab8500_fg_inst_curr_done() - check if fg conversion is done
 590 * @di:         pointer to the ab8500_fg structure
 591 *
 592 * Returns 1 if conversion done, 0 if still waiting
 593 */
 594int ab8500_fg_inst_curr_done(struct ab8500_fg *di)
 595{
 596	return completion_done(&di->ab8500_fg_complete);
 597}
 598
 599/**
 600 * ab8500_fg_inst_curr_finalize() - battery instantaneous current
 601 * @di:         pointer to the ab8500_fg structure
 602 * @curr_ua:	battery instantenous current in microampere (on success)
 603 *
 604 * Returns 0 or an error code
 605 * Note: This is part "two" and has to be called at earliest 250 ms
 606 * after ab8500_fg_inst_curr_start()
 607 */
 608int ab8500_fg_inst_curr_finalize(struct ab8500_fg *di, int *curr_ua)
 609{
 610	u8 low, high;
 611	int val;
 612	int ret;
 613	unsigned long timeout;
 614
 615	if (!completion_done(&di->ab8500_fg_complete)) {
 616		timeout = wait_for_completion_timeout(
 617			&di->ab8500_fg_complete,
 618			INS_CURR_TIMEOUT);
 619		dev_dbg(di->dev, "Finalize time: %d ms\n",
 620			jiffies_to_msecs(INS_CURR_TIMEOUT - timeout));
 621		if (!timeout) {
 622			ret = -ETIME;
 623			disable_irq(di->irq);
 624			di->nbr_cceoc_irq_cnt = 0;
 625			dev_err(di->dev, "completion timed out [%d]\n",
 626				__LINE__);
 627			goto fail;
 628		}
 629	}
 630
 631	disable_irq(di->irq);
 632	di->nbr_cceoc_irq_cnt = 0;
 633
 634	ret = abx500_mask_and_set_register_interruptible(di->dev,
 635			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
 636			READ_REQ, READ_REQ);
 637
 638	/* 100uS between read request and read is needed */
 639	usleep_range(100, 100);
 640
 641	/* Read CC Sample conversion value Low and high */
 642	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 643		AB8500_GASG_CC_SMPL_CNVL_REG,  &low);
 644	if (ret < 0)
 645		goto fail;
 646
 647	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 648		AB8500_GASG_CC_SMPL_CNVH_REG,  &high);
 649	if (ret < 0)
 650		goto fail;
 651
 652	/*
 653	 * negative value for Discharging
 654	 * convert 2's complement into decimal
 655	 */
 656	if (high & 0x10)
 657		val = (low | (high << 8) | 0xFFFFE000);
 658	else
 659		val = (low | (high << 8));
 660
 661	/*
 662	 * Convert to unit value in mA
 663	 * Full scale input voltage is
 664	 * 63.160mV => LSB = 63.160mV/(4096*res) = 1.542.000 uA
 665	 * Given a 250ms conversion cycle time the LSB corresponds
 666	 * to 107.1 nAh. Convert to current by dividing by the conversion
 667	 * time in hours (250ms = 1 / (3600 * 4)h)
 668	 * 107.1nAh assumes 10mOhm, but fg_res is in 0.1mOhm
 669	 */
 670	val = (val * QLSB_NANO_AMP_HOURS_X10 * 36 * 4) / di->bm->fg_res;
 671
 672	if (di->turn_off_fg) {
 673		dev_dbg(di->dev, "%s Disable FG\n", __func__);
 674
 675		/* Clear any pending read requests */
 676		ret = abx500_set_register_interruptible(di->dev,
 677			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG, 0);
 678		if (ret)
 679			goto fail;
 680
 681		/* Stop the CC */
 682		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
 683			AB8500_RTC_CC_CONF_REG, 0);
 684		if (ret)
 685			goto fail;
 686	}
 687	mutex_unlock(&di->cc_lock);
 688	*curr_ua = val;
 689
 690	return 0;
 691fail:
 692	mutex_unlock(&di->cc_lock);
 693	return ret;
 694}
 695
 696/**
 697 * ab8500_fg_inst_curr_blocking() - battery instantaneous current
 698 * @di:         pointer to the ab8500_fg structure
 699 *
 700 * Returns battery instantenous current in microampere (on success)
 701 * else error code
 702 */
 703int ab8500_fg_inst_curr_blocking(struct ab8500_fg *di)
 704{
 705	int ret;
 706	unsigned long timeout;
 707	int curr_ua = 0;
 708
 709	ret = ab8500_fg_inst_curr_start(di);
 710	if (ret) {
 711		dev_err(di->dev, "Failed to initialize fg_inst\n");
 712		return 0;
 713	}
 714
 715	/* Wait for CC to actually start */
 716	if (!completion_done(&di->ab8500_fg_started)) {
 717		timeout = wait_for_completion_timeout(
 718			&di->ab8500_fg_started,
 719			INS_CURR_TIMEOUT);
 720		dev_dbg(di->dev, "Start time: %d ms\n",
 721			jiffies_to_msecs(INS_CURR_TIMEOUT - timeout));
 722		if (!timeout) {
 723			ret = -ETIME;
 724			dev_err(di->dev, "completion timed out [%d]\n",
 725				__LINE__);
 726			goto fail;
 727		}
 728	}
 729
 730	ret = ab8500_fg_inst_curr_finalize(di, &curr_ua);
 731	if (ret) {
 732		dev_err(di->dev, "Failed to finalize fg_inst\n");
 733		return 0;
 734	}
 735
 736	dev_dbg(di->dev, "%s instant current: %d uA", __func__, curr_ua);
 737	return curr_ua;
 738fail:
 739	disable_irq(di->irq);
 740	mutex_unlock(&di->cc_lock);
 741	return ret;
 742}
 743
 744/**
 745 * ab8500_fg_acc_cur_work() - average battery current
 746 * @work:	pointer to the work_struct structure
 747 *
 748 * Updated the average battery current obtained from the
 749 * coulomb counter.
 750 */
 751static void ab8500_fg_acc_cur_work(struct work_struct *work)
 752{
 753	int val;
 754	int ret;
 755	u8 low, med, high;
 756
 757	struct ab8500_fg *di = container_of(work,
 758		struct ab8500_fg, fg_acc_cur_work);
 759
 760	mutex_lock(&di->cc_lock);
 761	ret = abx500_set_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 762		AB8500_GASG_CC_NCOV_ACCU_CTRL, RD_NCONV_ACCU_REQ);
 763	if (ret)
 764		goto exit;
 765
 766	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 767		AB8500_GASG_CC_NCOV_ACCU_LOW,  &low);
 768	if (ret < 0)
 769		goto exit;
 770
 771	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 772		AB8500_GASG_CC_NCOV_ACCU_MED,  &med);
 773	if (ret < 0)
 774		goto exit;
 775
 776	ret = abx500_get_register_interruptible(di->dev, AB8500_GAS_GAUGE,
 777		AB8500_GASG_CC_NCOV_ACCU_HIGH, &high);
 778	if (ret < 0)
 779		goto exit;
 780
 781	/* Check for sign bit in case of negative value, 2's complement */
 782	if (high & 0x10)
 783		val = (low | (med << 8) | (high << 16) | 0xFFE00000);
 784	else
 785		val = (low | (med << 8) | (high << 16));
 786
 787	/*
 788	 * Convert to uAh
 789	 * Given a 250ms conversion cycle time the LSB corresponds
 790	 * to 112.9 nAh.
 791	 * 112.9nAh assumes 10mOhm, but fg_res is in 0.1mOhm
 792	 */
 793	di->accu_charge = (val * QLSB_NANO_AMP_HOURS_X10) /
 794		(100 * di->bm->fg_res);
 795
 796	/*
 797	 * Convert to unit value in uA
 798	 * by dividing by the conversion
 799	 * time in hours (= samples / (3600 * 4)h)
 800	 */
 801	di->avg_curr_ua = (val * QLSB_NANO_AMP_HOURS_X10 * 36) /
 802		(di->bm->fg_res * (di->fg_samples / 4));
 803
 804	di->flags.conv_done = true;
 805
 806	mutex_unlock(&di->cc_lock);
 807
 808	queue_work(di->fg_wq, &di->fg_work);
 809
 810	dev_dbg(di->dev, "fg_res: %d, fg_samples: %d, gasg: %d, accu_charge: %d \n",
 811				di->bm->fg_res, di->fg_samples, val, di->accu_charge);
 812	return;
 813exit:
 814	dev_err(di->dev,
 815		"Failed to read or write gas gauge registers\n");
 816	mutex_unlock(&di->cc_lock);
 817	queue_work(di->fg_wq, &di->fg_work);
 818}
 819
 820/**
 821 * ab8500_fg_bat_voltage() - get battery voltage
 822 * @di:		pointer to the ab8500_fg structure
 823 *
 824 * Returns battery voltage in microvolts (on success) else error code
 825 */
 826static int ab8500_fg_bat_voltage(struct ab8500_fg *di)
 827{
 828	int vbat, ret;
 829	static int prev;
 830
 831	ret = iio_read_channel_processed(di->main_bat_v, &vbat);
 832	if (ret < 0) {
 833		dev_err(di->dev,
 834			"%s ADC conversion failed, using previous value\n",
 835			__func__);
 836		return prev;
 837	}
 838
 839	/* IIO returns millivolts but we want microvolts */
 840	vbat *= 1000;
 841	prev = vbat;
 842	return vbat;
 843}
 844
 845/**
 846 * ab8500_fg_volt_to_capacity() - Voltage based capacity
 847 * @di:		pointer to the ab8500_fg structure
 848 * @voltage_uv:	The voltage to convert to a capacity in microvolt
 849 *
 850 * Returns battery capacity in per mille based on voltage
 851 */
 852static int ab8500_fg_volt_to_capacity(struct ab8500_fg *di, int voltage_uv)
 853{
 854	struct power_supply_battery_info *bi = di->bm->bi;
 855
 856	/* Multiply by 10 because the capacity is tracked in per mille */
 857	return power_supply_batinfo_ocv2cap(bi, voltage_uv, di->bat_temp) *  10;
 858}
 859
 860/**
 861 * ab8500_fg_uncomp_volt_to_capacity() - Uncompensated voltage based capacity
 862 * @di:		pointer to the ab8500_fg structure
 863 *
 864 * Returns battery capacity based on battery voltage that is not compensated
 865 * for the voltage drop due to the load
 866 */
 867static int ab8500_fg_uncomp_volt_to_capacity(struct ab8500_fg *di)
 868{
 869	di->vbat_uv = ab8500_fg_bat_voltage(di);
 870	return ab8500_fg_volt_to_capacity(di, di->vbat_uv);
 871}
 872
 873/**
 874 * ab8500_fg_battery_resistance() - Returns the battery inner resistance
 875 * @di:		pointer to the ab8500_fg structure
 876 * @vbat_uncomp_uv: Uncompensated VBAT voltage
 877 *
 878 * Returns battery inner resistance added with the fuel gauge resistor value
 879 * to get the total resistance in the whole link from gnd to bat+ node
 880 * in milliohm.
 881 */
 882static int ab8500_fg_battery_resistance(struct ab8500_fg *di, int vbat_uncomp_uv)
 883{
 884	struct power_supply_battery_info *bi = di->bm->bi;
 885	int resistance_percent = 0;
 886	int resistance;
 887
 888	/*
 889	 * Determine the resistance at this voltage. First try VBAT-to-Ri else
 890	 * just infer it from the surrounding temperature, if nothing works just
 891	 * use the internal resistance.
 892	 */
 893	if (power_supply_supports_vbat2ri(bi)) {
 894		resistance = power_supply_vbat2ri(bi, vbat_uncomp_uv, di->flags.charging);
 895		/* Convert to milliohm */
 896		resistance = resistance / 1000;
 897	} else if (power_supply_supports_temp2ri(bi)) {
 898		resistance_percent = power_supply_temp2resist_simple(bi->resist_table,
 899								     bi->resist_table_size,
 900								     di->bat_temp / 10);
 901		/* Convert to milliohm */
 902		resistance = bi->factory_internal_resistance_uohm / 1000;
 903		resistance = resistance * resistance_percent / 100;
 904	} else {
 905		/* Last fallback */
 906		resistance = bi->factory_internal_resistance_uohm / 1000;
 907	}
 908
 909	/* Compensate for line impedance */
 910	resistance += (di->line_impedance_uohm / 1000);
 911
 912	dev_dbg(di->dev, "%s Temp: %d battery internal resistance: %d"
 913	    " fg resistance %d, total: %d (mOhm)\n",
 914		__func__, di->bat_temp, resistance, di->bm->fg_res / 10,
 915		(di->bm->fg_res / 10) + resistance);
 916
 917	/* fg_res variable is in 0.1mOhm */
 918	resistance += di->bm->fg_res / 10;
 919
 920	return resistance;
 921}
 922
 923/**
 924 * ab8500_load_comp_fg_bat_voltage() - get load compensated battery voltage
 925 * @di:		pointer to the ab8500_fg structure
 926 * @always:	always return a voltage, also uncompensated
 927 *
 928 * Returns compensated battery voltage (on success) else error code.
 929 * If always is specified, we always return a voltage but it may be
 930 * uncompensated.
 931 */
 932static int ab8500_load_comp_fg_bat_voltage(struct ab8500_fg *di, bool always)
 933{
 934	int i = 0;
 935	int vbat_uv = 0;
 936	int rcomp;
 937
 938	/* Average the instant current to get a stable current measurement */
 939	ab8500_fg_inst_curr_start(di);
 940
 941	do {
 942		vbat_uv += ab8500_fg_bat_voltage(di);
 943		i++;
 944		usleep_range(5000, 6000);
 945	} while (!ab8500_fg_inst_curr_done(di) &&
 946		 i <= WAIT_FOR_INST_CURRENT_MAX);
 947
 948	if (i > WAIT_FOR_INST_CURRENT_MAX) {
 949		dev_err(di->dev,
 950			"TIMEOUT: return uncompensated measurement of VBAT\n");
 951		di->vbat_uv = vbat_uv / i;
 952		return di->vbat_uv;
 953	}
 954
 955	ab8500_fg_inst_curr_finalize(di, &di->inst_curr_ua);
 956
 957	/*
 958	 * If there is too high current dissipation, the compensation cannot be
 959	 * trusted so return an error unless we must return something here, as
 960	 * enforced by the "always" parameter.
 961	 */
 962	if (!always && di->inst_curr_ua < IGNORE_VBAT_HIGHCUR)
 963		return -EINVAL;
 964
 965	vbat_uv = vbat_uv / i;
 966
 967	/* Next we apply voltage compensation from internal resistance */
 968	rcomp = ab8500_fg_battery_resistance(di, vbat_uv);
 969	vbat_uv = vbat_uv - (di->inst_curr_ua * rcomp) / 1000;
 970
 971	/* Always keep this state at latest measurement */
 972	di->vbat_uv = vbat_uv;
 973
 974	return vbat_uv;
 975}
 976
 977/**
 978 * ab8500_fg_load_comp_volt_to_capacity() - Load compensated voltage based capacity
 979 * @di:		pointer to the ab8500_fg structure
 980 *
 981 * Returns battery capacity based on battery voltage that is load compensated
 982 * for the voltage drop
 983 */
 984static int ab8500_fg_load_comp_volt_to_capacity(struct ab8500_fg *di)
 985{
 986	int vbat_comp_uv;
 987
 988	vbat_comp_uv = ab8500_load_comp_fg_bat_voltage(di, true);
 989
 990	return ab8500_fg_volt_to_capacity(di, vbat_comp_uv);
 991}
 992
 993/**
 994 * ab8500_fg_convert_mah_to_permille() - Capacity in mAh to permille
 995 * @di:		pointer to the ab8500_fg structure
 996 * @cap_mah:	capacity in mAh
 997 *
 998 * Converts capacity in mAh to capacity in permille
 999 */
1000static int ab8500_fg_convert_mah_to_permille(struct ab8500_fg *di, int cap_mah)
1001{
1002	return (cap_mah * 1000) / di->bat_cap.max_mah_design;
1003}
1004
1005/**
1006 * ab8500_fg_convert_permille_to_mah() - Capacity in permille to mAh
1007 * @di:		pointer to the ab8500_fg structure
1008 * @cap_pm:	capacity in permille
1009 *
1010 * Converts capacity in permille to capacity in mAh
1011 */
1012static int ab8500_fg_convert_permille_to_mah(struct ab8500_fg *di, int cap_pm)
1013{
1014	return cap_pm * di->bat_cap.max_mah_design / 1000;
1015}
1016
1017/**
1018 * ab8500_fg_convert_mah_to_uwh() - Capacity in mAh to uWh
1019 * @di:		pointer to the ab8500_fg structure
1020 * @cap_mah:	capacity in mAh
1021 *
1022 * Converts capacity in mAh to capacity in uWh
1023 */
1024static int ab8500_fg_convert_mah_to_uwh(struct ab8500_fg *di, int cap_mah)
1025{
1026	u64 div_res;
1027	u32 div_rem;
1028
1029	/*
1030	 * Capacity is in milli ampere hours (10^-3)Ah
1031	 * Nominal voltage is in microvolts (10^-6)V
1032	 * divide by 1000000 after multiplication to get to mWh
1033	 */
1034	div_res = ((u64) cap_mah) * ((u64) di->vbat_nom_uv);
1035	div_rem = do_div(div_res, 1000000);
1036
1037	/* Make sure to round upwards if necessary */
1038	if (div_rem >= 1000000 / 2)
1039		div_res++;
1040
1041	return (int) div_res;
1042}
1043
1044/**
1045 * ab8500_fg_calc_cap_charging() - Calculate remaining capacity while charging
1046 * @di:		pointer to the ab8500_fg structure
1047 *
1048 * Return the capacity in mAh based on previous calculated capcity and the FG
1049 * accumulator register value. The filter is filled with this capacity
1050 */
1051static int ab8500_fg_calc_cap_charging(struct ab8500_fg *di)
1052{
1053	dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1054		__func__,
1055		di->bat_cap.mah,
1056		di->accu_charge);
1057
1058	/* Capacity should not be less than 0 */
1059	if (di->bat_cap.mah + di->accu_charge > 0)
1060		di->bat_cap.mah += di->accu_charge;
1061	else
1062		di->bat_cap.mah = 0;
1063	/*
1064	 * We force capacity to 100% once when the algorithm
1065	 * reports that it's full.
1066	 */
1067	if (di->bat_cap.mah >= di->bat_cap.max_mah_design ||
1068		di->flags.force_full) {
1069		di->bat_cap.mah = di->bat_cap.max_mah_design;
1070	}
1071
1072	ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1073	di->bat_cap.permille =
1074		ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1075
1076	/* We need to update battery voltage and inst current when charging */
1077	di->vbat_uv = ab8500_fg_bat_voltage(di);
1078	di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1079
1080	return di->bat_cap.mah;
1081}
1082
1083/**
1084 * ab8500_fg_calc_cap_discharge_voltage() - Capacity in discharge with voltage
1085 * @di:		pointer to the ab8500_fg structure
1086 *
1087 * Return the capacity in mAh based on the load compensated battery voltage.
1088 * This value is added to the filter and a new mean value is calculated and
1089 * returned.
1090 */
1091static int ab8500_fg_calc_cap_discharge_voltage(struct ab8500_fg *di)
1092{
1093	int permille, mah;
1094
1095	permille = ab8500_fg_load_comp_volt_to_capacity(di);
1096
1097	mah = ab8500_fg_convert_permille_to_mah(di, permille);
1098
1099	di->bat_cap.mah = ab8500_fg_add_cap_sample(di, mah);
1100	di->bat_cap.permille =
1101		ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1102
1103	return di->bat_cap.mah;
1104}
1105
1106/**
1107 * ab8500_fg_calc_cap_discharge_fg() - Capacity in discharge with FG
1108 * @di:		pointer to the ab8500_fg structure
1109 *
1110 * Return the capacity in mAh based on previous calculated capcity and the FG
1111 * accumulator register value. This value is added to the filter and a
1112 * new mean value is calculated and returned.
1113 */
1114static int ab8500_fg_calc_cap_discharge_fg(struct ab8500_fg *di)
1115{
1116	int permille_volt, permille;
1117
1118	dev_dbg(di->dev, "%s cap_mah %d accu_charge %d\n",
1119		__func__,
1120		di->bat_cap.mah,
1121		di->accu_charge);
1122
1123	/* Capacity should not be less than 0 */
1124	if (di->bat_cap.mah + di->accu_charge > 0)
1125		di->bat_cap.mah += di->accu_charge;
1126	else
1127		di->bat_cap.mah = 0;
1128
1129	if (di->bat_cap.mah >= di->bat_cap.max_mah_design)
1130		di->bat_cap.mah = di->bat_cap.max_mah_design;
1131
1132	/*
1133	 * Check against voltage based capacity. It can not be lower
1134	 * than what the uncompensated voltage says
1135	 */
1136	permille = ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1137	permille_volt = ab8500_fg_uncomp_volt_to_capacity(di);
1138
1139	if (permille < permille_volt) {
1140		di->bat_cap.permille = permille_volt;
1141		di->bat_cap.mah = ab8500_fg_convert_permille_to_mah(di,
1142			di->bat_cap.permille);
1143
1144		dev_dbg(di->dev, "%s voltage based: perm %d perm_volt %d\n",
1145			__func__,
1146			permille,
1147			permille_volt);
1148
1149		ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1150	} else {
1151		ab8500_fg_fill_cap_sample(di, di->bat_cap.mah);
1152		di->bat_cap.permille =
1153			ab8500_fg_convert_mah_to_permille(di, di->bat_cap.mah);
1154	}
1155
1156	return di->bat_cap.mah;
1157}
1158
1159/**
1160 * ab8500_fg_capacity_level() - Get the battery capacity level
1161 * @di:		pointer to the ab8500_fg structure
1162 *
1163 * Get the battery capacity level based on the capacity in percent
1164 */
1165static int ab8500_fg_capacity_level(struct ab8500_fg *di)
1166{
1167	int ret, percent;
1168
1169	percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1170
1171	if (percent <= di->bm->cap_levels->critical ||
1172		di->flags.low_bat)
1173		ret = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1174	else if (percent <= di->bm->cap_levels->low)
1175		ret = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1176	else if (percent <= di->bm->cap_levels->normal)
1177		ret = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1178	else if (percent <= di->bm->cap_levels->high)
1179		ret = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1180	else
1181		ret = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1182
1183	return ret;
1184}
1185
1186/**
1187 * ab8500_fg_calculate_scaled_capacity() - Capacity scaling
1188 * @di:		pointer to the ab8500_fg structure
1189 *
1190 * Calculates the capacity to be shown to upper layers. Scales the capacity
1191 * to have 100% as a reference from the actual capacity upon removal of charger
1192 * when charging is in maintenance mode.
1193 */
1194static int ab8500_fg_calculate_scaled_capacity(struct ab8500_fg *di)
1195{
1196	struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1197	int capacity = di->bat_cap.prev_percent;
1198
1199	if (!cs->enable)
1200		return capacity;
1201
1202	/*
1203	 * As long as we are in fully charge mode scale the capacity
1204	 * to show 100%.
1205	 */
1206	if (di->flags.fully_charged) {
1207		cs->cap_to_scale[0] = 100;
1208		cs->cap_to_scale[1] =
1209			max(capacity, di->bm->fg_params->maint_thres);
1210		dev_dbg(di->dev, "Scale cap with %d/%d\n",
1211			 cs->cap_to_scale[0], cs->cap_to_scale[1]);
1212	}
1213
1214	/* Calculates the scaled capacity. */
1215	if ((cs->cap_to_scale[0] != cs->cap_to_scale[1])
1216					&& (cs->cap_to_scale[1] > 0))
1217		capacity = min(100,
1218				 DIV_ROUND_CLOSEST(di->bat_cap.prev_percent *
1219						 cs->cap_to_scale[0],
1220						 cs->cap_to_scale[1]));
1221
1222	if (di->flags.charging) {
1223		if (capacity < cs->disable_cap_level) {
1224			cs->disable_cap_level = capacity;
1225			dev_dbg(di->dev, "Cap to stop scale lowered %d%%\n",
1226				cs->disable_cap_level);
1227		} else if (!di->flags.fully_charged) {
1228			if (di->bat_cap.prev_percent >=
1229			    cs->disable_cap_level) {
1230				dev_dbg(di->dev, "Disabling scaled capacity\n");
1231				cs->enable = false;
1232				capacity = di->bat_cap.prev_percent;
1233			} else {
1234				dev_dbg(di->dev,
1235					"Waiting in cap to level %d%%\n",
1236					cs->disable_cap_level);
1237				capacity = cs->disable_cap_level;
1238			}
1239		}
1240	}
1241
1242	return capacity;
1243}
1244
1245/**
1246 * ab8500_fg_update_cap_scalers() - Capacity scaling
1247 * @di:		pointer to the ab8500_fg structure
1248 *
1249 * To be called when state change from charge<->discharge to update
1250 * the capacity scalers.
1251 */
1252static void ab8500_fg_update_cap_scalers(struct ab8500_fg *di)
1253{
1254	struct ab8500_fg_cap_scaling *cs = &di->bat_cap.cap_scale;
1255
1256	if (!cs->enable)
1257		return;
1258	if (di->flags.charging) {
1259		di->bat_cap.cap_scale.disable_cap_level =
1260			di->bat_cap.cap_scale.scaled_cap;
1261		dev_dbg(di->dev, "Cap to stop scale at charge %d%%\n",
1262				di->bat_cap.cap_scale.disable_cap_level);
1263	} else {
1264		if (cs->scaled_cap != 100) {
1265			cs->cap_to_scale[0] = cs->scaled_cap;
1266			cs->cap_to_scale[1] = di->bat_cap.prev_percent;
1267		} else {
1268			cs->cap_to_scale[0] = 100;
1269			cs->cap_to_scale[1] =
1270				max(di->bat_cap.prev_percent,
1271				    di->bm->fg_params->maint_thres);
1272		}
1273
1274		dev_dbg(di->dev, "Cap to scale at discharge %d/%d\n",
1275				cs->cap_to_scale[0], cs->cap_to_scale[1]);
1276	}
1277}
1278
1279/**
1280 * ab8500_fg_check_capacity_limits() - Check if capacity has changed
1281 * @di:		pointer to the ab8500_fg structure
1282 * @init:	capacity is allowed to go up in init mode
1283 *
1284 * Check if capacity or capacity limit has changed and notify the system
1285 * about it using the power_supply framework
1286 */
1287static void ab8500_fg_check_capacity_limits(struct ab8500_fg *di, bool init)
1288{
1289	bool changed = false;
1290	int percent = DIV_ROUND_CLOSEST(di->bat_cap.permille, 10);
1291
1292	di->bat_cap.level = ab8500_fg_capacity_level(di);
1293
1294	if (di->bat_cap.level != di->bat_cap.prev_level) {
1295		/*
1296		 * We do not allow reported capacity level to go up
1297		 * unless we're charging or if we're in init
1298		 */
1299		if (!(!di->flags.charging && di->bat_cap.level >
1300			di->bat_cap.prev_level) || init) {
1301			dev_dbg(di->dev, "level changed from %d to %d\n",
1302				di->bat_cap.prev_level,
1303				di->bat_cap.level);
1304			di->bat_cap.prev_level = di->bat_cap.level;
1305			changed = true;
1306		} else {
1307			dev_dbg(di->dev, "level not allowed to go up "
1308				"since no charger is connected: %d to %d\n",
1309				di->bat_cap.prev_level,
1310				di->bat_cap.level);
1311		}
1312	}
1313
1314	/*
1315	 * If we have received the LOW_BAT IRQ, set capacity to 0 to initiate
1316	 * shutdown
1317	 */
1318	if (di->flags.low_bat) {
1319		dev_dbg(di->dev, "Battery low, set capacity to 0\n");
1320		di->bat_cap.prev_percent = 0;
1321		di->bat_cap.permille = 0;
1322		percent = 0;
1323		di->bat_cap.prev_mah = 0;
1324		di->bat_cap.mah = 0;
1325		changed = true;
1326	} else if (di->flags.fully_charged) {
1327		/*
1328		 * We report 100% if algorithm reported fully charged
1329		 * and show 100% during maintenance charging (scaling).
1330		 */
1331		if (di->flags.force_full) {
1332			di->bat_cap.prev_percent = percent;
1333			di->bat_cap.prev_mah = di->bat_cap.mah;
1334
1335			changed = true;
1336
1337			if (!di->bat_cap.cap_scale.enable &&
1338						di->bm->capacity_scaling) {
1339				di->bat_cap.cap_scale.enable = true;
1340				di->bat_cap.cap_scale.cap_to_scale[0] = 100;
1341				di->bat_cap.cap_scale.cap_to_scale[1] =
1342						di->bat_cap.prev_percent;
1343				di->bat_cap.cap_scale.disable_cap_level = 100;
1344			}
1345		} else if (di->bat_cap.prev_percent != percent) {
1346			dev_dbg(di->dev,
1347				"battery reported full "
1348				"but capacity dropping: %d\n",
1349				percent);
1350			di->bat_cap.prev_percent = percent;
1351			di->bat_cap.prev_mah = di->bat_cap.mah;
1352
1353			changed = true;
1354		}
1355	} else if (di->bat_cap.prev_percent != percent) {
1356		if (percent == 0) {
1357			/*
1358			 * We will not report 0% unless we've got
1359			 * the LOW_BAT IRQ, no matter what the FG
1360			 * algorithm says.
1361			 */
1362			di->bat_cap.prev_percent = 1;
1363			percent = 1;
1364
1365			changed = true;
1366		} else if (!(!di->flags.charging &&
1367			percent > di->bat_cap.prev_percent) || init) {
1368			/*
1369			 * We do not allow reported capacity to go up
1370			 * unless we're charging or if we're in init
1371			 */
1372			dev_dbg(di->dev,
1373				"capacity changed from %d to %d (%d)\n",
1374				di->bat_cap.prev_percent,
1375				percent,
1376				di->bat_cap.permille);
1377			di->bat_cap.prev_percent = percent;
1378			di->bat_cap.prev_mah = di->bat_cap.mah;
1379
1380			changed = true;
1381		} else {
1382			dev_dbg(di->dev, "capacity not allowed to go up since "
1383				"no charger is connected: %d to %d (%d)\n",
1384				di->bat_cap.prev_percent,
1385				percent,
1386				di->bat_cap.permille);
1387		}
1388	}
1389
1390	if (changed) {
1391		if (di->bm->capacity_scaling) {
1392			di->bat_cap.cap_scale.scaled_cap =
1393				ab8500_fg_calculate_scaled_capacity(di);
1394
1395			dev_info(di->dev, "capacity=%d (%d)\n",
1396				di->bat_cap.prev_percent,
1397				di->bat_cap.cap_scale.scaled_cap);
1398		}
1399		power_supply_changed(di->fg_psy);
1400		if (di->flags.fully_charged && di->flags.force_full) {
1401			dev_dbg(di->dev, "Battery full, notifying.\n");
1402			di->flags.force_full = false;
1403			sysfs_notify(&di->fg_kobject, NULL, "charge_full");
1404		}
1405		sysfs_notify(&di->fg_kobject, NULL, "charge_now");
1406	}
1407}
1408
1409static void ab8500_fg_charge_state_to(struct ab8500_fg *di,
1410	enum ab8500_fg_charge_state new_state)
1411{
1412	dev_dbg(di->dev, "Charge state from %d [%s] to %d [%s]\n",
1413		di->charge_state,
1414		charge_state[di->charge_state],
1415		new_state,
1416		charge_state[new_state]);
1417
1418	di->charge_state = new_state;
1419}
1420
1421static void ab8500_fg_discharge_state_to(struct ab8500_fg *di,
1422	enum ab8500_fg_discharge_state new_state)
1423{
1424	dev_dbg(di->dev, "Discharge state from %d [%s] to %d [%s]\n",
1425		di->discharge_state,
1426		discharge_state[di->discharge_state],
1427		new_state,
1428		discharge_state[new_state]);
1429
1430	di->discharge_state = new_state;
1431}
1432
1433/**
1434 * ab8500_fg_algorithm_charging() - FG algorithm for when charging
1435 * @di:		pointer to the ab8500_fg structure
1436 *
1437 * Battery capacity calculation state machine for when we're charging
1438 */
1439static void ab8500_fg_algorithm_charging(struct ab8500_fg *di)
1440{
1441	/*
1442	 * If we change to discharge mode
1443	 * we should start with recovery
1444	 */
1445	if (di->discharge_state != AB8500_FG_DISCHARGE_INIT_RECOVERY)
1446		ab8500_fg_discharge_state_to(di,
1447			AB8500_FG_DISCHARGE_INIT_RECOVERY);
1448
1449	switch (di->charge_state) {
1450	case AB8500_FG_CHARGE_INIT:
1451		di->fg_samples = SEC_TO_SAMPLE(
1452			di->bm->fg_params->accu_charging);
1453
1454		ab8500_fg_coulomb_counter(di, true);
1455		ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_READOUT);
1456
1457		break;
1458
1459	case AB8500_FG_CHARGE_READOUT:
1460		/*
1461		 * Read the FG and calculate the new capacity
1462		 */
1463		mutex_lock(&di->cc_lock);
1464		if (!di->flags.conv_done && !di->flags.force_full) {
1465			/* Wasn't the CC IRQ that got us here */
1466			mutex_unlock(&di->cc_lock);
1467			dev_dbg(di->dev, "%s CC conv not done\n",
1468				__func__);
1469
1470			break;
1471		}
1472		di->flags.conv_done = false;
1473		mutex_unlock(&di->cc_lock);
1474
1475		ab8500_fg_calc_cap_charging(di);
1476
1477		break;
1478
1479	default:
1480		break;
1481	}
1482
1483	/* Check capacity limits */
1484	ab8500_fg_check_capacity_limits(di, false);
1485}
1486
1487static void force_capacity(struct ab8500_fg *di)
1488{
1489	int cap;
1490
1491	ab8500_fg_clear_cap_samples(di);
1492	cap = di->bat_cap.user_mah;
1493	if (cap > di->bat_cap.max_mah_design) {
1494		dev_dbg(di->dev, "Remaining cap %d can't be bigger than total"
1495			" %d\n", cap, di->bat_cap.max_mah_design);
1496		cap = di->bat_cap.max_mah_design;
1497	}
1498	ab8500_fg_fill_cap_sample(di, di->bat_cap.user_mah);
1499	di->bat_cap.permille = ab8500_fg_convert_mah_to_permille(di, cap);
1500	di->bat_cap.mah = cap;
1501	ab8500_fg_check_capacity_limits(di, true);
1502}
1503
1504static bool check_sysfs_capacity(struct ab8500_fg *di)
1505{
1506	int cap, lower, upper;
1507	int cap_permille;
1508
1509	cap = di->bat_cap.user_mah;
1510
1511	cap_permille = ab8500_fg_convert_mah_to_permille(di,
1512		di->bat_cap.user_mah);
1513
1514	lower = di->bat_cap.permille - di->bm->fg_params->user_cap_limit * 10;
1515	upper = di->bat_cap.permille + di->bm->fg_params->user_cap_limit * 10;
1516
1517	if (lower < 0)
1518		lower = 0;
1519	/* 1000 is permille, -> 100 percent */
1520	if (upper > 1000)
1521		upper = 1000;
1522
1523	dev_dbg(di->dev, "Capacity limits:"
1524		" (Lower: %d User: %d Upper: %d) [user: %d, was: %d]\n",
1525		lower, cap_permille, upper, cap, di->bat_cap.mah);
1526
1527	/* If within limits, use the saved capacity and exit estimation...*/
1528	if (cap_permille > lower && cap_permille < upper) {
1529		dev_dbg(di->dev, "OK! Using users cap %d uAh now\n", cap);
1530		force_capacity(di);
1531		return true;
1532	}
1533	dev_dbg(di->dev, "Capacity from user out of limits, ignoring");
1534	return false;
1535}
1536
1537/**
1538 * ab8500_fg_algorithm_discharging() - FG algorithm for when discharging
1539 * @di:		pointer to the ab8500_fg structure
1540 *
1541 * Battery capacity calculation state machine for when we're discharging
1542 */
1543static void ab8500_fg_algorithm_discharging(struct ab8500_fg *di)
1544{
1545	int sleep_time;
1546
1547	/* If we change to charge mode we should start with init */
1548	if (di->charge_state != AB8500_FG_CHARGE_INIT)
1549		ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
1550
1551	switch (di->discharge_state) {
1552	case AB8500_FG_DISCHARGE_INIT:
1553		/* We use the FG IRQ to work on */
1554		di->init_cnt = 0;
1555		di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
1556		ab8500_fg_coulomb_counter(di, true);
1557		ab8500_fg_discharge_state_to(di,
1558			AB8500_FG_DISCHARGE_INITMEASURING);
1559
1560		fallthrough;
1561	case AB8500_FG_DISCHARGE_INITMEASURING:
1562		/*
1563		 * Discard a number of samples during startup.
1564		 * After that, use compensated voltage for a few
1565		 * samples to get an initial capacity.
1566		 * Then go to READOUT
1567		 */
1568		sleep_time = di->bm->fg_params->init_timer;
1569
1570		/* Discard the first [x] seconds */
1571		if (di->init_cnt > di->bm->fg_params->init_discard_time) {
1572			ab8500_fg_calc_cap_discharge_voltage(di);
1573
1574			ab8500_fg_check_capacity_limits(di, true);
1575		}
1576
1577		di->init_cnt += sleep_time;
1578		if (di->init_cnt > di->bm->fg_params->init_total_time)
1579			ab8500_fg_discharge_state_to(di,
1580				AB8500_FG_DISCHARGE_READOUT_INIT);
1581
1582		break;
1583
1584	case AB8500_FG_DISCHARGE_INIT_RECOVERY:
1585		di->recovery_cnt = 0;
1586		di->recovery_needed = true;
1587		ab8500_fg_discharge_state_to(di,
1588			AB8500_FG_DISCHARGE_RECOVERY);
1589
1590		fallthrough;
1591
1592	case AB8500_FG_DISCHARGE_RECOVERY:
1593		sleep_time = di->bm->fg_params->recovery_sleep_timer;
1594
1595		/*
1596		 * We should check the power consumption
1597		 * If low, go to READOUT (after x min) or
1598		 * RECOVERY_SLEEP if time left.
1599		 * If high, go to READOUT
1600		 */
1601		di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1602
1603		if (ab8500_fg_is_low_curr(di, di->inst_curr_ua)) {
1604			if (di->recovery_cnt >
1605				di->bm->fg_params->recovery_total_time) {
1606				di->fg_samples = SEC_TO_SAMPLE(
1607					di->bm->fg_params->accu_high_curr);
1608				ab8500_fg_coulomb_counter(di, true);
1609				ab8500_fg_discharge_state_to(di,
1610					AB8500_FG_DISCHARGE_READOUT);
1611				di->recovery_needed = false;
1612			} else {
1613				queue_delayed_work(di->fg_wq,
1614					&di->fg_periodic_work,
1615					sleep_time * HZ);
1616			}
1617			di->recovery_cnt += sleep_time;
1618		} else {
1619			di->fg_samples = SEC_TO_SAMPLE(
1620				di->bm->fg_params->accu_high_curr);
1621			ab8500_fg_coulomb_counter(di, true);
1622			ab8500_fg_discharge_state_to(di,
1623				AB8500_FG_DISCHARGE_READOUT);
1624		}
1625		break;
1626
1627	case AB8500_FG_DISCHARGE_READOUT_INIT:
1628		di->fg_samples = SEC_TO_SAMPLE(
1629			di->bm->fg_params->accu_high_curr);
1630		ab8500_fg_coulomb_counter(di, true);
1631		ab8500_fg_discharge_state_to(di,
1632				AB8500_FG_DISCHARGE_READOUT);
1633		break;
1634
1635	case AB8500_FG_DISCHARGE_READOUT:
1636		di->inst_curr_ua = ab8500_fg_inst_curr_blocking(di);
1637
1638		if (ab8500_fg_is_low_curr(di, di->inst_curr_ua)) {
1639			/* Detect mode change */
1640			if (di->high_curr_mode) {
1641				di->high_curr_mode = false;
1642				di->high_curr_cnt = 0;
1643			}
1644
1645			if (di->recovery_needed) {
1646				ab8500_fg_discharge_state_to(di,
1647					AB8500_FG_DISCHARGE_INIT_RECOVERY);
1648
1649				queue_delayed_work(di->fg_wq,
1650					&di->fg_periodic_work, 0);
1651
1652				break;
1653			}
1654
1655			ab8500_fg_calc_cap_discharge_voltage(di);
1656		} else {
1657			mutex_lock(&di->cc_lock);
1658			if (!di->flags.conv_done) {
1659				/* Wasn't the CC IRQ that got us here */
1660				mutex_unlock(&di->cc_lock);
1661				dev_dbg(di->dev, "%s CC conv not done\n",
1662					__func__);
1663
1664				break;
1665			}
1666			di->flags.conv_done = false;
1667			mutex_unlock(&di->cc_lock);
1668
1669			/* Detect mode change */
1670			if (!di->high_curr_mode) {
1671				di->high_curr_mode = true;
1672				di->high_curr_cnt = 0;
1673			}
1674
1675			di->high_curr_cnt +=
1676				di->bm->fg_params->accu_high_curr;
1677			if (di->high_curr_cnt >
1678				di->bm->fg_params->high_curr_time)
1679				di->recovery_needed = true;
1680
1681			ab8500_fg_calc_cap_discharge_fg(di);
1682		}
1683
1684		ab8500_fg_check_capacity_limits(di, false);
1685
1686		break;
1687
1688	case AB8500_FG_DISCHARGE_WAKEUP:
1689		ab8500_fg_calc_cap_discharge_voltage(di);
1690
1691		di->fg_samples = SEC_TO_SAMPLE(
1692			di->bm->fg_params->accu_high_curr);
1693		ab8500_fg_coulomb_counter(di, true);
1694		ab8500_fg_discharge_state_to(di,
1695				AB8500_FG_DISCHARGE_READOUT);
1696
1697		ab8500_fg_check_capacity_limits(di, false);
1698
1699		break;
1700
1701	default:
1702		break;
1703	}
1704}
1705
1706/**
1707 * ab8500_fg_algorithm_calibrate() - Internal columb counter offset calibration
1708 * @di:		pointer to the ab8500_fg structure
1709 *
1710 */
1711static void ab8500_fg_algorithm_calibrate(struct ab8500_fg *di)
1712{
1713	int ret;
1714
1715	switch (di->calib_state) {
1716	case AB8500_FG_CALIB_INIT:
1717		dev_dbg(di->dev, "Calibration ongoing...\n");
1718
1719		ret = abx500_mask_and_set_register_interruptible(di->dev,
1720			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1721			CC_INT_CAL_N_AVG_MASK, CC_INT_CAL_SAMPLES_8);
1722		if (ret < 0)
1723			goto err;
1724
1725		ret = abx500_mask_and_set_register_interruptible(di->dev,
1726			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1727			CC_INTAVGOFFSET_ENA, CC_INTAVGOFFSET_ENA);
1728		if (ret < 0)
1729			goto err;
1730		di->calib_state = AB8500_FG_CALIB_WAIT;
1731		break;
1732	case AB8500_FG_CALIB_END:
1733		ret = abx500_mask_and_set_register_interruptible(di->dev,
1734			AB8500_GAS_GAUGE, AB8500_GASG_CC_CTRL_REG,
1735			CC_MUXOFFSET, CC_MUXOFFSET);
1736		if (ret < 0)
1737			goto err;
1738		di->flags.calibrate = false;
1739		dev_dbg(di->dev, "Calibration done...\n");
1740		queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1741		break;
1742	case AB8500_FG_CALIB_WAIT:
1743		dev_dbg(di->dev, "Calibration WFI\n");
1744		break;
1745	default:
1746		break;
1747	}
1748	return;
1749err:
1750	/* Something went wrong, don't calibrate then */
1751	dev_err(di->dev, "failed to calibrate the CC\n");
1752	di->flags.calibrate = false;
1753	di->calib_state = AB8500_FG_CALIB_INIT;
1754	queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1755}
1756
1757/**
1758 * ab8500_fg_algorithm() - Entry point for the FG algorithm
1759 * @di:		pointer to the ab8500_fg structure
1760 *
1761 * Entry point for the battery capacity calculation state machine
1762 */
1763static void ab8500_fg_algorithm(struct ab8500_fg *di)
1764{
1765	if (di->flags.calibrate)
1766		ab8500_fg_algorithm_calibrate(di);
1767	else {
1768		if (di->flags.charging)
1769			ab8500_fg_algorithm_charging(di);
1770		else
1771			ab8500_fg_algorithm_discharging(di);
1772	}
1773
1774	dev_dbg(di->dev, "[FG_DATA] %d %d %d %d %d %d %d %d %d %d "
1775		"%d %d %d %d %d %d %d\n",
1776		di->bat_cap.max_mah_design,
1777		di->bat_cap.max_mah,
1778		di->bat_cap.mah,
1779		di->bat_cap.permille,
1780		di->bat_cap.level,
1781		di->bat_cap.prev_mah,
1782		di->bat_cap.prev_percent,
1783		di->bat_cap.prev_level,
1784		di->vbat_uv,
1785		di->inst_curr_ua,
1786		di->avg_curr_ua,
1787		di->accu_charge,
1788		di->flags.charging,
1789		di->charge_state,
1790		di->discharge_state,
1791		di->high_curr_mode,
1792		di->recovery_needed);
1793}
1794
1795/**
1796 * ab8500_fg_periodic_work() - Run the FG state machine periodically
1797 * @work:	pointer to the work_struct structure
1798 *
1799 * Work queue function for periodic work
1800 */
1801static void ab8500_fg_periodic_work(struct work_struct *work)
1802{
1803	struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1804		fg_periodic_work.work);
1805
1806	if (di->init_capacity) {
1807		/* Get an initial capacity calculation */
1808		ab8500_fg_calc_cap_discharge_voltage(di);
1809		ab8500_fg_check_capacity_limits(di, true);
1810		di->init_capacity = false;
1811
1812		queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1813	} else if (di->flags.user_cap) {
1814		if (check_sysfs_capacity(di)) {
1815			ab8500_fg_check_capacity_limits(di, true);
1816			if (di->flags.charging)
1817				ab8500_fg_charge_state_to(di,
1818					AB8500_FG_CHARGE_INIT);
1819			else
1820				ab8500_fg_discharge_state_to(di,
1821					AB8500_FG_DISCHARGE_READOUT_INIT);
1822		}
1823		di->flags.user_cap = false;
1824		queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
1825	} else
1826		ab8500_fg_algorithm(di);
1827
1828}
1829
1830/**
1831 * ab8500_fg_check_hw_failure_work() - Check OVV_BAT condition
1832 * @work:	pointer to the work_struct structure
1833 *
1834 * Work queue function for checking the OVV_BAT condition
1835 */
1836static void ab8500_fg_check_hw_failure_work(struct work_struct *work)
1837{
1838	int ret;
1839	u8 reg_value;
1840
1841	struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1842		fg_check_hw_failure_work.work);
1843
1844	/*
1845	 * If we have had a battery over-voltage situation,
1846	 * check ovv-bit to see if it should be reset.
1847	 */
1848	ret = abx500_get_register_interruptible(di->dev,
1849		AB8500_CHARGER, AB8500_CH_STAT_REG,
1850		&reg_value);
1851	if (ret < 0) {
1852		dev_err(di->dev, "%s ab8500 read failed\n", __func__);
1853		return;
1854	}
1855	if ((reg_value & BATT_OVV) == BATT_OVV) {
1856		if (!di->flags.bat_ovv) {
1857			dev_dbg(di->dev, "Battery OVV\n");
1858			di->flags.bat_ovv = true;
1859			power_supply_changed(di->fg_psy);
1860		}
1861		/* Not yet recovered from ovv, reschedule this test */
1862		queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work,
1863				   HZ);
1864		} else {
1865			dev_dbg(di->dev, "Battery recovered from OVV\n");
1866			di->flags.bat_ovv = false;
1867			power_supply_changed(di->fg_psy);
1868	}
1869}
1870
1871/**
1872 * ab8500_fg_low_bat_work() - Check LOW_BAT condition
1873 * @work:	pointer to the work_struct structure
1874 *
1875 * Work queue function for checking the LOW_BAT condition
1876 */
1877static void ab8500_fg_low_bat_work(struct work_struct *work)
1878{
1879	int vbat_uv;
1880
1881	struct ab8500_fg *di = container_of(work, struct ab8500_fg,
1882		fg_low_bat_work.work);
1883
1884	vbat_uv = ab8500_fg_bat_voltage(di);
1885
1886	/* Check if LOW_BAT still fulfilled */
1887	if (vbat_uv < di->bm->fg_params->lowbat_threshold_uv) {
1888		/* Is it time to shut down? */
1889		if (di->low_bat_cnt < 1) {
1890			di->flags.low_bat = true;
1891			dev_warn(di->dev, "Shut down pending...\n");
1892		} else {
1893			/*
1894			* Else we need to re-schedule this check to be able to detect
1895			* if the voltage increases again during charging or
1896			* due to decreasing load.
1897			*/
1898			di->low_bat_cnt--;
1899			dev_warn(di->dev, "Battery voltage still LOW\n");
1900			queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
1901				round_jiffies(LOW_BAT_CHECK_INTERVAL));
1902		}
1903	} else {
1904		di->flags.low_bat_delay = false;
1905		di->low_bat_cnt = 10;
1906		dev_warn(di->dev, "Battery voltage OK again\n");
1907	}
1908
1909	/* This is needed to dispatch LOW_BAT */
1910	ab8500_fg_check_capacity_limits(di, false);
1911}
1912
1913/**
1914 * ab8500_fg_battok_calc - calculate the bit pattern corresponding
1915 * to the target voltage.
1916 * @di:       pointer to the ab8500_fg structure
1917 * @target:   target voltage
1918 *
1919 * Returns bit pattern closest to the target voltage
1920 * valid return values are 0-14. (0-BATT_OK_MAX_NR_INCREMENTS)
1921 */
1922
1923static int ab8500_fg_battok_calc(struct ab8500_fg *di, int target)
1924{
1925	if (target > BATT_OK_MIN +
1926		(BATT_OK_INCREMENT * BATT_OK_MAX_NR_INCREMENTS))
1927		return BATT_OK_MAX_NR_INCREMENTS;
1928	if (target < BATT_OK_MIN)
1929		return 0;
1930	return (target - BATT_OK_MIN) / BATT_OK_INCREMENT;
1931}
1932
1933/**
1934 * ab8500_fg_battok_init_hw_register - init battok levels
1935 * @di:       pointer to the ab8500_fg structure
1936 *
1937 */
1938
1939static int ab8500_fg_battok_init_hw_register(struct ab8500_fg *di)
1940{
1941	int selected;
1942	int sel0;
1943	int sel1;
1944	int cbp_sel0;
1945	int cbp_sel1;
1946	int ret;
1947	int new_val;
1948
1949	sel0 = di->bm->fg_params->battok_falling_th_sel0;
1950	sel1 = di->bm->fg_params->battok_raising_th_sel1;
1951
1952	cbp_sel0 = ab8500_fg_battok_calc(di, sel0);
1953	cbp_sel1 = ab8500_fg_battok_calc(di, sel1);
1954
1955	selected = BATT_OK_MIN + cbp_sel0 * BATT_OK_INCREMENT;
1956
1957	if (selected != sel0)
1958		dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1959			sel0, selected, cbp_sel0);
1960
1961	selected = BATT_OK_MIN + cbp_sel1 * BATT_OK_INCREMENT;
1962
1963	if (selected != sel1)
1964		dev_warn(di->dev, "Invalid voltage step:%d, using %d %d\n",
1965			sel1, selected, cbp_sel1);
1966
1967	new_val = cbp_sel0 | (cbp_sel1 << 4);
1968
1969	dev_dbg(di->dev, "using: %x %d %d\n", new_val, cbp_sel0, cbp_sel1);
1970	ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK,
1971		AB8500_BATT_OK_REG, new_val);
1972	return ret;
1973}
1974
1975/**
1976 * ab8500_fg_instant_work() - Run the FG state machine instantly
1977 * @work:	pointer to the work_struct structure
1978 *
1979 * Work queue function for instant work
1980 */
1981static void ab8500_fg_instant_work(struct work_struct *work)
1982{
1983	struct ab8500_fg *di = container_of(work, struct ab8500_fg, fg_work);
1984
1985	ab8500_fg_algorithm(di);
1986}
1987
1988/**
1989 * ab8500_fg_cc_data_end_handler() - end of data conversion isr.
1990 * @irq:       interrupt number
1991 * @_di:       pointer to the ab8500_fg structure
1992 *
1993 * Returns IRQ status(IRQ_HANDLED)
1994 */
1995static irqreturn_t ab8500_fg_cc_data_end_handler(int irq, void *_di)
1996{
1997	struct ab8500_fg *di = _di;
1998	if (!di->nbr_cceoc_irq_cnt) {
1999		di->nbr_cceoc_irq_cnt++;
2000		complete(&di->ab8500_fg_started);
2001	} else {
2002		di->nbr_cceoc_irq_cnt = 0;
2003		complete(&di->ab8500_fg_complete);
2004	}
2005	return IRQ_HANDLED;
2006}
2007
2008/**
2009 * ab8500_fg_cc_int_calib_handler () - end of calibration isr.
2010 * @irq:       interrupt number
2011 * @_di:       pointer to the ab8500_fg structure
2012 *
2013 * Returns IRQ status(IRQ_HANDLED)
2014 */
2015static irqreturn_t ab8500_fg_cc_int_calib_handler(int irq, void *_di)
2016{
2017	struct ab8500_fg *di = _di;
2018	di->calib_state = AB8500_FG_CALIB_END;
2019	queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2020	return IRQ_HANDLED;
2021}
2022
2023/**
2024 * ab8500_fg_cc_convend_handler() - isr to get battery avg current.
2025 * @irq:       interrupt number
2026 * @_di:       pointer to the ab8500_fg structure
2027 *
2028 * Returns IRQ status(IRQ_HANDLED)
2029 */
2030static irqreturn_t ab8500_fg_cc_convend_handler(int irq, void *_di)
2031{
2032	struct ab8500_fg *di = _di;
2033
2034	queue_work(di->fg_wq, &di->fg_acc_cur_work);
2035
2036	return IRQ_HANDLED;
2037}
2038
2039/**
2040 * ab8500_fg_batt_ovv_handler() - Battery OVV occured
2041 * @irq:       interrupt number
2042 * @_di:       pointer to the ab8500_fg structure
2043 *
2044 * Returns IRQ status(IRQ_HANDLED)
2045 */
2046static irqreturn_t ab8500_fg_batt_ovv_handler(int irq, void *_di)
2047{
2048	struct ab8500_fg *di = _di;
2049
2050	dev_dbg(di->dev, "Battery OVV\n");
2051
2052	/* Schedule a new HW failure check */
2053	queue_delayed_work(di->fg_wq, &di->fg_check_hw_failure_work, 0);
2054
2055	return IRQ_HANDLED;
2056}
2057
2058/**
2059 * ab8500_fg_lowbatf_handler() - Battery voltage is below LOW threshold
2060 * @irq:       interrupt number
2061 * @_di:       pointer to the ab8500_fg structure
2062 *
2063 * Returns IRQ status(IRQ_HANDLED)
2064 */
2065static irqreturn_t ab8500_fg_lowbatf_handler(int irq, void *_di)
2066{
2067	struct ab8500_fg *di = _di;
2068
2069	/* Initiate handling in ab8500_fg_low_bat_work() if not already initiated. */
2070	if (!di->flags.low_bat_delay) {
2071		dev_warn(di->dev, "Battery voltage is below LOW threshold\n");
2072		di->flags.low_bat_delay = true;
2073		/*
2074		 * Start a timer to check LOW_BAT again after some time
2075		 * This is done to avoid shutdown on single voltage dips
2076		 */
2077		queue_delayed_work(di->fg_wq, &di->fg_low_bat_work,
2078			round_jiffies(LOW_BAT_CHECK_INTERVAL));
2079	}
2080	return IRQ_HANDLED;
2081}
2082
2083/**
2084 * ab8500_fg_get_property() - get the fg properties
2085 * @psy:	pointer to the power_supply structure
2086 * @psp:	pointer to the power_supply_property structure
2087 * @val:	pointer to the power_supply_propval union
2088 *
2089 * This function gets called when an application tries to get the
2090 * fg properties by reading the sysfs files.
2091 * voltage_now:		battery voltage
2092 * current_now:		battery instant current
2093 * current_avg:		battery average current
2094 * charge_full_design:	capacity where battery is considered full
2095 * charge_now:		battery capacity in nAh
2096 * capacity:		capacity in percent
2097 * capacity_level:	capacity level
2098 *
2099 * Returns error code in case of failure else 0 on success
2100 */
2101static int ab8500_fg_get_property(struct power_supply *psy,
2102	enum power_supply_property psp,
2103	union power_supply_propval *val)
2104{
2105	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2106
2107	/*
2108	 * If battery is identified as unknown and charging of unknown
2109	 * batteries is disabled, we always report 100% capacity and
2110	 * capacity level UNKNOWN, since we can't calculate
2111	 * remaining capacity
2112	 */
2113
2114	switch (psp) {
2115	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
2116		if (di->flags.bat_ovv)
2117			val->intval = BATT_OVV_VALUE;
2118		else
2119			val->intval = di->vbat_uv;
2120		break;
2121	case POWER_SUPPLY_PROP_CURRENT_NOW:
2122		val->intval = di->inst_curr_ua;
2123		break;
2124	case POWER_SUPPLY_PROP_CURRENT_AVG:
2125		val->intval = di->avg_curr_ua;
2126		break;
2127	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
2128		val->intval = ab8500_fg_convert_mah_to_uwh(di,
2129				di->bat_cap.max_mah_design);
2130		break;
2131	case POWER_SUPPLY_PROP_ENERGY_FULL:
2132		val->intval = ab8500_fg_convert_mah_to_uwh(di,
2133				di->bat_cap.max_mah);
2134		break;
2135	case POWER_SUPPLY_PROP_ENERGY_NOW:
2136		if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2137				di->flags.batt_id_received)
2138			val->intval = ab8500_fg_convert_mah_to_uwh(di,
2139					di->bat_cap.max_mah);
2140		else
2141			val->intval = ab8500_fg_convert_mah_to_uwh(di,
2142					di->bat_cap.prev_mah);
2143		break;
2144	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
2145		val->intval = di->bat_cap.max_mah_design;
2146		break;
2147	case POWER_SUPPLY_PROP_CHARGE_FULL:
2148		val->intval = di->bat_cap.max_mah;
2149		break;
2150	case POWER_SUPPLY_PROP_CHARGE_NOW:
2151		if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2152				di->flags.batt_id_received)
2153			val->intval = di->bat_cap.max_mah;
2154		else
2155			val->intval = di->bat_cap.prev_mah;
2156		break;
2157	case POWER_SUPPLY_PROP_CAPACITY:
2158		if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2159				di->flags.batt_id_received)
2160			val->intval = 100;
2161		else
2162			val->intval = di->bat_cap.prev_percent;
2163		break;
2164	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
2165		if (di->flags.batt_unknown && !di->bm->chg_unknown_bat &&
2166				di->flags.batt_id_received)
2167			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
2168		else
2169			val->intval = di->bat_cap.prev_level;
2170		break;
2171	default:
2172		return -EINVAL;
2173	}
2174	return 0;
2175}
2176
2177static int ab8500_fg_get_ext_psy_data(struct power_supply *ext, void *data)
2178{
2179	struct power_supply *psy;
2180	const char **supplicants = (const char **)ext->supplied_to;
2181	struct ab8500_fg *di;
2182	struct power_supply_battery_info *bi;
2183	union power_supply_propval ret;
2184	int j;
2185
2186	psy = (struct power_supply *)data;
2187	di = power_supply_get_drvdata(psy);
2188	bi = di->bm->bi;
2189
2190	/*
2191	 * For all psy where the name of your driver
2192	 * appears in any supplied_to
2193	 */
2194	j = match_string(supplicants, ext->num_supplicants, psy->desc->name);
2195	if (j < 0)
2196		return 0;
2197
2198	/* Go through all properties for the psy */
2199	for (j = 0; j < ext->desc->num_properties; j++) {
2200		enum power_supply_property prop;
2201		prop = ext->desc->properties[j];
2202
2203		if (power_supply_get_property(ext, prop, &ret))
2204			continue;
2205
2206		switch (prop) {
2207		case POWER_SUPPLY_PROP_STATUS:
2208			switch (ext->desc->type) {
2209			case POWER_SUPPLY_TYPE_BATTERY:
2210				switch (ret.intval) {
2211				case POWER_SUPPLY_STATUS_UNKNOWN:
2212				case POWER_SUPPLY_STATUS_DISCHARGING:
2213				case POWER_SUPPLY_STATUS_NOT_CHARGING:
2214					if (!di->flags.charging)
2215						break;
2216					di->flags.charging = false;
2217					di->flags.fully_charged = false;
2218					if (di->bm->capacity_scaling)
2219						ab8500_fg_update_cap_scalers(di);
2220					queue_work(di->fg_wq, &di->fg_work);
2221					break;
2222				case POWER_SUPPLY_STATUS_FULL:
2223					if (di->flags.fully_charged)
2224						break;
2225					di->flags.fully_charged = true;
2226					di->flags.force_full = true;
2227					/* Save current capacity as maximum */
2228					di->bat_cap.max_mah = di->bat_cap.mah;
2229					queue_work(di->fg_wq, &di->fg_work);
2230					break;
2231				case POWER_SUPPLY_STATUS_CHARGING:
2232					if (di->flags.charging &&
2233						!di->flags.fully_charged)
2234						break;
2235					di->flags.charging = true;
2236					di->flags.fully_charged = false;
2237					if (di->bm->capacity_scaling)
2238						ab8500_fg_update_cap_scalers(di);
2239					queue_work(di->fg_wq, &di->fg_work);
2240					break;
2241				}
2242				break;
2243			default:
2244				break;
2245			}
2246			break;
2247		case POWER_SUPPLY_PROP_TECHNOLOGY:
2248			switch (ext->desc->type) {
2249			case POWER_SUPPLY_TYPE_BATTERY:
2250				if (!di->flags.batt_id_received &&
2251				    (bi && (bi->technology !=
2252					    POWER_SUPPLY_TECHNOLOGY_UNKNOWN))) {
2253					di->flags.batt_id_received = true;
2254
2255					di->bat_cap.max_mah_design =
2256						di->bm->bi->charge_full_design_uah;
2257
2258					di->bat_cap.max_mah =
2259						di->bat_cap.max_mah_design;
2260
2261					di->vbat_nom_uv =
2262						di->bm->bi->voltage_max_design_uv;
2263				}
2264
2265				if (ret.intval)
2266					di->flags.batt_unknown = false;
2267				else
2268					di->flags.batt_unknown = true;
2269				break;
2270			default:
2271				break;
2272			}
2273			break;
2274		case POWER_SUPPLY_PROP_TEMP:
2275			switch (ext->desc->type) {
2276			case POWER_SUPPLY_TYPE_BATTERY:
2277				if (di->flags.batt_id_received)
2278					di->bat_temp = ret.intval;
2279				break;
2280			default:
2281				break;
2282			}
2283			break;
2284		default:
2285			break;
2286		}
2287	}
2288	return 0;
2289}
2290
2291/**
2292 * ab8500_fg_init_hw_registers() - Set up FG related registers
2293 * @di:		pointer to the ab8500_fg structure
2294 *
2295 * Set up battery OVV, low battery voltage registers
2296 */
2297static int ab8500_fg_init_hw_registers(struct ab8500_fg *di)
2298{
2299	int ret;
2300
2301	/*
2302	 * Set VBAT OVV (overvoltage) threshold to 4.75V (typ) this is what
2303	 * the hardware supports, nothing else can be configured in hardware.
2304	 * See this as an "outer limit" where the charger will certainly
2305	 * shut down. Other (lower) overvoltage levels need to be implemented
2306	 * in software.
2307	 */
2308	ret = abx500_mask_and_set_register_interruptible(di->dev,
2309		AB8500_CHARGER,
2310		AB8500_BATT_OVV,
2311		BATT_OVV_TH_4P75,
2312		BATT_OVV_TH_4P75);
2313	if (ret) {
2314		dev_err(di->dev, "failed to set BATT_OVV\n");
2315		goto out;
2316	}
2317
2318	/* Enable VBAT OVV detection */
2319	ret = abx500_mask_and_set_register_interruptible(di->dev,
2320		AB8500_CHARGER,
2321		AB8500_BATT_OVV,
2322		BATT_OVV_ENA,
2323		BATT_OVV_ENA);
2324	if (ret) {
2325		dev_err(di->dev, "failed to enable BATT_OVV\n");
2326		goto out;
2327	}
2328
2329	/* Low Battery Voltage */
2330	ret = abx500_set_register_interruptible(di->dev,
2331		AB8500_SYS_CTRL2_BLOCK,
2332		AB8500_LOW_BAT_REG,
2333		ab8500_volt_to_regval(
2334			di->bm->fg_params->lowbat_threshold_uv) << 1 |
2335		LOW_BAT_ENABLE);
2336	if (ret) {
2337		dev_err(di->dev, "%s write failed\n", __func__);
2338		goto out;
2339	}
2340
2341	/* Battery OK threshold */
2342	ret = ab8500_fg_battok_init_hw_register(di);
2343	if (ret) {
2344		dev_err(di->dev, "BattOk init write failed.\n");
2345		goto out;
2346	}
2347
2348	if (is_ab8505(di->parent)) {
2349		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2350			AB8505_RTC_PCUT_MAX_TIME_REG, di->bm->fg_params->pcut_max_time);
2351
2352		if (ret) {
2353			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_MAX_TIME_REG\n", __func__);
2354			goto out;
2355		}
2356
2357		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2358			AB8505_RTC_PCUT_FLAG_TIME_REG, di->bm->fg_params->pcut_flag_time);
2359
2360		if (ret) {
2361			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_FLAG_TIME_REG\n", __func__);
2362			goto out;
2363		}
2364
2365		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2366			AB8505_RTC_PCUT_RESTART_REG, di->bm->fg_params->pcut_max_restart);
2367
2368		if (ret) {
2369			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_RESTART_REG\n", __func__);
2370			goto out;
2371		}
2372
2373		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2374			AB8505_RTC_PCUT_DEBOUNCE_REG, di->bm->fg_params->pcut_debounce_time);
2375
2376		if (ret) {
2377			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_DEBOUNCE_REG\n", __func__);
2378			goto out;
2379		}
2380
2381		ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2382			AB8505_RTC_PCUT_CTL_STATUS_REG, di->bm->fg_params->pcut_enable);
2383
2384		if (ret) {
2385			dev_err(di->dev, "%s write failed AB8505_RTC_PCUT_CTL_STATUS_REG\n", __func__);
2386			goto out;
2387		}
2388	}
2389out:
2390	return ret;
2391}
2392
2393/**
2394 * ab8500_fg_external_power_changed() - callback for power supply changes
2395 * @psy:       pointer to the structure power_supply
2396 *
2397 * This function is the entry point of the pointer external_power_changed
2398 * of the structure power_supply.
2399 * This function gets executed when there is a change in any external power
2400 * supply that this driver needs to be notified of.
2401 */
2402static void ab8500_fg_external_power_changed(struct power_supply *psy)
2403{
2404	power_supply_for_each_psy(psy, ab8500_fg_get_ext_psy_data);
2405}
2406
2407/**
2408 * ab8500_fg_reinit_work() - work to reset the FG algorithm
2409 * @work:	pointer to the work_struct structure
2410 *
2411 * Used to reset the current battery capacity to be able to
2412 * retrigger a new voltage base capacity calculation. For
2413 * test and verification purpose.
2414 */
2415static void ab8500_fg_reinit_work(struct work_struct *work)
2416{
2417	struct ab8500_fg *di = container_of(work, struct ab8500_fg,
2418		fg_reinit_work.work);
2419
2420	if (!di->flags.calibrate) {
2421		dev_dbg(di->dev, "Resetting FG state machine to init.\n");
2422		ab8500_fg_clear_cap_samples(di);
2423		ab8500_fg_calc_cap_discharge_voltage(di);
2424		ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
2425		ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
2426		queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2427
2428	} else {
2429		dev_err(di->dev, "Residual offset calibration ongoing "
2430			"retrying..\n");
2431		/* Wait one second until next try*/
2432		queue_delayed_work(di->fg_wq, &di->fg_reinit_work,
2433			round_jiffies(1));
2434	}
2435}
2436
2437/* Exposure to the sysfs interface */
2438
2439struct ab8500_fg_sysfs_entry {
2440	struct attribute attr;
2441	ssize_t (*show)(struct ab8500_fg *, char *);
2442	ssize_t (*store)(struct ab8500_fg *, const char *, size_t);
2443};
2444
2445static ssize_t charge_full_show(struct ab8500_fg *di, char *buf)
2446{
2447	return sysfs_emit(buf, "%d\n", di->bat_cap.max_mah);
2448}
2449
2450static ssize_t charge_full_store(struct ab8500_fg *di, const char *buf,
2451				 size_t count)
2452{
2453	unsigned long charge_full;
2454	int ret;
2455
2456	ret = kstrtoul(buf, 10, &charge_full);
2457	if (ret)
2458		return ret;
2459
2460	di->bat_cap.max_mah = (int) charge_full;
2461	return count;
2462}
2463
2464static ssize_t charge_now_show(struct ab8500_fg *di, char *buf)
2465{
2466	return sysfs_emit(buf, "%d\n", di->bat_cap.prev_mah);
2467}
2468
2469static ssize_t charge_now_store(struct ab8500_fg *di, const char *buf,
2470				 size_t count)
2471{
2472	unsigned long charge_now;
2473	int ret;
2474
2475	ret = kstrtoul(buf, 10, &charge_now);
2476	if (ret)
2477		return ret;
2478
2479	di->bat_cap.user_mah = (int) charge_now;
2480	di->flags.user_cap = true;
2481	queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
2482	return count;
2483}
2484
2485static struct ab8500_fg_sysfs_entry charge_full_attr =
2486	__ATTR(charge_full, 0644, charge_full_show, charge_full_store);
2487
2488static struct ab8500_fg_sysfs_entry charge_now_attr =
2489	__ATTR(charge_now, 0644, charge_now_show, charge_now_store);
2490
2491static ssize_t
2492ab8500_fg_show(struct kobject *kobj, struct attribute *attr, char *buf)
2493{
2494	struct ab8500_fg_sysfs_entry *entry;
2495	struct ab8500_fg *di;
2496
2497	entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2498	di = container_of(kobj, struct ab8500_fg, fg_kobject);
2499
2500	if (!entry->show)
2501		return -EIO;
2502
2503	return entry->show(di, buf);
2504}
2505static ssize_t
2506ab8500_fg_store(struct kobject *kobj, struct attribute *attr, const char *buf,
2507		size_t count)
2508{
2509	struct ab8500_fg_sysfs_entry *entry;
2510	struct ab8500_fg *di;
2511
2512	entry = container_of(attr, struct ab8500_fg_sysfs_entry, attr);
2513	di = container_of(kobj, struct ab8500_fg, fg_kobject);
2514
2515	if (!entry->store)
2516		return -EIO;
2517
2518	return entry->store(di, buf, count);
2519}
2520
2521static const struct sysfs_ops ab8500_fg_sysfs_ops = {
2522	.show = ab8500_fg_show,
2523	.store = ab8500_fg_store,
2524};
2525
2526static struct attribute *ab8500_fg_attrs[] = {
2527	&charge_full_attr.attr,
2528	&charge_now_attr.attr,
2529	NULL,
2530};
2531ATTRIBUTE_GROUPS(ab8500_fg);
2532
2533static const struct kobj_type ab8500_fg_ktype = {
2534	.sysfs_ops = &ab8500_fg_sysfs_ops,
2535	.default_groups = ab8500_fg_groups,
2536};
2537
2538/**
2539 * ab8500_fg_sysfs_exit() - de-init of sysfs entry
2540 * @di:                pointer to the struct ab8500_chargalg
2541 *
2542 * This function removes the entry in sysfs.
2543 */
2544static void ab8500_fg_sysfs_exit(struct ab8500_fg *di)
2545{
2546	kobject_del(&di->fg_kobject);
2547}
2548
2549/**
2550 * ab8500_fg_sysfs_init() - init of sysfs entry
2551 * @di:                pointer to the struct ab8500_chargalg
2552 *
2553 * This function adds an entry in sysfs.
2554 * Returns error code in case of failure else 0(on success)
2555 */
2556static int ab8500_fg_sysfs_init(struct ab8500_fg *di)
2557{
2558	int ret = 0;
2559
2560	ret = kobject_init_and_add(&di->fg_kobject,
2561		&ab8500_fg_ktype,
2562		NULL, "battery");
2563	if (ret < 0) {
2564		kobject_put(&di->fg_kobject);
2565		dev_err(di->dev, "failed to create sysfs entry\n");
2566	}
2567
2568	return ret;
2569}
2570
2571static ssize_t ab8505_powercut_flagtime_read(struct device *dev,
2572			     struct device_attribute *attr,
2573			     char *buf)
2574{
2575	int ret;
2576	u8 reg_value;
2577	struct power_supply *psy = dev_to_psy(dev);
2578	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2579
2580	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2581		AB8505_RTC_PCUT_FLAG_TIME_REG, &reg_value);
2582
2583	if (ret < 0) {
2584		dev_err(dev, "Failed to read AB8505_RTC_PCUT_FLAG_TIME_REG\n");
2585		goto fail;
2586	}
2587
2588	return sysfs_emit(buf, "%d\n", (reg_value & 0x7F));
2589
2590fail:
2591	return ret;
2592}
2593
2594static ssize_t ab8505_powercut_flagtime_write(struct device *dev,
2595				  struct device_attribute *attr,
2596				  const char *buf, size_t count)
2597{
2598	int ret;
2599	int reg_value;
2600	struct power_supply *psy = dev_to_psy(dev);
2601	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2602
2603	if (kstrtoint(buf, 10, &reg_value))
2604		goto fail;
2605
2606	if (reg_value > 0x7F) {
2607		dev_err(dev, "Incorrect parameter, echo 0 (1.98s) - 127 (15.625ms) for flagtime\n");
2608		goto fail;
2609	}
2610
2611	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2612		AB8505_RTC_PCUT_FLAG_TIME_REG, (u8)reg_value);
2613
2614	if (ret < 0)
2615		dev_err(dev, "Failed to set AB8505_RTC_PCUT_FLAG_TIME_REG\n");
2616
2617fail:
2618	return count;
2619}
2620
2621static ssize_t ab8505_powercut_maxtime_read(struct device *dev,
2622			     struct device_attribute *attr,
2623			     char *buf)
2624{
2625	int ret;
2626	u8 reg_value;
2627	struct power_supply *psy = dev_to_psy(dev);
2628	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2629
2630	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2631		AB8505_RTC_PCUT_MAX_TIME_REG, &reg_value);
2632
2633	if (ret < 0) {
2634		dev_err(dev, "Failed to read AB8505_RTC_PCUT_MAX_TIME_REG\n");
2635		goto fail;
2636	}
2637
2638	return sysfs_emit(buf, "%d\n", (reg_value & 0x7F));
2639
2640fail:
2641	return ret;
2642
2643}
2644
2645static ssize_t ab8505_powercut_maxtime_write(struct device *dev,
2646				  struct device_attribute *attr,
2647				  const char *buf, size_t count)
2648{
2649	int ret;
2650	int reg_value;
2651	struct power_supply *psy = dev_to_psy(dev);
2652	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2653
2654	if (kstrtoint(buf, 10, &reg_value))
2655		goto fail;
2656
2657	if (reg_value > 0x7F) {
2658		dev_err(dev, "Incorrect parameter, echo 0 (0.0s) - 127 (1.98s) for maxtime\n");
2659		goto fail;
2660	}
2661
2662	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2663		AB8505_RTC_PCUT_MAX_TIME_REG, (u8)reg_value);
2664
2665	if (ret < 0)
2666		dev_err(dev, "Failed to set AB8505_RTC_PCUT_MAX_TIME_REG\n");
2667
2668fail:
2669	return count;
2670}
2671
2672static ssize_t ab8505_powercut_restart_read(struct device *dev,
2673			     struct device_attribute *attr,
2674			     char *buf)
2675{
2676	int ret;
2677	u8 reg_value;
2678	struct power_supply *psy = dev_to_psy(dev);
2679	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2680
2681	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2682		AB8505_RTC_PCUT_RESTART_REG, &reg_value);
2683
2684	if (ret < 0) {
2685		dev_err(dev, "Failed to read AB8505_RTC_PCUT_RESTART_REG\n");
2686		goto fail;
2687	}
2688
2689	return sysfs_emit(buf, "%d\n", (reg_value & 0xF));
2690
2691fail:
2692	return ret;
2693}
2694
2695static ssize_t ab8505_powercut_restart_write(struct device *dev,
2696					     struct device_attribute *attr,
2697					     const char *buf, size_t count)
2698{
2699	int ret;
2700	int reg_value;
2701	struct power_supply *psy = dev_to_psy(dev);
2702	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2703
2704	if (kstrtoint(buf, 10, &reg_value))
2705		goto fail;
2706
2707	if (reg_value > 0xF) {
2708		dev_err(dev, "Incorrect parameter, echo 0 - 15 for number of restart\n");
2709		goto fail;
2710	}
2711
2712	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2713						AB8505_RTC_PCUT_RESTART_REG, (u8)reg_value);
2714
2715	if (ret < 0)
2716		dev_err(dev, "Failed to set AB8505_RTC_PCUT_RESTART_REG\n");
2717
2718fail:
2719	return count;
2720
2721}
2722
2723static ssize_t ab8505_powercut_timer_read(struct device *dev,
2724					  struct device_attribute *attr,
2725					  char *buf)
2726{
2727	int ret;
2728	u8 reg_value;
2729	struct power_supply *psy = dev_to_psy(dev);
2730	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2731
2732	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2733						AB8505_RTC_PCUT_TIME_REG, &reg_value);
2734
2735	if (ret < 0) {
2736		dev_err(dev, "Failed to read AB8505_RTC_PCUT_TIME_REG\n");
2737		goto fail;
2738	}
2739
2740	return sysfs_emit(buf, "%d\n", (reg_value & 0x7F));
2741
2742fail:
2743	return ret;
2744}
2745
2746static ssize_t ab8505_powercut_restart_counter_read(struct device *dev,
2747						    struct device_attribute *attr,
2748						    char *buf)
2749{
2750	int ret;
2751	u8 reg_value;
2752	struct power_supply *psy = dev_to_psy(dev);
2753	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2754
2755	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2756						AB8505_RTC_PCUT_RESTART_REG, &reg_value);
2757
2758	if (ret < 0) {
2759		dev_err(dev, "Failed to read AB8505_RTC_PCUT_RESTART_REG\n");
2760		goto fail;
2761	}
2762
2763	return sysfs_emit(buf, "%d\n", (reg_value & 0xF0) >> 4);
2764
2765fail:
2766	return ret;
2767}
2768
2769static ssize_t ab8505_powercut_read(struct device *dev,
2770				    struct device_attribute *attr,
2771				    char *buf)
2772{
2773	int ret;
2774	u8 reg_value;
2775	struct power_supply *psy = dev_to_psy(dev);
2776	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2777
2778	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2779						AB8505_RTC_PCUT_CTL_STATUS_REG, &reg_value);
2780
2781	if (ret < 0)
2782		goto fail;
2783
2784	return sysfs_emit(buf, "%d\n", (reg_value & 0x1));
2785
2786fail:
2787	return ret;
2788}
2789
2790static ssize_t ab8505_powercut_write(struct device *dev,
2791				     struct device_attribute *attr,
2792				     const char *buf, size_t count)
2793{
2794	int ret;
2795	int reg_value;
2796	struct power_supply *psy = dev_to_psy(dev);
2797	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2798
2799	if (kstrtoint(buf, 10, &reg_value))
2800		goto fail;
2801
2802	if (reg_value > 0x1) {
2803		dev_err(dev, "Incorrect parameter, echo 0/1 to disable/enable Pcut feature\n");
2804		goto fail;
2805	}
2806
2807	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2808						AB8505_RTC_PCUT_CTL_STATUS_REG, (u8)reg_value);
2809
2810	if (ret < 0)
2811		dev_err(dev, "Failed to set AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2812
2813fail:
2814	return count;
2815}
2816
2817static ssize_t ab8505_powercut_flag_read(struct device *dev,
2818					 struct device_attribute *attr,
2819					 char *buf)
2820{
2821
2822	int ret;
2823	u8 reg_value;
2824	struct power_supply *psy = dev_to_psy(dev);
2825	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2826
2827	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2828						AB8505_RTC_PCUT_CTL_STATUS_REG,  &reg_value);
2829
2830	if (ret < 0) {
2831		dev_err(dev, "Failed to read AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2832		goto fail;
2833	}
2834
2835	return sysfs_emit(buf, "%d\n", ((reg_value & 0x10) >> 4));
2836
2837fail:
2838	return ret;
2839}
2840
2841static ssize_t ab8505_powercut_debounce_read(struct device *dev,
2842					     struct device_attribute *attr,
2843					     char *buf)
2844{
2845	int ret;
2846	u8 reg_value;
2847	struct power_supply *psy = dev_to_psy(dev);
2848	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2849
2850	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2851						AB8505_RTC_PCUT_DEBOUNCE_REG,  &reg_value);
2852
2853	if (ret < 0) {
2854		dev_err(dev, "Failed to read AB8505_RTC_PCUT_DEBOUNCE_REG\n");
2855		goto fail;
2856	}
2857
2858	return sysfs_emit(buf, "%d\n", (reg_value & 0x7));
2859
2860fail:
2861	return ret;
2862}
2863
2864static ssize_t ab8505_powercut_debounce_write(struct device *dev,
2865					      struct device_attribute *attr,
2866					      const char *buf, size_t count)
2867{
2868	int ret;
2869	int reg_value;
2870	struct power_supply *psy = dev_to_psy(dev);
2871	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2872
2873	if (kstrtoint(buf, 10, &reg_value))
2874		goto fail;
2875
2876	if (reg_value > 0x7) {
2877		dev_err(dev, "Incorrect parameter, echo 0 to 7 for debounce setting\n");
2878		goto fail;
2879	}
2880
2881	ret = abx500_set_register_interruptible(di->dev, AB8500_RTC,
2882						AB8505_RTC_PCUT_DEBOUNCE_REG, (u8)reg_value);
2883
2884	if (ret < 0)
2885		dev_err(dev, "Failed to set AB8505_RTC_PCUT_DEBOUNCE_REG\n");
2886
2887fail:
2888	return count;
2889}
2890
2891static ssize_t ab8505_powercut_enable_status_read(struct device *dev,
2892						  struct device_attribute *attr,
2893						  char *buf)
2894{
2895	int ret;
2896	u8 reg_value;
2897	struct power_supply *psy = dev_to_psy(dev);
2898	struct ab8500_fg *di = power_supply_get_drvdata(psy);
2899
2900	ret = abx500_get_register_interruptible(di->dev, AB8500_RTC,
2901						AB8505_RTC_PCUT_CTL_STATUS_REG, &reg_value);
2902
2903	if (ret < 0) {
2904		dev_err(dev, "Failed to read AB8505_RTC_PCUT_CTL_STATUS_REG\n");
2905		goto fail;
2906	}
2907
2908	return sysfs_emit(buf, "%d\n", ((reg_value & 0x20) >> 5));
2909
2910fail:
2911	return ret;
2912}
2913
2914static struct device_attribute ab8505_fg_sysfs_psy_attrs[] = {
2915	__ATTR(powercut_flagtime, (S_IRUGO | S_IWUSR | S_IWGRP),
2916		ab8505_powercut_flagtime_read, ab8505_powercut_flagtime_write),
2917	__ATTR(powercut_maxtime, (S_IRUGO | S_IWUSR | S_IWGRP),
2918		ab8505_powercut_maxtime_read, ab8505_powercut_maxtime_write),
2919	__ATTR(powercut_restart_max, (S_IRUGO | S_IWUSR | S_IWGRP),
2920		ab8505_powercut_restart_read, ab8505_powercut_restart_write),
2921	__ATTR(powercut_timer, S_IRUGO, ab8505_powercut_timer_read, NULL),
2922	__ATTR(powercut_restart_counter, S_IRUGO,
2923		ab8505_powercut_restart_counter_read, NULL),
2924	__ATTR(powercut_enable, (S_IRUGO | S_IWUSR | S_IWGRP),
2925		ab8505_powercut_read, ab8505_powercut_write),
2926	__ATTR(powercut_flag, S_IRUGO, ab8505_powercut_flag_read, NULL),
2927	__ATTR(powercut_debounce_time, (S_IRUGO | S_IWUSR | S_IWGRP),
2928		ab8505_powercut_debounce_read, ab8505_powercut_debounce_write),
2929	__ATTR(powercut_enable_status, S_IRUGO,
2930		ab8505_powercut_enable_status_read, NULL),
2931};
2932
2933static int ab8500_fg_sysfs_psy_create_attrs(struct ab8500_fg *di)
2934{
2935	unsigned int i;
2936
2937	if (is_ab8505(di->parent)) {
2938		for (i = 0; i < ARRAY_SIZE(ab8505_fg_sysfs_psy_attrs); i++)
2939			if (device_create_file(&di->fg_psy->dev,
2940					       &ab8505_fg_sysfs_psy_attrs[i]))
2941				goto sysfs_psy_create_attrs_failed_ab8505;
2942	}
2943	return 0;
2944sysfs_psy_create_attrs_failed_ab8505:
2945	dev_err(&di->fg_psy->dev, "Failed creating sysfs psy attrs for ab8505.\n");
2946	while (i--)
2947		device_remove_file(&di->fg_psy->dev,
2948				   &ab8505_fg_sysfs_psy_attrs[i]);
2949
2950	return -EIO;
2951}
2952
2953static void ab8500_fg_sysfs_psy_remove_attrs(struct ab8500_fg *di)
2954{
2955	unsigned int i;
2956
2957	if (is_ab8505(di->parent)) {
2958		for (i = 0; i < ARRAY_SIZE(ab8505_fg_sysfs_psy_attrs); i++)
2959			(void)device_remove_file(&di->fg_psy->dev,
2960						 &ab8505_fg_sysfs_psy_attrs[i]);
2961	}
2962}
2963
2964/* Exposure to the sysfs interface <<END>> */
2965
2966static int __maybe_unused ab8500_fg_resume(struct device *dev)
2967{
2968	struct ab8500_fg *di = dev_get_drvdata(dev);
2969
2970	/*
2971	 * Change state if we're not charging. If we're charging we will wake
2972	 * up on the FG IRQ
2973	 */
2974	if (!di->flags.charging) {
2975		ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_WAKEUP);
2976		queue_work(di->fg_wq, &di->fg_work);
2977	}
2978
2979	return 0;
2980}
2981
2982static int __maybe_unused ab8500_fg_suspend(struct device *dev)
2983{
2984	struct ab8500_fg *di = dev_get_drvdata(dev);
2985
2986	flush_delayed_work(&di->fg_periodic_work);
2987	flush_work(&di->fg_work);
2988	flush_work(&di->fg_acc_cur_work);
2989	flush_delayed_work(&di->fg_reinit_work);
2990	flush_delayed_work(&di->fg_low_bat_work);
2991	flush_delayed_work(&di->fg_check_hw_failure_work);
2992
2993	/*
2994	 * If the FG is enabled we will disable it before going to suspend
2995	 * only if we're not charging
2996	 */
2997	if (di->flags.fg_enabled && !di->flags.charging)
2998		ab8500_fg_coulomb_counter(di, false);
2999
3000	return 0;
3001}
3002
3003/* ab8500 fg driver interrupts and their respective isr */
3004static struct ab8500_fg_interrupts ab8500_fg_irq[] = {
3005	{"NCONV_ACCU", ab8500_fg_cc_convend_handler},
3006	{"BATT_OVV", ab8500_fg_batt_ovv_handler},
3007	{"LOW_BAT_F", ab8500_fg_lowbatf_handler},
3008	{"CC_INT_CALIB", ab8500_fg_cc_int_calib_handler},
3009	{"CCEOC", ab8500_fg_cc_data_end_handler},
3010};
3011
3012static char *supply_interface[] = {
3013	"ab8500_chargalg",
3014	"ab8500_usb",
3015};
3016
3017static const struct power_supply_desc ab8500_fg_desc = {
3018	.name			= "ab8500_fg",
3019	.type			= POWER_SUPPLY_TYPE_BATTERY,
3020	.properties		= ab8500_fg_props,
3021	.num_properties		= ARRAY_SIZE(ab8500_fg_props),
3022	.get_property		= ab8500_fg_get_property,
3023	.external_power_changed	= ab8500_fg_external_power_changed,
3024};
3025
3026static int ab8500_fg_bind(struct device *dev, struct device *master,
3027			  void *data)
3028{
3029	struct ab8500_fg *di = dev_get_drvdata(dev);
3030
3031	di->bat_cap.max_mah_design = di->bm->bi->charge_full_design_uah;
3032	di->bat_cap.max_mah = di->bat_cap.max_mah_design;
3033	di->vbat_nom_uv = di->bm->bi->voltage_max_design_uv;
3034
3035	/* Start the coulomb counter */
3036	ab8500_fg_coulomb_counter(di, true);
3037	/* Run the FG algorithm */
3038	queue_delayed_work(di->fg_wq, &di->fg_periodic_work, 0);
3039
3040	return 0;
3041}
3042
3043static void ab8500_fg_unbind(struct device *dev, struct device *master,
3044			     void *data)
3045{
3046	struct ab8500_fg *di = dev_get_drvdata(dev);
3047	int ret;
3048
3049	/* Disable coulomb counter */
3050	ret = ab8500_fg_coulomb_counter(di, false);
3051	if (ret)
3052		dev_err(dev, "failed to disable coulomb counter\n");
3053
3054	flush_workqueue(di->fg_wq);
3055}
3056
3057static const struct component_ops ab8500_fg_component_ops = {
3058	.bind = ab8500_fg_bind,
3059	.unbind = ab8500_fg_unbind,
3060};
3061
3062static int ab8500_fg_probe(struct platform_device *pdev)
3063{
3064	struct device *dev = &pdev->dev;
3065	struct power_supply_config psy_cfg = {};
3066	struct ab8500_fg *di;
3067	int i, irq;
3068	int ret = 0;
3069
3070	di = devm_kzalloc(dev, sizeof(*di), GFP_KERNEL);
3071	if (!di)
3072		return -ENOMEM;
3073
3074	di->bm = &ab8500_bm_data;
3075
3076	mutex_init(&di->cc_lock);
3077
3078	/* get parent data */
3079	di->dev = dev;
3080	di->parent = dev_get_drvdata(pdev->dev.parent);
3081
3082	di->main_bat_v = devm_iio_channel_get(dev, "main_bat_v");
3083	if (IS_ERR(di->main_bat_v)) {
3084		ret = dev_err_probe(dev, PTR_ERR(di->main_bat_v),
3085				    "failed to get main battery ADC channel\n");
3086		return ret;
3087	}
3088
3089	if (!of_property_read_u32(dev->of_node, "line-impedance-micro-ohms",
3090				  &di->line_impedance_uohm))
3091		dev_info(dev, "line impedance: %u uOhm\n",
3092			 di->line_impedance_uohm);
3093
3094	psy_cfg.supplied_to = supply_interface;
3095	psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface);
3096	psy_cfg.drv_data = di;
3097
3098	di->init_capacity = true;
3099
3100	ab8500_fg_charge_state_to(di, AB8500_FG_CHARGE_INIT);
3101	ab8500_fg_discharge_state_to(di, AB8500_FG_DISCHARGE_INIT);
3102
3103	/* Create a work queue for running the FG algorithm */
3104	di->fg_wq = alloc_ordered_workqueue("ab8500_fg_wq", WQ_MEM_RECLAIM);
3105	if (di->fg_wq == NULL) {
3106		dev_err(dev, "failed to create work queue\n");
3107		return -ENOMEM;
3108	}
3109
3110	/* Init work for running the fg algorithm instantly */
3111	INIT_WORK(&di->fg_work, ab8500_fg_instant_work);
3112
3113	/* Init work for getting the battery accumulated current */
3114	INIT_WORK(&di->fg_acc_cur_work, ab8500_fg_acc_cur_work);
3115
3116	/* Init work for reinitialising the fg algorithm */
3117	INIT_DEFERRABLE_WORK(&di->fg_reinit_work,
3118		ab8500_fg_reinit_work);
3119
3120	/* Work delayed Queue to run the state machine */
3121	INIT_DEFERRABLE_WORK(&di->fg_periodic_work,
3122		ab8500_fg_periodic_work);
3123
3124	/* Work to check low battery condition */
3125	INIT_DEFERRABLE_WORK(&di->fg_low_bat_work,
3126		ab8500_fg_low_bat_work);
3127
3128	/* Init work for HW failure check */
3129	INIT_DEFERRABLE_WORK(&di->fg_check_hw_failure_work,
3130		ab8500_fg_check_hw_failure_work);
3131
3132	/* Reset battery low voltage flag */
3133	di->flags.low_bat = false;
3134
3135	/* Initialize low battery counter */
3136	di->low_bat_cnt = 10;
3137
3138	/* Initialize OVV, and other registers */
3139	ret = ab8500_fg_init_hw_registers(di);
3140	if (ret) {
3141		dev_err(dev, "failed to initialize registers\n");
3142		destroy_workqueue(di->fg_wq);
3143		return ret;
3144	}
3145
3146	/* Consider battery unknown until we're informed otherwise */
3147	di->flags.batt_unknown = true;
3148	di->flags.batt_id_received = false;
3149
3150	/* Register FG power supply class */
3151	di->fg_psy = devm_power_supply_register(dev, &ab8500_fg_desc, &psy_cfg);
3152	if (IS_ERR(di->fg_psy)) {
3153		dev_err(dev, "failed to register FG psy\n");
3154		destroy_workqueue(di->fg_wq);
3155		return PTR_ERR(di->fg_psy);
3156	}
3157
3158	di->fg_samples = SEC_TO_SAMPLE(di->bm->fg_params->init_timer);
3159
3160	/*
3161	 * Initialize completion used to notify completion and start
3162	 * of inst current
3163	 */
3164	init_completion(&di->ab8500_fg_started);
3165	init_completion(&di->ab8500_fg_complete);
3166
3167	/* Register primary interrupt handlers */
3168	for (i = 0; i < ARRAY_SIZE(ab8500_fg_irq); i++) {
3169		irq = platform_get_irq_byname(pdev, ab8500_fg_irq[i].name);
3170		if (irq < 0) {
3171			destroy_workqueue(di->fg_wq);
3172			return irq;
3173		}
3174
3175		ret = devm_request_threaded_irq(dev, irq, NULL,
3176				  ab8500_fg_irq[i].isr,
3177				  IRQF_SHARED | IRQF_NO_SUSPEND | IRQF_ONESHOT,
3178				  ab8500_fg_irq[i].name, di);
3179
3180		if (ret != 0) {
3181			dev_err(dev, "failed to request %s IRQ %d: %d\n",
3182				ab8500_fg_irq[i].name, irq, ret);
3183			destroy_workqueue(di->fg_wq);
3184			return ret;
3185		}
3186		dev_dbg(dev, "Requested %s IRQ %d: %d\n",
3187			ab8500_fg_irq[i].name, irq, ret);
3188	}
3189
3190	di->irq = platform_get_irq_byname(pdev, "CCEOC");
3191	disable_irq(di->irq);
3192	di->nbr_cceoc_irq_cnt = 0;
3193
3194	platform_set_drvdata(pdev, di);
3195
3196	ret = ab8500_fg_sysfs_init(di);
3197	if (ret) {
3198		dev_err(dev, "failed to create sysfs entry\n");
3199		destroy_workqueue(di->fg_wq);
3200		return ret;
3201	}
3202
3203	ret = ab8500_fg_sysfs_psy_create_attrs(di);
3204	if (ret) {
3205		dev_err(dev, "failed to create FG psy\n");
3206		ab8500_fg_sysfs_exit(di);
3207		destroy_workqueue(di->fg_wq);
3208		return ret;
3209	}
3210
3211	/* Calibrate the fg first time */
3212	di->flags.calibrate = true;
3213	di->calib_state = AB8500_FG_CALIB_INIT;
3214
3215	/* Use room temp as default value until we get an update from driver. */
3216	di->bat_temp = 210;
3217
3218	list_add_tail(&di->node, &ab8500_fg_list);
3219
3220	return component_add(dev, &ab8500_fg_component_ops);
3221}
3222
3223static void ab8500_fg_remove(struct platform_device *pdev)
3224{
3225	struct ab8500_fg *di = platform_get_drvdata(pdev);
3226
3227	destroy_workqueue(di->fg_wq);
3228	component_del(&pdev->dev, &ab8500_fg_component_ops);
3229	list_del(&di->node);
3230	ab8500_fg_sysfs_exit(di);
3231	ab8500_fg_sysfs_psy_remove_attrs(di);
3232}
3233
3234static SIMPLE_DEV_PM_OPS(ab8500_fg_pm_ops, ab8500_fg_suspend, ab8500_fg_resume);
3235
3236static const struct of_device_id ab8500_fg_match[] = {
3237	{ .compatible = "stericsson,ab8500-fg", },
3238	{ },
3239};
3240MODULE_DEVICE_TABLE(of, ab8500_fg_match);
3241
3242struct platform_driver ab8500_fg_driver = {
3243	.probe = ab8500_fg_probe,
3244	.remove = ab8500_fg_remove,
3245	.driver = {
3246		.name = "ab8500-fg",
3247		.of_match_table = ab8500_fg_match,
3248		.pm = &ab8500_fg_pm_ops,
3249	},
3250};
3251MODULE_LICENSE("GPL v2");
3252MODULE_AUTHOR("Johan Palsson, Karl Komierowski");
3253MODULE_ALIAS("platform:ab8500-fg");
3254MODULE_DESCRIPTION("AB8500 Fuel Gauge driver");
~/ Read-only file preview.