GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / video / backlight / pwm_bl.c
1 /*
2  * linux/drivers/video/backlight/pwm_bl.c
3  *
4  * simple PWM based backlight control, board code has to setup
5  * 1) pin configuration so PWM waveforms can output
6  * 2) platform_data being correctly configured
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as
10  * published by the Free Software Foundation.
11  */
12
13 #include <linux/delay.h>
14 #include <linux/gpio/consumer.h>
15 #include <linux/gpio.h>
16 #include <linux/module.h>
17 #include <linux/kernel.h>
18 #include <linux/init.h>
19 #include <linux/platform_device.h>
20 #include <linux/fb.h>
21 #include <linux/backlight.h>
22 #include <linux/err.h>
23 #include <linux/pwm.h>
24 #include <linux/pwm_backlight.h>
25 #include <linux/regulator/consumer.h>
26 #include <linux/slab.h>
27
28 struct pwm_bl_data {
29         struct pwm_device       *pwm;
30         struct device           *dev;
31         unsigned int            period;
32         unsigned int            lth_brightness;
33         unsigned int            *levels;
34         bool                    enabled;
35         struct regulator        *power_supply;
36         struct gpio_desc        *enable_gpio;
37         unsigned int            scale;
38         bool                    legacy;
39         unsigned int            post_pwm_on_delay;
40         unsigned int            pwm_off_delay;
41         int                     (*notify)(struct device *,
42                                           int brightness);
43         void                    (*notify_after)(struct device *,
44                                         int brightness);
45         int                     (*check_fb)(struct device *, struct fb_info *);
46         void                    (*exit)(struct device *);
47 };
48
49 static void pwm_backlight_power_on(struct pwm_bl_data *pb, int brightness)
50 {
51         int err;
52
53         if (pb->enabled)
54                 return;
55
56         err = regulator_enable(pb->power_supply);
57         if (err < 0)
58                 dev_err(pb->dev, "failed to enable power supply\n");
59
60         pwm_enable(pb->pwm);
61
62         if (pb->post_pwm_on_delay)
63                 msleep(pb->post_pwm_on_delay);
64
65         if (pb->enable_gpio)
66                 gpiod_set_value_cansleep(pb->enable_gpio, 1);
67
68         pb->enabled = true;
69 }
70
71 static void pwm_backlight_power_off(struct pwm_bl_data *pb)
72 {
73         if (!pb->enabled)
74                 return;
75
76         if (pb->enable_gpio)
77                 gpiod_set_value_cansleep(pb->enable_gpio, 0);
78
79         if (pb->pwm_off_delay)
80                 msleep(pb->pwm_off_delay);
81
82         pwm_config(pb->pwm, 0, pb->period);
83         pwm_disable(pb->pwm);
84
85         regulator_disable(pb->power_supply);
86         pb->enabled = false;
87 }
88
89 static int compute_duty_cycle(struct pwm_bl_data *pb, int brightness)
90 {
91         unsigned int lth = pb->lth_brightness;
92         u64 duty_cycle;
93
94         if (pb->levels)
95                 duty_cycle = pb->levels[brightness];
96         else
97                 duty_cycle = brightness;
98
99         duty_cycle *= pb->period - lth;
100         do_div(duty_cycle, pb->scale);
101
102         return duty_cycle + lth;
103 }
104
105 static int pwm_backlight_update_status(struct backlight_device *bl)
106 {
107         struct pwm_bl_data *pb = bl_get_data(bl);
108         int brightness = bl->props.brightness;
109         int duty_cycle;
110
111         if (bl->props.power != FB_BLANK_UNBLANK ||
112             bl->props.fb_blank != FB_BLANK_UNBLANK ||
113             bl->props.state & BL_CORE_FBBLANK)
114                 brightness = 0;
115
116         if (pb->notify)
117                 brightness = pb->notify(pb->dev, brightness);
118
119         if (brightness > 0) {
120                 duty_cycle = compute_duty_cycle(pb, brightness);
121                 pwm_config(pb->pwm, duty_cycle, pb->period);
122                 pwm_backlight_power_on(pb, brightness);
123         } else
124                 pwm_backlight_power_off(pb);
125
126         if (pb->notify_after)
127                 pb->notify_after(pb->dev, brightness);
128
129         return 0;
130 }
131
132 static int pwm_backlight_check_fb(struct backlight_device *bl,
133                                   struct fb_info *info)
134 {
135         struct pwm_bl_data *pb = bl_get_data(bl);
136
137         return !pb->check_fb || pb->check_fb(pb->dev, info);
138 }
139
140 static const struct backlight_ops pwm_backlight_ops = {
141         .update_status  = pwm_backlight_update_status,
142         .check_fb       = pwm_backlight_check_fb,
143 };
144
145 #ifdef CONFIG_OF
146 #define PWM_LUMINANCE_SCALE     10000 /* luminance scale */
147
148 /* An integer based power function */
149 static u64 int_pow(u64 base, int exp)
150 {
151         u64 result = 1;
152
153         while (exp) {
154                 if (exp & 1)
155                         result *= base;
156                 exp >>= 1;
157                 base *= base;
158         }
159
160         return result;
161 }
162
163 /*
164  * CIE lightness to PWM conversion.
165  *
166  * The CIE 1931 lightness formula is what actually describes how we perceive
167  * light:
168  *          Y = (L* / 902.3)           if L* ≤ 0.08856
169  *          Y = ((L* + 16) / 116)^3    if L* > 0.08856
170  *
171  * Where Y is the luminance, the amount of light coming out of the screen, and
172  * is a number between 0.0 and 1.0; and L* is the lightness, how bright a human
173  * perceives the screen to be, and is a number between 0 and 100.
174  *
175  * The following function does the fixed point maths needed to implement the
176  * above formula.
177  */
178 static u64 cie1931(unsigned int lightness, unsigned int scale)
179 {
180         u64 retval;
181
182         lightness *= 100;
183         if (lightness <= (8 * scale)) {
184                 retval = DIV_ROUND_CLOSEST_ULL(lightness * 10, 9023);
185         } else {
186                 retval = int_pow((lightness + (16 * scale)) / 116, 3);
187                 retval = DIV_ROUND_CLOSEST_ULL(retval, (scale * scale));
188         }
189
190         return retval;
191 }
192
193 /*
194  * Create a default correction table for PWM values to create linear brightness
195  * for LED based backlights using the CIE1931 algorithm.
196  */
197 static
198 int pwm_backlight_brightness_default(struct device *dev,
199                                      struct platform_pwm_backlight_data *data,
200                                      unsigned int period)
201 {
202         unsigned int i;
203         u64 retval;
204
205         /*
206          * Once we have 4096 levels there's little point going much higher...
207          * neither interactive sliders nor animation benefits from having
208          * more values in the table.
209          */
210         data->max_brightness =
211                 min((int)DIV_ROUND_UP(period, fls(period)), 4096);
212
213         data->levels = devm_kcalloc(dev, data->max_brightness,
214                                     sizeof(*data->levels), GFP_KERNEL);
215         if (!data->levels)
216                 return -ENOMEM;
217
218         /* Fill the table using the cie1931 algorithm */
219         for (i = 0; i < data->max_brightness; i++) {
220                 retval = cie1931((i * PWM_LUMINANCE_SCALE) /
221                                  data->max_brightness, PWM_LUMINANCE_SCALE) *
222                                  period;
223                 retval = DIV_ROUND_CLOSEST_ULL(retval, PWM_LUMINANCE_SCALE);
224                 if (retval > UINT_MAX)
225                         return -EINVAL;
226                 data->levels[i] = (unsigned int)retval;
227         }
228
229         data->dft_brightness = data->max_brightness / 2;
230         data->max_brightness--;
231
232         return 0;
233 }
234
235 static int pwm_backlight_parse_dt(struct device *dev,
236                                   struct platform_pwm_backlight_data *data)
237 {
238         struct device_node *node = dev->of_node;
239         unsigned int num_levels = 0;
240         unsigned int levels_count;
241         unsigned int num_steps = 0;
242         struct property *prop;
243         unsigned int *table;
244         int length;
245         u32 value;
246         int ret;
247
248         if (!node)
249                 return -ENODEV;
250
251         memset(data, 0, sizeof(*data));
252
253         /*
254          * These values are optional and set as 0 by default, the out values
255          * are modified only if a valid u32 value can be decoded.
256          */
257         of_property_read_u32(node, "post-pwm-on-delay-ms",
258                              &data->post_pwm_on_delay);
259         of_property_read_u32(node, "pwm-off-delay-ms", &data->pwm_off_delay);
260
261         data->enable_gpio = -EINVAL;
262
263         /*
264          * Determine the number of brightness levels, if this property is not
265          * set a default table of brightness levels will be used.
266          */
267         prop = of_find_property(node, "brightness-levels", &length);
268         if (!prop)
269                 return 0;
270
271         data->max_brightness = length / sizeof(u32);
272
273         /* read brightness levels from DT property */
274         if (data->max_brightness > 0) {
275                 size_t size = sizeof(*data->levels) * data->max_brightness;
276                 unsigned int i, j, n = 0;
277
278                 data->levels = devm_kzalloc(dev, size, GFP_KERNEL);
279                 if (!data->levels)
280                         return -ENOMEM;
281
282                 ret = of_property_read_u32_array(node, "brightness-levels",
283                                                  data->levels,
284                                                  data->max_brightness);
285                 if (ret < 0)
286                         return ret;
287
288                 ret = of_property_read_u32(node, "default-brightness-level",
289                                            &value);
290                 if (ret < 0)
291                         return ret;
292
293                 data->dft_brightness = value;
294
295                 /*
296                  * This property is optional, if is set enables linear
297                  * interpolation between each of the values of brightness levels
298                  * and creates a new pre-computed table.
299                  */
300                 of_property_read_u32(node, "num-interpolated-steps",
301                                      &num_steps);
302
303                 /*
304                  * Make sure that there is at least two entries in the
305                  * brightness-levels table, otherwise we can't interpolate
306                  * between two points.
307                  */
308                 if (num_steps) {
309                         if (data->max_brightness < 2) {
310                                 dev_err(dev, "can't interpolate\n");
311                                 return -EINVAL;
312                         }
313
314                         /*
315                          * Recalculate the number of brightness levels, now
316                          * taking in consideration the number of interpolated
317                          * steps between two levels.
318                          */
319                         for (i = 0; i < data->max_brightness - 1; i++) {
320                                 if ((data->levels[i + 1] - data->levels[i]) /
321                                    num_steps)
322                                         num_levels += num_steps;
323                                 else
324                                         num_levels++;
325                         }
326                         num_levels++;
327                         dev_dbg(dev, "new number of brightness levels: %d\n",
328                                 num_levels);
329
330                         /*
331                          * Create a new table of brightness levels with all the
332                          * interpolated steps.
333                          */
334                         size = sizeof(*table) * num_levels;
335                         table = devm_kzalloc(dev, size, GFP_KERNEL);
336                         if (!table)
337                                 return -ENOMEM;
338
339                         /* Fill the interpolated table. */
340                         levels_count = 0;
341                         for (i = 0; i < data->max_brightness - 1; i++) {
342                                 value = data->levels[i];
343                                 n = (data->levels[i + 1] - value) / num_steps;
344                                 if (n > 0) {
345                                         for (j = 0; j < num_steps; j++) {
346                                                 table[levels_count] = value;
347                                                 value += n;
348                                                 levels_count++;
349                                         }
350                                 } else {
351                                         table[levels_count] = data->levels[i];
352                                         levels_count++;
353                                 }
354                         }
355                         table[levels_count] = data->levels[i];
356
357                         /*
358                          * As we use interpolation lets remove current
359                          * brightness levels table and replace for the
360                          * new interpolated table.
361                          */
362                         devm_kfree(dev, data->levels);
363                         data->levels = table;
364
365                         /*
366                          * Reassign max_brightness value to the new total number
367                          * of brightness levels.
368                          */
369                         data->max_brightness = num_levels;
370                 }
371
372                 data->max_brightness--;
373         }
374
375         return 0;
376 }
377
378 static const struct of_device_id pwm_backlight_of_match[] = {
379         { .compatible = "pwm-backlight" },
380         { }
381 };
382
383 MODULE_DEVICE_TABLE(of, pwm_backlight_of_match);
384 #else
385 static int pwm_backlight_parse_dt(struct device *dev,
386                                   struct platform_pwm_backlight_data *data)
387 {
388         return -ENODEV;
389 }
390
391 static
392 int pwm_backlight_brightness_default(struct device *dev,
393                                      struct platform_pwm_backlight_data *data,
394                                      unsigned int period)
395 {
396         return -ENODEV;
397 }
398 #endif
399
400 static int pwm_backlight_initial_power_state(const struct pwm_bl_data *pb)
401 {
402         struct device_node *node = pb->dev->of_node;
403         bool active = true;
404
405         /*
406          * If the enable GPIO is present, observable (either as input
407          * or output) and off then the backlight is not currently active.
408          * */
409         if (pb->enable_gpio && gpiod_get_value_cansleep(pb->enable_gpio) == 0)
410                 active = false;
411
412         if (!regulator_is_enabled(pb->power_supply))
413                 active = false;
414
415         if (!pwm_is_enabled(pb->pwm))
416                 active = false;
417
418         /*
419          * Synchronize the enable_gpio with the observed state of the
420          * hardware.
421          */
422         if (pb->enable_gpio)
423                 gpiod_direction_output(pb->enable_gpio, active);
424
425         /*
426          * Do not change pb->enabled here! pb->enabled essentially
427          * tells us if we own one of the regulator's use counts and
428          * right now we do not.
429          */
430
431         /* Not booted with device tree or no phandle link to the node */
432         if (!node || !node->phandle)
433                 return FB_BLANK_UNBLANK;
434
435         /*
436          * If the driver is probed from the device tree and there is a
437          * phandle link pointing to the backlight node, it is safe to
438          * assume that another driver will enable the backlight at the
439          * appropriate time. Therefore, if it is disabled, keep it so.
440          */
441         return active ? FB_BLANK_UNBLANK: FB_BLANK_POWERDOWN;
442 }
443
444 static int pwm_backlight_probe(struct platform_device *pdev)
445 {
446         struct platform_pwm_backlight_data *data = dev_get_platdata(&pdev->dev);
447         struct platform_pwm_backlight_data defdata;
448         struct backlight_properties props;
449         struct backlight_device *bl;
450         struct device_node *node = pdev->dev.of_node;
451         struct pwm_bl_data *pb;
452         struct pwm_state state;
453         struct pwm_args pargs;
454         unsigned int i;
455         int ret;
456
457         if (!data) {
458                 ret = pwm_backlight_parse_dt(&pdev->dev, &defdata);
459                 if (ret < 0) {
460                         dev_err(&pdev->dev, "failed to find platform data\n");
461                         return ret;
462                 }
463
464                 data = &defdata;
465         }
466
467         if (data->init) {
468                 ret = data->init(&pdev->dev);
469                 if (ret < 0)
470                         return ret;
471         }
472
473         pb = devm_kzalloc(&pdev->dev, sizeof(*pb), GFP_KERNEL);
474         if (!pb) {
475                 ret = -ENOMEM;
476                 goto err_alloc;
477         }
478
479         pb->notify = data->notify;
480         pb->notify_after = data->notify_after;
481         pb->check_fb = data->check_fb;
482         pb->exit = data->exit;
483         pb->dev = &pdev->dev;
484         pb->enabled = false;
485         pb->post_pwm_on_delay = data->post_pwm_on_delay;
486         pb->pwm_off_delay = data->pwm_off_delay;
487
488         pb->enable_gpio = devm_gpiod_get_optional(&pdev->dev, "enable",
489                                                   GPIOD_ASIS);
490         if (IS_ERR(pb->enable_gpio)) {
491                 ret = PTR_ERR(pb->enable_gpio);
492                 goto err_alloc;
493         }
494
495         /*
496          * Compatibility fallback for drivers still using the integer GPIO
497          * platform data. Must go away soon.
498          */
499         if (!pb->enable_gpio && gpio_is_valid(data->enable_gpio)) {
500                 ret = devm_gpio_request_one(&pdev->dev, data->enable_gpio,
501                                             GPIOF_OUT_INIT_HIGH, "enable");
502                 if (ret < 0) {
503                         dev_err(&pdev->dev, "failed to request GPIO#%d: %d\n",
504                                 data->enable_gpio, ret);
505                         goto err_alloc;
506                 }
507
508                 pb->enable_gpio = gpio_to_desc(data->enable_gpio);
509         }
510
511         pb->power_supply = devm_regulator_get(&pdev->dev, "power");
512         if (IS_ERR(pb->power_supply)) {
513                 ret = PTR_ERR(pb->power_supply);
514                 goto err_alloc;
515         }
516
517         pb->pwm = devm_pwm_get(&pdev->dev, NULL);
518         if (IS_ERR(pb->pwm) && PTR_ERR(pb->pwm) != -EPROBE_DEFER && !node) {
519                 dev_err(&pdev->dev, "unable to request PWM, trying legacy API\n");
520                 pb->legacy = true;
521                 pb->pwm = pwm_request(data->pwm_id, "pwm-backlight");
522         }
523
524         if (IS_ERR(pb->pwm)) {
525                 ret = PTR_ERR(pb->pwm);
526                 if (ret != -EPROBE_DEFER)
527                         dev_err(&pdev->dev, "unable to request PWM\n");
528                 goto err_alloc;
529         }
530
531         dev_dbg(&pdev->dev, "got pwm for backlight\n");
532
533         if (!data->levels) {
534                 /* Get the PWM period (in nanoseconds) */
535                 pwm_get_state(pb->pwm, &state);
536
537                 ret = pwm_backlight_brightness_default(&pdev->dev, data,
538                                                        state.period);
539                 if (ret < 0) {
540                         dev_err(&pdev->dev,
541                                 "failed to setup default brightness table\n");
542                         goto err_alloc;
543                 }
544         }
545
546         for (i = 0; i <= data->max_brightness; i++) {
547                 if (data->levels[i] > pb->scale)
548                         pb->scale = data->levels[i];
549
550                 pb->levels = data->levels;
551         }
552
553         /*
554          * FIXME: pwm_apply_args() should be removed when switching to
555          * the atomic PWM API.
556          */
557         pwm_apply_args(pb->pwm);
558
559         /*
560          * The DT case will set the pwm_period_ns field to 0 and store the
561          * period, parsed from the DT, in the PWM device. For the non-DT case,
562          * set the period from platform data if it has not already been set
563          * via the PWM lookup table.
564          */
565         pwm_get_args(pb->pwm, &pargs);
566         pb->period = pargs.period;
567         if (!pb->period && (data->pwm_period_ns > 0))
568                 pb->period = data->pwm_period_ns;
569
570         pb->lth_brightness = data->lth_brightness * (pb->period / pb->scale);
571
572         memset(&props, 0, sizeof(struct backlight_properties));
573         props.type = BACKLIGHT_RAW;
574         props.max_brightness = data->max_brightness;
575         bl = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, pb,
576                                        &pwm_backlight_ops, &props);
577         if (IS_ERR(bl)) {
578                 dev_err(&pdev->dev, "failed to register backlight\n");
579                 ret = PTR_ERR(bl);
580                 if (pb->legacy)
581                         pwm_free(pb->pwm);
582                 goto err_alloc;
583         }
584
585         if (data->dft_brightness > data->max_brightness) {
586                 dev_warn(&pdev->dev,
587                          "invalid default brightness level: %u, using %u\n",
588                          data->dft_brightness, data->max_brightness);
589                 data->dft_brightness = data->max_brightness;
590         }
591
592         bl->props.brightness = data->dft_brightness;
593         bl->props.power = pwm_backlight_initial_power_state(pb);
594         backlight_update_status(bl);
595
596         platform_set_drvdata(pdev, bl);
597         return 0;
598
599 err_alloc:
600         if (data->exit)
601                 data->exit(&pdev->dev);
602         return ret;
603 }
604
605 static int pwm_backlight_remove(struct platform_device *pdev)
606 {
607         struct backlight_device *bl = platform_get_drvdata(pdev);
608         struct pwm_bl_data *pb = bl_get_data(bl);
609
610         backlight_device_unregister(bl);
611         pwm_backlight_power_off(pb);
612
613         if (pb->exit)
614                 pb->exit(&pdev->dev);
615         if (pb->legacy)
616                 pwm_free(pb->pwm);
617
618         return 0;
619 }
620
621 static void pwm_backlight_shutdown(struct platform_device *pdev)
622 {
623         struct backlight_device *bl = platform_get_drvdata(pdev);
624         struct pwm_bl_data *pb = bl_get_data(bl);
625
626         pwm_backlight_power_off(pb);
627 }
628
629 #ifdef CONFIG_PM_SLEEP
630 static int pwm_backlight_suspend(struct device *dev)
631 {
632         struct backlight_device *bl = dev_get_drvdata(dev);
633         struct pwm_bl_data *pb = bl_get_data(bl);
634
635         if (pb->notify)
636                 pb->notify(pb->dev, 0);
637
638         pwm_backlight_power_off(pb);
639
640         if (pb->notify_after)
641                 pb->notify_after(pb->dev, 0);
642
643         return 0;
644 }
645
646 static int pwm_backlight_resume(struct device *dev)
647 {
648         struct backlight_device *bl = dev_get_drvdata(dev);
649
650         backlight_update_status(bl);
651
652         return 0;
653 }
654 #endif
655
656 static const struct dev_pm_ops pwm_backlight_pm_ops = {
657 #ifdef CONFIG_PM_SLEEP
658         .suspend = pwm_backlight_suspend,
659         .resume = pwm_backlight_resume,
660         .poweroff = pwm_backlight_suspend,
661         .restore = pwm_backlight_resume,
662 #endif
663 };
664
665 static struct platform_driver pwm_backlight_driver = {
666         .driver         = {
667                 .name           = "pwm-backlight",
668                 .pm             = &pwm_backlight_pm_ops,
669                 .of_match_table = of_match_ptr(pwm_backlight_of_match),
670         },
671         .probe          = pwm_backlight_probe,
672         .remove         = pwm_backlight_remove,
673         .shutdown       = pwm_backlight_shutdown,
674 };
675
676 module_platform_driver(pwm_backlight_driver);
677
678 MODULE_DESCRIPTION("PWM based Backlight Driver");
679 MODULE_LICENSE("GPL");
680 MODULE_ALIAS("platform:pwm-backlight");