ACPI / video: Filter the _BCL table for duplicate brightness values
[firefly-linux-kernel-4.4.55.git] / drivers / acpi / video.c
1 /*
2  *  video.c - ACPI Video Driver
3  *
4  *  Copyright (C) 2004 Luming Yu <luming.yu@intel.com>
5  *  Copyright (C) 2004 Bruno Ducrot <ducrot@poupinou.org>
6  *  Copyright (C) 2006 Thomas Tuttle <linux-kernel@ttuttle.net>
7  *
8  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or (at
13  *  your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful, but
16  *  WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  *  General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License along
21  *  with this program; if not, write to the Free Software Foundation, Inc.,
22  *  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
23  *
24  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
25  */
26
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/init.h>
30 #include <linux/types.h>
31 #include <linux/list.h>
32 #include <linux/mutex.h>
33 #include <linux/input.h>
34 #include <linux/backlight.h>
35 #include <linux/thermal.h>
36 #include <linux/sort.h>
37 #include <linux/pci.h>
38 #include <linux/pci_ids.h>
39 #include <linux/slab.h>
40 #include <linux/dmi.h>
41 #include <linux/suspend.h>
42 #include <linux/acpi.h>
43 #include <acpi/video.h>
44 #include <asm/uaccess.h>
45
46 #include "internal.h"
47
48 #define PREFIX "ACPI: "
49
50 #define ACPI_VIDEO_BUS_NAME             "Video Bus"
51 #define ACPI_VIDEO_DEVICE_NAME          "Video Device"
52 #define ACPI_VIDEO_NOTIFY_SWITCH        0x80
53 #define ACPI_VIDEO_NOTIFY_PROBE         0x81
54 #define ACPI_VIDEO_NOTIFY_CYCLE         0x82
55 #define ACPI_VIDEO_NOTIFY_NEXT_OUTPUT   0x83
56 #define ACPI_VIDEO_NOTIFY_PREV_OUTPUT   0x84
57
58 #define ACPI_VIDEO_NOTIFY_CYCLE_BRIGHTNESS      0x85
59 #define ACPI_VIDEO_NOTIFY_INC_BRIGHTNESS        0x86
60 #define ACPI_VIDEO_NOTIFY_DEC_BRIGHTNESS        0x87
61 #define ACPI_VIDEO_NOTIFY_ZERO_BRIGHTNESS       0x88
62 #define ACPI_VIDEO_NOTIFY_DISPLAY_OFF           0x89
63
64 #define MAX_NAME_LEN    20
65
66 #define _COMPONENT              ACPI_VIDEO_COMPONENT
67 ACPI_MODULE_NAME("video");
68
69 MODULE_AUTHOR("Bruno Ducrot");
70 MODULE_DESCRIPTION("ACPI Video Driver");
71 MODULE_LICENSE("GPL");
72
73 static bool brightness_switch_enabled = 1;
74 module_param(brightness_switch_enabled, bool, 0644);
75
76 /*
77  * By default, we don't allow duplicate ACPI video bus devices
78  * under the same VGA controller
79  */
80 static bool allow_duplicates;
81 module_param(allow_duplicates, bool, 0644);
82
83 /*
84  * For Windows 8 systems: if set ture and the GPU driver has
85  * registered a backlight interface, skip registering ACPI video's.
86  */
87 static bool use_native_backlight = false;
88 module_param(use_native_backlight, bool, 0644);
89
90 static int register_count;
91 static struct mutex video_list_lock;
92 static struct list_head video_bus_head;
93 static int acpi_video_bus_add(struct acpi_device *device);
94 static int acpi_video_bus_remove(struct acpi_device *device);
95 static void acpi_video_bus_notify(struct acpi_device *device, u32 event);
96
97 static const struct acpi_device_id video_device_ids[] = {
98         {ACPI_VIDEO_HID, 0},
99         {"", 0},
100 };
101 MODULE_DEVICE_TABLE(acpi, video_device_ids);
102
103 static struct acpi_driver acpi_video_bus = {
104         .name = "video",
105         .class = ACPI_VIDEO_CLASS,
106         .ids = video_device_ids,
107         .ops = {
108                 .add = acpi_video_bus_add,
109                 .remove = acpi_video_bus_remove,
110                 .notify = acpi_video_bus_notify,
111                 },
112 };
113
114 struct acpi_video_bus_flags {
115         u8 multihead:1;         /* can switch video heads */
116         u8 rom:1;               /* can retrieve a video rom */
117         u8 post:1;              /* can configure the head to */
118         u8 reserved:5;
119 };
120
121 struct acpi_video_bus_cap {
122         u8 _DOS:1;              /* Enable/Disable output switching */
123         u8 _DOD:1;              /* Enumerate all devices attached to display adapter */
124         u8 _ROM:1;              /* Get ROM Data */
125         u8 _GPD:1;              /* Get POST Device */
126         u8 _SPD:1;              /* Set POST Device */
127         u8 _VPO:1;              /* Video POST Options */
128         u8 reserved:2;
129 };
130
131 struct acpi_video_device_attrib {
132         u32 display_index:4;    /* A zero-based instance of the Display */
133         u32 display_port_attachment:4;  /* This field differentiates the display type */
134         u32 display_type:4;     /* Describe the specific type in use */
135         u32 vendor_specific:4;  /* Chipset Vendor Specific */
136         u32 bios_can_detect:1;  /* BIOS can detect the device */
137         u32 depend_on_vga:1;    /* Non-VGA output device whose power is related to
138                                    the VGA device. */
139         u32 pipe_id:3;          /* For VGA multiple-head devices. */
140         u32 reserved:10;        /* Must be 0 */
141         u32 device_id_scheme:1; /* Device ID Scheme */
142 };
143
144 struct acpi_video_enumerated_device {
145         union {
146                 u32 int_val;
147                 struct acpi_video_device_attrib attrib;
148         } value;
149         struct acpi_video_device *bind_info;
150 };
151
152 struct acpi_video_bus {
153         struct acpi_device *device;
154         u8 dos_setting;
155         struct acpi_video_enumerated_device *attached_array;
156         u8 attached_count;
157         struct acpi_video_bus_cap cap;
158         struct acpi_video_bus_flags flags;
159         struct list_head video_device_list;
160         struct mutex device_list_lock;  /* protects video_device_list */
161         struct list_head entry;
162         struct input_dev *input;
163         char phys[32];  /* for input device */
164         struct notifier_block pm_nb;
165 };
166
167 struct acpi_video_device_flags {
168         u8 crt:1;
169         u8 lcd:1;
170         u8 tvout:1;
171         u8 dvi:1;
172         u8 bios:1;
173         u8 unknown:1;
174         u8 notify:1;
175         u8 reserved:1;
176 };
177
178 struct acpi_video_device_cap {
179         u8 _ADR:1;              /* Return the unique ID */
180         u8 _BCL:1;              /* Query list of brightness control levels supported */
181         u8 _BCM:1;              /* Set the brightness level */
182         u8 _BQC:1;              /* Get current brightness level */
183         u8 _BCQ:1;              /* Some buggy BIOS uses _BCQ instead of _BQC */
184         u8 _DDC:1;              /* Return the EDID for this device */
185 };
186
187 struct acpi_video_brightness_flags {
188         u8 _BCL_no_ac_battery_levels:1; /* no AC/Battery levels in _BCL */
189         u8 _BCL_reversed:1;             /* _BCL package is in a reversed order */
190         u8 _BQC_use_index:1;            /* _BQC returns an index value */
191 };
192
193 struct acpi_video_device_brightness {
194         int curr;
195         int count;
196         int *levels;
197         struct acpi_video_brightness_flags flags;
198 };
199
200 struct acpi_video_device {
201         unsigned long device_id;
202         struct acpi_video_device_flags flags;
203         struct acpi_video_device_cap cap;
204         struct list_head entry;
205         struct acpi_video_bus *video;
206         struct acpi_device *dev;
207         struct acpi_video_device_brightness *brightness;
208         struct backlight_device *backlight;
209         struct thermal_cooling_device *cooling_dev;
210 };
211
212 static const char device_decode[][30] = {
213         "motherboard VGA device",
214         "PCI VGA device",
215         "AGP VGA device",
216         "UNKNOWN",
217 };
218
219 static void acpi_video_device_notify(acpi_handle handle, u32 event, void *data);
220 static void acpi_video_device_rebind(struct acpi_video_bus *video);
221 static void acpi_video_device_bind(struct acpi_video_bus *video,
222                                    struct acpi_video_device *device);
223 static int acpi_video_device_enumerate(struct acpi_video_bus *video);
224 static int acpi_video_device_lcd_set_level(struct acpi_video_device *device,
225                         int level);
226 static int acpi_video_device_lcd_get_level_current(
227                         struct acpi_video_device *device,
228                         unsigned long long *level, bool raw);
229 static int acpi_video_get_next_level(struct acpi_video_device *device,
230                                      u32 level_current, u32 event);
231 static int acpi_video_switch_brightness(struct acpi_video_device *device,
232                                          int event);
233
234 static bool acpi_video_verify_backlight_support(void)
235 {
236         if (acpi_osi_is_win8() && use_native_backlight &&
237             backlight_device_registered(BACKLIGHT_RAW))
238                 return false;
239         return acpi_video_backlight_support();
240 }
241
242 /* backlight device sysfs support */
243 static int acpi_video_get_brightness(struct backlight_device *bd)
244 {
245         unsigned long long cur_level;
246         int i;
247         struct acpi_video_device *vd = bl_get_data(bd);
248
249         if (acpi_video_device_lcd_get_level_current(vd, &cur_level, false))
250                 return -EINVAL;
251         for (i = 2; i < vd->brightness->count; i++) {
252                 if (vd->brightness->levels[i] == cur_level)
253                         /*
254                          * The first two entries are special - see page 575
255                          * of the ACPI spec 3.0
256                          */
257                         return i - 2;
258         }
259         return 0;
260 }
261
262 static int acpi_video_set_brightness(struct backlight_device *bd)
263 {
264         int request_level = bd->props.brightness + 2;
265         struct acpi_video_device *vd = bl_get_data(bd);
266
267         return acpi_video_device_lcd_set_level(vd,
268                                 vd->brightness->levels[request_level]);
269 }
270
271 static const struct backlight_ops acpi_backlight_ops = {
272         .get_brightness = acpi_video_get_brightness,
273         .update_status  = acpi_video_set_brightness,
274 };
275
276 /* thermal cooling device callbacks */
277 static int video_get_max_state(struct thermal_cooling_device *cooling_dev, unsigned
278                                long *state)
279 {
280         struct acpi_device *device = cooling_dev->devdata;
281         struct acpi_video_device *video = acpi_driver_data(device);
282
283         *state = video->brightness->count - 3;
284         return 0;
285 }
286
287 static int video_get_cur_state(struct thermal_cooling_device *cooling_dev, unsigned
288                                long *state)
289 {
290         struct acpi_device *device = cooling_dev->devdata;
291         struct acpi_video_device *video = acpi_driver_data(device);
292         unsigned long long level;
293         int offset;
294
295         if (acpi_video_device_lcd_get_level_current(video, &level, false))
296                 return -EINVAL;
297         for (offset = 2; offset < video->brightness->count; offset++)
298                 if (level == video->brightness->levels[offset]) {
299                         *state = video->brightness->count - offset - 1;
300                         return 0;
301                 }
302
303         return -EINVAL;
304 }
305
306 static int
307 video_set_cur_state(struct thermal_cooling_device *cooling_dev, unsigned long state)
308 {
309         struct acpi_device *device = cooling_dev->devdata;
310         struct acpi_video_device *video = acpi_driver_data(device);
311         int level;
312
313         if (state >= video->brightness->count - 2)
314                 return -EINVAL;
315
316         state = video->brightness->count - state;
317         level = video->brightness->levels[state - 1];
318         return acpi_video_device_lcd_set_level(video, level);
319 }
320
321 static const struct thermal_cooling_device_ops video_cooling_ops = {
322         .get_max_state = video_get_max_state,
323         .get_cur_state = video_get_cur_state,
324         .set_cur_state = video_set_cur_state,
325 };
326
327 /*
328  * --------------------------------------------------------------------------
329  *                             Video Management
330  * --------------------------------------------------------------------------
331  */
332
333 static int
334 acpi_video_device_lcd_query_levels(struct acpi_video_device *device,
335                                    union acpi_object **levels)
336 {
337         int status;
338         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
339         union acpi_object *obj;
340
341
342         *levels = NULL;
343
344         status = acpi_evaluate_object(device->dev->handle, "_BCL", NULL, &buffer);
345         if (!ACPI_SUCCESS(status))
346                 return status;
347         obj = (union acpi_object *)buffer.pointer;
348         if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) {
349                 printk(KERN_ERR PREFIX "Invalid _BCL data\n");
350                 status = -EFAULT;
351                 goto err;
352         }
353
354         *levels = obj;
355
356         return 0;
357
358 err:
359         kfree(buffer.pointer);
360
361         return status;
362 }
363
364 static int
365 acpi_video_device_lcd_set_level(struct acpi_video_device *device, int level)
366 {
367         int status;
368         int state;
369
370         status = acpi_execute_simple_method(device->dev->handle,
371                                             "_BCM", level);
372         if (ACPI_FAILURE(status)) {
373                 ACPI_ERROR((AE_INFO, "Evaluating _BCM failed"));
374                 return -EIO;
375         }
376
377         device->brightness->curr = level;
378         for (state = 2; state < device->brightness->count; state++)
379                 if (level == device->brightness->levels[state]) {
380                         if (device->backlight)
381                                 device->backlight->props.brightness = state - 2;
382                         return 0;
383                 }
384
385         ACPI_ERROR((AE_INFO, "Current brightness invalid"));
386         return -EINVAL;
387 }
388
389 /*
390  * For some buggy _BQC methods, we need to add a constant value to
391  * the _BQC return value to get the actual current brightness level
392  */
393
394 static int bqc_offset_aml_bug_workaround;
395 static int __init video_set_bqc_offset(const struct dmi_system_id *d)
396 {
397         bqc_offset_aml_bug_workaround = 9;
398         return 0;
399 }
400
401 static struct dmi_system_id video_dmi_table[] __initdata = {
402         /*
403          * Broken _BQC workaround http://bugzilla.kernel.org/show_bug.cgi?id=13121
404          */
405         {
406          .callback = video_set_bqc_offset,
407          .ident = "Acer Aspire 5720",
408          .matches = {
409                 DMI_MATCH(DMI_BOARD_VENDOR, "Acer"),
410                 DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 5720"),
411                 },
412         },
413         {
414          .callback = video_set_bqc_offset,
415          .ident = "Acer Aspire 5710Z",
416          .matches = {
417                 DMI_MATCH(DMI_BOARD_VENDOR, "Acer"),
418                 DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 5710Z"),
419                 },
420         },
421         {
422          .callback = video_set_bqc_offset,
423          .ident = "eMachines E510",
424          .matches = {
425                 DMI_MATCH(DMI_BOARD_VENDOR, "EMACHINES"),
426                 DMI_MATCH(DMI_PRODUCT_NAME, "eMachines E510"),
427                 },
428         },
429         {
430          .callback = video_set_bqc_offset,
431          .ident = "Acer Aspire 5315",
432          .matches = {
433                 DMI_MATCH(DMI_BOARD_VENDOR, "Acer"),
434                 DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 5315"),
435                 },
436         },
437         {
438          .callback = video_set_bqc_offset,
439          .ident = "Acer Aspire 7720",
440          .matches = {
441                 DMI_MATCH(DMI_BOARD_VENDOR, "Acer"),
442                 DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 7720"),
443                 },
444         },
445         {}
446 };
447
448 static unsigned long long
449 acpi_video_bqc_value_to_level(struct acpi_video_device *device,
450                               unsigned long long bqc_value)
451 {
452         unsigned long long level;
453
454         if (device->brightness->flags._BQC_use_index) {
455                 /*
456                  * _BQC returns an index that doesn't account for
457                  * the first 2 items with special meaning, so we need
458                  * to compensate for that by offsetting ourselves
459                  */
460                 if (device->brightness->flags._BCL_reversed)
461                         bqc_value = device->brightness->count - 3 - bqc_value;
462
463                 level = device->brightness->levels[bqc_value + 2];
464         } else {
465                 level = bqc_value;
466         }
467
468         level += bqc_offset_aml_bug_workaround;
469
470         return level;
471 }
472
473 static int
474 acpi_video_device_lcd_get_level_current(struct acpi_video_device *device,
475                                         unsigned long long *level, bool raw)
476 {
477         acpi_status status = AE_OK;
478         int i;
479
480         if (device->cap._BQC || device->cap._BCQ) {
481                 char *buf = device->cap._BQC ? "_BQC" : "_BCQ";
482
483                 status = acpi_evaluate_integer(device->dev->handle, buf,
484                                                 NULL, level);
485                 if (ACPI_SUCCESS(status)) {
486                         if (raw) {
487                                 /*
488                                  * Caller has indicated he wants the raw
489                                  * value returned by _BQC, so don't furtherly
490                                  * mess with the value.
491                                  */
492                                 return 0;
493                         }
494
495                         *level = acpi_video_bqc_value_to_level(device, *level);
496
497                         for (i = 2; i < device->brightness->count; i++)
498                                 if (device->brightness->levels[i] == *level) {
499                                         device->brightness->curr = *level;
500                                         return 0;
501                                 }
502                         /*
503                          * BQC returned an invalid level.
504                          * Stop using it.
505                          */
506                         ACPI_WARNING((AE_INFO,
507                                       "%s returned an invalid level",
508                                       buf));
509                         device->cap._BQC = device->cap._BCQ = 0;
510                 } else {
511                         /*
512                          * Fixme:
513                          * should we return an error or ignore this failure?
514                          * dev->brightness->curr is a cached value which stores
515                          * the correct current backlight level in most cases.
516                          * ACPI video backlight still works w/ buggy _BQC.
517                          * http://bugzilla.kernel.org/show_bug.cgi?id=12233
518                          */
519                         ACPI_WARNING((AE_INFO, "Evaluating %s failed", buf));
520                         device->cap._BQC = device->cap._BCQ = 0;
521                 }
522         }
523
524         *level = device->brightness->curr;
525         return 0;
526 }
527
528 static int
529 acpi_video_device_EDID(struct acpi_video_device *device,
530                        union acpi_object **edid, ssize_t length)
531 {
532         int status;
533         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
534         union acpi_object *obj;
535         union acpi_object arg0 = { ACPI_TYPE_INTEGER };
536         struct acpi_object_list args = { 1, &arg0 };
537
538
539         *edid = NULL;
540
541         if (!device)
542                 return -ENODEV;
543         if (length == 128)
544                 arg0.integer.value = 1;
545         else if (length == 256)
546                 arg0.integer.value = 2;
547         else
548                 return -EINVAL;
549
550         status = acpi_evaluate_object(device->dev->handle, "_DDC", &args, &buffer);
551         if (ACPI_FAILURE(status))
552                 return -ENODEV;
553
554         obj = buffer.pointer;
555
556         if (obj && obj->type == ACPI_TYPE_BUFFER)
557                 *edid = obj;
558         else {
559                 printk(KERN_ERR PREFIX "Invalid _DDC data\n");
560                 status = -EFAULT;
561                 kfree(obj);
562         }
563
564         return status;
565 }
566
567 /* bus */
568
569 /*
570  *  Arg:
571  *      video           : video bus device pointer
572  *      bios_flag       :
573  *              0.      The system BIOS should NOT automatically switch(toggle)
574  *                      the active display output.
575  *              1.      The system BIOS should automatically switch (toggle) the
576  *                      active display output. No switch event.
577  *              2.      The _DGS value should be locked.
578  *              3.      The system BIOS should not automatically switch (toggle) the
579  *                      active display output, but instead generate the display switch
580  *                      event notify code.
581  *      lcd_flag        :
582  *              0.      The system BIOS should automatically control the brightness level
583  *                      of the LCD when the power changes from AC to DC
584  *              1.      The system BIOS should NOT automatically control the brightness
585  *                      level of the LCD when the power changes from AC to DC.
586  *  Return Value:
587  *              -EINVAL wrong arg.
588  */
589
590 static int
591 acpi_video_bus_DOS(struct acpi_video_bus *video, int bios_flag, int lcd_flag)
592 {
593         acpi_status status;
594
595         if (!video->cap._DOS)
596                 return 0;
597
598         if (bios_flag < 0 || bios_flag > 3 || lcd_flag < 0 || lcd_flag > 1)
599                 return -EINVAL;
600         video->dos_setting = (lcd_flag << 2) | bios_flag;
601         status = acpi_execute_simple_method(video->device->handle, "_DOS",
602                                             (lcd_flag << 2) | bios_flag);
603         if (ACPI_FAILURE(status))
604                 return -EIO;
605
606         return 0;
607 }
608
609 /*
610  * Simple comparison function used to sort backlight levels.
611  */
612
613 static int
614 acpi_video_cmp_level(const void *a, const void *b)
615 {
616         return *(int *)a - *(int *)b;
617 }
618
619 /*
620  * Decides if _BQC/_BCQ for this system is usable
621  *
622  * We do this by changing the level first and then read out the current
623  * brightness level, if the value does not match, find out if it is using
624  * index. If not, clear the _BQC/_BCQ capability.
625  */
626 static int acpi_video_bqc_quirk(struct acpi_video_device *device,
627                                 int max_level, int current_level)
628 {
629         struct acpi_video_device_brightness *br = device->brightness;
630         int result;
631         unsigned long long level;
632         int test_level;
633
634         /* don't mess with existing known broken systems */
635         if (bqc_offset_aml_bug_workaround)
636                 return 0;
637
638         /*
639          * Some systems always report current brightness level as maximum
640          * through _BQC, we need to test another value for them.
641          */
642         test_level = current_level == max_level ? br->levels[3] : max_level;
643
644         result = acpi_video_device_lcd_set_level(device, test_level);
645         if (result)
646                 return result;
647
648         result = acpi_video_device_lcd_get_level_current(device, &level, true);
649         if (result)
650                 return result;
651
652         if (level != test_level) {
653                 /* buggy _BQC found, need to find out if it uses index */
654                 if (level < br->count) {
655                         if (br->flags._BCL_reversed)
656                                 level = br->count - 3 - level;
657                         if (br->levels[level + 2] == test_level)
658                                 br->flags._BQC_use_index = 1;
659                 }
660
661                 if (!br->flags._BQC_use_index)
662                         device->cap._BQC = device->cap._BCQ = 0;
663         }
664
665         return 0;
666 }
667
668
669 /*
670  *  Arg:
671  *      device  : video output device (LCD, CRT, ..)
672  *
673  *  Return Value:
674  *      Maximum brightness level
675  *
676  *  Allocate and initialize device->brightness.
677  */
678
679 static int
680 acpi_video_init_brightness(struct acpi_video_device *device)
681 {
682         union acpi_object *obj = NULL;
683         int i, max_level = 0, count = 0, level_ac_battery = 0;
684         unsigned long long level, level_old;
685         union acpi_object *o;
686         struct acpi_video_device_brightness *br = NULL;
687         int result = -EINVAL;
688         u32 value;
689
690         if (!ACPI_SUCCESS(acpi_video_device_lcd_query_levels(device, &obj))) {
691                 ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Could not query available "
692                                                 "LCD brightness level\n"));
693                 goto out;
694         }
695
696         if (obj->package.count < 2)
697                 goto out;
698
699         br = kzalloc(sizeof(*br), GFP_KERNEL);
700         if (!br) {
701                 printk(KERN_ERR "can't allocate memory\n");
702                 result = -ENOMEM;
703                 goto out;
704         }
705
706         br->levels = kmalloc((obj->package.count + 2) * sizeof *(br->levels),
707                                 GFP_KERNEL);
708         if (!br->levels) {
709                 result = -ENOMEM;
710                 goto out_free;
711         }
712
713         for (i = 0; i < obj->package.count; i++) {
714                 o = (union acpi_object *)&obj->package.elements[i];
715                 if (o->type != ACPI_TYPE_INTEGER) {
716                         printk(KERN_ERR PREFIX "Invalid data\n");
717                         continue;
718                 }
719                 value = (u32) o->integer.value;
720                 /* Skip duplicate entries */
721                 if (count > 2 && br->levels[count - 1] == value)
722                         continue;
723
724                 br->levels[count] = value;
725
726                 if (br->levels[count] > max_level)
727                         max_level = br->levels[count];
728                 count++;
729         }
730
731         /*
732          * some buggy BIOS don't export the levels
733          * when machine is on AC/Battery in _BCL package.
734          * In this case, the first two elements in _BCL packages
735          * are also supported brightness levels that OS should take care of.
736          */
737         for (i = 2; i < count; i++) {
738                 if (br->levels[i] == br->levels[0])
739                         level_ac_battery++;
740                 if (br->levels[i] == br->levels[1])
741                         level_ac_battery++;
742         }
743
744         if (level_ac_battery < 2) {
745                 level_ac_battery = 2 - level_ac_battery;
746                 br->flags._BCL_no_ac_battery_levels = 1;
747                 for (i = (count - 1 + level_ac_battery); i >= 2; i--)
748                         br->levels[i] = br->levels[i - level_ac_battery];
749                 count += level_ac_battery;
750         } else if (level_ac_battery > 2)
751                 ACPI_ERROR((AE_INFO, "Too many duplicates in _BCL package"));
752
753         /* Check if the _BCL package is in a reversed order */
754         if (max_level == br->levels[2]) {
755                 br->flags._BCL_reversed = 1;
756                 sort(&br->levels[2], count - 2, sizeof(br->levels[2]),
757                         acpi_video_cmp_level, NULL);
758         } else if (max_level != br->levels[count - 1])
759                 ACPI_ERROR((AE_INFO,
760                             "Found unordered _BCL package"));
761
762         br->count = count;
763         device->brightness = br;
764
765         /* _BQC uses INDEX while _BCL uses VALUE in some laptops */
766         br->curr = level = max_level;
767
768         if (!device->cap._BQC)
769                 goto set_level;
770
771         result = acpi_video_device_lcd_get_level_current(device,
772                                                          &level_old, true);
773         if (result)
774                 goto out_free_levels;
775
776         result = acpi_video_bqc_quirk(device, max_level, level_old);
777         if (result)
778                 goto out_free_levels;
779         /*
780          * cap._BQC may get cleared due to _BQC is found to be broken
781          * in acpi_video_bqc_quirk, so check again here.
782          */
783         if (!device->cap._BQC)
784                 goto set_level;
785
786         level = acpi_video_bqc_value_to_level(device, level_old);
787         /*
788          * On some buggy laptops, _BQC returns an uninitialized
789          * value when invoked for the first time, i.e.
790          * level_old is invalid (no matter whether it's a level
791          * or an index). Set the backlight to max_level in this case.
792          */
793         for (i = 2; i < br->count; i++)
794                 if (level == br->levels[i])
795                         break;
796         if (i == br->count || !level)
797                 level = max_level;
798
799 set_level:
800         result = acpi_video_device_lcd_set_level(device, level);
801         if (result)
802                 goto out_free_levels;
803
804         ACPI_DEBUG_PRINT((ACPI_DB_INFO,
805                           "found %d brightness levels\n", count - 2));
806         kfree(obj);
807         return result;
808
809 out_free_levels:
810         kfree(br->levels);
811 out_free:
812         kfree(br);
813 out:
814         device->brightness = NULL;
815         kfree(obj);
816         return result;
817 }
818
819 /*
820  *  Arg:
821  *      device  : video output device (LCD, CRT, ..)
822  *
823  *  Return Value:
824  *      None
825  *
826  *  Find out all required AML methods defined under the output
827  *  device.
828  */
829
830 static void acpi_video_device_find_cap(struct acpi_video_device *device)
831 {
832         if (acpi_has_method(device->dev->handle, "_ADR"))
833                 device->cap._ADR = 1;
834         if (acpi_has_method(device->dev->handle, "_BCL"))
835                 device->cap._BCL = 1;
836         if (acpi_has_method(device->dev->handle, "_BCM"))
837                 device->cap._BCM = 1;
838         if (acpi_has_method(device->dev->handle, "_BQC")) {
839                 device->cap._BQC = 1;
840         } else if (acpi_has_method(device->dev->handle, "_BCQ")) {
841                 printk(KERN_WARNING FW_BUG "_BCQ is used instead of _BQC\n");
842                 device->cap._BCQ = 1;
843         }
844
845         if (acpi_has_method(device->dev->handle, "_DDC"))
846                 device->cap._DDC = 1;
847 }
848
849 /*
850  *  Arg:
851  *      device  : video output device (VGA)
852  *
853  *  Return Value:
854  *      None
855  *
856  *  Find out all required AML methods defined under the video bus device.
857  */
858
859 static void acpi_video_bus_find_cap(struct acpi_video_bus *video)
860 {
861         if (acpi_has_method(video->device->handle, "_DOS"))
862                 video->cap._DOS = 1;
863         if (acpi_has_method(video->device->handle, "_DOD"))
864                 video->cap._DOD = 1;
865         if (acpi_has_method(video->device->handle, "_ROM"))
866                 video->cap._ROM = 1;
867         if (acpi_has_method(video->device->handle, "_GPD"))
868                 video->cap._GPD = 1;
869         if (acpi_has_method(video->device->handle, "_SPD"))
870                 video->cap._SPD = 1;
871         if (acpi_has_method(video->device->handle, "_VPO"))
872                 video->cap._VPO = 1;
873 }
874
875 /*
876  * Check whether the video bus device has required AML method to
877  * support the desired features
878  */
879
880 static int acpi_video_bus_check(struct acpi_video_bus *video)
881 {
882         acpi_status status = -ENOENT;
883         struct pci_dev *dev;
884
885         if (!video)
886                 return -EINVAL;
887
888         dev = acpi_get_pci_dev(video->device->handle);
889         if (!dev)
890                 return -ENODEV;
891         pci_dev_put(dev);
892
893         /*
894          * Since there is no HID, CID and so on for VGA driver, we have
895          * to check well known required nodes.
896          */
897
898         /* Does this device support video switching? */
899         if (video->cap._DOS || video->cap._DOD) {
900                 if (!video->cap._DOS) {
901                         printk(KERN_WARNING FW_BUG
902                                 "ACPI(%s) defines _DOD but not _DOS\n",
903                                 acpi_device_bid(video->device));
904                 }
905                 video->flags.multihead = 1;
906                 status = 0;
907         }
908
909         /* Does this device support retrieving a video ROM? */
910         if (video->cap._ROM) {
911                 video->flags.rom = 1;
912                 status = 0;
913         }
914
915         /* Does this device support configuring which video device to POST? */
916         if (video->cap._GPD && video->cap._SPD && video->cap._VPO) {
917                 video->flags.post = 1;
918                 status = 0;
919         }
920
921         return status;
922 }
923
924 /*
925  * --------------------------------------------------------------------------
926  *                               Driver Interface
927  * --------------------------------------------------------------------------
928  */
929
930 /* device interface */
931 static struct acpi_video_device_attrib *
932 acpi_video_get_device_attr(struct acpi_video_bus *video, unsigned long device_id)
933 {
934         struct acpi_video_enumerated_device *ids;
935         int i;
936
937         for (i = 0; i < video->attached_count; i++) {
938                 ids = &video->attached_array[i];
939                 if ((ids->value.int_val & 0xffff) == device_id)
940                         return &ids->value.attrib;
941         }
942
943         return NULL;
944 }
945
946 static int
947 acpi_video_get_device_type(struct acpi_video_bus *video,
948                            unsigned long device_id)
949 {
950         struct acpi_video_enumerated_device *ids;
951         int i;
952
953         for (i = 0; i < video->attached_count; i++) {
954                 ids = &video->attached_array[i];
955                 if ((ids->value.int_val & 0xffff) == device_id)
956                         return ids->value.int_val;
957         }
958
959         return 0;
960 }
961
962 static int
963 acpi_video_bus_get_one_device(struct acpi_device *device,
964                               struct acpi_video_bus *video)
965 {
966         unsigned long long device_id;
967         int status, device_type;
968         struct acpi_video_device *data;
969         struct acpi_video_device_attrib *attribute;
970
971         status =
972             acpi_evaluate_integer(device->handle, "_ADR", NULL, &device_id);
973         /* Some device omits _ADR, we skip them instead of fail */
974         if (ACPI_FAILURE(status))
975                 return 0;
976
977         data = kzalloc(sizeof(struct acpi_video_device), GFP_KERNEL);
978         if (!data)
979                 return -ENOMEM;
980
981         strcpy(acpi_device_name(device), ACPI_VIDEO_DEVICE_NAME);
982         strcpy(acpi_device_class(device), ACPI_VIDEO_CLASS);
983         device->driver_data = data;
984
985         data->device_id = device_id;
986         data->video = video;
987         data->dev = device;
988
989         attribute = acpi_video_get_device_attr(video, device_id);
990
991         if (attribute && attribute->device_id_scheme) {
992                 switch (attribute->display_type) {
993                 case ACPI_VIDEO_DISPLAY_CRT:
994                         data->flags.crt = 1;
995                         break;
996                 case ACPI_VIDEO_DISPLAY_TV:
997                         data->flags.tvout = 1;
998                         break;
999                 case ACPI_VIDEO_DISPLAY_DVI:
1000                         data->flags.dvi = 1;
1001                         break;
1002                 case ACPI_VIDEO_DISPLAY_LCD:
1003                         data->flags.lcd = 1;
1004                         break;
1005                 default:
1006                         data->flags.unknown = 1;
1007                         break;
1008                 }
1009                 if (attribute->bios_can_detect)
1010                         data->flags.bios = 1;
1011         } else {
1012                 /* Check for legacy IDs */
1013                 device_type = acpi_video_get_device_type(video, device_id);
1014                 /* Ignore bits 16 and 18-20 */
1015                 switch (device_type & 0xffe2ffff) {
1016                 case ACPI_VIDEO_DISPLAY_LEGACY_MONITOR:
1017                         data->flags.crt = 1;
1018                         break;
1019                 case ACPI_VIDEO_DISPLAY_LEGACY_PANEL:
1020                         data->flags.lcd = 1;
1021                         break;
1022                 case ACPI_VIDEO_DISPLAY_LEGACY_TV:
1023                         data->flags.tvout = 1;
1024                         break;
1025                 default:
1026                         data->flags.unknown = 1;
1027                 }
1028         }
1029
1030         acpi_video_device_bind(video, data);
1031         acpi_video_device_find_cap(data);
1032
1033         mutex_lock(&video->device_list_lock);
1034         list_add_tail(&data->entry, &video->video_device_list);
1035         mutex_unlock(&video->device_list_lock);
1036
1037         return status;
1038 }
1039
1040 /*
1041  *  Arg:
1042  *      video   : video bus device
1043  *
1044  *  Return:
1045  *      none
1046  *
1047  *  Enumerate the video device list of the video bus,
1048  *  bind the ids with the corresponding video devices
1049  *  under the video bus.
1050  */
1051
1052 static void acpi_video_device_rebind(struct acpi_video_bus *video)
1053 {
1054         struct acpi_video_device *dev;
1055
1056         mutex_lock(&video->device_list_lock);
1057
1058         list_for_each_entry(dev, &video->video_device_list, entry)
1059                 acpi_video_device_bind(video, dev);
1060
1061         mutex_unlock(&video->device_list_lock);
1062 }
1063
1064 /*
1065  *  Arg:
1066  *      video   : video bus device
1067  *      device  : video output device under the video
1068  *              bus
1069  *
1070  *  Return:
1071  *      none
1072  *
1073  *  Bind the ids with the corresponding video devices
1074  *  under the video bus.
1075  */
1076
1077 static void
1078 acpi_video_device_bind(struct acpi_video_bus *video,
1079                        struct acpi_video_device *device)
1080 {
1081         struct acpi_video_enumerated_device *ids;
1082         int i;
1083
1084         for (i = 0; i < video->attached_count; i++) {
1085                 ids = &video->attached_array[i];
1086                 if (device->device_id == (ids->value.int_val & 0xffff)) {
1087                         ids->bind_info = device;
1088                         ACPI_DEBUG_PRINT((ACPI_DB_INFO, "device_bind %d\n", i));
1089                 }
1090         }
1091 }
1092
1093 /*
1094  *  Arg:
1095  *      video   : video bus device
1096  *
1097  *  Return:
1098  *      < 0     : error
1099  *
1100  *  Call _DOD to enumerate all devices attached to display adapter
1101  *
1102  */
1103
1104 static int acpi_video_device_enumerate(struct acpi_video_bus *video)
1105 {
1106         int status;
1107         int count;
1108         int i;
1109         struct acpi_video_enumerated_device *active_list;
1110         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
1111         union acpi_object *dod = NULL;
1112         union acpi_object *obj;
1113
1114         status = acpi_evaluate_object(video->device->handle, "_DOD", NULL, &buffer);
1115         if (!ACPI_SUCCESS(status)) {
1116                 ACPI_EXCEPTION((AE_INFO, status, "Evaluating _DOD"));
1117                 return status;
1118         }
1119
1120         dod = buffer.pointer;
1121         if (!dod || (dod->type != ACPI_TYPE_PACKAGE)) {
1122                 ACPI_EXCEPTION((AE_INFO, status, "Invalid _DOD data"));
1123                 status = -EFAULT;
1124                 goto out;
1125         }
1126
1127         ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Found %d video heads in _DOD\n",
1128                           dod->package.count));
1129
1130         active_list = kcalloc(1 + dod->package.count,
1131                               sizeof(struct acpi_video_enumerated_device),
1132                               GFP_KERNEL);
1133         if (!active_list) {
1134                 status = -ENOMEM;
1135                 goto out;
1136         }
1137
1138         count = 0;
1139         for (i = 0; i < dod->package.count; i++) {
1140                 obj = &dod->package.elements[i];
1141
1142                 if (obj->type != ACPI_TYPE_INTEGER) {
1143                         printk(KERN_ERR PREFIX
1144                                 "Invalid _DOD data in element %d\n", i);
1145                         continue;
1146                 }
1147
1148                 active_list[count].value.int_val = obj->integer.value;
1149                 active_list[count].bind_info = NULL;
1150                 ACPI_DEBUG_PRINT((ACPI_DB_INFO, "dod element[%d] = %d\n", i,
1151                                   (int)obj->integer.value));
1152                 count++;
1153         }
1154
1155         kfree(video->attached_array);
1156
1157         video->attached_array = active_list;
1158         video->attached_count = count;
1159
1160 out:
1161         kfree(buffer.pointer);
1162         return status;
1163 }
1164
1165 static int
1166 acpi_video_get_next_level(struct acpi_video_device *device,
1167                           u32 level_current, u32 event)
1168 {
1169         int min, max, min_above, max_below, i, l, delta = 255;
1170         max = max_below = 0;
1171         min = min_above = 255;
1172         /* Find closest level to level_current */
1173         for (i = 2; i < device->brightness->count; i++) {
1174                 l = device->brightness->levels[i];
1175                 if (abs(l - level_current) < abs(delta)) {
1176                         delta = l - level_current;
1177                         if (!delta)
1178                                 break;
1179                 }
1180         }
1181         /* Ajust level_current to closest available level */
1182         level_current += delta;
1183         for (i = 2; i < device->brightness->count; i++) {
1184                 l = device->brightness->levels[i];
1185                 if (l < min)
1186                         min = l;
1187                 if (l > max)
1188                         max = l;
1189                 if (l < min_above && l > level_current)
1190                         min_above = l;
1191                 if (l > max_below && l < level_current)
1192                         max_below = l;
1193         }
1194
1195         switch (event) {
1196         case ACPI_VIDEO_NOTIFY_CYCLE_BRIGHTNESS:
1197                 return (level_current < max) ? min_above : min;
1198         case ACPI_VIDEO_NOTIFY_INC_BRIGHTNESS:
1199                 return (level_current < max) ? min_above : max;
1200         case ACPI_VIDEO_NOTIFY_DEC_BRIGHTNESS:
1201                 return (level_current > min) ? max_below : min;
1202         case ACPI_VIDEO_NOTIFY_ZERO_BRIGHTNESS:
1203         case ACPI_VIDEO_NOTIFY_DISPLAY_OFF:
1204                 return 0;
1205         default:
1206                 return level_current;
1207         }
1208 }
1209
1210 static int
1211 acpi_video_switch_brightness(struct acpi_video_device *device, int event)
1212 {
1213         unsigned long long level_current, level_next;
1214         int result = -EINVAL;
1215
1216         /* no warning message if acpi_backlight=vendor or a quirk is used */
1217         if (!acpi_video_verify_backlight_support())
1218                 return 0;
1219
1220         if (!device->brightness)
1221                 goto out;
1222
1223         result = acpi_video_device_lcd_get_level_current(device,
1224                                                          &level_current,
1225                                                          false);
1226         if (result)
1227                 goto out;
1228
1229         level_next = acpi_video_get_next_level(device, level_current, event);
1230
1231         result = acpi_video_device_lcd_set_level(device, level_next);
1232
1233         if (!result)
1234                 backlight_force_update(device->backlight,
1235                                        BACKLIGHT_UPDATE_HOTKEY);
1236
1237 out:
1238         if (result)
1239                 printk(KERN_ERR PREFIX "Failed to switch the brightness\n");
1240
1241         return result;
1242 }
1243
1244 int acpi_video_get_edid(struct acpi_device *device, int type, int device_id,
1245                         void **edid)
1246 {
1247         struct acpi_video_bus *video;
1248         struct acpi_video_device *video_device;
1249         union acpi_object *buffer = NULL;
1250         acpi_status status;
1251         int i, length;
1252
1253         if (!device || !acpi_driver_data(device))
1254                 return -EINVAL;
1255
1256         video = acpi_driver_data(device);
1257
1258         for (i = 0; i < video->attached_count; i++) {
1259                 video_device = video->attached_array[i].bind_info;
1260                 length = 256;
1261
1262                 if (!video_device)
1263                         continue;
1264
1265                 if (!video_device->cap._DDC)
1266                         continue;
1267
1268                 if (type) {
1269                         switch (type) {
1270                         case ACPI_VIDEO_DISPLAY_CRT:
1271                                 if (!video_device->flags.crt)
1272                                         continue;
1273                                 break;
1274                         case ACPI_VIDEO_DISPLAY_TV:
1275                                 if (!video_device->flags.tvout)
1276                                         continue;
1277                                 break;
1278                         case ACPI_VIDEO_DISPLAY_DVI:
1279                                 if (!video_device->flags.dvi)
1280                                         continue;
1281                                 break;
1282                         case ACPI_VIDEO_DISPLAY_LCD:
1283                                 if (!video_device->flags.lcd)
1284                                         continue;
1285                                 break;
1286                         }
1287                 } else if (video_device->device_id != device_id) {
1288                         continue;
1289                 }
1290
1291                 status = acpi_video_device_EDID(video_device, &buffer, length);
1292
1293                 if (ACPI_FAILURE(status) || !buffer ||
1294                     buffer->type != ACPI_TYPE_BUFFER) {
1295                         length = 128;
1296                         status = acpi_video_device_EDID(video_device, &buffer,
1297                                                         length);
1298                         if (ACPI_FAILURE(status) || !buffer ||
1299                             buffer->type != ACPI_TYPE_BUFFER) {
1300                                 continue;
1301                         }
1302                 }
1303
1304                 *edid = buffer->buffer.pointer;
1305                 return length;
1306         }
1307
1308         return -ENODEV;
1309 }
1310 EXPORT_SYMBOL(acpi_video_get_edid);
1311
1312 static int
1313 acpi_video_bus_get_devices(struct acpi_video_bus *video,
1314                            struct acpi_device *device)
1315 {
1316         int status = 0;
1317         struct acpi_device *dev;
1318
1319         /*
1320          * There are systems where video module known to work fine regardless
1321          * of broken _DOD and ignoring returned value here doesn't cause
1322          * any issues later.
1323          */
1324         acpi_video_device_enumerate(video);
1325
1326         list_for_each_entry(dev, &device->children, node) {
1327
1328                 status = acpi_video_bus_get_one_device(dev, video);
1329                 if (status) {
1330                         dev_err(&dev->dev, "Can't attach device\n");
1331                         break;
1332                 }
1333         }
1334         return status;
1335 }
1336
1337 /* acpi_video interface */
1338
1339 /*
1340  * Win8 requires setting bit2 of _DOS to let firmware know it shouldn't
1341  * preform any automatic brightness change on receiving a notification.
1342  */
1343 static int acpi_video_bus_start_devices(struct acpi_video_bus *video)
1344 {
1345         return acpi_video_bus_DOS(video, 0,
1346                                   acpi_osi_is_win8() ? 1 : 0);
1347 }
1348
1349 static int acpi_video_bus_stop_devices(struct acpi_video_bus *video)
1350 {
1351         return acpi_video_bus_DOS(video, 0,
1352                                   acpi_osi_is_win8() ? 0 : 1);
1353 }
1354
1355 static void acpi_video_bus_notify(struct acpi_device *device, u32 event)
1356 {
1357         struct acpi_video_bus *video = acpi_driver_data(device);
1358         struct input_dev *input;
1359         int keycode = 0;
1360
1361         if (!video || !video->input)
1362                 return;
1363
1364         input = video->input;
1365
1366         switch (event) {
1367         case ACPI_VIDEO_NOTIFY_SWITCH:  /* User requested a switch,
1368                                          * most likely via hotkey. */
1369                 keycode = KEY_SWITCHVIDEOMODE;
1370                 break;
1371
1372         case ACPI_VIDEO_NOTIFY_PROBE:   /* User plugged in or removed a video
1373                                          * connector. */
1374                 acpi_video_device_enumerate(video);
1375                 acpi_video_device_rebind(video);
1376                 keycode = KEY_SWITCHVIDEOMODE;
1377                 break;
1378
1379         case ACPI_VIDEO_NOTIFY_CYCLE:   /* Cycle Display output hotkey pressed. */
1380                 keycode = KEY_SWITCHVIDEOMODE;
1381                 break;
1382         case ACPI_VIDEO_NOTIFY_NEXT_OUTPUT:     /* Next Display output hotkey pressed. */
1383                 keycode = KEY_VIDEO_NEXT;
1384                 break;
1385         case ACPI_VIDEO_NOTIFY_PREV_OUTPUT:     /* previous Display output hotkey pressed. */
1386                 keycode = KEY_VIDEO_PREV;
1387                 break;
1388
1389         default:
1390                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1391                                   "Unsupported event [0x%x]\n", event));
1392                 break;
1393         }
1394
1395         if (acpi_notifier_call_chain(device, event, 0))
1396                 /* Something vetoed the keypress. */
1397                 keycode = 0;
1398
1399         if (keycode) {
1400                 input_report_key(input, keycode, 1);
1401                 input_sync(input);
1402                 input_report_key(input, keycode, 0);
1403                 input_sync(input);
1404         }
1405
1406         return;
1407 }
1408
1409 static void acpi_video_device_notify(acpi_handle handle, u32 event, void *data)
1410 {
1411         struct acpi_video_device *video_device = data;
1412         struct acpi_device *device = NULL;
1413         struct acpi_video_bus *bus;
1414         struct input_dev *input;
1415         int keycode = 0;
1416
1417         if (!video_device)
1418                 return;
1419
1420         device = video_device->dev;
1421         bus = video_device->video;
1422         input = bus->input;
1423
1424         switch (event) {
1425         case ACPI_VIDEO_NOTIFY_CYCLE_BRIGHTNESS:        /* Cycle brightness */
1426                 if (brightness_switch_enabled)
1427                         acpi_video_switch_brightness(video_device, event);
1428                 keycode = KEY_BRIGHTNESS_CYCLE;
1429                 break;
1430         case ACPI_VIDEO_NOTIFY_INC_BRIGHTNESS:  /* Increase brightness */
1431                 if (brightness_switch_enabled)
1432                         acpi_video_switch_brightness(video_device, event);
1433                 keycode = KEY_BRIGHTNESSUP;
1434                 break;
1435         case ACPI_VIDEO_NOTIFY_DEC_BRIGHTNESS:  /* Decrease brightness */
1436                 if (brightness_switch_enabled)
1437                         acpi_video_switch_brightness(video_device, event);
1438                 keycode = KEY_BRIGHTNESSDOWN;
1439                 break;
1440         case ACPI_VIDEO_NOTIFY_ZERO_BRIGHTNESS: /* zero brightness */
1441                 if (brightness_switch_enabled)
1442                         acpi_video_switch_brightness(video_device, event);
1443                 keycode = KEY_BRIGHTNESS_ZERO;
1444                 break;
1445         case ACPI_VIDEO_NOTIFY_DISPLAY_OFF:     /* display device off */
1446                 if (brightness_switch_enabled)
1447                         acpi_video_switch_brightness(video_device, event);
1448                 keycode = KEY_DISPLAY_OFF;
1449                 break;
1450         default:
1451                 ACPI_DEBUG_PRINT((ACPI_DB_INFO,
1452                                   "Unsupported event [0x%x]\n", event));
1453                 break;
1454         }
1455
1456         acpi_notifier_call_chain(device, event, 0);
1457
1458         if (keycode) {
1459                 input_report_key(input, keycode, 1);
1460                 input_sync(input);
1461                 input_report_key(input, keycode, 0);
1462                 input_sync(input);
1463         }
1464
1465         return;
1466 }
1467
1468 static int acpi_video_resume(struct notifier_block *nb,
1469                                 unsigned long val, void *ign)
1470 {
1471         struct acpi_video_bus *video;
1472         struct acpi_video_device *video_device;
1473         int i;
1474
1475         switch (val) {
1476         case PM_HIBERNATION_PREPARE:
1477         case PM_SUSPEND_PREPARE:
1478         case PM_RESTORE_PREPARE:
1479                 return NOTIFY_DONE;
1480         }
1481
1482         video = container_of(nb, struct acpi_video_bus, pm_nb);
1483
1484         dev_info(&video->device->dev, "Restoring backlight state\n");
1485
1486         for (i = 0; i < video->attached_count; i++) {
1487                 video_device = video->attached_array[i].bind_info;
1488                 if (video_device && video_device->backlight)
1489                         acpi_video_set_brightness(video_device->backlight);
1490         }
1491
1492         return NOTIFY_OK;
1493 }
1494
1495 static acpi_status
1496 acpi_video_bus_match(acpi_handle handle, u32 level, void *context,
1497                         void **return_value)
1498 {
1499         struct acpi_device *device = context;
1500         struct acpi_device *sibling;
1501         int result;
1502
1503         if (handle == device->handle)
1504                 return AE_CTRL_TERMINATE;
1505
1506         result = acpi_bus_get_device(handle, &sibling);
1507         if (result)
1508                 return AE_OK;
1509
1510         if (!strcmp(acpi_device_name(sibling), ACPI_VIDEO_BUS_NAME))
1511                         return AE_ALREADY_EXISTS;
1512
1513         return AE_OK;
1514 }
1515
1516 static void acpi_video_dev_register_backlight(struct acpi_video_device *device)
1517 {
1518         if (acpi_video_verify_backlight_support()) {
1519                 struct backlight_properties props;
1520                 struct pci_dev *pdev;
1521                 acpi_handle acpi_parent;
1522                 struct device *parent = NULL;
1523                 int result;
1524                 static int count;
1525                 char *name;
1526
1527                 result = acpi_video_init_brightness(device);
1528                 if (result)
1529                         return;
1530                 name = kasprintf(GFP_KERNEL, "acpi_video%d", count);
1531                 if (!name)
1532                         return;
1533                 count++;
1534
1535                 acpi_get_parent(device->dev->handle, &acpi_parent);
1536
1537                 pdev = acpi_get_pci_dev(acpi_parent);
1538                 if (pdev) {
1539                         parent = &pdev->dev;
1540                         pci_dev_put(pdev);
1541                 }
1542
1543                 memset(&props, 0, sizeof(struct backlight_properties));
1544                 props.type = BACKLIGHT_FIRMWARE;
1545                 props.max_brightness = device->brightness->count - 3;
1546                 device->backlight = backlight_device_register(name,
1547                                                               parent,
1548                                                               device,
1549                                                               &acpi_backlight_ops,
1550                                                               &props);
1551                 kfree(name);
1552                 if (IS_ERR(device->backlight))
1553                         return;
1554
1555                 /*
1556                  * Save current brightness level in case we have to restore it
1557                  * before acpi_video_device_lcd_set_level() is called next time.
1558                  */
1559                 device->backlight->props.brightness =
1560                                 acpi_video_get_brightness(device->backlight);
1561
1562                 device->cooling_dev = thermal_cooling_device_register("LCD",
1563                                         device->dev, &video_cooling_ops);
1564                 if (IS_ERR(device->cooling_dev)) {
1565                         /*
1566                          * Set cooling_dev to NULL so we don't crash trying to
1567                          * free it.
1568                          * Also, why the hell we are returning early and
1569                          * not attempt to register video output if cooling
1570                          * device registration failed?
1571                          * -- dtor
1572                          */
1573                         device->cooling_dev = NULL;
1574                         return;
1575                 }
1576
1577                 dev_info(&device->dev->dev, "registered as cooling_device%d\n",
1578                          device->cooling_dev->id);
1579                 result = sysfs_create_link(&device->dev->dev.kobj,
1580                                 &device->cooling_dev->device.kobj,
1581                                 "thermal_cooling");
1582                 if (result)
1583                         printk(KERN_ERR PREFIX "Create sysfs link\n");
1584                 result = sysfs_create_link(&device->cooling_dev->device.kobj,
1585                                 &device->dev->dev.kobj, "device");
1586                 if (result)
1587                         printk(KERN_ERR PREFIX "Create sysfs link\n");
1588         }
1589 }
1590
1591 static int acpi_video_bus_register_backlight(struct acpi_video_bus *video)
1592 {
1593         struct acpi_video_device *dev;
1594
1595         mutex_lock(&video->device_list_lock);
1596         list_for_each_entry(dev, &video->video_device_list, entry)
1597                 acpi_video_dev_register_backlight(dev);
1598         mutex_unlock(&video->device_list_lock);
1599
1600         video->pm_nb.notifier_call = acpi_video_resume;
1601         video->pm_nb.priority = 0;
1602         return register_pm_notifier(&video->pm_nb);
1603 }
1604
1605 static void acpi_video_dev_unregister_backlight(struct acpi_video_device *device)
1606 {
1607         if (device->backlight) {
1608                 backlight_device_unregister(device->backlight);
1609                 device->backlight = NULL;
1610         }
1611         if (device->brightness) {
1612                 kfree(device->brightness->levels);
1613                 kfree(device->brightness);
1614                 device->brightness = NULL;
1615         }
1616         if (device->cooling_dev) {
1617                 sysfs_remove_link(&device->dev->dev.kobj, "thermal_cooling");
1618                 sysfs_remove_link(&device->cooling_dev->device.kobj, "device");
1619                 thermal_cooling_device_unregister(device->cooling_dev);
1620                 device->cooling_dev = NULL;
1621         }
1622 }
1623
1624 static int acpi_video_bus_unregister_backlight(struct acpi_video_bus *video)
1625 {
1626         struct acpi_video_device *dev;
1627         int error = unregister_pm_notifier(&video->pm_nb);
1628
1629         mutex_lock(&video->device_list_lock);
1630         list_for_each_entry(dev, &video->video_device_list, entry)
1631                 acpi_video_dev_unregister_backlight(dev);
1632         mutex_unlock(&video->device_list_lock);
1633
1634         return error;
1635 }
1636
1637 static void acpi_video_dev_add_notify_handler(struct acpi_video_device *device)
1638 {
1639         acpi_status status;
1640         struct acpi_device *adev = device->dev;
1641
1642         status = acpi_install_notify_handler(adev->handle, ACPI_DEVICE_NOTIFY,
1643                                              acpi_video_device_notify, device);
1644         if (ACPI_FAILURE(status))
1645                 dev_err(&adev->dev, "Error installing notify handler\n");
1646         else
1647                 device->flags.notify = 1;
1648 }
1649
1650 static int acpi_video_bus_add_notify_handler(struct acpi_video_bus *video)
1651 {
1652         struct input_dev *input;
1653         struct acpi_video_device *dev;
1654         int error;
1655
1656         video->input = input = input_allocate_device();
1657         if (!input) {
1658                 error = -ENOMEM;
1659                 goto out;
1660         }
1661
1662         error = acpi_video_bus_start_devices(video);
1663         if (error)
1664                 goto err_free_input;
1665
1666         snprintf(video->phys, sizeof(video->phys),
1667                         "%s/video/input0", acpi_device_hid(video->device));
1668
1669         input->name = acpi_device_name(video->device);
1670         input->phys = video->phys;
1671         input->id.bustype = BUS_HOST;
1672         input->id.product = 0x06;
1673         input->dev.parent = &video->device->dev;
1674         input->evbit[0] = BIT(EV_KEY);
1675         set_bit(KEY_SWITCHVIDEOMODE, input->keybit);
1676         set_bit(KEY_VIDEO_NEXT, input->keybit);
1677         set_bit(KEY_VIDEO_PREV, input->keybit);
1678         set_bit(KEY_BRIGHTNESS_CYCLE, input->keybit);
1679         set_bit(KEY_BRIGHTNESSUP, input->keybit);
1680         set_bit(KEY_BRIGHTNESSDOWN, input->keybit);
1681         set_bit(KEY_BRIGHTNESS_ZERO, input->keybit);
1682         set_bit(KEY_DISPLAY_OFF, input->keybit);
1683
1684         error = input_register_device(input);
1685         if (error)
1686                 goto err_stop_dev;
1687
1688         mutex_lock(&video->device_list_lock);
1689         list_for_each_entry(dev, &video->video_device_list, entry)
1690                 acpi_video_dev_add_notify_handler(dev);
1691         mutex_unlock(&video->device_list_lock);
1692
1693         return 0;
1694
1695 err_stop_dev:
1696         acpi_video_bus_stop_devices(video);
1697 err_free_input:
1698         input_free_device(input);
1699         video->input = NULL;
1700 out:
1701         return error;
1702 }
1703
1704 static void acpi_video_dev_remove_notify_handler(struct acpi_video_device *dev)
1705 {
1706         if (dev->flags.notify) {
1707                 acpi_remove_notify_handler(dev->dev->handle, ACPI_DEVICE_NOTIFY,
1708                                            acpi_video_device_notify);
1709                 dev->flags.notify = 0;
1710         }
1711 }
1712
1713 static void acpi_video_bus_remove_notify_handler(struct acpi_video_bus *video)
1714 {
1715         struct acpi_video_device *dev;
1716
1717         mutex_lock(&video->device_list_lock);
1718         list_for_each_entry(dev, &video->video_device_list, entry)
1719                 acpi_video_dev_remove_notify_handler(dev);
1720         mutex_unlock(&video->device_list_lock);
1721
1722         acpi_video_bus_stop_devices(video);
1723         input_unregister_device(video->input);
1724         video->input = NULL;
1725 }
1726
1727 static int acpi_video_bus_put_devices(struct acpi_video_bus *video)
1728 {
1729         struct acpi_video_device *dev, *next;
1730
1731         mutex_lock(&video->device_list_lock);
1732         list_for_each_entry_safe(dev, next, &video->video_device_list, entry) {
1733                 list_del(&dev->entry);
1734                 kfree(dev);
1735         }
1736         mutex_unlock(&video->device_list_lock);
1737
1738         return 0;
1739 }
1740
1741 static int instance;
1742
1743 static int acpi_video_bus_add(struct acpi_device *device)
1744 {
1745         struct acpi_video_bus *video;
1746         int error;
1747         acpi_status status;
1748
1749         status = acpi_walk_namespace(ACPI_TYPE_DEVICE,
1750                                 device->parent->handle, 1,
1751                                 acpi_video_bus_match, NULL,
1752                                 device, NULL);
1753         if (status == AE_ALREADY_EXISTS) {
1754                 printk(KERN_WARNING FW_BUG
1755                         "Duplicate ACPI video bus devices for the"
1756                         " same VGA controller, please try module "
1757                         "parameter \"video.allow_duplicates=1\""
1758                         "if the current driver doesn't work.\n");
1759                 if (!allow_duplicates)
1760                         return -ENODEV;
1761         }
1762
1763         video = kzalloc(sizeof(struct acpi_video_bus), GFP_KERNEL);
1764         if (!video)
1765                 return -ENOMEM;
1766
1767         /* a hack to fix the duplicate name "VID" problem on T61 */
1768         if (!strcmp(device->pnp.bus_id, "VID")) {
1769                 if (instance)
1770                         device->pnp.bus_id[3] = '0' + instance;
1771                 instance++;
1772         }
1773         /* a hack to fix the duplicate name "VGA" problem on Pa 3553 */
1774         if (!strcmp(device->pnp.bus_id, "VGA")) {
1775                 if (instance)
1776                         device->pnp.bus_id[3] = '0' + instance;
1777                 instance++;
1778         }
1779
1780         video->device = device;
1781         strcpy(acpi_device_name(device), ACPI_VIDEO_BUS_NAME);
1782         strcpy(acpi_device_class(device), ACPI_VIDEO_CLASS);
1783         device->driver_data = video;
1784
1785         acpi_video_bus_find_cap(video);
1786         error = acpi_video_bus_check(video);
1787         if (error)
1788                 goto err_free_video;
1789
1790         mutex_init(&video->device_list_lock);
1791         INIT_LIST_HEAD(&video->video_device_list);
1792
1793         error = acpi_video_bus_get_devices(video, device);
1794         if (error)
1795                 goto err_put_video;
1796
1797         printk(KERN_INFO PREFIX "%s [%s] (multi-head: %s  rom: %s  post: %s)\n",
1798                ACPI_VIDEO_DEVICE_NAME, acpi_device_bid(device),
1799                video->flags.multihead ? "yes" : "no",
1800                video->flags.rom ? "yes" : "no",
1801                video->flags.post ? "yes" : "no");
1802         mutex_lock(&video_list_lock);
1803         list_add_tail(&video->entry, &video_bus_head);
1804         mutex_unlock(&video_list_lock);
1805
1806         acpi_video_bus_register_backlight(video);
1807         acpi_video_bus_add_notify_handler(video);
1808
1809         return 0;
1810
1811 err_put_video:
1812         acpi_video_bus_put_devices(video);
1813         kfree(video->attached_array);
1814 err_free_video:
1815         kfree(video);
1816         device->driver_data = NULL;
1817
1818         return error;
1819 }
1820
1821 static int acpi_video_bus_remove(struct acpi_device *device)
1822 {
1823         struct acpi_video_bus *video = NULL;
1824
1825
1826         if (!device || !acpi_driver_data(device))
1827                 return -EINVAL;
1828
1829         video = acpi_driver_data(device);
1830
1831         acpi_video_bus_remove_notify_handler(video);
1832         acpi_video_bus_unregister_backlight(video);
1833         acpi_video_bus_put_devices(video);
1834
1835         mutex_lock(&video_list_lock);
1836         list_del(&video->entry);
1837         mutex_unlock(&video_list_lock);
1838
1839         kfree(video->attached_array);
1840         kfree(video);
1841
1842         return 0;
1843 }
1844
1845 static int __init is_i740(struct pci_dev *dev)
1846 {
1847         if (dev->device == 0x00D1)
1848                 return 1;
1849         if (dev->device == 0x7000)
1850                 return 1;
1851         return 0;
1852 }
1853
1854 static int __init intel_opregion_present(void)
1855 {
1856         int opregion = 0;
1857         struct pci_dev *dev = NULL;
1858         u32 address;
1859
1860         for_each_pci_dev(dev) {
1861                 if ((dev->class >> 8) != PCI_CLASS_DISPLAY_VGA)
1862                         continue;
1863                 if (dev->vendor != PCI_VENDOR_ID_INTEL)
1864                         continue;
1865                 /* We don't want to poke around undefined i740 registers */
1866                 if (is_i740(dev))
1867                         continue;
1868                 pci_read_config_dword(dev, 0xfc, &address);
1869                 if (!address)
1870                         continue;
1871                 opregion = 1;
1872         }
1873         return opregion;
1874 }
1875
1876 int acpi_video_register(void)
1877 {
1878         int result = 0;
1879         if (register_count) {
1880                 /*
1881                  * if the function of acpi_video_register is already called,
1882                  * don't register the acpi_vide_bus again and return no error.
1883                  */
1884                 return 0;
1885         }
1886
1887         mutex_init(&video_list_lock);
1888         INIT_LIST_HEAD(&video_bus_head);
1889
1890         result = acpi_bus_register_driver(&acpi_video_bus);
1891         if (result < 0)
1892                 return -ENODEV;
1893
1894         /*
1895          * When the acpi_video_bus is loaded successfully, increase
1896          * the counter reference.
1897          */
1898         register_count = 1;
1899
1900         return 0;
1901 }
1902 EXPORT_SYMBOL(acpi_video_register);
1903
1904 void acpi_video_unregister(void)
1905 {
1906         if (!register_count) {
1907                 /*
1908                  * If the acpi video bus is already unloaded, don't
1909                  * unload it again and return directly.
1910                  */
1911                 return;
1912         }
1913         acpi_bus_unregister_driver(&acpi_video_bus);
1914
1915         register_count = 0;
1916
1917         return;
1918 }
1919 EXPORT_SYMBOL(acpi_video_unregister);
1920
1921 /*
1922  * This is kind of nasty. Hardware using Intel chipsets may require
1923  * the video opregion code to be run first in order to initialise
1924  * state before any ACPI video calls are made. To handle this we defer
1925  * registration of the video class until the opregion code has run.
1926  */
1927
1928 static int __init acpi_video_init(void)
1929 {
1930         dmi_check_system(video_dmi_table);
1931
1932         if (intel_opregion_present())
1933                 return 0;
1934
1935         return acpi_video_register();
1936 }
1937
1938 static void __exit acpi_video_exit(void)
1939 {
1940         acpi_video_unregister();
1941
1942         return;
1943 }
1944
1945 module_init(acpi_video_init);
1946 module_exit(acpi_video_exit);