android_kernel_xiaomi_sm8350/drivers/video/backlight/pwm_bl.c
Greg Kroah-Hartman d756462d85 This is the 5.4.146 stable release
-----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEZH8oZUiU471FcZm+ONu9yGCSaT4FAmFBpSMACgkQONu9yGCS
 aT6PRw//T4GhyaqI0+hhYnYv2++RBzAtKsOAPE7JUZ8X5zNNe3NZKD/+c0q9loy3
 vs1GpkjppSzZcL2WGZidwpgOTO0fqEYiJKusI+E60UGbu8GmmoUl0EbV3A3PP1K7
 n+T1jzMID1j4NwmZQsAA1o3/9pkWrKLb/1+g0mHVCL6WQjA4/YROi5f6xhVeCq/u
 aZFLxrgJ8YRkT9znEHCBcipEGRLid5kQp1uxSA5KaQh0JJl01eoJ3M52swYiExC/
 8g+QXPHFWOs9a1vVyxUG5o4WCShnjKwY1fNkEJ5j54LMmmg52llHfMHajV2a1Kdt
 qihSgY5/pPY9FgEDQ3Sy6xiTO2Lvq17lvHtEbGIn5V7SjQ4ISEN15Pqv3l+PqAFc
 gHeukc28mBfw6/kbolKZ/wksIKyDzxCHd4QNEYZMKjSPbjpzg7zjsvCX53lHkKNb
 23I0iJTu9yVDcPzYYCh/8ndFtxEIBGXS8c9kL5YN8p2k1AMqXcr1qUbYzM9CJqwm
 MSaZ2C1rR58Uhd4CUvOK4N2K7lw+2PH6I0UcSGlp9jv+xHVlmERiM7uaZGBn7oLm
 +n+5BRAU/qDK+Vm1poIZogrsI4BwMp9ZH4terELR28i0gPwYo+tCzddWqq98BuGT
 52ylkG56l0gbC9Bvpf3Ou3K5/qbmhN9HYElt16HNFO6x/ufE2XI=
 =1neh
 -----END PGP SIGNATURE-----

Merge 5.4.146 into android11-5.4-lts

