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