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