Changes in 5.4.146
	locking/mutex: Fix HANDOFF condition
	regmap: fix the offset of register error log
	crypto: mxs-dcp - Check for DMA mapping errors
	sched/deadline: Fix reset_on_fork reporting of DL tasks
	power: supply: axp288_fuel_gauge: Report register-address on readb / writeb errors
	crypto: omap-sham - clear dma flags only after omap_sham_update_dma_stop()
	sched/deadline: Fix missing clock update in migrate_task_rq_dl()
	rcu/tree: Handle VM stoppage in stall detection
	posix-cpu-timers: Force next expiration recalc after itimer reset
	hrtimer: Avoid double reprogramming in __hrtimer_start_range_ns()
	hrtimer: Ensure timerfd notification for HIGHRES=n
	udf: Check LVID earlier
	udf: Fix iocharset=utf8 mount option
	isofs: joliet: Fix iocharset=utf8 mount option
	bcache: add proper error unwinding in bcache_device_init
	nvme-tcp: don't update queue count when failing to set io queues
	nvme-rdma: don't update queue count when failing to set io queues
	nvmet: pass back cntlid on successful completion
	power: supply: max17042_battery: fix typo in MAx17042_TOFF
	s390/cio: add dev_busid sysfs entry for each subchannel
	libata: fix ata_host_start()
	crypto: qat - do not ignore errors from enable_vf2pf_comms()
	crypto: qat - handle both source of interrupt in VF ISR
	crypto: qat - fix reuse of completion variable
	crypto: qat - fix naming for init/shutdown VF to PF notifications
	crypto: qat - do not export adf_iov_putmsg()
	fcntl: fix potential deadlock for &fasync_struct.fa_lock
	udf_get_extendedattr() had no boundary checks.
	s390/kasan: fix large PMD pages address alignment check
	s390/debug: fix debug area life cycle
	m68k: emu: Fix invalid free in nfeth_cleanup()
	sched: Fix UCLAMP_FLAG_IDLE setting
	spi: spi-fsl-dspi: Fix issue with uninitialized dma_slave_config
	spi: spi-pic32: Fix issue with uninitialized dma_slave_config
	genirq/timings: Fix error return code in irq_timings_test_irqs()
	lib/mpi: use kcalloc in mpi_resize
	clocksource/drivers/sh_cmt: Fix wrong setting if don't request IRQ for clock source channel
	block: nbd: add sanity check for first_minor
	crypto: qat - use proper type for vf_mask
	certs: Trigger creation of RSA module signing key if it's not an RSA key
	regulator: vctrl: Use locked regulator_get_voltage in probe path
	regulator: vctrl: Avoid lockdep warning in enable/disable ops
	spi: sprd: Fix the wrong WDG_LOAD_VAL
	spi: spi-zynq-qspi: use wait_for_completion_timeout to make zynq_qspi_exec_mem_op not interruptible
	EDAC/i10nm: Fix NVDIMM detection
	drm/panfrost: Fix missing clk_disable_unprepare() on error in panfrost_clk_init()
	media: TDA1997x: enable EDID support
	soc: rockchip: ROCKCHIP_GRF should not default to y, unconditionally
	media: cxd2880-spi: Fix an error handling path
	bpf: Fix a typo of reuseport map in bpf.h.
	bpf: Fix potential memleak and UAF in the verifier.
	ARM: dts: aspeed-g6: Fix HVI3C function-group in pinctrl dtsi
	arm64: dts: renesas: r8a77995: draak: Remove bogus adv7511w properties
	soc: qcom: rpmhpd: Use corner in power_off
	media: dvb-usb: fix uninit-value in dvb_usb_adapter_dvb_init
	media: dvb-usb: fix uninit-value in vp702x_read_mac_addr
	media: dvb-usb: Fix error handling in dvb_usb_i2c_init
	media: go7007: remove redundant initialization
	media: coda: fix frame_mem_ctrl for YUV420 and YVU420 formats
	Bluetooth: sco: prevent information leak in sco_conn_defer_accept()
	6lowpan: iphc: Fix an off-by-one check of array index
	netns: protect netns ID lookups with RCU
	drm/amdgpu/acp: Make PM domain really work
	tcp: seq_file: Avoid skipping sk during tcp_seek_last_pos
	ARM: dts: meson8: Use a higher default GPU clock frequency
	ARM: dts: meson8b: odroidc1: Fix the pwm regulator supply properties
	ARM: dts: meson8b: mxq: Fix the pwm regulator supply properties
	ARM: dts: meson8b: ec100: Fix the pwm regulator supply properties
	net/mlx5e: Prohibit inner indir TIRs in IPoIB
	cgroup/cpuset: Fix a partition bug with hotplug
	net: cipso: fix warnings in netlbl_cipsov4_add_std
	i2c: highlander: add IRQ check
	leds: lt3593: Put fwnode in any case during ->probe()
	leds: trigger: audio: Add an activate callback to ensure the initial brightness is set
	media: em28xx-input: fix refcount bug in em28xx_usb_disconnect
	media: venus: venc: Fix potential null pointer dereference on pointer fmt
	PCI: PM: Avoid forcing PCI_D0 for wakeup reasons inconsistently
	PCI: PM: Enable PME if it can be signaled from D3cold
	soc: qcom: smsm: Fix missed interrupts if state changes while masked
	debugfs: Return error during {full/open}_proxy_open() on rmmod
	Bluetooth: increase BTNAMSIZ to 21 chars to fix potential buffer overflow
	PM: EM: Increase energy calculation precision
	drm/msm/dpu: make dpu_hw_ctl_clear_all_blendstages clear necessary LMs
	arm64: dts: exynos: correct GIC CPU interfaces address range on Exynos7
	counter: 104-quad-8: Return error when invalid mode during ceiling_write
	Bluetooth: fix repeated calls to sco_sock_kill
	drm/msm/dsi: Fix some reference counted resource leaks
	usb: gadget: udc: at91: add IRQ check
	usb: phy: fsl-usb: add IRQ check
	usb: phy: twl6030: add IRQ checks
	usb: gadget: udc: renesas_usb3: Fix soc_device_match() abuse
	Bluetooth: Move shutdown callback before flushing tx and rx queue
	usb: host: ohci-tmio: add IRQ check
	usb: phy: tahvo: add IRQ check
	mac80211: Fix insufficient headroom issue for AMSDU
	lockd: Fix invalid lockowner cast after vfs_test_lock
	nfsd4: Fix forced-expiry locking
	usb: gadget: mv_u3d: request_irq() after initializing UDC
	mm/swap: consider max pages in iomap_swapfile_add_extent
	Bluetooth: add timeout sanity check to hci_inquiry
	i2c: iop3xx: fix deferred probing
	i2c: s3c2410: fix IRQ check
	rsi: fix error code in rsi_load_9116_firmware()
	rsi: fix an error code in rsi_probe()
	ASoC: Intel: Skylake: Leave data as is when invoking TLV IPCs
	ASoC: Intel: Skylake: Fix module resource and format selection
	mmc: dw_mmc: Fix issue with uninitialized dma_slave_config
	mmc: moxart: Fix issue with uninitialized dma_slave_config
	bpf: Fix possible out of bound write in narrow load handling
	CIFS: Fix a potencially linear read overflow
	i2c: mt65xx: fix IRQ check
	usb: ehci-orion: Handle errors of clk_prepare_enable() in probe
	usb: bdc: Fix an error handling path in 'bdc_probe()' when no suitable DMA config is available
	tty: serial: fsl_lpuart: fix the wrong mapbase value
	ASoC: wcd9335: Fix a double irq free in the remove function
	ASoC: wcd9335: Fix a memory leak in the error handling path of the probe function
	ASoC: wcd9335: Disable irq on slave ports in the remove function
	ath6kl: wmi: fix an error code in ath6kl_wmi_sync_point()
	bcma: Fix memory leak for internally-handled cores
	brcmfmac: pcie: fix oops on failure to resume and reprobe
	ipv6: make exception cache less predictible
	ipv4: make exception cache less predictible
	net: sched: Fix qdisc_rate_table refcount leak when get tcf_block failed
	net: qualcomm: fix QCA7000 checksum handling
	octeontx2-af: Fix loop in free and unmap counter
	ipv4: fix endianness issue in inet_rtm_getroute_build_skb()
	bpf: Introduce BPF nospec instruction for mitigating Spectre v4
	bpf: Fix leakage due to insufficient speculative store bypass mitigation
	bpf: verifier: Allocate idmap scratch in verifier env
	bpf: Fix pointer arithmetic mask tightening under state pruning
	time: Handle negative seconds correctly in timespec64_to_ns()
	tty: Fix data race between tiocsti() and flush_to_ldisc()
	perf/x86/amd/ibs: Extend PERF_PMU_CAP_NO_EXCLUDE to IBS Op
	x86/resctrl: Fix a maybe-uninitialized build warning treated as error
	KVM: s390: index kvm->arch.idle_mask by vcpu_idx
	KVM: x86: Update vCPU's hv_clock before back to guest when tsc_offset is adjusted
	KVM: nVMX: Unconditionally clear nested.pi_pending on nested VM-Enter
	fuse: truncate pagecache on atomic_o_trunc
	fuse: flush extending writes
	IMA: remove -Wmissing-prototypes warning
	IMA: remove the dependency on CRYPTO_MD5
	fbmem: don't allow too huge resolutions
	backlight: pwm_bl: Improve bootloader/kernel device handover
	clk: kirkwood: Fix a clocking boot regression
	Linux 5.4.146

