Linux Audio

Check our new training course

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