Signed-off-by: Greg Kroah-Hartman <gregkh@google.com>
Change-Id: I5524baa0c07d9d9b80c0736488e3ea0e4fb8e335
2021-09-15 14:01:16 +02:00

732 lines
18 KiB
C

// SPDX-License-Identifier: GPL-2.0-only
/*
* Simple PWM based backlight control, board code has to setup
* 1) pin configuration so PWM waveforms can output
* 2) platform_data being correctly configured
*/
#include <linux/delay.h>
#include <linux/gpio/consumer.h>
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <linux/err.h>
#include <linux/pwm.h>
#include <linux/pwm_backlight.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
struct pwm_bl_data {
struct pwm_device *pwm;
struct device *dev;
unsigned int lth_brightness;
unsigned int *levels;
bool enabled;
struct regulator *power_supply;
struct gpio_desc *enable_gpio;
unsigned int scale;
bool legacy;
unsigned int post_pwm_on_delay;
unsigned int pwm_off_delay;
int (*notify)(struct device *,
int brightness);
void (*notify_after)(struct device *,
int brightness);
int (*check_fb)(struct device *, struct fb_info *);
void (*exit)(struct device *);
};
static void pwm_backlight_power_on(struct pwm_bl_data *pb)
{
struct pwm_state state;
int err;
pwm_get_state(pb->pwm, &state);
if (pb->enabled)
return;
err = regulator_enable(pb->power_supply);
if (err < 0)
dev_err(pb->dev, "failed to enable power supply\n");
state.enabled = true;
pwm_apply_state(pb->pwm, &state);
if (pb->post_pwm_on_delay)
msleep(pb->post_pwm_on_delay);
if (pb->enable_gpio)
gpiod_set_value_cansleep(pb->enable_gpio, 1);
pb->enabled = true;
}
static void pwm_backlight_power_off(struct pwm_bl_data *pb)
{
struct pwm_state state;
pwm_get_state(pb->pwm, &state);
if (!pb->enabled)
return;
if (pb->enable_gpio)
gpiod_set_value_cansleep(pb->enable_gpio, 0);
if (pb->pwm_off_delay)
msleep(pb->pwm_off_delay);
state.enabled = false;
state.duty_cycle = 0;
pwm_apply_state(pb->pwm, &state);
regulator_disable(pb->power_supply);
pb->enabled = false;
}
static int compute_duty_cycle(struct pwm_bl_data *pb, int brightness)
{
unsigned int lth = pb->lth_brightness;
struct pwm_state state;
u64 duty_cycle;
pwm_get_state(pb->pwm, &state);
if (pb->levels)
duty_cycle = pb->levels[brightness];
else
duty_cycle = brightness;
duty_cycle *= state.period - lth;
do_div(duty_cycle, pb->scale);
return duty_cycle + lth;
}
static int pwm_backlight_update_status(struct backlight_device *bl)
{
struct pwm_bl_data *pb = bl_get_data(bl);
int brightness = bl->props.brightness;
struct pwm_state state;
if (bl->props.power != FB_BLANK_UNBLANK ||
bl->props.fb_blank != FB_BLANK_UNBLANK ||
bl->props.state & BL_CORE_FBBLANK)
brightness = 0;
if (pb->notify)
brightness = pb->notify(pb->dev, brightness);
if (brightness > 0) {
pwm_get_state(pb->pwm, &state);
state.duty_cycle = compute_duty_cycle(pb, brightness);
pwm_apply_state(pb->pwm, &state);
pwm_backlight_power_on(pb);
} else
pwm_backlight_power_off(pb);
if (pb->notify_after)
pb->notify_after(pb->dev, brightness);
return 0;
}
static int pwm_backlight_check_fb(struct backlight_device *bl,
struct fb_info *info)
{
struct pwm_bl_data *pb = bl_get_data(bl);
return !pb->check_fb || pb->check_fb(pb->dev, info);
}
static const struct backlight_ops pwm_backlight_ops = {
.update_status = pwm_backlight_update_status,
.check_fb = pwm_backlight_check_fb,
};
#ifdef CONFIG_OF
#define PWM_LUMINANCE_SCALE 10000 /* luminance scale */
/*
* CIE lightness to PWM conversion.
*
* The CIE 1931 lightness formula is what actually describes how we perceive
* light:
* Y = (L* / 902.3) if L* ≤ 0.08856
* Y = ((L* + 16) / 116)^3 if L* > 0.08856
*
* Where Y is the luminance, the amount of light coming out of the screen, and
* is a number between 0.0 and 1.0; and L* is the lightness, how bright a human
* perceives the screen to be, and is a number between 0 and 100.
*
* The following function does the fixed point maths needed to implement the
* above formula.
*/
static u64 cie1931(unsigned int lightness, unsigned int scale)
{
u64 retval;
lightness *= 100;
if (lightness <= (8 * scale)) {
retval = DIV_ROUND_CLOSEST_ULL(lightness * 10, 9023);
} else {
retval = int_pow((lightness + (16 * scale)) / 116, 3);
retval = DIV_ROUND_CLOSEST_ULL(retval, (scale * scale));
}
return retval;
}
/*
* Create a default correction table for PWM values to create linear brightness
* for LED based backlights using the CIE1931 algorithm.
*/
static
int pwm_backlight_brightness_default(struct device *dev,
struct platform_pwm_backlight_data *data,
unsigned int period)
{
unsigned int i;
u64 retval;
/*
* Once we have 4096 levels there's little point going much higher...
* neither interactive sliders nor animation benefits from having
* more values in the table.
*/
data->max_brightness =
min((int)DIV_ROUND_UP(period, fls(period)), 4096);
data->levels = devm_kcalloc(dev, data->max_brightness,
sizeof(*data->levels), GFP_KERNEL);
if (!data->levels)
return -ENOMEM;
/* Fill the table using the cie1931 algorithm */
for (i = 0; i < data->max_brightness; i++) {
retval = cie1931((i * PWM_LUMINANCE_SCALE) /
data->max_brightness, PWM_LUMINANCE_SCALE) *
period;
retval = DIV_ROUND_CLOSEST_ULL(retval, PWM_LUMINANCE_SCALE);
if (retval > UINT_MAX)
return -EINVAL;
data->levels[i] = (unsigned int)retval;
}
data->dft_brightness = data->max_brightness / 2;
data->max_brightness--;
return 0;
}
static int pwm_backlight_parse_dt(struct device *dev,
struct platform_pwm_backlight_data *data)
{
struct device_node *node = dev->of_node;
unsigned int num_levels = 0;
unsigned int levels_count;
unsigned int num_steps = 0;
struct property *prop;
unsigned int *table;
int length;
u32 value;
int ret;
if (!node)
return -ENODEV;
memset(data, 0, sizeof(*data));
/*
* These values are optional and set as 0 by default, the out values
* are modified only if a valid u32 value can be decoded.
*/
of_property_read_u32(node, "post-pwm-on-delay-ms",
&data->post_pwm_on_delay);
of_property_read_u32(node, "pwm-off-delay-ms", &data->pwm_off_delay);
data->enable_gpio = -EINVAL;
/*
* Determine the number of brightness levels, if this property is not
* set a default table of brightness levels will be used.
*/
prop = of_find_property(node, "brightness-levels", &length);
if (!prop)
return 0;
data->max_brightness = length / sizeof(u32);
/* read brightness levels from DT property */
if (data->max_brightness > 0) {
size_t size = sizeof(*data->levels) * data->max_brightness;
unsigned int i, j, n = 0;
data->levels = devm_kzalloc(dev, size, GFP_KERNEL);
if (!data->levels)
return -ENOMEM;
ret = of_property_read_u32_array(node, "brightness-levels",
data->levels,
data->max_brightness);
if (ret < 0)
return ret;
ret = of_property_read_u32(node, "default-brightness-level",
&value);
if (ret < 0)
return ret;
data->dft_brightness = value;
/*
* This property is optional, if is set enables linear
* interpolation between each of the values of brightness levels
* and creates a new pre-computed table.
*/
of_property_read_u32(node, "num-interpolated-steps",
&num_steps);
/*
* Make sure that there is at least two entries in the
* brightness-levels table, otherwise we can't interpolate
* between two points.
*/
if (num_steps) {
if (data->max_brightness < 2) {
dev_err(dev, "can't interpolate\n");
return -EINVAL;
}
/*
* Recalculate the number of brightness levels, now
* taking in consideration the number of interpolated
* steps between two levels.
*/
for (i = 0; i < data->max_brightness - 1; i++) {
if ((data->levels[i + 1] - data->levels[i]) /
num_steps)
num_levels += num_steps;
else
num_levels++;
}
num_levels++;
dev_dbg(dev, "new number of brightness levels: %d\n",
num_levels);
/*
* Create a new table of brightness levels with all the
* interpolated steps.
*/
size = sizeof(*table) * num_levels;
table = devm_kzalloc(dev, size, GFP_KERNEL);
if (!table)
return -ENOMEM;
/* Fill the interpolated table. */
levels_count = 0;
for (i = 0; i < data->max_brightness - 1; i++) {
value = data->levels[i];
n = (data->levels[i + 1] - value) / num_steps;
if (n > 0) {
for (j = 0; j < num_steps; j++) {
table[levels_count] = value;
value += n;
levels_count++;
}
} else {
table[levels_count] = data->levels[i];
levels_count++;
}
}
table[levels_count] = data->levels[i];
/*
* As we use interpolation lets remove current
* brightness levels table and replace for the
* new interpolated table.
*/
devm_kfree(dev, data->levels);
data->levels = table;
/*
* Reassign max_brightness value to the new total number
* of brightness levels.
*/
data->max_brightness = num_levels;
}
data->max_brightness--;
}
return 0;
}
static const struct of_device_id pwm_backlight_of_match[] = {
{ .compatible = "pwm-backlight" },
{ }
};
MODULE_DEVICE_TABLE(of, pwm_backlight_of_match);
#else
static int pwm_backlight_parse_dt(struct device *dev,
struct platform_pwm_backlight_data *data)
{
return -ENODEV;
}
static
int pwm_backlight_brightness_default(struct device *dev,
struct platform_pwm_backlight_data *data,
unsigned int period)
{
return -ENODEV;
}
#endif
static bool pwm_backlight_is_linear(struct platform_pwm_backlight_data *data)
{
unsigned int nlevels = data->max_brightness + 1;
unsigned int min_val = data->levels[0];
unsigned int max_val = data->levels[nlevels - 1];
/*
* Multiplying by 128 means that even in pathological cases such
* as (max_val - min_val) == nlevels the error at max_val is less
* than 1%.
*/
unsigned int slope = (128 * (max_val - min_val)) / nlevels;
unsigned int margin = (max_val - min_val) / 20; /* 5% */
int i;
for (i = 1; i < nlevels; i++) {
unsigned int linear_value = min_val + ((i * slope) / 128);
unsigned int delta = abs(linear_value - data->levels[i]);
if (delta > margin)
return false;
}
return true;
}
static int pwm_backlight_initial_power_state(const struct pwm_bl_data *pb)
{
struct device_node *node = pb->dev->of_node;
bool active = true;
/*
* If the enable GPIO is present, observable (either as input
* or output) and off then the backlight is not currently active.
* */
if (pb->enable_gpio && gpiod_get_value_cansleep(pb->enable_gpio) == 0)
active = false;
if (!regulator_is_enabled(pb->power_supply))
active = false;
if (!pwm_is_enabled(pb->pwm))
active = false;
/*
* Synchronize the enable_gpio with the observed state of the
* hardware.
*/
if (pb->enable_gpio)
gpiod_direction_output(pb->enable_gpio, active);
/*
* Do not change pb->enabled here! pb->enabled essentially
* tells us if we own one of the regulator's use counts and
* right now we do not.
*/
/* Not booted with device tree or no phandle link to the node */
if (!node || !node->phandle)
return FB_BLANK_UNBLANK;
/*
* If the driver is probed from the device tree and there is a
* phandle link pointing to the backlight node, it is safe to
* assume that another driver will enable the backlight at the
* appropriate time. Therefore, if it is disabled, keep it so.
*/
return active ? FB_BLANK_UNBLANK: FB_BLANK_POWERDOWN;
}
static int pwm_backlight_probe(struct platform_device *pdev)
{
struct platform_pwm_backlight_data *data = dev_get_platdata(&pdev->dev);
struct platform_pwm_backlight_data defdata;
struct backlight_properties props;
struct backlight_device *bl;
struct device_node *node = pdev->dev.of_node;
struct pwm_bl_data *pb;
struct pwm_state state;
unsigned int i;
int ret;
if (!data) {
ret = pwm_backlight_parse_dt(&pdev->dev, &defdata);
if (ret < 0) {
dev_err(&pdev->dev, "failed to find platform data\n");
return ret;
}
data = &defdata;
}
if (data->init) {
ret = data->init(&pdev->dev);
if (ret < 0)
return ret;
}
pb = devm_kzalloc(&pdev->dev, sizeof(*pb), GFP_KERNEL);
if (!pb) {
ret = -ENOMEM;
goto err_alloc;
}
pb->notify = data->notify;
pb->notify_after = data->notify_after;
pb->check_fb = data->check_fb;
pb->exit = data->exit;
pb->dev = &pdev->dev;
pb->enabled = false;
pb->post_pwm_on_delay = data->post_pwm_on_delay;
pb->pwm_off_delay = data->pwm_off_delay;
pb->enable_gpio = devm_gpiod_get_optional(&pdev->dev, "enable",
GPIOD_ASIS);
if (IS_ERR(pb->enable_gpio)) {
ret = PTR_ERR(pb->enable_gpio);
goto err_alloc;
}
/*
* Compatibility fallback for drivers still using the integer GPIO
* platform data. Must go away soon.
*/
if (!pb->enable_gpio && gpio_is_valid(data->enable_gpio)) {
ret = devm_gpio_request_one(&pdev->dev, data->enable_gpio,
GPIOF_OUT_INIT_HIGH, "enable");
if (ret < 0) {
dev_err(&pdev->dev, "failed to request GPIO#%d: %d\n",
data->enable_gpio, ret);
goto err_alloc;
}
pb->enable_gpio = gpio_to_desc(data->enable_gpio);
}
pb->power_supply = devm_regulator_get(&pdev->dev, "power");
if (IS_ERR(pb->power_supply)) {
ret = PTR_ERR(pb->power_supply);
goto err_alloc;
}
pb->pwm = devm_pwm_get(&pdev->dev, NULL);
if (IS_ERR(pb->pwm) && PTR_ERR(pb->pwm) != -EPROBE_DEFER && !node) {
dev_err(&pdev->dev, "unable to request PWM, trying legacy API\n");
pb->legacy = true;
pb->pwm = pwm_request(data->pwm_id, "pwm-backlight");
}
if (IS_ERR(pb->pwm)) {
ret = PTR_ERR(pb->pwm);
if (ret != -EPROBE_DEFER)
dev_err(&pdev->dev, "unable to request PWM\n");
goto err_alloc;
}
dev_dbg(&pdev->dev, "got pwm for backlight\n");
/* Sync up PWM state. */
pwm_init_state(pb->pwm, &state);
/*
* The DT case will set the pwm_period_ns field to 0 and store the
* period, parsed from the DT, in the PWM device. For the non-DT case,
* set the period from platform data if it has not already been set
* via the PWM lookup table.
*/
if (!state.period && (data->pwm_period_ns > 0))
state.period = data->pwm_period_ns;
ret = pwm_apply_state(pb->pwm, &state);
if (ret) {
dev_err(&pdev->dev, "failed to apply initial PWM state: %d\n",
ret);
goto err_alloc;
}
memset(&props, 0, sizeof(struct backlight_properties));
if (data->levels) {
/*
* For the DT case, only when brightness levels is defined
* data->levels is filled. For the non-DT case, data->levels
* can come from platform data, however is not usual.
*/
for (i = 0; i <= data->max_brightness; i++) {
if (data->levels[i] > pb->scale)
pb->scale = data->levels[i];
pb->levels = data->levels;
}
if (pwm_backlight_is_linear(data))
props.scale = BACKLIGHT_SCALE_LINEAR;
else
props.scale = BACKLIGHT_SCALE_NON_LINEAR;
} else if (!data->max_brightness) {
/*
* If no brightness levels are provided and max_brightness is
* not set, use the default brightness table. For the DT case,
* max_brightness is set to 0 when brightness levels is not
* specified. For the non-DT case, max_brightness is usually
* set to some value.
*/
/* Get the PWM period (in nanoseconds) */
pwm_get_state(pb->pwm, &state);
ret = pwm_backlight_brightness_default(&pdev->dev, data,
state.period);
if (ret < 0) {
dev_err(&pdev->dev,
"failed to setup default brightness table\n");
goto err_alloc;
}
for (i = 0; i <= data->max_brightness; i++) {
if (data->levels[i] > pb->scale)
pb->scale = data->levels[i];
pb->levels = data->levels;
}
props.scale = BACKLIGHT_SCALE_NON_LINEAR;
} else {
/*
* That only happens for the non-DT case, where platform data
* sets the max_brightness value.
*/
pb->scale = data->max_brightness;
}
pb->lth_brightness = data->lth_brightness * (div_u64(state.period,
pb->scale));
props.type = BACKLIGHT_RAW;
props.max_brightness = data->max_brightness;
bl = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, pb,
&pwm_backlight_ops, &props);
if (IS_ERR(bl)) {
dev_err(&pdev->dev, "failed to register backlight\n");
ret = PTR_ERR(bl);
if (pb->legacy)
pwm_free(pb->pwm);
goto err_alloc;
}
if (data->dft_brightness > data->max_brightness) {
dev_warn(&pdev->dev,
"invalid default brightness level: %u, using %u\n",
data->dft_brightness, data->max_brightness);
data->dft_brightness = data->max_brightness;
}
bl->props.brightness = data->dft_brightness;
bl->props.power = pwm_backlight_initial_power_state(pb);
backlight_update_status(bl);
platform_set_drvdata(pdev, bl);
return 0;
err_alloc:
if (data->exit)
data->exit(&pdev->dev);
return ret;
}
static int pwm_backlight_remove(struct platform_device *pdev)
{
struct backlight_device *bl = platform_get_drvdata(pdev);
struct pwm_bl_data *pb = bl_get_data(bl);
backlight_device_unregister(bl);
pwm_backlight_power_off(pb);
if (pb->exit)
pb->exit(&pdev->dev);
if (pb->legacy)
pwm_free(pb->pwm);
return 0;
}
static void pwm_backlight_shutdown(struct platform_device *pdev)
{
struct backlight_device *bl = platform_get_drvdata(pdev);
struct pwm_bl_data *pb = bl_get_data(bl);
pwm_backlight_power_off(pb);
}
#ifdef CONFIG_PM_SLEEP
static int pwm_backlight_suspend(struct device *dev)
{
struct backlight_device *bl = dev_get_drvdata(dev);
struct pwm_bl_data *pb = bl_get_data(bl);
if (pb->notify)
pb->notify(pb->dev, 0);
pwm_backlight_power_off(pb);
if (pb->notify_after)
pb->notify_after(pb->dev, 0);
return 0;
}
static int pwm_backlight_resume(struct device *dev)
{
struct backlight_device *bl = dev_get_drvdata(dev);
backlight_update_status(bl);
return 0;
}
#endif
static const struct dev_pm_ops pwm_backlight_pm_ops = {
#ifdef CONFIG_PM_SLEEP
.suspend = pwm_backlight_suspend,
.resume = pwm_backlight_resume,
.poweroff = pwm_backlight_suspend,
.restore = pwm_backlight_resume,
#endif
};
static struct platform_driver pwm_backlight_driver = {
.driver = {
.name = "pwm-backlight",
.pm = &pwm_backlight_pm_ops,
.of_match_table = of_match_ptr(pwm_backlight_of_match),
},
.probe = pwm_backlight_probe,
.remove = pwm_backlight_remove,
.shutdown = pwm_backlight_shutdown,
};
module_platform_driver(pwm_backlight_driver);
MODULE_DESCRIPTION("PWM based Backlight Driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:pwm-backlight");