ACPI: thinkpad-acpi: add CMOS NVRAM polling for hot keys (v9)
[sfrench/cifs-2.6.git] / drivers / misc / thinkpad_acpi.c
1 /*
2  *  thinkpad_acpi.c - ThinkPad ACPI Extras
3  *
4  *
5  *  Copyright (C) 2004-2005 Borislav Deianov <borislav@users.sf.net>
6  *  Copyright (C) 2006-2007 Henrique de Moraes Holschuh <hmh@hmh.eng.br>
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  *  02110-1301, USA.
22  */
23
24 #define IBM_VERSION "0.17"
25 #define TPACPI_SYSFS_VERSION 0x020101
26
27 /*
28  *  Changelog:
29  *  2007-03-27  0.14    renamed to thinkpad_acpi and moved to
30  *                      drivers/misc.
31  *
32  *  2006-11-22  0.13    new maintainer
33  *                      changelog now lives in git commit history, and will
34  *                      not be updated further in-file.
35  *
36  *  2005-08-17  0.12    fix compilation on 2.6.13-rc kernels
37  *  2005-03-17  0.11    support for 600e, 770x
38  *                          thanks to Jamie Lentin <lentinj@dial.pipex.com>
39  *                      support for 770e, G41
40  *                      G40 and G41 don't have a thinklight
41  *                      temperatures no longer experimental
42  *                      experimental brightness control
43  *                      experimental volume control
44  *                      experimental fan enable/disable
45  *  2005-01-16  0.10    fix module loading on R30, R31
46  *  2005-01-16  0.9     support for 570, R30, R31
47  *                      ultrabay support on A22p, A3x
48  *                      limit arg for cmos, led, beep, drop experimental status
49  *                      more capable led control on A21e, A22p, T20-22, X20
50  *                      experimental temperatures and fan speed
51  *                      experimental embedded controller register dump
52  *                      mark more functions as __init, drop incorrect __exit
53  *                      use MODULE_VERSION
54  *                          thanks to Henrik Brix Andersen <brix@gentoo.org>
55  *                      fix parameter passing on module loading
56  *                          thanks to Rusty Russell <rusty@rustcorp.com.au>
57  *                          thanks to Jim Radford <radford@blackbean.org>
58  *  2004-11-08  0.8     fix init error case, don't return from a macro
59  *                          thanks to Chris Wright <chrisw@osdl.org>
60  *  2004-10-23  0.7     fix module loading on A21e, A22p, T20, T21, X20
61  *                      fix led control on A21e
62  *  2004-10-19  0.6     use acpi_bus_register_driver() to claim HKEY device
63  *  2004-10-18  0.5     thinklight support on A21e, G40, R32, T20, T21, X20
64  *                      proc file format changed
65  *                      video_switch command
66  *                      experimental cmos control
67  *                      experimental led control
68  *                      experimental acpi sounds
69  *  2004-09-16  0.4     support for module parameters
70  *                      hotkey mask can be prefixed by 0x
71  *                      video output switching
72  *                      video expansion control
73  *                      ultrabay eject support
74  *                      removed lcd brightness/on/off control, didn't work
75  *  2004-08-17  0.3     support for R40
76  *                      lcd off, brightness control
77  *                      thinklight on/off
78  *  2004-08-14  0.2     support for T series, X20
79  *                      bluetooth enable/disable
80  *                      hotkey events disabled by default
81  *                      removed fan control, currently useless
82  *  2004-08-09  0.1     initial release, support for X series
83  */
84
85 #include "thinkpad_acpi.h"
86
87 MODULE_AUTHOR("Borislav Deianov, Henrique de Moraes Holschuh");
88 MODULE_DESCRIPTION(IBM_DESC);
89 MODULE_VERSION(IBM_VERSION);
90 MODULE_LICENSE("GPL");
91
92 /* Please remove this in year 2009 */
93 MODULE_ALIAS("ibm_acpi");
94
95 /*
96  * DMI matching for module autoloading
97  *
98  * See http://thinkwiki.org/wiki/List_of_DMI_IDs
99  * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads
100  *
101  * Only models listed in thinkwiki will be supported, so add yours
102  * if it is not there yet.
103  */
104 #define IBM_BIOS_MODULE_ALIAS(__type) \
105         MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW")
106
107 /* Non-ancient thinkpads */
108 MODULE_ALIAS("dmi:bvnIBM:*:svnIBM:*:pvrThinkPad*:rvnIBM:*");
109 MODULE_ALIAS("dmi:bvnLENOVO:*:svnLENOVO:*:pvrThinkPad*:rvnLENOVO:*");
110
111 /* Ancient thinkpad BIOSes have to be identified by
112  * BIOS type or model number, and there are far less
113  * BIOS types than model numbers... */
114 IBM_BIOS_MODULE_ALIAS("I[B,D,H,I,M,N,O,T,W,V,Y,Z]");
115 IBM_BIOS_MODULE_ALIAS("1[0,3,6,8,A-G,I,K,M-P,S,T]");
116 IBM_BIOS_MODULE_ALIAS("K[U,X-Z]");
117
118 #define __unused __attribute__ ((unused))
119
120 static enum {
121         TPACPI_LIFE_INIT = 0,
122         TPACPI_LIFE_RUNNING,
123         TPACPI_LIFE_EXITING,
124 } tpacpi_lifecycle;
125
126 /****************************************************************************
127  ****************************************************************************
128  *
129  * ACPI Helpers and device model
130  *
131  ****************************************************************************
132  ****************************************************************************/
133
134 /*************************************************************************
135  * ACPI basic handles
136  */
137
138 static acpi_handle root_handle;
139
140 #define IBM_HANDLE(object, parent, paths...)                    \
141         static acpi_handle  object##_handle;                    \
142         static acpi_handle *object##_parent = &parent##_handle; \
143         static char        *object##_path;                      \
144         static char        *object##_paths[] = { paths }
145
146 IBM_HANDLE(ec, root, "\\_SB.PCI0.ISA.EC0",      /* 240, 240x */
147            "\\_SB.PCI.ISA.EC",  /* 570 */
148            "\\_SB.PCI0.ISA0.EC0",       /* 600e/x, 770e, 770x */
149            "\\_SB.PCI0.ISA.EC", /* A21e, A2xm/p, T20-22, X20-21 */
150            "\\_SB.PCI0.AD4S.EC0",       /* i1400, R30 */
151            "\\_SB.PCI0.ICH3.EC0",       /* R31 */
152            "\\_SB.PCI0.LPC.EC", /* all others */
153            );
154
155 IBM_HANDLE(ecrd, ec, "ECRD");   /* 570 */
156 IBM_HANDLE(ecwr, ec, "ECWR");   /* 570 */
157
158
159 /*************************************************************************
160  * Misc ACPI handles
161  */
162
163 IBM_HANDLE(cmos, root, "\\UCMS",        /* R50, R50e, R50p, R51, T4x, X31, X40 */
164            "\\CMOS",            /* A3x, G4x, R32, T23, T30, X22-24, X30 */
165            "\\CMS",             /* R40, R40e */
166            );                   /* all others */
167
168 IBM_HANDLE(hkey, ec, "\\_SB.HKEY",      /* 600e/x, 770e, 770x */
169            "^HKEY",             /* R30, R31 */
170            "HKEY",              /* all others */
171            );                   /* 570 */
172
173
174 /*************************************************************************
175  * ACPI helpers
176  */
177
178 static int acpi_evalf(acpi_handle handle,
179                       void *res, char *method, char *fmt, ...)
180 {
181         char *fmt0 = fmt;
182         struct acpi_object_list params;
183         union acpi_object in_objs[IBM_MAX_ACPI_ARGS];
184         struct acpi_buffer result, *resultp;
185         union acpi_object out_obj;
186         acpi_status status;
187         va_list ap;
188         char res_type;
189         int success;
190         int quiet;
191
192         if (!*fmt) {
193                 printk(IBM_ERR "acpi_evalf() called with empty format\n");
194                 return 0;
195         }
196
197         if (*fmt == 'q') {
198                 quiet = 1;
199                 fmt++;
200         } else
201                 quiet = 0;
202
203         res_type = *(fmt++);
204
205         params.count = 0;
206         params.pointer = &in_objs[0];
207
208         va_start(ap, fmt);
209         while (*fmt) {
210                 char c = *(fmt++);
211                 switch (c) {
212                 case 'd':       /* int */
213                         in_objs[params.count].integer.value = va_arg(ap, int);
214                         in_objs[params.count++].type = ACPI_TYPE_INTEGER;
215                         break;
216                         /* add more types as needed */
217                 default:
218                         printk(IBM_ERR "acpi_evalf() called "
219                                "with invalid format character '%c'\n", c);
220                         return 0;
221                 }
222         }
223         va_end(ap);
224
225         if (res_type != 'v') {
226                 result.length = sizeof(out_obj);
227                 result.pointer = &out_obj;
228                 resultp = &result;
229         } else
230                 resultp = NULL;
231
232         status = acpi_evaluate_object(handle, method, &params, resultp);
233
234         switch (res_type) {
235         case 'd':               /* int */
236                 if (res)
237                         *(int *)res = out_obj.integer.value;
238                 success = status == AE_OK && out_obj.type == ACPI_TYPE_INTEGER;
239                 break;
240         case 'v':               /* void */
241                 success = status == AE_OK;
242                 break;
243                 /* add more types as needed */
244         default:
245                 printk(IBM_ERR "acpi_evalf() called "
246                        "with invalid format character '%c'\n", res_type);
247                 return 0;
248         }
249
250         if (!success && !quiet)
251                 printk(IBM_ERR "acpi_evalf(%s, %s, ...) failed: %d\n",
252                        method, fmt0, status);
253
254         return success;
255 }
256
257 static void __unused acpi_print_int(acpi_handle handle, char *method)
258 {
259         int i;
260
261         if (acpi_evalf(handle, &i, method, "d"))
262                 printk(IBM_INFO "%s = 0x%x\n", method, i);
263         else
264                 printk(IBM_ERR "error calling %s\n", method);
265 }
266
267 static int acpi_ec_read(int i, u8 * p)
268 {
269         int v;
270
271         if (ecrd_handle) {
272                 if (!acpi_evalf(ecrd_handle, &v, NULL, "dd", i))
273                         return 0;
274                 *p = v;
275         } else {
276                 if (ec_read(i, p) < 0)
277                         return 0;
278         }
279
280         return 1;
281 }
282
283 static int acpi_ec_write(int i, u8 v)
284 {
285         if (ecwr_handle) {
286                 if (!acpi_evalf(ecwr_handle, NULL, NULL, "vdd", i, v))
287                         return 0;
288         } else {
289                 if (ec_write(i, v) < 0)
290                         return 0;
291         }
292
293         return 1;
294 }
295
296 static int _sta(acpi_handle handle)
297 {
298         int status;
299
300         if (!handle || !acpi_evalf(handle, &status, "_STA", "d"))
301                 status = 0;
302
303         return status;
304 }
305
306 static int issue_thinkpad_cmos_command(int cmos_cmd)
307 {
308         if (!cmos_handle)
309                 return -ENXIO;
310
311         if (!acpi_evalf(cmos_handle, NULL, NULL, "vd", cmos_cmd))
312                 return -EIO;
313
314         return 0;
315 }
316
317 /*************************************************************************
318  * ACPI device model
319  */
320
321 static void drv_acpi_handle_init(char *name,
322                            acpi_handle *handle, acpi_handle parent,
323                            char **paths, int num_paths, char **path)
324 {
325         int i;
326         acpi_status status;
327
328         vdbg_printk(TPACPI_DBG_INIT, "trying to locate ACPI handle for %s\n",
329                 name);
330
331         for (i = 0; i < num_paths; i++) {
332                 status = acpi_get_handle(parent, paths[i], handle);
333                 if (ACPI_SUCCESS(status)) {
334                         *path = paths[i];
335                         dbg_printk(TPACPI_DBG_INIT,
336                                    "Found ACPI handle %s for %s\n",
337                                    *path, name);
338                         return;
339                 }
340         }
341
342         vdbg_printk(TPACPI_DBG_INIT, "ACPI handle for %s not found\n",
343                     name);
344         *handle = NULL;
345 }
346
347 static void dispatch_acpi_notify(acpi_handle handle, u32 event, void *data)
348 {
349         struct ibm_struct *ibm = data;
350
351         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
352                 return;
353
354         if (!ibm || !ibm->acpi || !ibm->acpi->notify)
355                 return;
356
357         ibm->acpi->notify(ibm, event);
358 }
359
360 static int __init setup_acpi_notify(struct ibm_struct *ibm)
361 {
362         acpi_status status;
363         int rc;
364
365         BUG_ON(!ibm->acpi);
366
367         if (!*ibm->acpi->handle)
368                 return 0;
369
370         vdbg_printk(TPACPI_DBG_INIT,
371                 "setting up ACPI notify for %s\n", ibm->name);
372
373         rc = acpi_bus_get_device(*ibm->acpi->handle, &ibm->acpi->device);
374         if (rc < 0) {
375                 printk(IBM_ERR "acpi_bus_get_device(%s) failed: %d\n",
376                         ibm->name, rc);
377                 return -ENODEV;
378         }
379
380         acpi_driver_data(ibm->acpi->device) = ibm;
381         sprintf(acpi_device_class(ibm->acpi->device), "%s/%s",
382                 IBM_ACPI_EVENT_PREFIX,
383                 ibm->name);
384
385         status = acpi_install_notify_handler(*ibm->acpi->handle,
386                         ibm->acpi->type, dispatch_acpi_notify, ibm);
387         if (ACPI_FAILURE(status)) {
388                 if (status == AE_ALREADY_EXISTS) {
389                         printk(IBM_NOTICE "another device driver is already handling %s events\n",
390                                 ibm->name);
391                 } else {
392                         printk(IBM_ERR "acpi_install_notify_handler(%s) failed: %d\n",
393                                 ibm->name, status);
394                 }
395                 return -ENODEV;
396         }
397         ibm->flags.acpi_notify_installed = 1;
398         return 0;
399 }
400
401 static int __init tpacpi_device_add(struct acpi_device *device)
402 {
403         return 0;
404 }
405
406 static int __init register_tpacpi_subdriver(struct ibm_struct *ibm)
407 {
408         int rc;
409
410         dbg_printk(TPACPI_DBG_INIT,
411                 "registering %s as an ACPI driver\n", ibm->name);
412
413         BUG_ON(!ibm->acpi);
414
415         ibm->acpi->driver = kzalloc(sizeof(struct acpi_driver), GFP_KERNEL);
416         if (!ibm->acpi->driver) {
417                 printk(IBM_ERR "kzalloc(ibm->driver) failed\n");
418                 return -ENOMEM;
419         }
420
421         sprintf(ibm->acpi->driver->name, "%s_%s", IBM_NAME, ibm->name);
422         ibm->acpi->driver->ids = ibm->acpi->hid;
423
424         ibm->acpi->driver->ops.add = &tpacpi_device_add;
425
426         rc = acpi_bus_register_driver(ibm->acpi->driver);
427         if (rc < 0) {
428                 printk(IBM_ERR "acpi_bus_register_driver(%s) failed: %d\n",
429                        ibm->name, rc);
430                 kfree(ibm->acpi->driver);
431                 ibm->acpi->driver = NULL;
432         } else if (!rc)
433                 ibm->flags.acpi_driver_registered = 1;
434
435         return rc;
436 }
437
438
439 /****************************************************************************
440  ****************************************************************************
441  *
442  * Procfs Helpers
443  *
444  ****************************************************************************
445  ****************************************************************************/
446
447 static int dispatch_procfs_read(char *page, char **start, off_t off,
448                         int count, int *eof, void *data)
449 {
450         struct ibm_struct *ibm = data;
451         int len;
452
453         if (!ibm || !ibm->read)
454                 return -EINVAL;
455
456         len = ibm->read(page);
457         if (len < 0)
458                 return len;
459
460         if (len <= off + count)
461                 *eof = 1;
462         *start = page + off;
463         len -= off;
464         if (len > count)
465                 len = count;
466         if (len < 0)
467                 len = 0;
468
469         return len;
470 }
471
472 static int dispatch_procfs_write(struct file *file,
473                         const char __user * userbuf,
474                         unsigned long count, void *data)
475 {
476         struct ibm_struct *ibm = data;
477         char *kernbuf;
478         int ret;
479
480         if (!ibm || !ibm->write)
481                 return -EINVAL;
482
483         kernbuf = kmalloc(count + 2, GFP_KERNEL);
484         if (!kernbuf)
485                 return -ENOMEM;
486
487         if (copy_from_user(kernbuf, userbuf, count)) {
488                 kfree(kernbuf);
489                 return -EFAULT;
490         }
491
492         kernbuf[count] = 0;
493         strcat(kernbuf, ",");
494         ret = ibm->write(kernbuf);
495         if (ret == 0)
496                 ret = count;
497
498         kfree(kernbuf);
499
500         return ret;
501 }
502
503 static char *next_cmd(char **cmds)
504 {
505         char *start = *cmds;
506         char *end;
507
508         while ((end = strchr(start, ',')) && end == start)
509                 start = end + 1;
510
511         if (!end)
512                 return NULL;
513
514         *end = 0;
515         *cmds = end + 1;
516         return start;
517 }
518
519
520 /****************************************************************************
521  ****************************************************************************
522  *
523  * Device model: input, hwmon and platform
524  *
525  ****************************************************************************
526  ****************************************************************************/
527
528 static struct platform_device *tpacpi_pdev;
529 static struct platform_device *tpacpi_sensors_pdev;
530 static struct device *tpacpi_hwmon;
531 static struct input_dev *tpacpi_inputdev;
532 static struct mutex tpacpi_inputdev_send_mutex;
533
534
535 static int tpacpi_resume_handler(struct platform_device *pdev)
536 {
537         struct ibm_struct *ibm, *itmp;
538
539         list_for_each_entry_safe(ibm, itmp,
540                                  &tpacpi_all_drivers,
541                                  all_drivers) {
542                 if (ibm->resume)
543                         (ibm->resume)();
544         }
545
546         return 0;
547 }
548
549 static struct platform_driver tpacpi_pdriver = {
550         .driver = {
551                 .name = IBM_DRVR_NAME,
552                 .owner = THIS_MODULE,
553         },
554         .resume = tpacpi_resume_handler,
555 };
556
557 static struct platform_driver tpacpi_hwmon_pdriver = {
558         .driver = {
559                 .name = IBM_HWMON_DRVR_NAME,
560                 .owner = THIS_MODULE,
561         },
562 };
563
564 /*************************************************************************
565  * thinkpad-acpi driver attributes
566  */
567
568 /* interface_version --------------------------------------------------- */
569 static ssize_t tpacpi_driver_interface_version_show(
570                                 struct device_driver *drv,
571                                 char *buf)
572 {
573         return snprintf(buf, PAGE_SIZE, "0x%08x\n", TPACPI_SYSFS_VERSION);
574 }
575
576 static DRIVER_ATTR(interface_version, S_IRUGO,
577                 tpacpi_driver_interface_version_show, NULL);
578
579 /* debug_level --------------------------------------------------------- */
580 static ssize_t tpacpi_driver_debug_show(struct device_driver *drv,
581                                                 char *buf)
582 {
583         return snprintf(buf, PAGE_SIZE, "0x%04x\n", dbg_level);
584 }
585
586 static ssize_t tpacpi_driver_debug_store(struct device_driver *drv,
587                                                 const char *buf, size_t count)
588 {
589         unsigned long t;
590
591         if (parse_strtoul(buf, 0xffff, &t))
592                 return -EINVAL;
593
594         dbg_level = t;
595
596         return count;
597 }
598
599 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
600                 tpacpi_driver_debug_show, tpacpi_driver_debug_store);
601
602 /* version ------------------------------------------------------------- */
603 static ssize_t tpacpi_driver_version_show(struct device_driver *drv,
604                                                 char *buf)
605 {
606         return snprintf(buf, PAGE_SIZE, "%s v%s\n", IBM_DESC, IBM_VERSION);
607 }
608
609 static DRIVER_ATTR(version, S_IRUGO,
610                 tpacpi_driver_version_show, NULL);
611
612 /* --------------------------------------------------------------------- */
613
614 static struct driver_attribute* tpacpi_driver_attributes[] = {
615         &driver_attr_debug_level, &driver_attr_version,
616         &driver_attr_interface_version,
617 };
618
619 static int __init tpacpi_create_driver_attributes(struct device_driver *drv)
620 {
621         int i, res;
622
623         i = 0;
624         res = 0;
625         while (!res && i < ARRAY_SIZE(tpacpi_driver_attributes)) {
626                 res = driver_create_file(drv, tpacpi_driver_attributes[i]);
627                 i++;
628         }
629
630         return res;
631 }
632
633 static void tpacpi_remove_driver_attributes(struct device_driver *drv)
634 {
635         int i;
636
637         for(i = 0; i < ARRAY_SIZE(tpacpi_driver_attributes); i++)
638                 driver_remove_file(drv, tpacpi_driver_attributes[i]);
639 }
640
641 /*************************************************************************
642  * sysfs support helpers
643  */
644
645 struct attribute_set_obj {
646         struct attribute_set s;
647         struct attribute *a;
648 } __attribute__((packed));
649
650 static struct attribute_set *create_attr_set(unsigned int max_members,
651                                                 const char* name)
652 {
653         struct attribute_set_obj *sobj;
654
655         if (max_members == 0)
656                 return NULL;
657
658         /* Allocates space for implicit NULL at the end too */
659         sobj = kzalloc(sizeof(struct attribute_set_obj) +
660                     max_members * sizeof(struct attribute *),
661                     GFP_KERNEL);
662         if (!sobj)
663                 return NULL;
664         sobj->s.max_members = max_members;
665         sobj->s.group.attrs = &sobj->a;
666         sobj->s.group.name = name;
667
668         return &sobj->s;
669 }
670
671 /* not multi-threaded safe, use it in a single thread per set */
672 static int add_to_attr_set(struct attribute_set* s, struct attribute *attr)
673 {
674         if (!s || !attr)
675                 return -EINVAL;
676
677         if (s->members >= s->max_members)
678                 return -ENOMEM;
679
680         s->group.attrs[s->members] = attr;
681         s->members++;
682
683         return 0;
684 }
685
686 static int add_many_to_attr_set(struct attribute_set* s,
687                         struct attribute **attr,
688                         unsigned int count)
689 {
690         int i, res;
691
692         for (i = 0; i < count; i++) {
693                 res = add_to_attr_set(s, attr[i]);
694                 if (res)
695                         return res;
696         }
697
698         return 0;
699 }
700
701 static void delete_attr_set(struct attribute_set* s, struct kobject *kobj)
702 {
703         sysfs_remove_group(kobj, &s->group);
704         destroy_attr_set(s);
705 }
706
707 static int parse_strtoul(const char *buf,
708                 unsigned long max, unsigned long *value)
709 {
710         char *endp;
711
712         while (*buf && isspace(*buf))
713                 buf++;
714         *value = simple_strtoul(buf, &endp, 0);
715         while (*endp && isspace(*endp))
716                 endp++;
717         if (*endp || *value > max)
718                 return -EINVAL;
719
720         return 0;
721 }
722
723 /****************************************************************************
724  ****************************************************************************
725  *
726  * Subdrivers
727  *
728  ****************************************************************************
729  ****************************************************************************/
730
731 /*************************************************************************
732  * thinkpad-acpi init subdriver
733  */
734
735 static int __init thinkpad_acpi_driver_init(struct ibm_init_struct *iibm)
736 {
737         printk(IBM_INFO "%s v%s\n", IBM_DESC, IBM_VERSION);
738         printk(IBM_INFO "%s\n", IBM_URL);
739
740         printk(IBM_INFO "ThinkPad BIOS %s, EC %s\n",
741                 (thinkpad_id.bios_version_str) ?
742                         thinkpad_id.bios_version_str : "unknown",
743                 (thinkpad_id.ec_version_str) ?
744                         thinkpad_id.ec_version_str : "unknown");
745
746         if (thinkpad_id.vendor && thinkpad_id.model_str)
747                 printk(IBM_INFO "%s %s\n",
748                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
749                                 "IBM" : ((thinkpad_id.vendor ==
750                                                 PCI_VENDOR_ID_LENOVO) ?
751                                         "Lenovo" : "Unknown vendor"),
752                         thinkpad_id.model_str);
753
754         return 0;
755 }
756
757 static int thinkpad_acpi_driver_read(char *p)
758 {
759         int len = 0;
760
761         len += sprintf(p + len, "driver:\t\t%s\n", IBM_DESC);
762         len += sprintf(p + len, "version:\t%s\n", IBM_VERSION);
763
764         return len;
765 }
766
767 static struct ibm_struct thinkpad_acpi_driver_data = {
768         .name = "driver",
769         .read = thinkpad_acpi_driver_read,
770 };
771
772 /*************************************************************************
773  * Hotkey subdriver
774  */
775
776 enum {  /* Keys available through NVRAM polling */
777         TPACPI_HKEY_NVRAM_KNOWN_MASK = 0x00fb88c0U,
778         TPACPI_HKEY_NVRAM_GOOD_MASK  = 0x00fb8000U,
779 };
780
781 enum {  /* Positions of some of the keys in hotkey masks */
782         TP_ACPI_HKEY_DISPSWTCH_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF7,
783         TP_ACPI_HKEY_DISPXPAND_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF8,
784         TP_ACPI_HKEY_HIBERNATE_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF12,
785         TP_ACPI_HKEY_BRGHTUP_MASK       = 1 << TP_ACPI_HOTKEYSCAN_FNHOME,
786         TP_ACPI_HKEY_BRGHTDWN_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNEND,
787         TP_ACPI_HKEY_THNKLGHT_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNPAGEUP,
788         TP_ACPI_HKEY_ZOOM_MASK          = 1 << TP_ACPI_HOTKEYSCAN_FNSPACE,
789         TP_ACPI_HKEY_VOLUP_MASK         = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEUP,
790         TP_ACPI_HKEY_VOLDWN_MASK        = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
791         TP_ACPI_HKEY_MUTE_MASK          = 1 << TP_ACPI_HOTKEYSCAN_MUTE,
792         TP_ACPI_HKEY_THINKPAD_MASK      = 1 << TP_ACPI_HOTKEYSCAN_THINKPAD,
793 };
794
795 enum {  /* NVRAM to ACPI HKEY group map */
796         TP_NVRAM_HKEY_GROUP_HK2         = TP_ACPI_HKEY_THINKPAD_MASK |
797                                           TP_ACPI_HKEY_ZOOM_MASK |
798                                           TP_ACPI_HKEY_DISPSWTCH_MASK |
799                                           TP_ACPI_HKEY_HIBERNATE_MASK,
800         TP_NVRAM_HKEY_GROUP_BRIGHTNESS  = TP_ACPI_HKEY_BRGHTUP_MASK |
801                                           TP_ACPI_HKEY_BRGHTDWN_MASK,
802         TP_NVRAM_HKEY_GROUP_VOLUME      = TP_ACPI_HKEY_VOLUP_MASK |
803                                           TP_ACPI_HKEY_VOLDWN_MASK |
804                                           TP_ACPI_HKEY_MUTE_MASK,
805 };
806
807 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
808 struct tp_nvram_state {
809        u16 thinkpad_toggle:1;
810        u16 zoom_toggle:1;
811        u16 display_toggle:1;
812        u16 thinklight_toggle:1;
813        u16 hibernate_toggle:1;
814        u16 displayexp_toggle:1;
815        u16 display_state:1;
816        u16 brightness_toggle:1;
817        u16 volume_toggle:1;
818        u16 mute:1;
819
820        u8 brightness_level;
821        u8 volume_level;
822 };
823
824 static struct task_struct *tpacpi_hotkey_task;
825 static u32 hotkey_source_mask;          /* bit mask 0=ACPI,1=NVRAM */
826 static int hotkey_poll_freq = 10;       /* Hz */
827 static struct mutex hotkey_thread_mutex;
828 static struct mutex hotkey_thread_data_mutex;
829 static unsigned int hotkey_config_change;
830
831 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
832
833 #define hotkey_source_mask 0U
834
835 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
836
837 static int hotkey_orig_status;
838 static u32 hotkey_orig_mask;
839 static u32 hotkey_all_mask;
840 static u32 hotkey_reserved_mask;
841 static u32 hotkey_mask;
842
843 static u16 *hotkey_keycode_map;
844
845 static struct attribute_set *hotkey_dev_attributes;
846
847 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
848 #define HOTKEY_CONFIG_CRITICAL_START \
849         mutex_lock(&hotkey_thread_data_mutex); \
850         hotkey_config_change++;
851 #define HOTKEY_CONFIG_CRITICAL_END \
852         mutex_unlock(&hotkey_thread_data_mutex);
853 #else
854 #define HOTKEY_CONFIG_CRITICAL_START
855 #define HOTKEY_CONFIG_CRITICAL_END
856 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
857
858 static int hotkey_get_wlsw(int *status)
859 {
860         if (!acpi_evalf(hkey_handle, status, "WLSW", "d"))
861                 return -EIO;
862         return 0;
863 }
864
865 /*
866  * Call with hotkey_mutex held
867  */
868 static int hotkey_mask_get(void)
869 {
870         u32 m = 0;
871
872         if (tp_features.hotkey_mask) {
873                 if (!acpi_evalf(hkey_handle, &m, "DHKN", "d"))
874                         return -EIO;
875         }
876         hotkey_mask = m | (hotkey_source_mask & hotkey_mask);
877
878         return 0;
879 }
880
881 /*
882  * Call with hotkey_mutex held
883  */
884 static int hotkey_mask_set(u32 mask)
885 {
886         int i;
887         int rc = 0;
888
889         if (tp_features.hotkey_mask) {
890                 HOTKEY_CONFIG_CRITICAL_START
891                 for (i = 0; i < 32; i++) {
892                         u32 m = 1 << i;
893                         /* enable in firmware mask only keys not in NVRAM
894                          * mode, but enable the key in the cached hotkey_mask
895                          * regardless of mode, or the key will end up
896                          * disabled by hotkey_mask_get() */
897                         if (!acpi_evalf(hkey_handle,
898                                         NULL, "MHKM", "vdd", i + 1,
899                                         !!((mask & ~hotkey_source_mask) & m))) {
900                                 rc = -EIO;
901                                 break;
902                         } else {
903                                 hotkey_mask = (hotkey_mask & ~m) | (mask & m);
904                         }
905                 }
906                 HOTKEY_CONFIG_CRITICAL_END
907
908                 /* hotkey_mask_get must be called unconditionally below */
909                 if (!hotkey_mask_get() && !rc &&
910                     (hotkey_mask & ~hotkey_source_mask) !=
911                      (mask & ~hotkey_source_mask)) {
912                         printk(IBM_NOTICE
913                                "requested hot key mask 0x%08x, but "
914                                "firmware forced it to 0x%08x\n",
915                                mask, hotkey_mask);
916                 }
917         } else {
918 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
919                 HOTKEY_CONFIG_CRITICAL_START
920                 hotkey_mask = mask & hotkey_source_mask;
921                 HOTKEY_CONFIG_CRITICAL_END
922                 hotkey_mask_get();
923                 if (hotkey_mask != mask) {
924                         printk(IBM_NOTICE
925                                "requested hot key mask 0x%08x, "
926                                "forced to 0x%08x (NVRAM poll mask is "
927                                "0x%08x): no firmware mask support\n",
928                                mask, hotkey_mask, hotkey_source_mask);
929                 }
930 #else
931                 hotkey_mask_get();
932                 rc = -ENXIO;
933 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
934         }
935
936         return rc;
937 }
938
939 static int hotkey_status_get(int *status)
940 {
941         if (!acpi_evalf(hkey_handle, status, "DHKC", "d"))
942                 return -EIO;
943
944         return 0;
945 }
946
947 static int hotkey_status_set(int status)
948 {
949         if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", status))
950                 return -EIO;
951
952         return 0;
953 }
954
955 static void tpacpi_input_send_radiosw(void)
956 {
957         int wlsw;
958
959         mutex_lock(&tpacpi_inputdev_send_mutex);
960
961         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&wlsw)) {
962                 input_report_switch(tpacpi_inputdev,
963                                     SW_RADIO, !!wlsw);
964                 input_sync(tpacpi_inputdev);
965         }
966
967         mutex_unlock(&tpacpi_inputdev_send_mutex);
968 }
969
970 static void tpacpi_input_send_key(unsigned int scancode)
971 {
972         unsigned int keycode;
973
974         keycode = hotkey_keycode_map[scancode];
975
976         if (keycode != KEY_RESERVED) {
977                 mutex_lock(&tpacpi_inputdev_send_mutex);
978
979                 input_report_key(tpacpi_inputdev, keycode, 1);
980                 if (keycode == KEY_UNKNOWN)
981                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
982                                     scancode);
983                 input_sync(tpacpi_inputdev);
984
985                 input_report_key(tpacpi_inputdev, keycode, 0);
986                 if (keycode == KEY_UNKNOWN)
987                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
988                                     scancode);
989                 input_sync(tpacpi_inputdev);
990
991                 mutex_unlock(&tpacpi_inputdev_send_mutex);
992         }
993 }
994
995 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
996 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver;
997
998 static void tpacpi_hotkey_send_key(unsigned int scancode)
999 {
1000         tpacpi_input_send_key(scancode);
1001         if (hotkey_report_mode < 2) {
1002                 acpi_bus_generate_proc_event(ibm_hotkey_acpidriver.device,
1003                                                 0x80, 0x1001 + scancode);
1004         }
1005 }
1006
1007 static void hotkey_read_nvram(struct tp_nvram_state *n, u32 m)
1008 {
1009         u8 d;
1010
1011         if (m & TP_NVRAM_HKEY_GROUP_HK2) {
1012                 d = nvram_read_byte(TP_NVRAM_ADDR_HK2);
1013                 n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD);
1014                 n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM);
1015                 n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY);
1016                 n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE);
1017         }
1018         if (m & TP_ACPI_HKEY_THNKLGHT_MASK) {
1019                 d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT);
1020                 n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT);
1021         }
1022         if (m & TP_ACPI_HKEY_DISPXPAND_MASK) {
1023                 d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO);
1024                 n->displayexp_toggle =
1025                                 !!(d & TP_NVRAM_MASK_HKT_DISPEXPND);
1026         }
1027         if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) {
1028                 d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
1029                 n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
1030                                 >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
1031                 n->brightness_toggle =
1032                                 !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS);
1033         }
1034         if (m & TP_NVRAM_HKEY_GROUP_VOLUME) {
1035                 d = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
1036                 n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME)
1037                                 >> TP_NVRAM_POS_LEVEL_VOLUME;
1038                 n->mute = !!(d & TP_NVRAM_MASK_MUTE);
1039                 n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME);
1040         }
1041 }
1042
1043 #define TPACPI_COMPARE_KEY(__scancode, __member) \
1044         do { if ((mask & (1 << __scancode)) && oldn->__member != newn->__member) \
1045                 tpacpi_hotkey_send_key(__scancode); } while (0)
1046
1047 #define TPACPI_MAY_SEND_KEY(__scancode) \
1048         do { if (mask & (1 << __scancode)) \
1049                 tpacpi_hotkey_send_key(__scancode); } while (0)
1050
1051 static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn,
1052                                            struct tp_nvram_state *newn,
1053                                            u32 mask)
1054 {
1055         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
1056         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
1057         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
1058         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
1059
1060         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
1061
1062         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
1063
1064         /* handle volume */
1065         if (oldn->volume_toggle != newn->volume_toggle) {
1066                 if (oldn->mute != newn->mute) {
1067                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
1068                 }
1069                 if (oldn->volume_level > newn->volume_level) {
1070                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
1071                 } else if (oldn->volume_level < newn->volume_level) {
1072                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
1073                 } else if (oldn->mute == newn->mute) {
1074                         /* repeated key presses that didn't change state */
1075                         if (newn->mute) {
1076                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
1077                         } else if (newn->volume_level != 0) {
1078                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
1079                         } else {
1080                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
1081                         }
1082                 }
1083         }
1084
1085         /* handle brightness */
1086         if (oldn->brightness_toggle != newn->brightness_toggle) {
1087                 if (oldn->brightness_level < newn->brightness_level) {
1088                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
1089                 } else if (oldn->brightness_level > newn->brightness_level) {
1090                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
1091                 } else {
1092                         /* repeated key presses that didn't change state */
1093                         if (newn->brightness_level != 0) {
1094                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
1095                         } else {
1096                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
1097                         }
1098                 }
1099         }
1100 }
1101
1102 #undef TPACPI_COMPARE_KEY
1103 #undef TPACPI_MAY_SEND_KEY
1104
1105 static int hotkey_kthread(void *data)
1106 {
1107         struct tp_nvram_state s[2];
1108         u32 mask;
1109         unsigned int si, so;
1110         unsigned long t;
1111         unsigned int change_detector, must_reset;
1112
1113         mutex_lock(&hotkey_thread_mutex);
1114
1115         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
1116                 goto exit;
1117
1118         set_freezable();
1119
1120         so = 0;
1121         si = 1;
1122         t = 0;
1123
1124         /* Initial state for compares */
1125         mutex_lock(&hotkey_thread_data_mutex);
1126         change_detector = hotkey_config_change;
1127         mask = hotkey_source_mask & hotkey_mask;
1128         mutex_unlock(&hotkey_thread_data_mutex);
1129         hotkey_read_nvram(&s[so], mask);
1130
1131         while (!kthread_should_stop() && hotkey_poll_freq) {
1132                 if (t == 0)
1133                         t = 1000/hotkey_poll_freq;
1134                 t = msleep_interruptible(t);
1135                 if (unlikely(kthread_should_stop()))
1136                         break;
1137                 must_reset = try_to_freeze();
1138                 if (t > 0 && !must_reset)
1139                         continue;
1140
1141                 mutex_lock(&hotkey_thread_data_mutex);
1142                 if (must_reset || hotkey_config_change != change_detector) {
1143                         /* forget old state on thaw or config change */
1144                         si = so;
1145                         t = 0;
1146                         change_detector = hotkey_config_change;
1147                 }
1148                 mask = hotkey_source_mask & hotkey_mask;
1149                 mutex_unlock(&hotkey_thread_data_mutex);
1150
1151                 if (likely(mask)) {
1152                         hotkey_read_nvram(&s[si], mask);
1153                         if (likely(si != so)) {
1154                                 hotkey_compare_and_issue_event(&s[so], &s[si],
1155                                                                mask);
1156                         }
1157                 }
1158
1159                 so = si;
1160                 si ^= 1;
1161         }
1162
1163 exit:
1164         mutex_unlock(&hotkey_thread_mutex);
1165         return 0;
1166 }
1167
1168 static void hotkey_poll_stop_sync(void)
1169 {
1170         if (tpacpi_hotkey_task) {
1171                 if (frozen(tpacpi_hotkey_task) ||
1172                     freezing(tpacpi_hotkey_task))
1173                         thaw_process(tpacpi_hotkey_task);
1174
1175                 kthread_stop(tpacpi_hotkey_task);
1176                 tpacpi_hotkey_task = NULL;
1177                 mutex_lock(&hotkey_thread_mutex);
1178                 /* at this point, the thread did exit */
1179                 mutex_unlock(&hotkey_thread_mutex);
1180         }
1181 }
1182
1183 /* call with hotkey_mutex held */
1184 static void hotkey_poll_setup(int may_warn)
1185 {
1186         if ((hotkey_source_mask & hotkey_mask) != 0 &&
1187             hotkey_poll_freq > 0 &&
1188             (tpacpi_inputdev->users > 0 || hotkey_report_mode < 2)) {
1189                 if (!tpacpi_hotkey_task) {
1190                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
1191                                                NULL, IBM_FILE "d");
1192                         if (IS_ERR(tpacpi_hotkey_task)) {
1193                                 tpacpi_hotkey_task = NULL;
1194                                 printk(IBM_ERR "could not create kernel thread "
1195                                        "for hotkey polling\n");
1196                         }
1197                 }
1198         } else {
1199                 hotkey_poll_stop_sync();
1200                 if (may_warn &&
1201                     hotkey_source_mask != 0 && hotkey_poll_freq == 0) {
1202                         printk(IBM_NOTICE "hot keys 0x%08x require polling, "
1203                                 "which is currently disabled\n",
1204                                 hotkey_source_mask);
1205                 }
1206         }
1207 }
1208
1209 static void hotkey_poll_setup_safe(int may_warn)
1210 {
1211         mutex_lock(&hotkey_mutex);
1212         hotkey_poll_setup(may_warn);
1213         mutex_unlock(&hotkey_mutex);
1214 }
1215
1216 static int hotkey_inputdev_open(struct input_dev *dev)
1217 {
1218         switch (tpacpi_lifecycle) {
1219         case TPACPI_LIFE_INIT:
1220                 /*
1221                  * hotkey_init will call hotkey_poll_setup_safe
1222                  * at the appropriate moment
1223                  */
1224                 return 0;
1225         case TPACPI_LIFE_EXITING:
1226                 return -EBUSY;
1227         case TPACPI_LIFE_RUNNING:
1228                 hotkey_poll_setup_safe(0);
1229                 return 0;
1230         }
1231
1232         /* Should only happen if tpacpi_lifecycle is corrupt */
1233         BUG();
1234         return -EBUSY;
1235 }
1236
1237 static void hotkey_inputdev_close(struct input_dev *dev)
1238 {
1239         /* disable hotkey polling when possible */
1240         if (tpacpi_lifecycle == TPACPI_LIFE_RUNNING)
1241                 hotkey_poll_setup_safe(0);
1242 }
1243 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1244
1245 /* sysfs hotkey enable ------------------------------------------------- */
1246 static ssize_t hotkey_enable_show(struct device *dev,
1247                            struct device_attribute *attr,
1248                            char *buf)
1249 {
1250         int res, status;
1251
1252         res = hotkey_status_get(&status);
1253         if (res)
1254                 return res;
1255
1256         return snprintf(buf, PAGE_SIZE, "%d\n", status);
1257 }
1258
1259 static ssize_t hotkey_enable_store(struct device *dev,
1260                             struct device_attribute *attr,
1261                             const char *buf, size_t count)
1262 {
1263         unsigned long t;
1264         int res;
1265
1266         if (parse_strtoul(buf, 1, &t))
1267                 return -EINVAL;
1268
1269         res = hotkey_status_set(t);
1270
1271         return (res) ? res : count;
1272 }
1273
1274 static struct device_attribute dev_attr_hotkey_enable =
1275         __ATTR(hotkey_enable, S_IWUSR | S_IRUGO,
1276                 hotkey_enable_show, hotkey_enable_store);
1277
1278 /* sysfs hotkey mask --------------------------------------------------- */
1279 static ssize_t hotkey_mask_show(struct device *dev,
1280                            struct device_attribute *attr,
1281                            char *buf)
1282 {
1283         int res;
1284
1285         if (mutex_lock_interruptible(&hotkey_mutex))
1286                 return -ERESTARTSYS;
1287         res = hotkey_mask_get();
1288         mutex_unlock(&hotkey_mutex);
1289
1290         return (res)?
1291                 res : snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_mask);
1292 }
1293
1294 static ssize_t hotkey_mask_store(struct device *dev,
1295                             struct device_attribute *attr,
1296                             const char *buf, size_t count)
1297 {
1298         unsigned long t;
1299         int res;
1300
1301         if (parse_strtoul(buf, 0xffffffffUL, &t))
1302                 return -EINVAL;
1303
1304         if (mutex_lock_interruptible(&hotkey_mutex))
1305                 return -ERESTARTSYS;
1306
1307         res = hotkey_mask_set(t);
1308
1309 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1310         hotkey_poll_setup(1);
1311 #endif
1312
1313         mutex_unlock(&hotkey_mutex);
1314
1315         return (res) ? res : count;
1316 }
1317
1318 static struct device_attribute dev_attr_hotkey_mask =
1319         __ATTR(hotkey_mask, S_IWUSR | S_IRUGO,
1320                 hotkey_mask_show, hotkey_mask_store);
1321
1322 /* sysfs hotkey bios_enabled ------------------------------------------- */
1323 static ssize_t hotkey_bios_enabled_show(struct device *dev,
1324                            struct device_attribute *attr,
1325                            char *buf)
1326 {
1327         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_orig_status);
1328 }
1329
1330 static struct device_attribute dev_attr_hotkey_bios_enabled =
1331         __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL);
1332
1333 /* sysfs hotkey bios_mask ---------------------------------------------- */
1334 static ssize_t hotkey_bios_mask_show(struct device *dev,
1335                            struct device_attribute *attr,
1336                            char *buf)
1337 {
1338         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
1339 }
1340
1341 static struct device_attribute dev_attr_hotkey_bios_mask =
1342         __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL);
1343
1344 /* sysfs hotkey all_mask ----------------------------------------------- */
1345 static ssize_t hotkey_all_mask_show(struct device *dev,
1346                            struct device_attribute *attr,
1347                            char *buf)
1348 {
1349         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
1350                                 hotkey_all_mask | hotkey_source_mask);
1351 }
1352
1353 static struct device_attribute dev_attr_hotkey_all_mask =
1354         __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL);
1355
1356 /* sysfs hotkey recommended_mask --------------------------------------- */
1357 static ssize_t hotkey_recommended_mask_show(struct device *dev,
1358                                             struct device_attribute *attr,
1359                                             char *buf)
1360 {
1361         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
1362                         (hotkey_all_mask | hotkey_source_mask)
1363                         & ~hotkey_reserved_mask);
1364 }
1365
1366 static struct device_attribute dev_attr_hotkey_recommended_mask =
1367         __ATTR(hotkey_recommended_mask, S_IRUGO,
1368                 hotkey_recommended_mask_show, NULL);
1369
1370 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1371
1372 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
1373 static ssize_t hotkey_source_mask_show(struct device *dev,
1374                            struct device_attribute *attr,
1375                            char *buf)
1376 {
1377         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
1378 }
1379
1380 static ssize_t hotkey_source_mask_store(struct device *dev,
1381                             struct device_attribute *attr,
1382                             const char *buf, size_t count)
1383 {
1384         unsigned long t;
1385
1386         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
1387                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
1388                 return -EINVAL;
1389
1390         if (mutex_lock_interruptible(&hotkey_mutex))
1391                 return -ERESTARTSYS;
1392
1393         HOTKEY_CONFIG_CRITICAL_START
1394         hotkey_source_mask = t;
1395         HOTKEY_CONFIG_CRITICAL_END
1396
1397         hotkey_poll_setup(1);
1398
1399         mutex_unlock(&hotkey_mutex);
1400
1401         return count;
1402 }
1403
1404 static struct device_attribute dev_attr_hotkey_source_mask =
1405         __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO,
1406                 hotkey_source_mask_show, hotkey_source_mask_store);
1407
1408 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
1409 static ssize_t hotkey_poll_freq_show(struct device *dev,
1410                            struct device_attribute *attr,
1411                            char *buf)
1412 {
1413         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
1414 }
1415
1416 static ssize_t hotkey_poll_freq_store(struct device *dev,
1417                             struct device_attribute *attr,
1418                             const char *buf, size_t count)
1419 {
1420         unsigned long t;
1421
1422         if (parse_strtoul(buf, 25, &t))
1423                 return -EINVAL;
1424
1425         if (mutex_lock_interruptible(&hotkey_mutex))
1426                 return -ERESTARTSYS;
1427
1428         hotkey_poll_freq = t;
1429
1430         hotkey_poll_setup(1);
1431         mutex_unlock(&hotkey_mutex);
1432
1433         return count;
1434 }
1435
1436 static struct device_attribute dev_attr_hotkey_poll_freq =
1437         __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO,
1438                 hotkey_poll_freq_show, hotkey_poll_freq_store);
1439
1440 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1441
1442 /* sysfs hotkey radio_sw ----------------------------------------------- */
1443 static ssize_t hotkey_radio_sw_show(struct device *dev,
1444                            struct device_attribute *attr,
1445                            char *buf)
1446 {
1447         int res, s;
1448         res = hotkey_get_wlsw(&s);
1449         if (res < 0)
1450                 return res;
1451
1452         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
1453 }
1454
1455 static struct device_attribute dev_attr_hotkey_radio_sw =
1456         __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL);
1457
1458 /* sysfs hotkey report_mode -------------------------------------------- */
1459 static ssize_t hotkey_report_mode_show(struct device *dev,
1460                            struct device_attribute *attr,
1461                            char *buf)
1462 {
1463         return snprintf(buf, PAGE_SIZE, "%d\n",
1464                 (hotkey_report_mode != 0) ? hotkey_report_mode : 1);
1465 }
1466
1467 static struct device_attribute dev_attr_hotkey_report_mode =
1468         __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL);
1469
1470 /* --------------------------------------------------------------------- */
1471
1472 static struct attribute *hotkey_attributes[] __initdata = {
1473         &dev_attr_hotkey_enable.attr,
1474         &dev_attr_hotkey_bios_enabled.attr,
1475         &dev_attr_hotkey_report_mode.attr,
1476 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1477         &dev_attr_hotkey_mask.attr,
1478         &dev_attr_hotkey_all_mask.attr,
1479         &dev_attr_hotkey_recommended_mask.attr,
1480         &dev_attr_hotkey_source_mask.attr,
1481         &dev_attr_hotkey_poll_freq.attr,
1482 #endif
1483 };
1484
1485 static struct attribute *hotkey_mask_attributes[] __initdata = {
1486         &dev_attr_hotkey_bios_mask.attr,
1487 #ifndef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1488         &dev_attr_hotkey_mask.attr,
1489         &dev_attr_hotkey_all_mask.attr,
1490         &dev_attr_hotkey_recommended_mask.attr,
1491 #endif
1492 };
1493
1494 static int __init hotkey_init(struct ibm_init_struct *iibm)
1495 {
1496         /* Requirements for changing the default keymaps:
1497          *
1498          * 1. Many of the keys are mapped to KEY_RESERVED for very
1499          *    good reasons.  Do not change them unless you have deep
1500          *    knowledge on the IBM and Lenovo ThinkPad firmware for
1501          *    the various ThinkPad models.  The driver behaves
1502          *    differently for KEY_RESERVED: such keys have their
1503          *    hot key mask *unset* in mask_recommended, and also
1504          *    in the initial hot key mask programmed into the
1505          *    firmware at driver load time, which means the firm-
1506          *    ware may react very differently if you change them to
1507          *    something else;
1508          *
1509          * 2. You must be subscribed to the linux-thinkpad and
1510          *    ibm-acpi-devel mailing lists, and you should read the
1511          *    list archives since 2007 if you want to change the
1512          *    keymaps.  This requirement exists so that you will
1513          *    know the past history of problems with the thinkpad-
1514          *    acpi driver keymaps, and also that you will be
1515          *    listening to any bug reports;
1516          *
1517          * 3. Do not send thinkpad-acpi specific patches directly to
1518          *    for merging, *ever*.  Send them to the linux-acpi
1519          *    mailinglist for comments.  Merging is to be done only
1520          *    through acpi-test and the ACPI maintainer.
1521          *
1522          * If the above is too much to ask, don't change the keymap.
1523          * Ask the thinkpad-acpi maintainer to do it, instead.
1524          */
1525         static u16 ibm_keycode_map[] __initdata = {
1526                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
1527                 KEY_FN_F1,      KEY_FN_F2,      KEY_COFFEE,     KEY_SLEEP,
1528                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
1529                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
1530
1531                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
1532                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
1533                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
1534                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
1535
1536                 /* brightness: firmware always reacts to them, unless
1537                  * X.org did some tricks in the radeon BIOS scratch
1538                  * registers of *some* models */
1539                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
1540                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
1541
1542                 /* Thinklight: firmware always react to it */
1543                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
1544
1545                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
1546                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
1547
1548                 /* Volume: firmware always react to it and reprograms
1549                  * the built-in *extra* mixer.  Never map it to control
1550                  * another mixer by default. */
1551                 KEY_RESERVED,   /* 0x14: VOLUME UP */
1552                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
1553                 KEY_RESERVED,   /* 0x16: MUTE */
1554
1555                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
1556
1557                 /* (assignments unknown, please report if found) */
1558                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
1559                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
1560         };
1561         static u16 lenovo_keycode_map[] __initdata = {
1562                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
1563                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
1564                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
1565                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
1566
1567                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
1568                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
1569                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
1570                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
1571
1572                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
1573                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
1574
1575                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
1576
1577                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
1578                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
1579
1580                 /* Volume: z60/z61, T60 (BIOS version?): firmware always
1581                  * react to it and reprograms the built-in *extra* mixer.
1582                  * Never map it to control another mixer by default.
1583                  *
1584                  * T60?, T61, R60?, R61: firmware and EC tries to send
1585                  * these over the regular keyboard, so these are no-ops,
1586                  * but there are still weird bugs re. MUTE, so do not
1587                  * change unless you get test reports from all Lenovo
1588                  * models.  May cause the BIOS to interfere with the
1589                  * HDA mixer.
1590                  */
1591                 KEY_RESERVED,   /* 0x14: VOLUME UP */
1592                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
1593                 KEY_RESERVED,   /* 0x16: MUTE */
1594
1595                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
1596
1597                 /* (assignments unknown, please report if found) */
1598                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
1599                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
1600         };
1601
1602 #define TPACPI_HOTKEY_MAP_LEN           ARRAY_SIZE(ibm_keycode_map)
1603 #define TPACPI_HOTKEY_MAP_SIZE          sizeof(ibm_keycode_map)
1604 #define TPACPI_HOTKEY_MAP_TYPESIZE      sizeof(ibm_keycode_map[0])
1605
1606         int res, i;
1607         int status;
1608         int hkeyv;
1609
1610         vdbg_printk(TPACPI_DBG_INIT, "initializing hotkey subdriver\n");
1611
1612         BUG_ON(!tpacpi_inputdev);
1613         BUG_ON(tpacpi_inputdev->open != NULL ||
1614                tpacpi_inputdev->close != NULL);
1615
1616         IBM_ACPIHANDLE_INIT(hkey);
1617         mutex_init(&hotkey_mutex);
1618
1619 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1620         mutex_init(&hotkey_thread_mutex);
1621         mutex_init(&hotkey_thread_data_mutex);
1622 #endif
1623
1624         /* hotkey not supported on 570 */
1625         tp_features.hotkey = hkey_handle != NULL;
1626
1627         vdbg_printk(TPACPI_DBG_INIT, "hotkeys are %s\n",
1628                 str_supported(tp_features.hotkey));
1629
1630         if (tp_features.hotkey) {
1631                 hotkey_dev_attributes = create_attr_set(10, NULL);
1632                 if (!hotkey_dev_attributes)
1633                         return -ENOMEM;
1634                 res = add_many_to_attr_set(hotkey_dev_attributes,
1635                                 hotkey_attributes,
1636                                 ARRAY_SIZE(hotkey_attributes));
1637                 if (res)
1638                         return res;
1639
1640                 /* mask not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
1641                    A30, R30, R31, T20-22, X20-21, X22-24.  Detected by checking
1642                    for HKEY interface version 0x100 */
1643                 if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) {
1644                         if ((hkeyv >> 8) != 1) {
1645                                 printk(IBM_ERR "unknown version of the "
1646                                        "HKEY interface: 0x%x\n", hkeyv);
1647                                 printk(IBM_ERR "please report this to %s\n",
1648                                        IBM_MAIL);
1649                         } else {
1650                                 /*
1651                                  * MHKV 0x100 in A31, R40, R40e,
1652                                  * T4x, X31, and later
1653                                  */
1654                                 tp_features.hotkey_mask = 1;
1655                         }
1656                 }
1657
1658                 vdbg_printk(TPACPI_DBG_INIT, "hotkey masks are %s\n",
1659                         str_supported(tp_features.hotkey_mask));
1660
1661                 if (tp_features.hotkey_mask) {
1662                         if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
1663                                         "MHKA", "qd")) {
1664                                 printk(IBM_ERR
1665                                        "missing MHKA handler, "
1666                                        "please report this to %s\n",
1667                                        IBM_MAIL);
1668                                 hotkey_all_mask = 0x080cU; /* FN+F12, FN+F4, FN+F3 */
1669                         }
1670                 }
1671
1672                 /* hotkey_source_mask *must* be zero for
1673                  * the first hotkey_mask_get */
1674                 res = hotkey_status_get(&hotkey_orig_status);
1675                 if (!res && tp_features.hotkey_mask) {
1676                         res = hotkey_mask_get();
1677                         hotkey_orig_mask = hotkey_mask;
1678                         if (!res) {
1679                                 res = add_many_to_attr_set(
1680                                         hotkey_dev_attributes,
1681                                         hotkey_mask_attributes,
1682                                         ARRAY_SIZE(hotkey_mask_attributes));
1683                         }
1684                 }
1685
1686 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1687                 if (tp_features.hotkey_mask) {
1688                         hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK
1689                                                 & ~hotkey_all_mask;
1690                 } else {
1691                         hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK;
1692                 }
1693
1694                 vdbg_printk(TPACPI_DBG_INIT,
1695                             "hotkey source mask 0x%08x, polling freq %d\n",
1696                             hotkey_source_mask, hotkey_poll_freq);
1697 #endif
1698
1699                 /* Not all thinkpads have a hardware radio switch */
1700                 if (!res && acpi_evalf(hkey_handle, &status, "WLSW", "qd")) {
1701                         tp_features.hotkey_wlsw = 1;
1702                         printk(IBM_INFO
1703                                 "radio switch found; radios are %s\n",
1704                                 enabled(status, 0));
1705                         res = add_to_attr_set(hotkey_dev_attributes,
1706                                         &dev_attr_hotkey_radio_sw.attr);
1707                 }
1708
1709                 if (!res)
1710                         res = register_attr_set_with_sysfs(
1711                                         hotkey_dev_attributes,
1712                                         &tpacpi_pdev->dev.kobj);
1713                 if (res)
1714                         return res;
1715
1716                 /* Set up key map */
1717
1718                 hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE,
1719                                                 GFP_KERNEL);
1720                 if (!hotkey_keycode_map) {
1721                         printk(IBM_ERR "failed to allocate memory for key map\n");
1722                         return -ENOMEM;
1723                 }
1724
1725                 if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO) {
1726                         dbg_printk(TPACPI_DBG_INIT,
1727                                    "using Lenovo default hot key map\n");
1728                         memcpy(hotkey_keycode_map, &lenovo_keycode_map,
1729                                 TPACPI_HOTKEY_MAP_SIZE);
1730                 } else {
1731                         dbg_printk(TPACPI_DBG_INIT,
1732                                    "using IBM default hot key map\n");
1733                         memcpy(hotkey_keycode_map, &ibm_keycode_map,
1734                                 TPACPI_HOTKEY_MAP_SIZE);
1735                 }
1736
1737                 set_bit(EV_KEY, tpacpi_inputdev->evbit);
1738                 set_bit(EV_MSC, tpacpi_inputdev->evbit);
1739                 set_bit(MSC_SCAN, tpacpi_inputdev->mscbit);
1740                 tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE;
1741                 tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN;
1742                 tpacpi_inputdev->keycode = hotkey_keycode_map;
1743                 for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) {
1744                         if (hotkey_keycode_map[i] != KEY_RESERVED) {
1745                                 set_bit(hotkey_keycode_map[i],
1746                                         tpacpi_inputdev->keybit);
1747                         } else {
1748                                 if (i < sizeof(hotkey_reserved_mask)*8)
1749                                         hotkey_reserved_mask |= 1 << i;
1750                         }
1751                 }
1752
1753                 if (tp_features.hotkey_wlsw) {
1754                         set_bit(EV_SW, tpacpi_inputdev->evbit);
1755                         set_bit(SW_RADIO, tpacpi_inputdev->swbit);
1756                 }
1757
1758                 dbg_printk(TPACPI_DBG_INIT,
1759                                 "enabling hot key handling\n");
1760                 res = hotkey_status_set(1);
1761                 if (res)
1762                         return res;
1763                 res = hotkey_mask_set(((hotkey_all_mask | hotkey_source_mask)
1764                                         & ~hotkey_reserved_mask)
1765                                         | hotkey_orig_mask);
1766                 if (res < 0 && res != -ENXIO)
1767                         return res;
1768
1769                 dbg_printk(TPACPI_DBG_INIT,
1770                                 "legacy hot key reporting over procfs %s\n",
1771                                 (hotkey_report_mode < 2) ?
1772                                         "enabled" : "disabled");
1773
1774 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1775                 tpacpi_inputdev->open = &hotkey_inputdev_open;
1776                 tpacpi_inputdev->close = &hotkey_inputdev_close;
1777
1778                 hotkey_poll_setup_safe(1);
1779 #endif
1780         }
1781
1782         return (tp_features.hotkey)? 0 : 1;
1783 }
1784
1785 static void hotkey_exit(void)
1786 {
1787 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1788         hotkey_poll_stop_sync();
1789 #endif
1790
1791         if (tp_features.hotkey) {
1792                 dbg_printk(TPACPI_DBG_EXIT, "restoring original hot key mask\n");
1793                 /* no short-circuit boolean operator below! */
1794                 if ((hotkey_mask_set(hotkey_orig_mask) |
1795                      hotkey_status_set(hotkey_orig_status)) != 0)
1796                         printk(IBM_ERR "failed to restore hot key mask to BIOS defaults\n");
1797         }
1798
1799         if (hotkey_dev_attributes) {
1800                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
1801                 hotkey_dev_attributes = NULL;
1802         }
1803 }
1804
1805 static void hotkey_notify(struct ibm_struct *ibm, u32 event)
1806 {
1807         u32 hkey;
1808         unsigned int scancode;
1809         int send_acpi_ev;
1810         int ignore_acpi_ev;
1811
1812         if (event != 0x80) {
1813                 printk(IBM_ERR "unknown HKEY notification event %d\n", event);
1814                 /* forward it to userspace, maybe it knows how to handle it */
1815                 acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
1816                                                 ibm->acpi->device->dev.bus_id,
1817                                                 event, 0);
1818                 return;
1819         }
1820
1821         while (1) {
1822                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
1823                         printk(IBM_ERR "failed to retrieve HKEY event\n");
1824                         return;
1825                 }
1826
1827                 if (hkey == 0) {
1828                         /* queue empty */
1829                         return;
1830                 }
1831
1832                 send_acpi_ev = 0;
1833                 ignore_acpi_ev = 0;
1834
1835                 switch (hkey >> 12) {
1836                 case 1:
1837                         /* 0x1000-0x1FFF: key presses */
1838                         scancode = hkey & 0xfff;
1839                         if (scancode > 0 && scancode < 0x21) {
1840                                 scancode--;
1841                                 if (!(hotkey_source_mask & (1 << scancode))) {
1842                                         tpacpi_input_send_key(scancode);
1843                                 } else {
1844                                         ignore_acpi_ev = 1;
1845                                 }
1846                         } else {
1847                                 printk(IBM_ERR
1848                                        "hotkey 0x%04x out of range for keyboard map\n",
1849                                        hkey);
1850                                 send_acpi_ev = 1;
1851                         }
1852                         break;
1853                 case 5:
1854                         /* 0x5000-0x5FFF: LID */
1855                         /* we don't handle it through this path, just
1856                          * eat up known LID events */
1857                         if (hkey != 0x5001 && hkey != 0x5002) {
1858                                 printk(IBM_ERR
1859                                        "unknown LID-related HKEY event: 0x%04x\n",
1860                                        hkey);
1861                                 send_acpi_ev = 1;
1862                         } else {
1863                                 ignore_acpi_ev = 1;
1864                         }
1865                         break;
1866                 case 7:
1867                         /* 0x7000-0x7FFF: misc */
1868                         if (tp_features.hotkey_wlsw && hkey == 0x7000) {
1869                                 tpacpi_input_send_radiosw();
1870                                 break;
1871                         }
1872                         /* fallthrough to default */
1873                 default:
1874                         /* case 2: dock-related */
1875                         /*      0x2305 - T43 waking up due to bay lever eject while aslept */
1876                         /* case 3: ultra-bay related. maybe bay in dock? */
1877                         /*      0x3003 - T43 after wake up by bay lever eject (0x2305) */
1878                         printk(IBM_NOTICE "unhandled HKEY event 0x%04x\n", hkey);
1879                         send_acpi_ev = 1;
1880                 }
1881
1882                 /* Legacy events */
1883                 if (!ignore_acpi_ev && (send_acpi_ev || hotkey_report_mode < 2)) {
1884                         acpi_bus_generate_proc_event(ibm->acpi->device, event, hkey);
1885                 }
1886
1887                 /* netlink events */
1888                 if (!ignore_acpi_ev && send_acpi_ev) {
1889                         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
1890                                                         ibm->acpi->device->dev.bus_id,
1891                                                         event, hkey);
1892                 }
1893         }
1894 }
1895
1896 static void hotkey_resume(void)
1897 {
1898         if (hotkey_mask_get())
1899                 printk(IBM_ERR "error while trying to read hot key mask from firmware\n");
1900         tpacpi_input_send_radiosw();
1901 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1902         hotkey_poll_setup_safe(0);
1903 #endif
1904 }
1905
1906 /* procfs -------------------------------------------------------------- */
1907 static int hotkey_read(char *p)
1908 {
1909         int res, status;
1910         int len = 0;
1911
1912         if (!tp_features.hotkey) {
1913                 len += sprintf(p + len, "status:\t\tnot supported\n");
1914                 return len;
1915         }
1916
1917         if (mutex_lock_interruptible(&hotkey_mutex))
1918                 return -ERESTARTSYS;
1919         res = hotkey_status_get(&status);
1920         if (!res)
1921                 res = hotkey_mask_get();
1922         mutex_unlock(&hotkey_mutex);
1923         if (res)
1924                 return res;
1925
1926         len += sprintf(p + len, "status:\t\t%s\n", enabled(status, 0));
1927         if (tp_features.hotkey_mask) {
1928                 len += sprintf(p + len, "mask:\t\t0x%08x\n", hotkey_mask);
1929                 len += sprintf(p + len,
1930                                "commands:\tenable, disable, reset, <mask>\n");
1931         } else {
1932                 len += sprintf(p + len, "mask:\t\tnot supported\n");
1933                 len += sprintf(p + len, "commands:\tenable, disable, reset\n");
1934         }
1935
1936         return len;
1937 }
1938
1939 static int hotkey_write(char *buf)
1940 {
1941         int res, status;
1942         u32 mask;
1943         char *cmd;
1944
1945         if (!tp_features.hotkey)
1946                 return -ENODEV;
1947
1948         if (mutex_lock_interruptible(&hotkey_mutex))
1949                 return -ERESTARTSYS;
1950
1951         status = -1;
1952         mask = hotkey_mask;
1953
1954         res = 0;
1955         while ((cmd = next_cmd(&buf))) {
1956                 if (strlencmp(cmd, "enable") == 0) {
1957                         status = 1;
1958                 } else if (strlencmp(cmd, "disable") == 0) {
1959                         status = 0;
1960                 } else if (strlencmp(cmd, "reset") == 0) {
1961                         status = hotkey_orig_status;
1962                         mask = hotkey_orig_mask;
1963                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
1964                         /* mask set */
1965                 } else if (sscanf(cmd, "%x", &mask) == 1) {
1966                         /* mask set */
1967                 } else {
1968                         res = -EINVAL;
1969                         goto errexit;
1970                 }
1971         }
1972         if (status != -1)
1973                 res = hotkey_status_set(status);
1974
1975         if (!res && mask != hotkey_mask)
1976                 res = hotkey_mask_set(mask);
1977
1978 errexit:
1979         mutex_unlock(&hotkey_mutex);
1980         return res;
1981 }
1982
1983 static const struct acpi_device_id ibm_htk_device_ids[] = {
1984         {IBM_HKEY_HID, 0},
1985         {"", 0},
1986 };
1987
1988 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
1989         .hid = ibm_htk_device_ids,
1990         .notify = hotkey_notify,
1991         .handle = &hkey_handle,
1992         .type = ACPI_DEVICE_NOTIFY,
1993 };
1994
1995 static struct ibm_struct hotkey_driver_data = {
1996         .name = "hotkey",
1997         .read = hotkey_read,
1998         .write = hotkey_write,
1999         .exit = hotkey_exit,
2000         .resume = hotkey_resume,
2001         .acpi = &ibm_hotkey_acpidriver,
2002 };
2003
2004 /*************************************************************************
2005  * Bluetooth subdriver
2006  */
2007
2008 /* sysfs bluetooth enable ---------------------------------------------- */
2009 static ssize_t bluetooth_enable_show(struct device *dev,
2010                            struct device_attribute *attr,
2011                            char *buf)
2012 {
2013         int status;
2014
2015         status = bluetooth_get_radiosw();
2016         if (status < 0)
2017                 return status;
2018
2019         return snprintf(buf, PAGE_SIZE, "%d\n", status ? 1 : 0);
2020 }
2021
2022 static ssize_t bluetooth_enable_store(struct device *dev,
2023                             struct device_attribute *attr,
2024                             const char *buf, size_t count)
2025 {
2026         unsigned long t;
2027         int res;
2028
2029         if (parse_strtoul(buf, 1, &t))
2030                 return -EINVAL;
2031
2032         res = bluetooth_set_radiosw(t);
2033
2034         return (res) ? res : count;
2035 }
2036
2037 static struct device_attribute dev_attr_bluetooth_enable =
2038         __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO,
2039                 bluetooth_enable_show, bluetooth_enable_store);
2040
2041 /* --------------------------------------------------------------------- */
2042
2043 static struct attribute *bluetooth_attributes[] = {
2044         &dev_attr_bluetooth_enable.attr,
2045         NULL
2046 };
2047
2048 static const struct attribute_group bluetooth_attr_group = {
2049         .attrs = bluetooth_attributes,
2050 };
2051
2052 static int __init bluetooth_init(struct ibm_init_struct *iibm)
2053 {
2054         int res;
2055         int status = 0;
2056
2057         vdbg_printk(TPACPI_DBG_INIT, "initializing bluetooth subdriver\n");
2058
2059         IBM_ACPIHANDLE_INIT(hkey);
2060
2061         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
2062            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
2063         tp_features.bluetooth = hkey_handle &&
2064             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
2065
2066         vdbg_printk(TPACPI_DBG_INIT, "bluetooth is %s, status 0x%02x\n",
2067                 str_supported(tp_features.bluetooth),
2068                 status);
2069
2070         if (tp_features.bluetooth) {
2071                 if (!(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
2072                         /* no bluetooth hardware present in system */
2073                         tp_features.bluetooth = 0;
2074                         dbg_printk(TPACPI_DBG_INIT,
2075                                    "bluetooth hardware not installed\n");
2076                 } else {
2077                         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
2078                                         &bluetooth_attr_group);
2079                         if (res)
2080                                 return res;
2081                 }
2082         }
2083
2084         return (tp_features.bluetooth)? 0 : 1;
2085 }
2086
2087 static void bluetooth_exit(void)
2088 {
2089         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
2090                         &bluetooth_attr_group);
2091 }
2092
2093 static int bluetooth_get_radiosw(void)
2094 {
2095         int status;
2096
2097         if (!tp_features.bluetooth)
2098                 return -ENODEV;
2099
2100         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
2101                 return -EIO;
2102
2103         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0);
2104 }
2105
2106 static int bluetooth_set_radiosw(int radio_on)
2107 {
2108         int status;
2109
2110         if (!tp_features.bluetooth)
2111                 return -ENODEV;
2112
2113         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
2114                 return -EIO;
2115         if (radio_on)
2116                 status |= TP_ACPI_BLUETOOTH_RADIOSSW;
2117         else
2118                 status &= ~TP_ACPI_BLUETOOTH_RADIOSSW;
2119         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
2120                 return -EIO;
2121
2122         return 0;
2123 }
2124
2125 /* procfs -------------------------------------------------------------- */
2126 static int bluetooth_read(char *p)
2127 {
2128         int len = 0;
2129         int status = bluetooth_get_radiosw();
2130
2131         if (!tp_features.bluetooth)
2132                 len += sprintf(p + len, "status:\t\tnot supported\n");
2133         else {
2134                 len += sprintf(p + len, "status:\t\t%s\n",
2135                                 (status)? "enabled" : "disabled");
2136                 len += sprintf(p + len, "commands:\tenable, disable\n");
2137         }
2138
2139         return len;
2140 }
2141
2142 static int bluetooth_write(char *buf)
2143 {
2144         char *cmd;
2145
2146         if (!tp_features.bluetooth)
2147                 return -ENODEV;
2148
2149         while ((cmd = next_cmd(&buf))) {
2150                 if (strlencmp(cmd, "enable") == 0) {
2151                         bluetooth_set_radiosw(1);
2152                 } else if (strlencmp(cmd, "disable") == 0) {
2153                         bluetooth_set_radiosw(0);
2154                 } else
2155                         return -EINVAL;
2156         }
2157
2158         return 0;
2159 }
2160
2161 static struct ibm_struct bluetooth_driver_data = {
2162         .name = "bluetooth",
2163         .read = bluetooth_read,
2164         .write = bluetooth_write,
2165         .exit = bluetooth_exit,
2166 };
2167
2168 /*************************************************************************
2169  * Wan subdriver
2170  */
2171
2172 /* sysfs wan enable ---------------------------------------------------- */
2173 static ssize_t wan_enable_show(struct device *dev,
2174                            struct device_attribute *attr,
2175                            char *buf)
2176 {
2177         int status;
2178
2179         status = wan_get_radiosw();
2180         if (status < 0)
2181                 return status;
2182
2183         return snprintf(buf, PAGE_SIZE, "%d\n", status ? 1 : 0);
2184 }
2185
2186 static ssize_t wan_enable_store(struct device *dev,
2187                             struct device_attribute *attr,
2188                             const char *buf, size_t count)
2189 {
2190         unsigned long t;
2191         int res;
2192
2193         if (parse_strtoul(buf, 1, &t))
2194                 return -EINVAL;
2195
2196         res = wan_set_radiosw(t);
2197
2198         return (res) ? res : count;
2199 }
2200
2201 static struct device_attribute dev_attr_wan_enable =
2202         __ATTR(wwan_enable, S_IWUSR | S_IRUGO,
2203                 wan_enable_show, wan_enable_store);
2204
2205 /* --------------------------------------------------------------------- */
2206
2207 static struct attribute *wan_attributes[] = {
2208         &dev_attr_wan_enable.attr,
2209         NULL
2210 };
2211
2212 static const struct attribute_group wan_attr_group = {
2213         .attrs = wan_attributes,
2214 };
2215
2216 static int __init wan_init(struct ibm_init_struct *iibm)
2217 {
2218         int res;
2219         int status = 0;
2220
2221         vdbg_printk(TPACPI_DBG_INIT, "initializing wan subdriver\n");
2222
2223         IBM_ACPIHANDLE_INIT(hkey);
2224
2225         tp_features.wan = hkey_handle &&
2226             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
2227
2228         vdbg_printk(TPACPI_DBG_INIT, "wan is %s, status 0x%02x\n",
2229                 str_supported(tp_features.wan),
2230                 status);
2231
2232         if (tp_features.wan) {
2233                 if (!(status & TP_ACPI_WANCARD_HWPRESENT)) {
2234                         /* no wan hardware present in system */
2235                         tp_features.wan = 0;
2236                         dbg_printk(TPACPI_DBG_INIT,
2237                                    "wan hardware not installed\n");
2238                 } else {
2239                         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
2240                                         &wan_attr_group);
2241                         if (res)
2242                                 return res;
2243                 }
2244         }
2245
2246         return (tp_features.wan)? 0 : 1;
2247 }
2248
2249 static void wan_exit(void)
2250 {
2251         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
2252                 &wan_attr_group);
2253 }
2254
2255 static int wan_get_radiosw(void)
2256 {
2257         int status;
2258
2259         if (!tp_features.wan)
2260                 return -ENODEV;
2261
2262         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
2263                 return -EIO;
2264
2265         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0);
2266 }
2267
2268 static int wan_set_radiosw(int radio_on)
2269 {
2270         int status;
2271
2272         if (!tp_features.wan)
2273                 return -ENODEV;
2274
2275         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
2276                 return -EIO;
2277         if (radio_on)
2278                 status |= TP_ACPI_WANCARD_RADIOSSW;
2279         else
2280                 status &= ~TP_ACPI_WANCARD_RADIOSSW;
2281         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
2282                 return -EIO;
2283
2284         return 0;
2285 }
2286
2287 /* procfs -------------------------------------------------------------- */
2288 static int wan_read(char *p)
2289 {
2290         int len = 0;
2291         int status = wan_get_radiosw();
2292
2293         if (!tp_features.wan)
2294                 len += sprintf(p + len, "status:\t\tnot supported\n");
2295         else {
2296                 len += sprintf(p + len, "status:\t\t%s\n",
2297                                 (status)? "enabled" : "disabled");
2298                 len += sprintf(p + len, "commands:\tenable, disable\n");
2299         }
2300
2301         return len;
2302 }
2303
2304 static int wan_write(char *buf)
2305 {
2306         char *cmd;
2307
2308         if (!tp_features.wan)
2309                 return -ENODEV;
2310
2311         while ((cmd = next_cmd(&buf))) {
2312                 if (strlencmp(cmd, "enable") == 0) {
2313                         wan_set_radiosw(1);
2314                 } else if (strlencmp(cmd, "disable") == 0) {
2315                         wan_set_radiosw(0);
2316                 } else
2317                         return -EINVAL;
2318         }
2319
2320         return 0;
2321 }
2322
2323 static struct ibm_struct wan_driver_data = {
2324         .name = "wan",
2325         .read = wan_read,
2326         .write = wan_write,
2327         .exit = wan_exit,
2328         .flags.experimental = 1,
2329 };
2330
2331 /*************************************************************************
2332  * Video subdriver
2333  */
2334
2335 static enum video_access_mode video_supported;
2336 static int video_orig_autosw;
2337
2338 IBM_HANDLE(vid, root, "\\_SB.PCI.AGP.VGA",      /* 570 */
2339            "\\_SB.PCI0.AGP0.VID0",      /* 600e/x, 770x */
2340            "\\_SB.PCI0.VID0",   /* 770e */
2341            "\\_SB.PCI0.VID",    /* A21e, G4x, R50e, X30, X40 */
2342            "\\_SB.PCI0.AGP.VID",        /* all others */
2343            );                           /* R30, R31 */
2344
2345 IBM_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");  /* G41 */
2346
2347 static int __init video_init(struct ibm_init_struct *iibm)
2348 {
2349         int ivga;
2350
2351         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
2352
2353         IBM_ACPIHANDLE_INIT(vid);
2354         IBM_ACPIHANDLE_INIT(vid2);
2355
2356         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
2357                 /* G41, assume IVGA doesn't change */
2358                 vid_handle = vid2_handle;
2359
2360         if (!vid_handle)
2361                 /* video switching not supported on R30, R31 */
2362                 video_supported = TPACPI_VIDEO_NONE;
2363         else if (acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
2364                 /* 570 */
2365                 video_supported = TPACPI_VIDEO_570;
2366         else if (acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
2367                 /* 600e/x, 770e, 770x */
2368                 video_supported = TPACPI_VIDEO_770;
2369         else
2370                 /* all others */
2371                 video_supported = TPACPI_VIDEO_NEW;
2372
2373         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
2374                 str_supported(video_supported != TPACPI_VIDEO_NONE),
2375                 video_supported);
2376
2377         return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1;
2378 }
2379
2380 static void video_exit(void)
2381 {
2382         dbg_printk(TPACPI_DBG_EXIT,
2383                    "restoring original video autoswitch mode\n");
2384         if (video_autosw_set(video_orig_autosw))
2385                 printk(IBM_ERR "error while trying to restore original "
2386                         "video autoswitch mode\n");
2387 }
2388
2389 static int video_outputsw_get(void)
2390 {
2391         int status = 0;
2392         int i;
2393
2394         switch (video_supported) {
2395         case TPACPI_VIDEO_570:
2396                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
2397                                  TP_ACPI_VIDEO_570_PHSCMD))
2398                         return -EIO;
2399                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
2400                 break;
2401         case TPACPI_VIDEO_770:
2402                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
2403                         return -EIO;
2404                 if (i)
2405                         status |= TP_ACPI_VIDEO_S_LCD;
2406                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
2407                         return -EIO;
2408                 if (i)
2409                         status |= TP_ACPI_VIDEO_S_CRT;
2410                 break;
2411         case TPACPI_VIDEO_NEW:
2412                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
2413                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
2414                         return -EIO;
2415                 if (i)
2416                         status |= TP_ACPI_VIDEO_S_CRT;
2417
2418                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
2419                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
2420                         return -EIO;
2421                 if (i)
2422                         status |= TP_ACPI_VIDEO_S_LCD;
2423                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
2424                         return -EIO;
2425                 if (i)
2426                         status |= TP_ACPI_VIDEO_S_DVI;
2427                 break;
2428         default:
2429                 return -ENOSYS;
2430         }
2431
2432         return status;
2433 }
2434
2435 static int video_outputsw_set(int status)
2436 {
2437         int autosw;
2438         int res = 0;
2439
2440         switch (video_supported) {
2441         case TPACPI_VIDEO_570:
2442                 res = acpi_evalf(NULL, NULL,
2443                                  "\\_SB.PHS2", "vdd",
2444                                  TP_ACPI_VIDEO_570_PHS2CMD,
2445                                  status | TP_ACPI_VIDEO_570_PHS2SET);
2446                 break;
2447         case TPACPI_VIDEO_770:
2448                 autosw = video_autosw_get();
2449                 if (autosw < 0)
2450                         return autosw;
2451
2452                 res = video_autosw_set(1);
2453                 if (res)
2454                         return res;
2455                 res = acpi_evalf(vid_handle, NULL,
2456                                  "ASWT", "vdd", status * 0x100, 0);
2457                 if (!autosw && video_autosw_set(autosw)) {
2458                         printk(IBM_ERR "video auto-switch left enabled due to error\n");
2459                         return -EIO;
2460                 }
2461                 break;
2462         case TPACPI_VIDEO_NEW:
2463                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
2464                         acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
2465                 break;
2466         default:
2467                 return -ENOSYS;
2468         }
2469
2470         return (res)? 0 : -EIO;
2471 }
2472
2473 static int video_autosw_get(void)
2474 {
2475         int autosw = 0;
2476
2477         switch (video_supported) {
2478         case TPACPI_VIDEO_570:
2479                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
2480                         return -EIO;
2481                 break;
2482         case TPACPI_VIDEO_770:
2483         case TPACPI_VIDEO_NEW:
2484                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
2485                         return -EIO;
2486                 break;
2487         default:
2488                 return -ENOSYS;
2489         }
2490
2491         return autosw & 1;
2492 }
2493
2494 static int video_autosw_set(int enable)
2495 {
2496         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0))
2497                 return -EIO;
2498         return 0;
2499 }
2500
2501 static int video_outputsw_cycle(void)
2502 {
2503         int autosw = video_autosw_get();
2504         int res;
2505
2506         if (autosw < 0)
2507                 return autosw;
2508
2509         switch (video_supported) {
2510         case TPACPI_VIDEO_570:
2511                 res = video_autosw_set(1);
2512                 if (res)
2513                         return res;
2514                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
2515                 break;
2516         case TPACPI_VIDEO_770:
2517         case TPACPI_VIDEO_NEW:
2518                 res = video_autosw_set(1);
2519                 if (res)
2520                         return res;
2521                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
2522                 break;
2523         default:
2524                 return -ENOSYS;
2525         }
2526         if (!autosw && video_autosw_set(autosw)) {
2527                 printk(IBM_ERR "video auto-switch left enabled due to error\n");
2528                 return -EIO;
2529         }
2530
2531         return (res)? 0 : -EIO;
2532 }
2533
2534 static int video_expand_toggle(void)
2535 {
2536         switch (video_supported) {
2537         case TPACPI_VIDEO_570:
2538                 return acpi_evalf(ec_handle, NULL, "_Q17", "v")?
2539                         0 : -EIO;
2540         case TPACPI_VIDEO_770:
2541                 return acpi_evalf(vid_handle, NULL, "VEXP", "v")?
2542                         0 : -EIO;
2543         case TPACPI_VIDEO_NEW:
2544                 return acpi_evalf(NULL, NULL, "\\VEXP", "v")?
2545                         0 : -EIO;
2546         default:
2547                 return -ENOSYS;
2548         }
2549         /* not reached */
2550 }
2551
2552 static int video_read(char *p)
2553 {
2554         int status, autosw;
2555         int len = 0;
2556
2557         if (video_supported == TPACPI_VIDEO_NONE) {
2558                 len += sprintf(p + len, "status:\t\tnot supported\n");
2559                 return len;
2560         }
2561
2562         status = video_outputsw_get();
2563         if (status < 0)
2564                 return status;
2565
2566         autosw = video_autosw_get();
2567         if (autosw < 0)
2568                 return autosw;
2569
2570         len += sprintf(p + len, "status:\t\tsupported\n");
2571         len += sprintf(p + len, "lcd:\t\t%s\n", enabled(status, 0));
2572         len += sprintf(p + len, "crt:\t\t%s\n", enabled(status, 1));
2573         if (video_supported == TPACPI_VIDEO_NEW)
2574                 len += sprintf(p + len, "dvi:\t\t%s\n", enabled(status, 3));
2575         len += sprintf(p + len, "auto:\t\t%s\n", enabled(autosw, 0));
2576         len += sprintf(p + len, "commands:\tlcd_enable, lcd_disable\n");
2577         len += sprintf(p + len, "commands:\tcrt_enable, crt_disable\n");
2578         if (video_supported == TPACPI_VIDEO_NEW)
2579                 len += sprintf(p + len, "commands:\tdvi_enable, dvi_disable\n");
2580         len += sprintf(p + len, "commands:\tauto_enable, auto_disable\n");
2581         len += sprintf(p + len, "commands:\tvideo_switch, expand_toggle\n");
2582
2583         return len;
2584 }
2585
2586 static int video_write(char *buf)
2587 {
2588         char *cmd;
2589         int enable, disable, status;
2590         int res;
2591
2592         if (video_supported == TPACPI_VIDEO_NONE)
2593                 return -ENODEV;
2594
2595         enable = 0;
2596         disable = 0;
2597
2598         while ((cmd = next_cmd(&buf))) {
2599                 if (strlencmp(cmd, "lcd_enable") == 0) {
2600                         enable |= TP_ACPI_VIDEO_S_LCD;
2601                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
2602                         disable |= TP_ACPI_VIDEO_S_LCD;
2603                 } else if (strlencmp(cmd, "crt_enable") == 0) {
2604                         enable |= TP_ACPI_VIDEO_S_CRT;
2605                 } else if (strlencmp(cmd, "crt_disable") == 0) {
2606                         disable |= TP_ACPI_VIDEO_S_CRT;
2607                 } else if (video_supported == TPACPI_VIDEO_NEW &&
2608                            strlencmp(cmd, "dvi_enable") == 0) {
2609                         enable |= TP_ACPI_VIDEO_S_DVI;
2610                 } else if (video_supported == TPACPI_VIDEO_NEW &&
2611                            strlencmp(cmd, "dvi_disable") == 0) {
2612                         disable |= TP_ACPI_VIDEO_S_DVI;
2613                 } else if (strlencmp(cmd, "auto_enable") == 0) {
2614                         res = video_autosw_set(1);
2615                         if (res)
2616                                 return res;
2617                 } else if (strlencmp(cmd, "auto_disable") == 0) {
2618                         res = video_autosw_set(0);
2619                         if (res)
2620                                 return res;
2621                 } else if (strlencmp(cmd, "video_switch") == 0) {
2622                         res = video_outputsw_cycle();
2623                         if (res)
2624                                 return res;
2625                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
2626                         res = video_expand_toggle();
2627                         if (res)
2628                                 return res;
2629                 } else
2630                         return -EINVAL;
2631         }
2632
2633         if (enable || disable) {
2634                 status = video_outputsw_get();
2635                 if (status < 0)
2636                         return status;
2637                 res = video_outputsw_set((status & ~disable) | enable);
2638                 if (res)
2639                         return res;
2640         }
2641
2642         return 0;
2643 }
2644
2645 static struct ibm_struct video_driver_data = {
2646         .name = "video",
2647         .read = video_read,
2648         .write = video_write,
2649         .exit = video_exit,
2650 };
2651
2652 /*************************************************************************
2653  * Light (thinklight) subdriver
2654  */
2655
2656 IBM_HANDLE(lght, root, "\\LGHT");       /* A21e, A2xm/p, T20-22, X20-21 */
2657 IBM_HANDLE(ledb, ec, "LEDB");           /* G4x */
2658
2659 static int __init light_init(struct ibm_init_struct *iibm)
2660 {
2661         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
2662
2663         IBM_ACPIHANDLE_INIT(ledb);
2664         IBM_ACPIHANDLE_INIT(lght);
2665         IBM_ACPIHANDLE_INIT(cmos);
2666
2667         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
2668         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
2669
2670         if (tp_features.light)
2671                 /* light status not supported on
2672                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
2673                 tp_features.light_status =
2674                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
2675
2676         vdbg_printk(TPACPI_DBG_INIT, "light is %s\n",
2677                 str_supported(tp_features.light));
2678
2679         return (tp_features.light)? 0 : 1;
2680 }
2681
2682 static int light_read(char *p)
2683 {
2684         int len = 0;
2685         int status = 0;
2686
2687         if (!tp_features.light) {
2688                 len += sprintf(p + len, "status:\t\tnot supported\n");
2689         } else if (!tp_features.light_status) {
2690                 len += sprintf(p + len, "status:\t\tunknown\n");
2691                 len += sprintf(p + len, "commands:\ton, off\n");
2692         } else {
2693                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
2694                         return -EIO;
2695                 len += sprintf(p + len, "status:\t\t%s\n", onoff(status, 0));
2696                 len += sprintf(p + len, "commands:\ton, off\n");
2697         }
2698
2699         return len;
2700 }
2701
2702 static int light_write(char *buf)
2703 {
2704         int cmos_cmd, lght_cmd;
2705         char *cmd;
2706         int success;
2707
2708         if (!tp_features.light)
2709                 return -ENODEV;
2710
2711         while ((cmd = next_cmd(&buf))) {
2712                 if (strlencmp(cmd, "on") == 0) {
2713                         cmos_cmd = 0x0c;
2714                         lght_cmd = 1;
2715                 } else if (strlencmp(cmd, "off") == 0) {
2716                         cmos_cmd = 0x0d;
2717                         lght_cmd = 0;
2718                 } else
2719                         return -EINVAL;
2720
2721                 success = cmos_handle ?
2722                     acpi_evalf(cmos_handle, NULL, NULL, "vd", cmos_cmd) :
2723                     acpi_evalf(lght_handle, NULL, NULL, "vd", lght_cmd);
2724                 if (!success)
2725                         return -EIO;
2726         }
2727
2728         return 0;
2729 }
2730
2731 static struct ibm_struct light_driver_data = {
2732         .name = "light",
2733         .read = light_read,
2734         .write = light_write,
2735 };
2736
2737 /*************************************************************************
2738  * Dock subdriver
2739  */
2740
2741 #ifdef CONFIG_THINKPAD_ACPI_DOCK
2742
2743 IBM_HANDLE(dock, root, "\\_SB.GDCK",    /* X30, X31, X40 */
2744            "\\_SB.PCI0.DOCK",   /* 600e/x,770e,770x,A2xm/p,T20-22,X20-21 */
2745            "\\_SB.PCI0.PCI1.DOCK",      /* all others */
2746            "\\_SB.PCI.ISA.SLCE",        /* 570 */
2747     );                          /* A21e,G4x,R30,R31,R32,R40,R40e,R50e */
2748
2749 /* don't list other alternatives as we install a notify handler on the 570 */
2750 IBM_HANDLE(pci, root, "\\_SB.PCI");     /* 570 */
2751
2752 static const struct acpi_device_id ibm_pci_device_ids[] = {
2753         {PCI_ROOT_HID_STRING, 0},
2754         {"", 0},
2755 };
2756
2757 static struct tp_acpi_drv_struct ibm_dock_acpidriver[2] = {
2758         {
2759          .notify = dock_notify,
2760          .handle = &dock_handle,
2761          .type = ACPI_SYSTEM_NOTIFY,
2762         },
2763         {
2764         /* THIS ONE MUST NEVER BE USED FOR DRIVER AUTOLOADING.
2765          * We just use it to get notifications of dock hotplug
2766          * in very old thinkpads */
2767          .hid = ibm_pci_device_ids,
2768          .notify = dock_notify,
2769          .handle = &pci_handle,
2770          .type = ACPI_SYSTEM_NOTIFY,
2771         },
2772 };
2773
2774 static struct ibm_struct dock_driver_data[2] = {
2775         {
2776          .name = "dock",
2777          .read = dock_read,
2778          .write = dock_write,
2779          .acpi = &ibm_dock_acpidriver[0],
2780         },
2781         {
2782          .name = "dock",
2783          .acpi = &ibm_dock_acpidriver[1],
2784         },
2785 };
2786
2787 #define dock_docked() (_sta(dock_handle) & 1)
2788
2789 static int __init dock_init(struct ibm_init_struct *iibm)
2790 {
2791         vdbg_printk(TPACPI_DBG_INIT, "initializing dock subdriver\n");
2792
2793         IBM_ACPIHANDLE_INIT(dock);
2794
2795         vdbg_printk(TPACPI_DBG_INIT, "dock is %s\n",
2796                 str_supported(dock_handle != NULL));
2797
2798         return (dock_handle)? 0 : 1;
2799 }
2800
2801 static int __init dock_init2(struct ibm_init_struct *iibm)
2802 {
2803         int dock2_needed;
2804
2805         vdbg_printk(TPACPI_DBG_INIT, "initializing dock subdriver part 2\n");
2806
2807         if (dock_driver_data[0].flags.acpi_driver_registered &&
2808             dock_driver_data[0].flags.acpi_notify_installed) {
2809                 IBM_ACPIHANDLE_INIT(pci);
2810                 dock2_needed = (pci_handle != NULL);
2811                 vdbg_printk(TPACPI_DBG_INIT,
2812                             "dock PCI handler for the TP 570 is %s\n",
2813                             str_supported(dock2_needed));
2814         } else {
2815                 vdbg_printk(TPACPI_DBG_INIT,
2816                 "dock subdriver part 2 not required\n");
2817                 dock2_needed = 0;
2818         }
2819
2820         return (dock2_needed)? 0 : 1;
2821 }
2822
2823 static void dock_notify(struct ibm_struct *ibm, u32 event)
2824 {
2825         int docked = dock_docked();
2826         int pci = ibm->acpi->hid && ibm->acpi->device &&
2827                 acpi_match_device_ids(ibm->acpi->device, ibm_pci_device_ids);
2828         int data;
2829
2830         if (event == 1 && !pci) /* 570 */
2831                 data = 1;       /* button */
2832         else if (event == 1 && pci)     /* 570 */
2833                 data = 3;       /* dock */
2834         else if (event == 3 && docked)
2835                 data = 1;       /* button */
2836         else if (event == 3 && !docked)
2837                 data = 2;       /* undock */
2838         else if (event == 0 && docked)
2839                 data = 3;       /* dock */
2840         else {
2841                 printk(IBM_ERR "unknown dock event %d, status %d\n",
2842                        event, _sta(dock_handle));
2843                 data = 0;       /* unknown */
2844         }
2845         acpi_bus_generate_proc_event(ibm->acpi->device, event, data);
2846         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
2847                                           ibm->acpi->device->dev.bus_id,
2848                                           event, data);
2849 }
2850
2851 static int dock_read(char *p)
2852 {
2853         int len = 0;
2854         int docked = dock_docked();
2855
2856         if (!dock_handle)
2857                 len += sprintf(p + len, "status:\t\tnot supported\n");
2858         else if (!docked)
2859                 len += sprintf(p + len, "status:\t\tundocked\n");
2860         else {
2861                 len += sprintf(p + len, "status:\t\tdocked\n");
2862                 len += sprintf(p + len, "commands:\tdock, undock\n");
2863         }
2864
2865         return len;
2866 }
2867
2868 static int dock_write(char *buf)
2869 {
2870         char *cmd;
2871
2872         if (!dock_docked())
2873                 return -ENODEV;
2874
2875         while ((cmd = next_cmd(&buf))) {
2876                 if (strlencmp(cmd, "undock") == 0) {
2877                         if (!acpi_evalf(dock_handle, NULL, "_DCK", "vd", 0) ||
2878                             !acpi_evalf(dock_handle, NULL, "_EJ0", "vd", 1))
2879                                 return -EIO;
2880                 } else if (strlencmp(cmd, "dock") == 0) {
2881                         if (!acpi_evalf(dock_handle, NULL, "_DCK", "vd", 1))
2882                                 return -EIO;
2883                 } else
2884                         return -EINVAL;
2885         }
2886
2887         return 0;
2888 }
2889
2890 #endif /* CONFIG_THINKPAD_ACPI_DOCK */
2891
2892 /*************************************************************************
2893  * Bay subdriver
2894  */
2895
2896 #ifdef CONFIG_THINKPAD_ACPI_BAY
2897 IBM_HANDLE(bay, root, "\\_SB.PCI.IDE.SECN.MAST",        /* 570 */
2898            "\\_SB.PCI0.IDE0.IDES.IDSM", /* 600e/x, 770e, 770x */
2899            "\\_SB.PCI0.SATA.SCND.MSTR", /* T60, X60, Z60 */
2900            "\\_SB.PCI0.IDE0.SCND.MSTR", /* all others */
2901            );                           /* A21e, R30, R31 */
2902 IBM_HANDLE(bay_ej, bay, "_EJ3", /* 600e/x, A2xm/p, A3x */
2903            "_EJ0",              /* all others */
2904            );                   /* 570,A21e,G4x,R30,R31,R32,R40e,R50e */
2905 IBM_HANDLE(bay2, root, "\\_SB.PCI0.IDE0.PRIM.SLAV",     /* A3x, R32 */
2906            "\\_SB.PCI0.IDE0.IDEP.IDPS", /* 600e/x, 770e, 770x */
2907            );                           /* all others */
2908 IBM_HANDLE(bay2_ej, bay2, "_EJ3",       /* 600e/x, 770e, A3x */
2909            "_EJ0",                      /* 770x */
2910            );                           /* all others */
2911
2912 static int __init bay_init(struct ibm_init_struct *iibm)
2913 {
2914         vdbg_printk(TPACPI_DBG_INIT, "initializing bay subdriver\n");
2915
2916         IBM_ACPIHANDLE_INIT(bay);
2917         if (bay_handle)
2918                 IBM_ACPIHANDLE_INIT(bay_ej);
2919         IBM_ACPIHANDLE_INIT(bay2);
2920         if (bay2_handle)
2921                 IBM_ACPIHANDLE_INIT(bay2_ej);
2922
2923         tp_features.bay_status = bay_handle &&
2924                 acpi_evalf(bay_handle, NULL, "_STA", "qv");
2925         tp_features.bay_status2 = bay2_handle &&
2926                 acpi_evalf(bay2_handle, NULL, "_STA", "qv");
2927
2928         tp_features.bay_eject = bay_handle && bay_ej_handle &&
2929                 (strlencmp(bay_ej_path, "_EJ0") == 0 || experimental);
2930         tp_features.bay_eject2 = bay2_handle && bay2_ej_handle &&
2931                 (strlencmp(bay2_ej_path, "_EJ0") == 0 || experimental);
2932
2933         vdbg_printk(TPACPI_DBG_INIT,
2934                 "bay 1: status %s, eject %s; bay 2: status %s, eject %s\n",
2935                 str_supported(tp_features.bay_status),
2936                 str_supported(tp_features.bay_eject),
2937                 str_supported(tp_features.bay_status2),
2938                 str_supported(tp_features.bay_eject2));
2939
2940         return (tp_features.bay_status || tp_features.bay_eject ||
2941                 tp_features.bay_status2 || tp_features.bay_eject2)? 0 : 1;
2942 }
2943
2944 static void bay_notify(struct ibm_struct *ibm, u32 event)
2945 {
2946         acpi_bus_generate_proc_event(ibm->acpi->device, event, 0);
2947         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
2948                                           ibm->acpi->device->dev.bus_id,
2949                                           event, 0);
2950 }
2951
2952 #define bay_occupied(b) (_sta(b##_handle) & 1)
2953
2954 static int bay_read(char *p)
2955 {
2956         int len = 0;
2957         int occupied = bay_occupied(bay);
2958         int occupied2 = bay_occupied(bay2);
2959         int eject, eject2;
2960
2961         len += sprintf(p + len, "status:\t\t%s\n",
2962                 tp_features.bay_status ?
2963                         (occupied ? "occupied" : "unoccupied") :
2964                                 "not supported");
2965         if (tp_features.bay_status2)
2966                 len += sprintf(p + len, "status2:\t%s\n", occupied2 ?
2967                                "occupied" : "unoccupied");
2968
2969         eject = tp_features.bay_eject && occupied;
2970         eject2 = tp_features.bay_eject2 && occupied2;
2971
2972         if (eject && eject2)
2973                 len += sprintf(p + len, "commands:\teject, eject2\n");
2974         else if (eject)
2975                 len += sprintf(p + len, "commands:\teject\n");
2976         else if (eject2)
2977                 len += sprintf(p + len, "commands:\teject2\n");
2978
2979         return len;
2980 }
2981
2982 static int bay_write(char *buf)
2983 {
2984         char *cmd;
2985
2986         if (!tp_features.bay_eject && !tp_features.bay_eject2)
2987                 return -ENODEV;
2988
2989         while ((cmd = next_cmd(&buf))) {
2990                 if (tp_features.bay_eject && strlencmp(cmd, "eject") == 0) {
2991                         if (!acpi_evalf(bay_ej_handle, NULL, NULL, "vd", 1))
2992                                 return -EIO;
2993                 } else if (tp_features.bay_eject2 &&
2994                            strlencmp(cmd, "eject2") == 0) {
2995                         if (!acpi_evalf(bay2_ej_handle, NULL, NULL, "vd", 1))
2996                                 return -EIO;
2997                 } else
2998                         return -EINVAL;
2999         }
3000
3001         return 0;
3002 }
3003
3004 static struct tp_acpi_drv_struct ibm_bay_acpidriver = {
3005         .notify = bay_notify,
3006         .handle = &bay_handle,
3007         .type = ACPI_SYSTEM_NOTIFY,
3008 };
3009
3010 static struct ibm_struct bay_driver_data = {
3011         .name = "bay",
3012         .read = bay_read,
3013         .write = bay_write,
3014         .acpi = &ibm_bay_acpidriver,
3015 };
3016
3017 #endif /* CONFIG_THINKPAD_ACPI_BAY */
3018
3019 /*************************************************************************
3020  * CMOS subdriver
3021  */
3022
3023 /* sysfs cmos_command -------------------------------------------------- */
3024 static ssize_t cmos_command_store(struct device *dev,
3025                             struct device_attribute *attr,
3026                             const char *buf, size_t count)
3027 {
3028         unsigned long cmos_cmd;
3029         int res;
3030
3031         if (parse_strtoul(buf, 21, &cmos_cmd))
3032                 return -EINVAL;
3033
3034         res = issue_thinkpad_cmos_command(cmos_cmd);
3035         return (res)? res : count;
3036 }
3037
3038 static struct device_attribute dev_attr_cmos_command =
3039         __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store);
3040
3041 /* --------------------------------------------------------------------- */
3042
3043 static int __init cmos_init(struct ibm_init_struct *iibm)
3044 {
3045         int res;
3046
3047         vdbg_printk(TPACPI_DBG_INIT,
3048                 "initializing cmos commands subdriver\n");
3049
3050         IBM_ACPIHANDLE_INIT(cmos);
3051
3052         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
3053                 str_supported(cmos_handle != NULL));
3054
3055         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
3056         if (res)
3057                 return res;
3058
3059         return (cmos_handle)? 0 : 1;
3060 }
3061
3062 static void cmos_exit(void)
3063 {
3064         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
3065 }
3066
3067 static int cmos_read(char *p)
3068 {
3069         int len = 0;
3070
3071         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
3072            R30, R31, T20-22, X20-21 */
3073         if (!cmos_handle)
3074                 len += sprintf(p + len, "status:\t\tnot supported\n");
3075         else {
3076                 len += sprintf(p + len, "status:\t\tsupported\n");
3077                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-21)\n");
3078         }
3079
3080         return len;
3081 }
3082
3083 static int cmos_write(char *buf)
3084 {
3085         char *cmd;
3086         int cmos_cmd, res;
3087
3088         while ((cmd = next_cmd(&buf))) {
3089                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
3090                     cmos_cmd >= 0 && cmos_cmd <= 21) {
3091                         /* cmos_cmd set */
3092                 } else
3093                         return -EINVAL;
3094
3095                 res = issue_thinkpad_cmos_command(cmos_cmd);
3096                 if (res)
3097                         return res;
3098         }
3099
3100         return 0;
3101 }
3102
3103 static struct ibm_struct cmos_driver_data = {
3104         .name = "cmos",
3105         .read = cmos_read,
3106         .write = cmos_write,
3107         .exit = cmos_exit,
3108 };
3109
3110 /*************************************************************************
3111  * LED subdriver
3112  */
3113
3114 static enum led_access_mode led_supported;
3115
3116 IBM_HANDLE(led, ec, "SLED",     /* 570 */
3117            "SYSL",              /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
3118            "LED",               /* all others */
3119            );                   /* R30, R31 */
3120
3121 static int __init led_init(struct ibm_init_struct *iibm)
3122 {
3123         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
3124
3125         IBM_ACPIHANDLE_INIT(led);
3126
3127         if (!led_handle)
3128                 /* led not supported on R30, R31 */
3129                 led_supported = TPACPI_LED_NONE;
3130         else if (strlencmp(led_path, "SLED") == 0)
3131                 /* 570 */
3132                 led_supported = TPACPI_LED_570;
3133         else if (strlencmp(led_path, "SYSL") == 0)
3134                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
3135                 led_supported = TPACPI_LED_OLD;
3136         else
3137                 /* all others */
3138                 led_supported = TPACPI_LED_NEW;
3139
3140         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
3141                 str_supported(led_supported), led_supported);
3142
3143         return (led_supported != TPACPI_LED_NONE)? 0 : 1;
3144 }
3145
3146 #define led_status(s) ((s) == 0 ? "off" : ((s) == 1 ? "on" : "blinking"))
3147
3148 static int led_read(char *p)
3149 {
3150         int len = 0;
3151
3152         if (!led_supported) {
3153                 len += sprintf(p + len, "status:\t\tnot supported\n");
3154                 return len;
3155         }
3156         len += sprintf(p + len, "status:\t\tsupported\n");
3157
3158         if (led_supported == TPACPI_LED_570) {
3159                 /* 570 */
3160                 int i, status;
3161                 for (i = 0; i < 8; i++) {
3162                         if (!acpi_evalf(ec_handle,
3163                                         &status, "GLED", "dd", 1 << i))
3164                                 return -EIO;
3165                         len += sprintf(p + len, "%d:\t\t%s\n",
3166                                        i, led_status(status));
3167                 }
3168         }
3169
3170         len += sprintf(p + len, "commands:\t"
3171                        "<led> on, <led> off, <led> blink (<led> is 0-7)\n");
3172
3173         return len;
3174 }
3175
3176 /* off, on, blink */
3177 static const int led_sled_arg1[] = { 0, 1, 3 };
3178 static const int led_exp_hlbl[] = { 0, 0, 1 };  /* led# * */
3179 static const int led_exp_hlcl[] = { 0, 1, 1 };  /* led# * */
3180 static const int led_led_arg1[] = { 0, 0x80, 0xc0 };
3181
3182 static int led_write(char *buf)
3183 {
3184         char *cmd;
3185         int led, ind, ret;
3186
3187         if (!led_supported)
3188                 return -ENODEV;
3189
3190         while ((cmd = next_cmd(&buf))) {
3191                 if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 7)
3192                         return -EINVAL;
3193
3194                 if (strstr(cmd, "off")) {
3195                         ind = 0;
3196                 } else if (strstr(cmd, "on")) {
3197                         ind = 1;
3198                 } else if (strstr(cmd, "blink")) {
3199                         ind = 2;
3200                 } else
3201                         return -EINVAL;
3202
3203                 if (led_supported == TPACPI_LED_570) {
3204                         /* 570 */
3205                         led = 1 << led;
3206                         if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
3207                                         led, led_sled_arg1[ind]))
3208                                 return -EIO;
3209                 } else if (led_supported == TPACPI_LED_OLD) {
3210                         /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
3211                         led = 1 << led;
3212                         ret = ec_write(TPACPI_LED_EC_HLMS, led);
3213                         if (ret >= 0)
3214                                 ret =
3215                                     ec_write(TPACPI_LED_EC_HLBL,
3216                                              led * led_exp_hlbl[ind]);
3217                         if (ret >= 0)
3218                                 ret =
3219                                     ec_write(TPACPI_LED_EC_HLCL,
3220                                              led * led_exp_hlcl[ind]);
3221                         if (ret < 0)
3222                                 return ret;
3223                 } else {
3224                         /* all others */
3225                         if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
3226                                         led, led_led_arg1[ind]))
3227                                 return -EIO;
3228                 }
3229         }
3230
3231         return 0;
3232 }
3233
3234 static struct ibm_struct led_driver_data = {
3235         .name = "led",
3236         .read = led_read,
3237         .write = led_write,
3238 };
3239
3240 /*************************************************************************
3241  * Beep subdriver
3242  */
3243
3244 IBM_HANDLE(beep, ec, "BEEP");   /* all except R30, R31 */
3245
3246 static int __init beep_init(struct ibm_init_struct *iibm)
3247 {
3248         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
3249
3250         IBM_ACPIHANDLE_INIT(beep);
3251
3252         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
3253                 str_supported(beep_handle != NULL));
3254
3255         return (beep_handle)? 0 : 1;
3256 }
3257
3258 static int beep_read(char *p)
3259 {
3260         int len = 0;
3261
3262         if (!beep_handle)
3263                 len += sprintf(p + len, "status:\t\tnot supported\n");
3264         else {
3265                 len += sprintf(p + len, "status:\t\tsupported\n");
3266                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-17)\n");
3267         }
3268
3269         return len;
3270 }
3271
3272 static int beep_write(char *buf)
3273 {
3274         char *cmd;
3275         int beep_cmd;
3276
3277         if (!beep_handle)
3278                 return -ENODEV;
3279
3280         while ((cmd = next_cmd(&buf))) {
3281                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
3282                     beep_cmd >= 0 && beep_cmd <= 17) {
3283                         /* beep_cmd set */
3284                 } else
3285                         return -EINVAL;
3286                 if (!acpi_evalf(beep_handle, NULL, NULL, "vdd", beep_cmd, 0))
3287                         return -EIO;
3288         }
3289
3290         return 0;
3291 }
3292
3293 static struct ibm_struct beep_driver_data = {
3294         .name = "beep",
3295         .read = beep_read,
3296         .write = beep_write,
3297 };
3298
3299 /*************************************************************************
3300  * Thermal subdriver
3301  */
3302
3303 static enum thermal_access_mode thermal_read_mode;
3304
3305 /* sysfs temp##_input -------------------------------------------------- */
3306
3307 static ssize_t thermal_temp_input_show(struct device *dev,
3308                            struct device_attribute *attr,
3309                            char *buf)
3310 {
3311         struct sensor_device_attribute *sensor_attr =
3312                                         to_sensor_dev_attr(attr);
3313         int idx = sensor_attr->index;
3314         s32 value;
3315         int res;
3316
3317         res = thermal_get_sensor(idx, &value);
3318         if (res)
3319                 return res;
3320         if (value == TP_EC_THERMAL_TMP_NA * 1000)
3321                 return -ENXIO;
3322
3323         return snprintf(buf, PAGE_SIZE, "%d\n", value);
3324 }
3325
3326 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
3327          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, thermal_temp_input_show, NULL, _idxB)
3328
3329 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
3330         THERMAL_SENSOR_ATTR_TEMP(1, 0),
3331         THERMAL_SENSOR_ATTR_TEMP(2, 1),
3332         THERMAL_SENSOR_ATTR_TEMP(3, 2),
3333         THERMAL_SENSOR_ATTR_TEMP(4, 3),
3334         THERMAL_SENSOR_ATTR_TEMP(5, 4),
3335         THERMAL_SENSOR_ATTR_TEMP(6, 5),
3336         THERMAL_SENSOR_ATTR_TEMP(7, 6),
3337         THERMAL_SENSOR_ATTR_TEMP(8, 7),
3338         THERMAL_SENSOR_ATTR_TEMP(9, 8),
3339         THERMAL_SENSOR_ATTR_TEMP(10, 9),
3340         THERMAL_SENSOR_ATTR_TEMP(11, 10),
3341         THERMAL_SENSOR_ATTR_TEMP(12, 11),
3342         THERMAL_SENSOR_ATTR_TEMP(13, 12),
3343         THERMAL_SENSOR_ATTR_TEMP(14, 13),
3344         THERMAL_SENSOR_ATTR_TEMP(15, 14),
3345         THERMAL_SENSOR_ATTR_TEMP(16, 15),
3346 };
3347
3348 #define THERMAL_ATTRS(X) \
3349         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
3350
3351 static struct attribute *thermal_temp_input_attr[] = {
3352         THERMAL_ATTRS(8),
3353         THERMAL_ATTRS(9),
3354         THERMAL_ATTRS(10),
3355         THERMAL_ATTRS(11),
3356         THERMAL_ATTRS(12),
3357         THERMAL_ATTRS(13),
3358         THERMAL_ATTRS(14),
3359         THERMAL_ATTRS(15),
3360         THERMAL_ATTRS(0),
3361         THERMAL_ATTRS(1),
3362         THERMAL_ATTRS(2),
3363         THERMAL_ATTRS(3),
3364         THERMAL_ATTRS(4),
3365         THERMAL_ATTRS(5),
3366         THERMAL_ATTRS(6),
3367         THERMAL_ATTRS(7),
3368         NULL
3369 };
3370
3371 static const struct attribute_group thermal_temp_input16_group = {
3372         .attrs = thermal_temp_input_attr
3373 };
3374
3375 static const struct attribute_group thermal_temp_input8_group = {
3376         .attrs = &thermal_temp_input_attr[8]
3377 };
3378
3379 #undef THERMAL_SENSOR_ATTR_TEMP
3380 #undef THERMAL_ATTRS
3381
3382 /* --------------------------------------------------------------------- */
3383
3384 static int __init thermal_init(struct ibm_init_struct *iibm)
3385 {
3386         u8 t, ta1, ta2;
3387         int i;
3388         int acpi_tmp7;
3389         int res;
3390
3391         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
3392
3393         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
3394
3395         if (thinkpad_id.ec_model) {
3396                 /*
3397                  * Direct EC access mode: sensors at registers
3398                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
3399                  * non-implemented, thermal sensors return 0x80 when
3400                  * not available
3401                  */
3402
3403                 ta1 = ta2 = 0;
3404                 for (i = 0; i < 8; i++) {
3405                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
3406                                 ta1 |= t;
3407                         } else {
3408                                 ta1 = 0;
3409                                 break;
3410                         }
3411                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
3412                                 ta2 |= t;
3413                         } else {
3414                                 ta1 = 0;
3415                                 break;
3416                         }
3417                 }
3418                 if (ta1 == 0) {
3419                         /* This is sheer paranoia, but we handle it anyway */
3420                         if (acpi_tmp7) {
3421                                 printk(IBM_ERR
3422                                        "ThinkPad ACPI EC access misbehaving, "
3423                                        "falling back to ACPI TMPx access mode\n");
3424                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
3425                         } else {
3426                                 printk(IBM_ERR
3427                                        "ThinkPad ACPI EC access misbehaving, "
3428                                        "disabling thermal sensors access\n");
3429                                 thermal_read_mode = TPACPI_THERMAL_NONE;
3430                         }
3431                 } else {
3432                         thermal_read_mode =
3433                             (ta2 != 0) ?
3434                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
3435                 }
3436         } else if (acpi_tmp7) {
3437                 if (acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
3438                         /* 600e/x, 770e, 770x */
3439                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
3440                 } else {
3441                         /* Standard ACPI TMPx access, max 8 sensors */
3442                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
3443                 }
3444         } else {
3445                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
3446                 thermal_read_mode = TPACPI_THERMAL_NONE;
3447         }
3448
3449         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
3450                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
3451                 thermal_read_mode);
3452
3453         switch(thermal_read_mode) {
3454         case TPACPI_THERMAL_TPEC_16:
3455                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
3456                                 &thermal_temp_input16_group);
3457                 if (res)
3458                         return res;
3459                 break;
3460         case TPACPI_THERMAL_TPEC_8:
3461         case TPACPI_THERMAL_ACPI_TMP07:
3462         case TPACPI_THERMAL_ACPI_UPDT:
3463                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
3464                                 &thermal_temp_input8_group);
3465                 if (res)
3466                         return res;
3467                 break;
3468         case TPACPI_THERMAL_NONE:
3469         default:
3470                 return 1;
3471         }
3472
3473         return 0;
3474 }
3475
3476 static void thermal_exit(void)
3477 {
3478         switch(thermal_read_mode) {
3479         case TPACPI_THERMAL_TPEC_16:
3480                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
3481                                    &thermal_temp_input16_group);
3482                 break;
3483         case TPACPI_THERMAL_TPEC_8:
3484         case TPACPI_THERMAL_ACPI_TMP07:
3485         case TPACPI_THERMAL_ACPI_UPDT:
3486                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
3487                                    &thermal_temp_input16_group);
3488                 break;
3489         case TPACPI_THERMAL_NONE:
3490         default:
3491                 break;
3492         }
3493 }
3494
3495 /* idx is zero-based */
3496 static int thermal_get_sensor(int idx, s32 *value)
3497 {
3498         int t;
3499         s8 tmp;
3500         char tmpi[5];
3501
3502         t = TP_EC_THERMAL_TMP0;
3503
3504         switch (thermal_read_mode) {
3505 #if TPACPI_MAX_THERMAL_SENSORS >= 16
3506         case TPACPI_THERMAL_TPEC_16:
3507                 if (idx >= 8 && idx <= 15) {
3508                         t = TP_EC_THERMAL_TMP8;
3509                         idx -= 8;
3510                 }
3511                 /* fallthrough */
3512 #endif
3513         case TPACPI_THERMAL_TPEC_8:
3514                 if (idx <= 7) {
3515                         if (!acpi_ec_read(t + idx, &tmp))
3516                                 return -EIO;
3517                         *value = tmp * 1000;
3518                         return 0;
3519                 }
3520                 break;
3521
3522         case TPACPI_THERMAL_ACPI_UPDT:
3523                 if (idx <= 7) {
3524                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
3525                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
3526                                 return -EIO;
3527                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
3528                                 return -EIO;
3529                         *value = (t - 2732) * 100;
3530                         return 0;
3531                 }
3532                 break;
3533
3534         case TPACPI_THERMAL_ACPI_TMP07:
3535                 if (idx <= 7) {
3536                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
3537                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
3538                                 return -EIO;
3539                         if (t > 127 || t < -127)
3540                                 t = TP_EC_THERMAL_TMP_NA;
3541                         *value = t * 1000;
3542                         return 0;
3543                 }
3544                 break;
3545
3546         case TPACPI_THERMAL_NONE:
3547         default:
3548                 return -ENOSYS;
3549         }
3550
3551         return -EINVAL;
3552 }
3553
3554 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
3555 {
3556         int res, i;
3557         int n;
3558
3559         n = 8;
3560         i = 0;
3561
3562         if (!s)
3563                 return -EINVAL;
3564
3565         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
3566                 n = 16;
3567
3568         for(i = 0 ; i < n; i++) {
3569                 res = thermal_get_sensor(i, &s->temp[i]);
3570                 if (res)
3571                         return res;
3572         }
3573
3574         return n;
3575 }
3576
3577 static int thermal_read(char *p)
3578 {
3579         int len = 0;
3580         int n, i;
3581         struct ibm_thermal_sensors_struct t;
3582
3583         n = thermal_get_sensors(&t);
3584         if (unlikely(n < 0))
3585                 return n;
3586
3587         len += sprintf(p + len, "temperatures:\t");
3588
3589         if (n > 0) {
3590                 for (i = 0; i < (n - 1); i++)
3591                         len += sprintf(p + len, "%d ", t.temp[i] / 1000);
3592                 len += sprintf(p + len, "%d\n", t.temp[i] / 1000);
3593         } else
3594                 len += sprintf(p + len, "not supported\n");
3595
3596         return len;
3597 }
3598
3599 static struct ibm_struct thermal_driver_data = {
3600         .name = "thermal",
3601         .read = thermal_read,
3602         .exit = thermal_exit,
3603 };
3604
3605 /*************************************************************************
3606  * EC Dump subdriver
3607  */
3608
3609 static u8 ecdump_regs[256];
3610
3611 static int ecdump_read(char *p)
3612 {
3613         int len = 0;
3614         int i, j;
3615         u8 v;
3616
3617         len += sprintf(p + len, "EC      "
3618                        " +00 +01 +02 +03 +04 +05 +06 +07"
3619                        " +08 +09 +0a +0b +0c +0d +0e +0f\n");
3620         for (i = 0; i < 256; i += 16) {
3621                 len += sprintf(p + len, "EC 0x%02x:", i);
3622                 for (j = 0; j < 16; j++) {
3623                         if (!acpi_ec_read(i + j, &v))
3624                                 break;
3625                         if (v != ecdump_regs[i + j])
3626                                 len += sprintf(p + len, " *%02x", v);
3627                         else
3628                                 len += sprintf(p + len, "  %02x", v);
3629                         ecdump_regs[i + j] = v;
3630                 }
3631                 len += sprintf(p + len, "\n");
3632                 if (j != 16)
3633                         break;
3634         }
3635
3636         /* These are way too dangerous to advertise openly... */
3637 #if 0
3638         len += sprintf(p + len, "commands:\t0x<offset> 0x<value>"
3639                        " (<offset> is 00-ff, <value> is 00-ff)\n");
3640         len += sprintf(p + len, "commands:\t0x<offset> <value>  "
3641                        " (<offset> is 00-ff, <value> is 0-255)\n");
3642 #endif
3643         return len;
3644 }
3645
3646 static int ecdump_write(char *buf)
3647 {
3648         char *cmd;
3649         int i, v;
3650
3651         while ((cmd = next_cmd(&buf))) {
3652                 if (sscanf(cmd, "0x%x 0x%x", &i, &v) == 2) {
3653                         /* i and v set */
3654                 } else if (sscanf(cmd, "0x%x %u", &i, &v) == 2) {
3655                         /* i and v set */
3656                 } else
3657                         return -EINVAL;
3658                 if (i >= 0 && i < 256 && v >= 0 && v < 256) {
3659                         if (!acpi_ec_write(i, v))
3660                                 return -EIO;
3661                 } else
3662                         return -EINVAL;
3663         }
3664
3665         return 0;
3666 }
3667
3668 static struct ibm_struct ecdump_driver_data = {
3669         .name = "ecdump",
3670         .read = ecdump_read,
3671         .write = ecdump_write,
3672         .flags.experimental = 1,
3673 };
3674
3675 /*************************************************************************
3676  * Backlight/brightness subdriver
3677  */
3678
3679 static struct backlight_device *ibm_backlight_device;
3680
3681 static struct backlight_ops ibm_backlight_data = {
3682         .get_brightness = brightness_get,
3683         .update_status  = brightness_update_status,
3684 };
3685
3686 static struct mutex brightness_mutex;
3687
3688 static int __init tpacpi_query_bcll_levels(acpi_handle handle)
3689 {
3690         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
3691         union acpi_object *obj;
3692         int rc;
3693
3694         if (ACPI_SUCCESS(acpi_evaluate_object(handle, NULL, NULL, &buffer))) {
3695                 obj = (union acpi_object *)buffer.pointer;
3696                 if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) {
3697                         printk(IBM_ERR "Unknown BCLL data, "
3698                                "please report this to %s\n", IBM_MAIL);
3699                         rc = 0;
3700                 } else {
3701                         rc = obj->package.count;
3702                 }
3703         } else {
3704                 return 0;
3705         }
3706
3707         kfree(buffer.pointer);
3708         return rc;
3709 }
3710
3711 static acpi_status __init brightness_find_bcll(acpi_handle handle, u32 lvl,
3712                                         void *context, void **rv)
3713 {
3714         char name[ACPI_PATH_SEGMENT_LENGTH];
3715         struct acpi_buffer buffer = { sizeof(name), &name };
3716
3717         if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer)) &&
3718             !strncmp("BCLL", name, sizeof(name) - 1)) {
3719                 if (tpacpi_query_bcll_levels(handle) == 16) {
3720                         *rv = handle;
3721                         return AE_CTRL_TERMINATE;
3722                 } else {
3723                         return AE_OK;
3724                 }
3725         } else {
3726                 return AE_OK;
3727         }
3728 }
3729
3730 static int __init brightness_check_levels(void)
3731 {
3732         int status;
3733         void *found_node = NULL;
3734
3735         if (!vid_handle) {
3736                 IBM_ACPIHANDLE_INIT(vid);
3737         }
3738         if (!vid_handle)
3739                 return 0;
3740
3741         /* Search for a BCLL package with 16 levels */
3742         status = acpi_walk_namespace(ACPI_TYPE_PACKAGE, vid_handle, 3,
3743                                         brightness_find_bcll, NULL, &found_node);
3744
3745         return (ACPI_SUCCESS(status) && found_node != NULL);
3746 }
3747
3748 static acpi_status __init brightness_find_bcl(acpi_handle handle, u32 lvl,
3749                                         void *context, void **rv)
3750 {
3751         char name[ACPI_PATH_SEGMENT_LENGTH];
3752         struct acpi_buffer buffer = { sizeof(name), &name };
3753
3754         if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer)) &&
3755             !strncmp("_BCL", name, sizeof(name) - 1)) {
3756                 *rv = handle;
3757                 return AE_CTRL_TERMINATE;
3758         } else {
3759                 return AE_OK;
3760         }
3761 }
3762
3763 static int __init brightness_check_std_acpi_support(void)
3764 {
3765         int status;
3766         void *found_node = NULL;
3767
3768         if (!vid_handle) {
3769                 IBM_ACPIHANDLE_INIT(vid);
3770         }
3771         if (!vid_handle)
3772                 return 0;
3773
3774         /* Search for a _BCL method, but don't execute it */
3775         status = acpi_walk_namespace(ACPI_TYPE_METHOD, vid_handle, 3,
3776                                      brightness_find_bcl, NULL, &found_node);
3777
3778         return (ACPI_SUCCESS(status) && found_node != NULL);
3779 }
3780
3781 static int __init brightness_init(struct ibm_init_struct *iibm)
3782 {
3783         int b;
3784
3785         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
3786
3787         mutex_init(&brightness_mutex);
3788
3789         if (!brightness_enable) {
3790                 dbg_printk(TPACPI_DBG_INIT,
3791                            "brightness support disabled by module parameter\n");
3792                 return 1;
3793         } else if (brightness_enable > 1) {
3794                 if (brightness_check_std_acpi_support()) {
3795                         printk(IBM_NOTICE
3796                                "standard ACPI backlight interface available, not loading native one...\n");
3797                         return 1;
3798                 }
3799         }
3800
3801         if (!brightness_mode) {
3802                 if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO)
3803                         brightness_mode = 2;
3804                 else
3805                         brightness_mode = 3;
3806
3807                 dbg_printk(TPACPI_DBG_INIT, "selected brightness_mode=%d\n",
3808                         brightness_mode);
3809         }
3810
3811         if (brightness_mode > 3)
3812                 return -EINVAL;
3813
3814         tp_features.bright_16levels =
3815                         thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO &&
3816                         brightness_check_levels();
3817
3818         b = brightness_get(NULL);
3819         if (b < 0)
3820                 return 1;
3821
3822         if (tp_features.bright_16levels)
3823                 printk(IBM_INFO "detected a 16-level brightness capable ThinkPad\n");
3824
3825         ibm_backlight_device = backlight_device_register(
3826                                         TPACPI_BACKLIGHT_DEV_NAME, NULL, NULL,
3827                                         &ibm_backlight_data);
3828         if (IS_ERR(ibm_backlight_device)) {
3829                 printk(IBM_ERR "Could not register backlight device\n");
3830                 return PTR_ERR(ibm_backlight_device);
3831         }
3832         vdbg_printk(TPACPI_DBG_INIT, "brightness is supported\n");
3833
3834         ibm_backlight_device->props.max_brightness =
3835                                 (tp_features.bright_16levels)? 15 : 7;
3836         ibm_backlight_device->props.brightness = b;
3837         backlight_update_status(ibm_backlight_device);
3838
3839         return 0;
3840 }
3841
3842 static void brightness_exit(void)
3843 {
3844         if (ibm_backlight_device) {
3845                 vdbg_printk(TPACPI_DBG_EXIT,
3846                             "calling backlight_device_unregister()\n");
3847                 backlight_device_unregister(ibm_backlight_device);
3848                 ibm_backlight_device = NULL;
3849         }
3850 }
3851
3852 static int brightness_update_status(struct backlight_device *bd)
3853 {
3854         /* it is the backlight class's job (caller) to handle
3855          * EINTR and other errors properly */
3856         return brightness_set(
3857                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
3858                  bd->props.power == FB_BLANK_UNBLANK) ?
3859                                 bd->props.brightness : 0);
3860 }
3861
3862 /*
3863  * ThinkPads can read brightness from two places: EC 0x31, or
3864  * CMOS NVRAM byte 0x5E, bits 0-3.
3865  */
3866 static int brightness_get(struct backlight_device *bd)
3867 {
3868         u8 lec = 0, lcmos = 0, level = 0;
3869
3870         if (brightness_mode & 1) {
3871                 if (!acpi_ec_read(brightness_offset, &lec))
3872                         return -EIO;
3873                 lec &= (tp_features.bright_16levels)? 0x0f : 0x07;
3874                 level = lec;
3875         };
3876         if (brightness_mode & 2) {
3877                 lcmos = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
3878                          & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
3879                         >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
3880                 lcmos &= (tp_features.bright_16levels)? 0x0f : 0x07;
3881                 level = lcmos;
3882         }
3883
3884         if (brightness_mode == 3 && lec != lcmos) {
3885                 printk(IBM_ERR
3886                         "CMOS NVRAM (%u) and EC (%u) do not agree "
3887                         "on display brightness level\n",
3888                         (unsigned int) lcmos,
3889                         (unsigned int) lec);
3890                 return -EIO;
3891         }
3892
3893         return level;
3894 }
3895
3896 /* May return EINTR which can always be mapped to ERESTARTSYS */
3897 static int brightness_set(int value)
3898 {
3899         int cmos_cmd, inc, i, res;
3900         int current_value;
3901
3902         if (value > ((tp_features.bright_16levels)? 15 : 7))
3903                 return -EINVAL;
3904
3905         res = mutex_lock_interruptible(&brightness_mutex);
3906         if (res < 0)
3907                 return res;
3908
3909         current_value = brightness_get(NULL);
3910         if (current_value < 0) {
3911                 res = current_value;
3912                 goto errout;
3913         }
3914
3915         cmos_cmd = value > current_value ?
3916                         TP_CMOS_BRIGHTNESS_UP :
3917                         TP_CMOS_BRIGHTNESS_DOWN;
3918         inc = (value > current_value)? 1 : -1;
3919
3920         res = 0;
3921         for (i = current_value; i != value; i += inc) {
3922                 if ((brightness_mode & 2) &&
3923                     issue_thinkpad_cmos_command(cmos_cmd)) {
3924                         res = -EIO;
3925                         goto errout;
3926                 }
3927                 if ((brightness_mode & 1) &&
3928                     !acpi_ec_write(brightness_offset, i + inc)) {
3929                         res = -EIO;
3930                         goto errout;;
3931                 }
3932         }
3933
3934 errout:
3935         mutex_unlock(&brightness_mutex);
3936         return res;
3937 }
3938
3939 static int brightness_read(char *p)
3940 {
3941         int len = 0;
3942         int level;
3943
3944         if ((level = brightness_get(NULL)) < 0) {
3945                 len += sprintf(p + len, "level:\t\tunreadable\n");
3946         } else {
3947                 len += sprintf(p + len, "level:\t\t%d\n", level);
3948                 len += sprintf(p + len, "commands:\tup, down\n");
3949                 len += sprintf(p + len, "commands:\tlevel <level>"
3950                                " (<level> is 0-%d)\n",
3951                                (tp_features.bright_16levels) ? 15 : 7);
3952         }
3953
3954         return len;
3955 }
3956
3957 static int brightness_write(char *buf)
3958 {
3959         int level;
3960         int rc;
3961         char *cmd;
3962         int max_level = (tp_features.bright_16levels) ? 15 : 7;
3963
3964         level = brightness_get(NULL);
3965         if (level < 0)
3966                 return level;
3967
3968         while ((cmd = next_cmd(&buf))) {
3969                 if (strlencmp(cmd, "up") == 0) {
3970                         if (level < max_level)
3971                                 level++;
3972                 } else if (strlencmp(cmd, "down") == 0) {
3973                         if (level > 0)
3974                                 level--;
3975                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
3976                            level >= 0 && level <= max_level) {
3977                         /* new level set */
3978                 } else
3979                         return -EINVAL;
3980         }
3981
3982         /*
3983          * Now we know what the final level should be, so we try to set it.
3984          * Doing it this way makes the syscall restartable in case of EINTR
3985          */
3986         rc = brightness_set(level);
3987         return (rc == -EINTR)? ERESTARTSYS : rc;
3988 }
3989
3990 static struct ibm_struct brightness_driver_data = {
3991         .name = "brightness",
3992         .read = brightness_read,
3993         .write = brightness_write,
3994         .exit = brightness_exit,
3995 };
3996
3997 /*************************************************************************
3998  * Volume subdriver
3999  */
4000
4001 static int volume_read(char *p)
4002 {
4003         int len = 0;
4004         u8 level;
4005
4006         if (!acpi_ec_read(volume_offset, &level)) {
4007                 len += sprintf(p + len, "level:\t\tunreadable\n");
4008         } else {
4009                 len += sprintf(p + len, "level:\t\t%d\n", level & 0xf);
4010                 len += sprintf(p + len, "mute:\t\t%s\n", onoff(level, 6));
4011                 len += sprintf(p + len, "commands:\tup, down, mute\n");
4012                 len += sprintf(p + len, "commands:\tlevel <level>"
4013                                " (<level> is 0-15)\n");
4014         }
4015
4016         return len;
4017 }
4018
4019 static int volume_write(char *buf)
4020 {
4021         int cmos_cmd, inc, i;
4022         u8 level, mute;
4023         int new_level, new_mute;
4024         char *cmd;
4025
4026         while ((cmd = next_cmd(&buf))) {
4027                 if (!acpi_ec_read(volume_offset, &level))
4028                         return -EIO;
4029                 new_mute = mute = level & 0x40;
4030                 new_level = level = level & 0xf;
4031
4032                 if (strlencmp(cmd, "up") == 0) {
4033                         if (mute)
4034                                 new_mute = 0;
4035                         else
4036                                 new_level = level == 15 ? 15 : level + 1;
4037                 } else if (strlencmp(cmd, "down") == 0) {
4038                         if (mute)
4039                                 new_mute = 0;
4040                         else
4041                                 new_level = level == 0 ? 0 : level - 1;
4042                 } else if (sscanf(cmd, "level %d", &new_level) == 1 &&
4043                            new_level >= 0 && new_level <= 15) {
4044                         /* new_level set */
4045                 } else if (strlencmp(cmd, "mute") == 0) {
4046                         new_mute = 0x40;
4047                 } else
4048                         return -EINVAL;
4049
4050                 if (new_level != level) {       /* mute doesn't change */
4051                         cmos_cmd = new_level > level ? TP_CMOS_VOLUME_UP : TP_CMOS_VOLUME_DOWN;
4052                         inc = new_level > level ? 1 : -1;
4053
4054                         if (mute && (issue_thinkpad_cmos_command(cmos_cmd) ||
4055                                      !acpi_ec_write(volume_offset, level)))
4056                                 return -EIO;
4057
4058                         for (i = level; i != new_level; i += inc)
4059                                 if (issue_thinkpad_cmos_command(cmos_cmd) ||
4060                                     !acpi_ec_write(volume_offset, i + inc))
4061                                         return -EIO;
4062
4063                         if (mute && (issue_thinkpad_cmos_command(TP_CMOS_VOLUME_MUTE) ||
4064                                      !acpi_ec_write(volume_offset,
4065                                                     new_level + mute)))
4066                                 return -EIO;
4067                 }
4068
4069                 if (new_mute != mute) { /* level doesn't change */
4070                         cmos_cmd = new_mute ? TP_CMOS_VOLUME_MUTE : TP_CMOS_VOLUME_UP;
4071
4072                         if (issue_thinkpad_cmos_command(cmos_cmd) ||
4073                             !acpi_ec_write(volume_offset, level + new_mute))
4074                                 return -EIO;
4075                 }
4076         }
4077
4078         return 0;
4079 }
4080
4081 static struct ibm_struct volume_driver_data = {
4082         .name = "volume",
4083         .read = volume_read,
4084         .write = volume_write,
4085 };
4086
4087 /*************************************************************************
4088  * Fan subdriver
4089  */
4090
4091 /*
4092  * FAN ACCESS MODES
4093  *
4094  * TPACPI_FAN_RD_ACPI_GFAN:
4095  *      ACPI GFAN method: returns fan level
4096  *
4097  *      see TPACPI_FAN_WR_ACPI_SFAN
4098  *      EC 0x2f (HFSP) not available if GFAN exists
4099  *
4100  * TPACPI_FAN_WR_ACPI_SFAN:
4101  *      ACPI SFAN method: sets fan level, 0 (stop) to 7 (max)
4102  *
4103  *      EC 0x2f (HFSP) might be available *for reading*, but do not use
4104  *      it for writing.
4105  *
4106  * TPACPI_FAN_WR_TPEC:
4107  *      ThinkPad EC register 0x2f (HFSP): fan control loop mode
4108  *      Supported on almost all ThinkPads
4109  *
4110  *      Fan speed changes of any sort (including those caused by the
4111  *      disengaged mode) are usually done slowly by the firmware as the
4112  *      maximum ammount of fan duty cycle change per second seems to be
4113  *      limited.
4114  *
4115  *      Reading is not available if GFAN exists.
4116  *      Writing is not available if SFAN exists.
4117  *
4118  *      Bits
4119  *       7      automatic mode engaged;
4120  *              (default operation mode of the ThinkPad)
4121  *              fan level is ignored in this mode.
4122  *       6      full speed mode (takes precedence over bit 7);
4123  *              not available on all thinkpads.  May disable
4124  *              the tachometer while the fan controller ramps up
4125  *              the speed (which can take up to a few *minutes*).
4126  *              Speeds up fan to 100% duty-cycle, which is far above
4127  *              the standard RPM levels.  It is not impossible that
4128  *              it could cause hardware damage.
4129  *      5-3     unused in some models.  Extra bits for fan level
4130  *              in others, but still useless as all values above
4131  *              7 map to the same speed as level 7 in these models.
4132  *      2-0     fan level (0..7 usually)
4133  *                      0x00 = stop
4134  *                      0x07 = max (set when temperatures critical)
4135  *              Some ThinkPads may have other levels, see
4136  *              TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41)
4137  *
4138  *      FIRMWARE BUG: on some models, EC 0x2f might not be initialized at
4139  *      boot. Apparently the EC does not intialize it, so unless ACPI DSDT
4140  *      does so, its initial value is meaningless (0x07).
4141  *
4142  *      For firmware bugs, refer to:
4143  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
4144  *
4145  *      ----
4146  *
4147  *      ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
4148  *      Main fan tachometer reading (in RPM)
4149  *
4150  *      This register is present on all ThinkPads with a new-style EC, and
4151  *      it is known not to be present on the A21m/e, and T22, as there is
4152  *      something else in offset 0x84 according to the ACPI DSDT.  Other
4153  *      ThinkPads from this same time period (and earlier) probably lack the
4154  *      tachometer as well.
4155  *
4156  *      Unfortunately a lot of ThinkPads with new-style ECs but whose firwmare
4157  *      was never fixed by IBM to report the EC firmware version string
4158  *      probably support the tachometer (like the early X models), so
4159  *      detecting it is quite hard.  We need more data to know for sure.
4160  *
4161  *      FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
4162  *      might result.
4163  *
4164  *      FIRMWARE BUG: may go stale while the EC is switching to full speed
4165  *      mode.
4166  *
4167  *      For firmware bugs, refer to:
4168  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
4169  *
4170  * TPACPI_FAN_WR_ACPI_FANS:
4171  *      ThinkPad X31, X40, X41.  Not available in the X60.
4172  *
4173  *      FANS ACPI handle: takes three arguments: low speed, medium speed,
4174  *      high speed.  ACPI DSDT seems to map these three speeds to levels
4175  *      as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH
4176  *      (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3")
4177  *
4178  *      The speeds are stored on handles
4179  *      (FANA:FAN9), (FANC:FANB), (FANE:FAND).
4180  *
4181  *      There are three default speed sets, acessible as handles:
4182  *      FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H
4183  *
4184  *      ACPI DSDT switches which set is in use depending on various
4185  *      factors.
4186  *
4187  *      TPACPI_FAN_WR_TPEC is also available and should be used to
4188  *      command the fan.  The X31/X40/X41 seems to have 8 fan levels,
4189  *      but the ACPI tables just mention level 7.
4190  */
4191
4192 static enum fan_status_access_mode fan_status_access_mode;
4193 static enum fan_control_access_mode fan_control_access_mode;
4194 static enum fan_control_commands fan_control_commands;
4195
4196 static u8 fan_control_initial_status;
4197 static u8 fan_control_desired_level;
4198
4199 static void fan_watchdog_fire(struct work_struct *ignored);
4200 static int fan_watchdog_maxinterval;
4201 static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire);
4202
4203 IBM_HANDLE(fans, ec, "FANS");   /* X31, X40, X41 */
4204 IBM_HANDLE(gfan, ec, "GFAN",    /* 570 */
4205            "\\FSPD",            /* 600e/x, 770e, 770x */
4206            );                   /* all others */
4207 IBM_HANDLE(sfan, ec, "SFAN",    /* 570 */
4208            "JFNS",              /* 770x-JL */
4209            );                   /* all others */
4210
4211 /*
4212  * SYSFS fan layout: hwmon compatible (device)
4213  *
4214  * pwm*_enable:
4215  *      0: "disengaged" mode
4216  *      1: manual mode
4217  *      2: native EC "auto" mode (recommended, hardware default)
4218  *
4219  * pwm*: set speed in manual mode, ignored otherwise.
4220  *      0 is level 0; 255 is level 7. Intermediate points done with linear
4221  *      interpolation.
4222  *
4223  * fan*_input: tachometer reading, RPM
4224  *
4225  *
4226  * SYSFS fan layout: extensions
4227  *
4228  * fan_watchdog (driver):
4229  *      fan watchdog interval in seconds, 0 disables (default), max 120
4230  */
4231
4232 /* sysfs fan pwm1_enable ----------------------------------------------- */
4233 static ssize_t fan_pwm1_enable_show(struct device *dev,
4234                                     struct device_attribute *attr,
4235                                     char *buf)
4236 {
4237         int res, mode;
4238         u8 status;
4239
4240         res = fan_get_status_safe(&status);
4241         if (res)
4242                 return res;
4243
4244         if (unlikely(tp_features.fan_ctrl_status_undef)) {
4245                 if (status != fan_control_initial_status) {
4246                         tp_features.fan_ctrl_status_undef = 0;
4247                 } else {
4248                         /* Return most likely status. In fact, it
4249                          * might be the only possible status */
4250                         status = TP_EC_FAN_AUTO;
4251                 }
4252         }
4253
4254         if (status & TP_EC_FAN_FULLSPEED) {
4255                 mode = 0;
4256         } else if (status & TP_EC_FAN_AUTO) {
4257                 mode = 2;
4258         } else
4259                 mode = 1;
4260
4261         return snprintf(buf, PAGE_SIZE, "%d\n", mode);
4262 }
4263
4264 static ssize_t fan_pwm1_enable_store(struct device *dev,
4265                                      struct device_attribute *attr,
4266                                      const char *buf, size_t count)
4267 {
4268         unsigned long t;
4269         int res, level;
4270
4271         if (parse_strtoul(buf, 2, &t))
4272                 return -EINVAL;
4273
4274         switch (t) {
4275         case 0:
4276                 level = TP_EC_FAN_FULLSPEED;
4277                 break;
4278         case 1:
4279                 level = TPACPI_FAN_LAST_LEVEL;
4280                 break;
4281         case 2:
4282                 level = TP_EC_FAN_AUTO;
4283                 break;
4284         case 3:
4285                 /* reserved for software-controlled auto mode */
4286                 return -ENOSYS;
4287         default:
4288                 return -EINVAL;
4289         }
4290
4291         res = fan_set_level_safe(level);
4292         if (res == -ENXIO)
4293                 return -EINVAL;
4294         else if (res < 0)
4295                 return res;
4296
4297         fan_watchdog_reset();
4298
4299         return count;
4300 }
4301
4302 static struct device_attribute dev_attr_fan_pwm1_enable =
4303         __ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
4304                 fan_pwm1_enable_show, fan_pwm1_enable_store);
4305
4306 /* sysfs fan pwm1 ------------------------------------------------------ */
4307 static ssize_t fan_pwm1_show(struct device *dev,
4308                              struct device_attribute *attr,
4309                              char *buf)
4310 {
4311         int res;
4312         u8 status;
4313
4314         res = fan_get_status_safe(&status);
4315         if (res)
4316                 return res;
4317
4318         if (unlikely(tp_features.fan_ctrl_status_undef)) {
4319                 if (status != fan_control_initial_status) {
4320                         tp_features.fan_ctrl_status_undef = 0;
4321                 } else {
4322                         status = TP_EC_FAN_AUTO;
4323                 }
4324         }
4325
4326         if ((status &
4327              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0)
4328                 status = fan_control_desired_level;
4329
4330         if (status > 7)
4331                 status = 7;
4332
4333         return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7);
4334 }
4335
4336 static ssize_t fan_pwm1_store(struct device *dev,
4337                               struct device_attribute *attr,
4338                               const char *buf, size_t count)
4339 {
4340         unsigned long s;
4341         int rc;
4342         u8 status, newlevel;
4343
4344         if (parse_strtoul(buf, 255, &s))
4345                 return -EINVAL;
4346
4347         /* scale down from 0-255 to 0-7 */
4348         newlevel = (s >> 5) & 0x07;
4349
4350         if (mutex_lock_interruptible(&fan_mutex))
4351                 return -ERESTARTSYS;
4352
4353         rc = fan_get_status(&status);
4354         if (!rc && (status &
4355                     (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
4356                 rc = fan_set_level(newlevel);
4357                 if (rc == -ENXIO)
4358                         rc = -EINVAL;
4359                 else if (!rc) {
4360                         fan_update_desired_level(newlevel);
4361                         fan_watchdog_reset();
4362                 }
4363         }
4364
4365         mutex_unlock(&fan_mutex);
4366         return (rc)? rc : count;
4367 }
4368
4369 static struct device_attribute dev_attr_fan_pwm1 =
4370         __ATTR(pwm1, S_IWUSR | S_IRUGO,
4371                 fan_pwm1_show, fan_pwm1_store);
4372
4373 /* sysfs fan fan1_input ------------------------------------------------ */
4374 static ssize_t fan_fan1_input_show(struct device *dev,
4375                            struct device_attribute *attr,
4376                            char *buf)
4377 {
4378         int res;
4379         unsigned int speed;
4380
4381         res = fan_get_speed(&speed);
4382         if (res < 0)
4383                 return res;
4384
4385         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
4386 }
4387
4388 static struct device_attribute dev_attr_fan_fan1_input =
4389         __ATTR(fan1_input, S_IRUGO,
4390                 fan_fan1_input_show, NULL);
4391
4392 /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */
4393 static ssize_t fan_fan_watchdog_show(struct device_driver *drv,
4394                                      char *buf)
4395 {
4396         return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval);
4397 }
4398
4399 static ssize_t fan_fan_watchdog_store(struct device_driver *drv,
4400                                       const char *buf, size_t count)
4401 {
4402         unsigned long t;
4403
4404         if (parse_strtoul(buf, 120, &t))
4405                 return -EINVAL;
4406
4407         if (!fan_control_allowed)
4408                 return -EPERM;
4409
4410         fan_watchdog_maxinterval = t;
4411         fan_watchdog_reset();
4412
4413         return count;
4414 }
4415
4416 static DRIVER_ATTR(fan_watchdog, S_IWUSR | S_IRUGO,
4417                 fan_fan_watchdog_show, fan_fan_watchdog_store);
4418
4419 /* --------------------------------------------------------------------- */
4420 static struct attribute *fan_attributes[] = {
4421         &dev_attr_fan_pwm1_enable.attr, &dev_attr_fan_pwm1.attr,
4422         &dev_attr_fan_fan1_input.attr,
4423         NULL
4424 };
4425
4426 static const struct attribute_group fan_attr_group = {
4427         .attrs = fan_attributes,
4428 };
4429
4430 static int __init fan_init(struct ibm_init_struct *iibm)
4431 {
4432         int rc;
4433
4434         vdbg_printk(TPACPI_DBG_INIT, "initializing fan subdriver\n");
4435
4436         mutex_init(&fan_mutex);
4437         fan_status_access_mode = TPACPI_FAN_NONE;
4438         fan_control_access_mode = TPACPI_FAN_WR_NONE;
4439         fan_control_commands = 0;
4440         fan_watchdog_maxinterval = 0;
4441         tp_features.fan_ctrl_status_undef = 0;
4442         fan_control_desired_level = 7;
4443
4444         IBM_ACPIHANDLE_INIT(fans);
4445         IBM_ACPIHANDLE_INIT(gfan);
4446         IBM_ACPIHANDLE_INIT(sfan);
4447
4448         if (gfan_handle) {
4449                 /* 570, 600e/x, 770e, 770x */
4450                 fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN;
4451         } else {
4452                 /* all other ThinkPads: note that even old-style
4453                  * ThinkPad ECs supports the fan control register */
4454                 if (likely(acpi_ec_read(fan_status_offset,
4455                                         &fan_control_initial_status))) {
4456                         fan_status_access_mode = TPACPI_FAN_RD_TPEC;
4457
4458                         /* In some ThinkPads, neither the EC nor the ACPI
4459                          * DSDT initialize the fan status, and it ends up
4460                          * being set to 0x07 when it *could* be either
4461                          * 0x07 or 0x80.
4462                          *
4463                          * Enable for TP-1Y (T43), TP-78 (R51e),
4464                          * TP-76 (R52), TP-70 (T43, R52), which are known
4465                          * to be buggy. */
4466                         if (fan_control_initial_status == 0x07) {
4467                                 switch (thinkpad_id.ec_model) {
4468                                 case 0x5931: /* TP-1Y */
4469                                 case 0x3837: /* TP-78 */
4470                                 case 0x3637: /* TP-76 */
4471                                 case 0x3037: /* TP-70 */
4472                                         printk(IBM_NOTICE
4473                                                "fan_init: initial fan status is "
4474                                                "unknown, assuming it is in auto "
4475                                                "mode\n");
4476                                         tp_features.fan_ctrl_status_undef = 1;
4477                                         ;;
4478                                 }
4479                         }
4480                 } else {
4481                         printk(IBM_ERR
4482                                "ThinkPad ACPI EC access misbehaving, "
4483                                "fan status and control unavailable\n");
4484                         return 1;
4485                 }
4486         }
4487
4488         if (sfan_handle) {
4489                 /* 570, 770x-JL */
4490                 fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN;
4491                 fan_control_commands |=
4492                     TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE;
4493         } else {
4494                 if (!gfan_handle) {
4495                         /* gfan without sfan means no fan control */
4496                         /* all other models implement TP EC 0x2f control */
4497
4498                         if (fans_handle) {
4499                                 /* X31, X40, X41 */
4500                                 fan_control_access_mode =
4501                                     TPACPI_FAN_WR_ACPI_FANS;
4502                                 fan_control_commands |=
4503                                     TPACPI_FAN_CMD_SPEED |
4504                                     TPACPI_FAN_CMD_LEVEL |
4505                                     TPACPI_FAN_CMD_ENABLE;
4506                         } else {
4507                                 fan_control_access_mode = TPACPI_FAN_WR_TPEC;
4508                                 fan_control_commands |=
4509                                     TPACPI_FAN_CMD_LEVEL |
4510                                     TPACPI_FAN_CMD_ENABLE;
4511                         }
4512                 }
4513         }
4514
4515         vdbg_printk(TPACPI_DBG_INIT, "fan is %s, modes %d, %d\n",
4516                 str_supported(fan_status_access_mode != TPACPI_FAN_NONE ||
4517                   fan_control_access_mode != TPACPI_FAN_WR_NONE),
4518                 fan_status_access_mode, fan_control_access_mode);
4519
4520         /* fan control master switch */
4521         if (!fan_control_allowed) {
4522                 fan_control_access_mode = TPACPI_FAN_WR_NONE;
4523                 fan_control_commands = 0;
4524                 dbg_printk(TPACPI_DBG_INIT,
4525                            "fan control features disabled by parameter\n");
4526         }
4527
4528         /* update fan_control_desired_level */
4529         if (fan_status_access_mode != TPACPI_FAN_NONE)
4530                 fan_get_status_safe(NULL);
4531
4532         if (fan_status_access_mode != TPACPI_FAN_NONE ||
4533             fan_control_access_mode != TPACPI_FAN_WR_NONE) {
4534                 rc = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
4535                                          &fan_attr_group);
4536                 if (!(rc < 0))
4537                         rc = driver_create_file(&tpacpi_hwmon_pdriver.driver,
4538                                         &driver_attr_fan_watchdog);
4539                 if (rc < 0)
4540                         return rc;
4541                 return 0;
4542         } else
4543                 return 1;
4544 }
4545
4546 /*
4547  * Call with fan_mutex held
4548  */
4549 static void fan_update_desired_level(u8 status)
4550 {
4551         if ((status &
4552              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
4553                 if (status > 7)
4554                         fan_control_desired_level = 7;
4555                 else
4556                         fan_control_desired_level = status;
4557         }
4558 }
4559
4560 static int fan_get_status(u8 *status)
4561 {
4562         u8 s;
4563
4564         /* TODO:
4565          * Add TPACPI_FAN_RD_ACPI_FANS ? */
4566
4567         switch (fan_status_access_mode) {
4568         case TPACPI_FAN_RD_ACPI_GFAN:
4569                 /* 570, 600e/x, 770e, 770x */
4570
4571                 if (unlikely(!acpi_evalf(gfan_handle, &s, NULL, "d")))
4572                         return -EIO;
4573
4574                 if (likely(status))
4575                         *status = s & 0x07;
4576
4577                 break;
4578
4579         case TPACPI_FAN_RD_TPEC:
4580                 /* all except 570, 600e/x, 770e, 770x */
4581                 if (unlikely(!acpi_ec_read(fan_status_offset, &s)))
4582                         return -EIO;
4583
4584                 if (likely(status))
4585                         *status = s;
4586
4587                 break;
4588
4589         default:
4590                 return -ENXIO;
4591         }
4592
4593         return 0;
4594 }
4595
4596 static int fan_get_status_safe(u8 *status)
4597 {
4598         int rc;
4599         u8 s;
4600
4601         if (mutex_lock_interruptible(&fan_mutex))
4602                 return -ERESTARTSYS;
4603         rc = fan_get_status(&s);
4604         if (!rc)
4605                 fan_update_desired_level(s);
4606         mutex_unlock(&fan_mutex);
4607
4608         if (status)
4609                 *status = s;
4610
4611         return rc;
4612 }
4613
4614 static void fan_exit(void)
4615 {
4616         vdbg_printk(TPACPI_DBG_EXIT, "cancelling any pending fan watchdog tasks\n");
4617
4618         /* FIXME: can we really do this unconditionally? */
4619         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group);
4620         driver_remove_file(&tpacpi_hwmon_pdriver.driver, &driver_attr_fan_watchdog);
4621
4622         cancel_delayed_work(&fan_watchdog_task);
4623         flush_scheduled_work();
4624 }
4625
4626 static int fan_get_speed(unsigned int *speed)
4627 {
4628         u8 hi, lo;
4629
4630         switch (fan_status_access_mode) {
4631         case TPACPI_FAN_RD_TPEC:
4632                 /* all except 570, 600e/x, 770e, 770x */
4633                 if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) ||
4634                              !acpi_ec_read(fan_rpm_offset + 1, &hi)))
4635                         return -EIO;
4636
4637                 if (likely(speed))
4638                         *speed = (hi << 8) | lo;
4639
4640                 break;
4641
4642         default:
4643                 return -ENXIO;
4644         }
4645
4646         return 0;
4647 }
4648
4649 static void fan_watchdog_fire(struct work_struct *ignored)
4650 {
4651         int rc;
4652
4653         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
4654                 return;
4655
4656         printk(IBM_NOTICE "fan watchdog: enabling fan\n");
4657         rc = fan_set_enable();
4658         if (rc < 0) {
4659                 printk(IBM_ERR "fan watchdog: error %d while enabling fan, "
4660                         "will try again later...\n", -rc);
4661                 /* reschedule for later */
4662                 fan_watchdog_reset();
4663         }
4664 }
4665
4666 static void fan_watchdog_reset(void)
4667 {
4668         static int fan_watchdog_active;
4669
4670         if (fan_control_access_mode == TPACPI_FAN_WR_NONE)
4671                 return;
4672
4673         if (fan_watchdog_active)
4674                 cancel_delayed_work(&fan_watchdog_task);
4675
4676         if (fan_watchdog_maxinterval > 0 &&
4677             tpacpi_lifecycle != TPACPI_LIFE_EXITING) {
4678                 fan_watchdog_active = 1;
4679                 if (!schedule_delayed_work(&fan_watchdog_task,
4680                                 msecs_to_jiffies(fan_watchdog_maxinterval
4681                                                  * 1000))) {
4682                         printk(IBM_ERR "failed to schedule the fan watchdog, "
4683                                "watchdog will not trigger\n");
4684                 }
4685         } else
4686                 fan_watchdog_active = 0;
4687 }
4688
4689 static int fan_set_level(int level)
4690 {
4691         if (!fan_control_allowed)
4692                 return -EPERM;
4693
4694         switch (fan_control_access_mode) {
4695         case TPACPI_FAN_WR_ACPI_SFAN:
4696                 if (level >= 0 && level <= 7) {
4697                         if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level))
4698                                 return -EIO;
4699                 } else
4700                         return -EINVAL;
4701                 break;
4702
4703         case TPACPI_FAN_WR_ACPI_FANS:
4704         case TPACPI_FAN_WR_TPEC:
4705                 if ((level != TP_EC_FAN_AUTO) &&
4706                     (level != TP_EC_FAN_FULLSPEED) &&
4707                     ((level < 0) || (level > 7)))
4708                         return -EINVAL;
4709
4710                 /* safety net should the EC not support AUTO
4711                  * or FULLSPEED mode bits and just ignore them */
4712                 if (level & TP_EC_FAN_FULLSPEED)
4713                         level |= 7;     /* safety min speed 7 */
4714                 else if (level & TP_EC_FAN_FULLSPEED)
4715                         level |= 4;     /* safety min speed 4 */
4716
4717                 if (!acpi_ec_write(fan_status_offset, level))
4718                         return -EIO;
4719                 else
4720                         tp_features.fan_ctrl_status_undef = 0;
4721                 break;
4722
4723         default:
4724                 return -ENXIO;
4725         }
4726         return 0;
4727 }
4728
4729 static int fan_set_level_safe(int level)
4730 {
4731         int rc;
4732
4733         if (!fan_control_allowed)
4734                 return -EPERM;
4735
4736         if (mutex_lock_interruptible(&fan_mutex))
4737                 return -ERESTARTSYS;
4738
4739         if (level == TPACPI_FAN_LAST_LEVEL)
4740                 level = fan_control_desired_level;
4741
4742         rc = fan_set_level(level);
4743         if (!rc)
4744                 fan_update_desired_level(level);
4745
4746         mutex_unlock(&fan_mutex);
4747         return rc;
4748 }
4749
4750 static int fan_set_enable(void)
4751 {
4752         u8 s;
4753         int rc;
4754
4755         if (!fan_control_allowed)
4756                 return -EPERM;
4757
4758         if (mutex_lock_interruptible(&fan_mutex))
4759                 return -ERESTARTSYS;
4760
4761         switch (fan_control_access_mode) {
4762         case TPACPI_FAN_WR_ACPI_FANS:
4763         case TPACPI_FAN_WR_TPEC:
4764                 rc = fan_get_status(&s);
4765                 if (rc < 0)
4766                         break;
4767
4768                 /* Don't go out of emergency fan mode */
4769                 if (s != 7) {
4770                         s &= 0x07;
4771                         s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */
4772                 }
4773
4774                 if (!acpi_ec_write(fan_status_offset, s))
4775                         rc = -EIO;
4776                 else {
4777                         tp_features.fan_ctrl_status_undef = 0;
4778                         rc = 0;
4779                 }
4780                 break;
4781
4782         case TPACPI_FAN_WR_ACPI_SFAN:
4783                 rc = fan_get_status(&s);
4784                 if (rc < 0)
4785                         break;
4786
4787                 s &= 0x07;
4788
4789                 /* Set fan to at least level 4 */
4790                 s |= 4;
4791
4792                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s))
4793                         rc= -EIO;
4794                 else
4795                         rc = 0;
4796                 break;
4797
4798         default:
4799                 rc = -ENXIO;
4800         }
4801
4802         mutex_unlock(&fan_mutex);
4803         return rc;
4804 }
4805
4806 static int fan_set_disable(void)
4807 {
4808         int rc;
4809
4810         if (!fan_control_allowed)
4811                 return -EPERM;
4812
4813         if (mutex_lock_interruptible(&fan_mutex))
4814                 return -ERESTARTSYS;
4815
4816         rc = 0;
4817         switch (fan_control_access_mode) {
4818         case TPACPI_FAN_WR_ACPI_FANS:
4819         case TPACPI_FAN_WR_TPEC:
4820                 if (!acpi_ec_write(fan_status_offset, 0x00))
4821                         rc = -EIO;
4822                 else {
4823                         fan_control_desired_level = 0;
4824                         tp_features.fan_ctrl_status_undef = 0;
4825                 }
4826                 break;
4827
4828         case TPACPI_FAN_WR_ACPI_SFAN:
4829                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00))
4830                         rc = -EIO;
4831                 else
4832                         fan_control_desired_level = 0;
4833                 break;
4834
4835         default:
4836                 rc = -ENXIO;
4837         }
4838
4839
4840         mutex_unlock(&fan_mutex);
4841         return rc;
4842 }
4843
4844 static int fan_set_speed(int speed)
4845 {
4846         int rc;
4847
4848         if (!fan_control_allowed)
4849                 return -EPERM;
4850
4851         if (mutex_lock_interruptible(&fan_mutex))
4852                 return -ERESTARTSYS;
4853
4854         rc = 0;
4855         switch (fan_control_access_mode) {
4856         case TPACPI_FAN_WR_ACPI_FANS:
4857                 if (speed >= 0 && speed <= 65535) {
4858                         if (!acpi_evalf(fans_handle, NULL, NULL, "vddd",
4859                                         speed, speed, speed))
4860                                 rc = -EIO;
4861                 } else
4862                         rc = -EINVAL;
4863                 break;
4864
4865         default:
4866                 rc = -ENXIO;
4867         }
4868
4869         mutex_unlock(&fan_mutex);
4870         return rc;
4871 }
4872
4873 static int fan_read(char *p)
4874 {
4875         int len = 0;
4876         int rc;
4877         u8 status;
4878         unsigned int speed = 0;
4879
4880         switch (fan_status_access_mode) {
4881         case TPACPI_FAN_RD_ACPI_GFAN:
4882                 /* 570, 600e/x, 770e, 770x */
4883                 if ((rc = fan_get_status_safe(&status)) < 0)
4884                         return rc;
4885
4886                 len += sprintf(p + len, "status:\t\t%s\n"
4887                                "level:\t\t%d\n",
4888                                (status != 0) ? "enabled" : "disabled", status);
4889                 break;
4890
4891         case TPACPI_FAN_RD_TPEC:
4892                 /* all except 570, 600e/x, 770e, 770x */
4893                 if ((rc = fan_get_status_safe(&status)) < 0)
4894                         return rc;
4895
4896                 if (unlikely(tp_features.fan_ctrl_status_undef)) {
4897                         if (status != fan_control_initial_status)
4898                                 tp_features.fan_ctrl_status_undef = 0;
4899                         else
4900                                 /* Return most likely status. In fact, it
4901                                  * might be the only possible status */
4902                                 status = TP_EC_FAN_AUTO;
4903                 }
4904
4905                 len += sprintf(p + len, "status:\t\t%s\n",
4906                                (status != 0) ? "enabled" : "disabled");
4907
4908                 if ((rc = fan_get_speed(&speed)) < 0)
4909                         return rc;
4910
4911                 len += sprintf(p + len, "speed:\t\t%d\n", speed);
4912
4913                 if (status & TP_EC_FAN_FULLSPEED)
4914                         /* Disengaged mode takes precedence */
4915                         len += sprintf(p + len, "level:\t\tdisengaged\n");
4916                 else if (status & TP_EC_FAN_AUTO)
4917                         len += sprintf(p + len, "level:\t\tauto\n");
4918                 else
4919                         len += sprintf(p + len, "level:\t\t%d\n", status);
4920                 break;
4921
4922         case TPACPI_FAN_NONE:
4923         default:
4924                 len += sprintf(p + len, "status:\t\tnot supported\n");
4925         }
4926
4927         if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) {
4928                 len += sprintf(p + len, "commands:\tlevel <level>");
4929
4930                 switch (fan_control_access_mode) {
4931                 case TPACPI_FAN_WR_ACPI_SFAN:
4932                         len += sprintf(p + len, " (<level> is 0-7)\n");
4933                         break;
4934
4935                 default:
4936                         len += sprintf(p + len, " (<level> is 0-7, "
4937                                        "auto, disengaged, full-speed)\n");
4938                         break;
4939                 }
4940         }
4941
4942         if (fan_control_commands & TPACPI_FAN_CMD_ENABLE)
4943                 len += sprintf(p + len, "commands:\tenable, disable\n"
4944                                "commands:\twatchdog <timeout> (<timeout> is 0 (off), "
4945                                "1-120 (seconds))\n");
4946
4947         if (fan_control_commands & TPACPI_FAN_CMD_SPEED)
4948                 len += sprintf(p + len, "commands:\tspeed <speed>"
4949                                " (<speed> is 0-65535)\n");
4950
4951         return len;
4952 }
4953
4954 static int fan_write_cmd_level(const char *cmd, int *rc)
4955 {
4956         int level;
4957
4958         if (strlencmp(cmd, "level auto") == 0)
4959                 level = TP_EC_FAN_AUTO;
4960         else if ((strlencmp(cmd, "level disengaged") == 0) |
4961                  (strlencmp(cmd, "level full-speed") == 0))
4962                 level = TP_EC_FAN_FULLSPEED;
4963         else if (sscanf(cmd, "level %d", &level) != 1)
4964                 return 0;
4965
4966         if ((*rc = fan_set_level_safe(level)) == -ENXIO)
4967                 printk(IBM_ERR "level command accepted for unsupported "
4968                        "access mode %d", fan_control_access_mode);
4969
4970         return 1;
4971 }
4972
4973 static int fan_write_cmd_enable(const char *cmd, int *rc)
4974 {
4975         if (strlencmp(cmd, "enable") != 0)
4976                 return 0;
4977
4978         if ((*rc = fan_set_enable()) == -ENXIO)
4979                 printk(IBM_ERR "enable command accepted for unsupported "
4980                        "access mode %d", fan_control_access_mode);
4981
4982         return 1;
4983 }
4984
4985 static int fan_write_cmd_disable(const char *cmd, int *rc)
4986 {
4987         if (strlencmp(cmd, "disable") != 0)
4988                 return 0;
4989
4990         if ((*rc = fan_set_disable()) == -ENXIO)
4991                 printk(IBM_ERR "disable command accepted for unsupported "
4992                        "access mode %d", fan_control_access_mode);
4993
4994         return 1;
4995 }
4996
4997 static int fan_write_cmd_speed(const char *cmd, int *rc)
4998 {
4999         int speed;
5000
5001         /* TODO:
5002          * Support speed <low> <medium> <high> ? */
5003
5004         if (sscanf(cmd, "speed %d", &speed) != 1)
5005                 return 0;
5006
5007         if ((*rc = fan_set_speed(speed)) == -ENXIO)
5008                 printk(IBM_ERR "speed command accepted for unsupported "
5009                        "access mode %d", fan_control_access_mode);
5010
5011         return 1;
5012 }
5013
5014 static int fan_write_cmd_watchdog(const char *cmd, int *rc)
5015 {
5016         int interval;
5017
5018         if (sscanf(cmd, "watchdog %d", &interval) != 1)
5019                 return 0;
5020
5021         if (interval < 0 || interval > 120)
5022                 *rc = -EINVAL;
5023         else
5024                 fan_watchdog_maxinterval = interval;
5025
5026         return 1;
5027 }
5028
5029 static int fan_write(char *buf)
5030 {
5031         char *cmd;
5032         int rc = 0;
5033
5034         while (!rc && (cmd = next_cmd(&buf))) {
5035                 if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) &&
5036                       fan_write_cmd_level(cmd, &rc)) &&
5037                     !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) &&
5038                       (fan_write_cmd_enable(cmd, &rc) ||
5039                        fan_write_cmd_disable(cmd, &rc) ||
5040                        fan_write_cmd_watchdog(cmd, &rc))) &&
5041                     !((fan_control_commands & TPACPI_FAN_CMD_SPEED) &&
5042                       fan_write_cmd_speed(cmd, &rc))
5043                     )
5044                         rc = -EINVAL;
5045                 else if (!rc)
5046                         fan_watchdog_reset();
5047         }
5048
5049         return rc;
5050 }
5051
5052 static struct ibm_struct fan_driver_data = {
5053         .name = "fan",
5054         .read = fan_read,
5055         .write = fan_write,
5056         .exit = fan_exit,
5057 };
5058
5059 /****************************************************************************
5060  ****************************************************************************
5061  *
5062  * Infrastructure
5063  *
5064  ****************************************************************************
5065  ****************************************************************************/
5066
5067 /* sysfs name ---------------------------------------------------------- */
5068 static ssize_t thinkpad_acpi_pdev_name_show(struct device *dev,
5069                            struct device_attribute *attr,
5070                            char *buf)
5071 {
5072         return snprintf(buf, PAGE_SIZE, "%s\n", IBM_NAME);
5073 }
5074
5075 static struct device_attribute dev_attr_thinkpad_acpi_pdev_name =
5076         __ATTR(name, S_IRUGO, thinkpad_acpi_pdev_name_show, NULL);
5077
5078 /* --------------------------------------------------------------------- */
5079
5080 /* /proc support */
5081 static struct proc_dir_entry *proc_dir;
5082
5083 /* Subdriver registry */
5084 static LIST_HEAD(tpacpi_all_drivers);
5085
5086
5087 /*
5088  * Module and infrastructure proble, init and exit handling
5089  */
5090
5091 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
5092 static const char * __init str_supported(int is_supported)
5093 {
5094         static char text_unsupported[] __initdata = "not supported";
5095
5096         return (is_supported)? &text_unsupported[4] : &text_unsupported[0];
5097 }
5098 #endif /* CONFIG_THINKPAD_ACPI_DEBUG */
5099
5100 static int __init ibm_init(struct ibm_init_struct *iibm)
5101 {
5102         int ret;
5103         struct ibm_struct *ibm = iibm->data;
5104         struct proc_dir_entry *entry;
5105
5106         BUG_ON(ibm == NULL);
5107
5108         INIT_LIST_HEAD(&ibm->all_drivers);
5109
5110         if (ibm->flags.experimental && !experimental)
5111                 return 0;
5112
5113         dbg_printk(TPACPI_DBG_INIT,
5114                 "probing for %s\n", ibm->name);
5115
5116         if (iibm->init) {
5117                 ret = iibm->init(iibm);
5118                 if (ret > 0)
5119                         return 0;       /* probe failed */
5120                 if (ret)
5121                         return ret;
5122
5123                 ibm->flags.init_called = 1;
5124         }
5125
5126         if (ibm->acpi) {
5127                 if (ibm->acpi->hid) {
5128                         ret = register_tpacpi_subdriver(ibm);
5129                         if (ret)
5130                                 goto err_out;
5131                 }
5132
5133                 if (ibm->acpi->notify) {
5134                         ret = setup_acpi_notify(ibm);
5135                         if (ret == -ENODEV) {
5136                                 printk(IBM_NOTICE "disabling subdriver %s\n",
5137                                         ibm->name);
5138                                 ret = 0;
5139                                 goto err_out;
5140                         }
5141                         if (ret < 0)
5142                                 goto err_out;
5143                 }
5144         }
5145
5146         dbg_printk(TPACPI_DBG_INIT,
5147                 "%s installed\n", ibm->name);
5148
5149         if (ibm->read) {
5150                 entry = create_proc_entry(ibm->name,
5151                                           S_IFREG | S_IRUGO | S_IWUSR,
5152                                           proc_dir);
5153                 if (!entry) {
5154                         printk(IBM_ERR "unable to create proc entry %s\n",
5155                                ibm->name);
5156                         ret = -ENODEV;
5157                         goto err_out;
5158                 }
5159                 entry->owner = THIS_MODULE;
5160                 entry->data = ibm;
5161                 entry->read_proc = &dispatch_procfs_read;
5162                 if (ibm->write)
5163                         entry->write_proc = &dispatch_procfs_write;
5164                 ibm->flags.proc_created = 1;
5165         }
5166
5167         list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers);
5168
5169         return 0;
5170
5171 err_out:
5172         dbg_printk(TPACPI_DBG_INIT,
5173                 "%s: at error exit path with result %d\n",
5174                 ibm->name, ret);
5175
5176         ibm_exit(ibm);
5177         return (ret < 0)? ret : 0;
5178 }
5179
5180 static void ibm_exit(struct ibm_struct *ibm)
5181 {
5182         dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name);
5183
5184         list_del_init(&ibm->all_drivers);
5185
5186         if (ibm->flags.acpi_notify_installed) {
5187                 dbg_printk(TPACPI_DBG_EXIT,
5188                         "%s: acpi_remove_notify_handler\n", ibm->name);
5189                 BUG_ON(!ibm->acpi);
5190                 acpi_remove_notify_handler(*ibm->acpi->handle,
5191                                            ibm->acpi->type,
5192                                            dispatch_acpi_notify);
5193                 ibm->flags.acpi_notify_installed = 0;
5194                 ibm->flags.acpi_notify_installed = 0;
5195         }
5196
5197         if (ibm->flags.proc_created) {
5198                 dbg_printk(TPACPI_DBG_EXIT,
5199                         "%s: remove_proc_entry\n", ibm->name);
5200                 remove_proc_entry(ibm->name, proc_dir);
5201                 ibm->flags.proc_created = 0;
5202         }
5203
5204         if (ibm->flags.acpi_driver_registered) {
5205                 dbg_printk(TPACPI_DBG_EXIT,
5206                         "%s: acpi_bus_unregister_driver\n", ibm->name);
5207                 BUG_ON(!ibm->acpi);
5208                 acpi_bus_unregister_driver(ibm->acpi->driver);
5209                 kfree(ibm->acpi->driver);
5210                 ibm->acpi->driver = NULL;
5211                 ibm->flags.acpi_driver_registered = 0;
5212         }
5213
5214         if (ibm->flags.init_called && ibm->exit) {
5215                 ibm->exit();
5216                 ibm->flags.init_called = 0;
5217         }
5218
5219         dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name);
5220 }
5221
5222 /* Probing */
5223
5224 static void __init get_thinkpad_model_data(struct thinkpad_id_data *tp)
5225 {
5226         const struct dmi_device *dev = NULL;
5227         char ec_fw_string[18];
5228
5229         if (!tp)
5230                 return;
5231
5232         memset(tp, 0, sizeof(*tp));
5233
5234         if (dmi_name_in_vendors("IBM"))
5235                 tp->vendor = PCI_VENDOR_ID_IBM;
5236         else if (dmi_name_in_vendors("LENOVO"))
5237                 tp->vendor = PCI_VENDOR_ID_LENOVO;
5238         else
5239                 return;
5240
5241         tp->bios_version_str = kstrdup(dmi_get_system_info(DMI_BIOS_VERSION),
5242                                         GFP_KERNEL);
5243         if (!tp->bios_version_str)
5244                 return;
5245         tp->bios_model = tp->bios_version_str[0]
5246                          | (tp->bios_version_str[1] << 8);
5247
5248         /*
5249          * ThinkPad T23 or newer, A31 or newer, R50e or newer,
5250          * X32 or newer, all Z series;  Some models must have an
5251          * up-to-date BIOS or they will not be detected.
5252          *
5253          * See http://thinkwiki.org/wiki/List_of_DMI_IDs
5254          */
5255         while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
5256                 if (sscanf(dev->name,
5257                            "IBM ThinkPad Embedded Controller -[%17c",
5258                            ec_fw_string) == 1) {
5259                         ec_fw_string[sizeof(ec_fw_string) - 1] = 0;
5260                         ec_fw_string[strcspn(ec_fw_string, " ]")] = 0;
5261
5262                         tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL);
5263                         tp->ec_model = ec_fw_string[0]
5264                                         | (ec_fw_string[1] << 8);
5265                         break;
5266                 }
5267         }
5268
5269         tp->model_str = kstrdup(dmi_get_system_info(DMI_PRODUCT_VERSION),
5270                                         GFP_KERNEL);
5271         if (strnicmp(tp->model_str, "ThinkPad", 8) != 0) {
5272                 kfree(tp->model_str);
5273                 tp->model_str = NULL;
5274         }
5275 }
5276
5277 static int __init probe_for_thinkpad(void)
5278 {
5279         int is_thinkpad;
5280
5281         if (acpi_disabled)
5282                 return -ENODEV;
5283
5284         /*
5285          * Non-ancient models have better DMI tagging, but very old models
5286          * don't.
5287          */
5288         is_thinkpad = (thinkpad_id.model_str != NULL);
5289
5290         /* ec is required because many other handles are relative to it */
5291         IBM_ACPIHANDLE_INIT(ec);
5292         if (!ec_handle) {
5293                 if (is_thinkpad)
5294                         printk(IBM_ERR
5295                                 "Not yet supported ThinkPad detected!\n");
5296                 return -ENODEV;
5297         }
5298
5299         /*
5300          * Risks a regression on very old machines, but reduces potential
5301          * false positives a damn great deal
5302          */
5303         if (!is_thinkpad)
5304                 is_thinkpad = (thinkpad_id.vendor == PCI_VENDOR_ID_IBM);
5305
5306         if (!is_thinkpad && !force_load)
5307                 return -ENODEV;
5308
5309         return 0;
5310 }
5311
5312
5313 /* Module init, exit, parameters */
5314
5315 static struct ibm_init_struct ibms_init[] __initdata = {
5316         {
5317                 .init = thinkpad_acpi_driver_init,
5318                 .data = &thinkpad_acpi_driver_data,
5319         },
5320         {
5321                 .init = hotkey_init,
5322                 .data = &hotkey_driver_data,
5323         },
5324         {
5325                 .init = bluetooth_init,
5326                 .data = &bluetooth_driver_data,
5327         },
5328         {
5329                 .init = wan_init,
5330                 .data = &wan_driver_data,
5331         },
5332         {
5333                 .init = video_init,
5334                 .data = &video_driver_data,
5335         },
5336         {
5337                 .init = light_init,
5338                 .data = &light_driver_data,
5339         },
5340 #ifdef CONFIG_THINKPAD_ACPI_DOCK
5341         {
5342                 .init = dock_init,
5343                 .data = &dock_driver_data[0],
5344         },
5345         {
5346                 .init = dock_init2,
5347                 .data = &dock_driver_data[1],
5348         },
5349 #endif
5350 #ifdef CONFIG_THINKPAD_ACPI_BAY
5351         {
5352                 .init = bay_init,
5353                 .data = &bay_driver_data,
5354         },
5355 #endif
5356         {
5357                 .init = cmos_init,
5358                 .data = &cmos_driver_data,
5359         },
5360         {
5361                 .init = led_init,
5362                 .data = &led_driver_data,
5363         },
5364         {
5365                 .init = beep_init,
5366                 .data = &beep_driver_data,
5367         },
5368         {
5369                 .init = thermal_init,
5370                 .data = &thermal_driver_data,
5371         },
5372         {
5373                 .data = &ecdump_driver_data,
5374         },
5375         {
5376                 .init = brightness_init,
5377                 .data = &brightness_driver_data,
5378         },
5379         {
5380                 .data = &volume_driver_data,
5381         },
5382         {
5383                 .init = fan_init,
5384                 .data = &fan_driver_data,
5385         },
5386 };
5387
5388 static int __init set_ibm_param(const char *val, struct kernel_param *kp)
5389 {
5390         unsigned int i;
5391         struct ibm_struct *ibm;
5392
5393         if (!kp || !kp->name || !val)
5394                 return -EINVAL;
5395
5396         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
5397                 ibm = ibms_init[i].data;
5398                 WARN_ON(ibm == NULL);
5399
5400                 if (!ibm || !ibm->name)
5401                         continue;
5402
5403                 if (strcmp(ibm->name, kp->name) == 0 && ibm->write) {
5404                         if (strlen(val) > sizeof(ibms_init[i].param) - 2)
5405                                 return -ENOSPC;
5406                         strcpy(ibms_init[i].param, val);
5407                         strcat(ibms_init[i].param, ",");
5408                         return 0;
5409                 }
5410         }
5411
5412         return -EINVAL;
5413 }
5414
5415 static int experimental;
5416 module_param(experimental, int, 0);
5417
5418 static u32 dbg_level;
5419 module_param_named(debug, dbg_level, uint, 0);
5420
5421 static int force_load;
5422 module_param(force_load, bool, 0);
5423
5424 static int fan_control_allowed;
5425 module_param_named(fan_control, fan_control_allowed, bool, 0);
5426
5427 static int brightness_mode;
5428 module_param_named(brightness_mode, brightness_mode, int, 0);
5429
5430 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
5431 module_param(brightness_enable, uint, 0);
5432
5433 static unsigned int hotkey_report_mode;
5434 module_param(hotkey_report_mode, uint, 0);
5435
5436 #define IBM_PARAM(feature) \
5437         module_param_call(feature, set_ibm_param, NULL, NULL, 0)
5438
5439 IBM_PARAM(hotkey);
5440 IBM_PARAM(bluetooth);
5441 IBM_PARAM(video);
5442 IBM_PARAM(light);
5443 #ifdef CONFIG_THINKPAD_ACPI_DOCK
5444 IBM_PARAM(dock);
5445 #endif
5446 #ifdef CONFIG_THINKPAD_ACPI_BAY
5447 IBM_PARAM(bay);
5448 #endif /* CONFIG_THINKPAD_ACPI_BAY */
5449 IBM_PARAM(cmos);
5450 IBM_PARAM(led);
5451 IBM_PARAM(beep);
5452 IBM_PARAM(ecdump);
5453 IBM_PARAM(brightness);
5454 IBM_PARAM(volume);
5455 IBM_PARAM(fan);
5456
5457 static int __init thinkpad_acpi_module_init(void)
5458 {
5459         int ret, i;
5460
5461         tpacpi_lifecycle = TPACPI_LIFE_INIT;
5462
5463         /* Parameter checking */
5464         if (hotkey_report_mode > 2)
5465                 return -EINVAL;
5466
5467         /* Driver-level probe */
5468
5469         get_thinkpad_model_data(&thinkpad_id);
5470         ret = probe_for_thinkpad();
5471         if (ret) {
5472                 thinkpad_acpi_module_exit();
5473                 return ret;
5474         }
5475
5476         /* Driver initialization */
5477
5478         IBM_ACPIHANDLE_INIT(ecrd);
5479         IBM_ACPIHANDLE_INIT(ecwr);
5480
5481         proc_dir = proc_mkdir(IBM_PROC_DIR, acpi_root_dir);
5482         if (!proc_dir) {
5483                 printk(IBM_ERR "unable to create proc dir " IBM_PROC_DIR);
5484                 thinkpad_acpi_module_exit();
5485                 return -ENODEV;
5486         }
5487         proc_dir->owner = THIS_MODULE;
5488
5489         ret = platform_driver_register(&tpacpi_pdriver);
5490         if (ret) {
5491                 printk(IBM_ERR "unable to register main platform driver\n");
5492                 thinkpad_acpi_module_exit();
5493                 return ret;
5494         }
5495         tp_features.platform_drv_registered = 1;
5496
5497         ret = platform_driver_register(&tpacpi_hwmon_pdriver);
5498         if (ret) {
5499                 printk(IBM_ERR "unable to register hwmon platform driver\n");
5500                 thinkpad_acpi_module_exit();
5501                 return ret;
5502         }
5503         tp_features.sensors_pdrv_registered = 1;
5504
5505         ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver);
5506         if (!ret) {
5507                 tp_features.platform_drv_attrs_registered = 1;
5508                 ret = tpacpi_create_driver_attributes(&tpacpi_hwmon_pdriver.driver);
5509         }
5510         if (ret) {
5511                 printk(IBM_ERR "unable to create sysfs driver attributes\n");
5512                 thinkpad_acpi_module_exit();
5513                 return ret;
5514         }
5515         tp_features.sensors_pdrv_attrs_registered = 1;
5516
5517
5518         /* Device initialization */
5519         tpacpi_pdev = platform_device_register_simple(IBM_DRVR_NAME, -1,
5520                                                         NULL, 0);
5521         if (IS_ERR(tpacpi_pdev)) {
5522                 ret = PTR_ERR(tpacpi_pdev);
5523                 tpacpi_pdev = NULL;
5524                 printk(IBM_ERR "unable to register platform device\n");
5525                 thinkpad_acpi_module_exit();
5526                 return ret;
5527         }
5528         tpacpi_sensors_pdev = platform_device_register_simple(
5529                                                         IBM_HWMON_DRVR_NAME,
5530                                                         -1, NULL, 0);
5531         if (IS_ERR(tpacpi_sensors_pdev)) {
5532                 ret = PTR_ERR(tpacpi_sensors_pdev);
5533                 tpacpi_sensors_pdev = NULL;
5534                 printk(IBM_ERR "unable to register hwmon platform device\n");
5535                 thinkpad_acpi_module_exit();
5536                 return ret;
5537         }
5538         ret = device_create_file(&tpacpi_sensors_pdev->dev,
5539                                  &dev_attr_thinkpad_acpi_pdev_name);
5540         if (ret) {
5541                 printk(IBM_ERR
5542                         "unable to create sysfs hwmon device attributes\n");
5543                 thinkpad_acpi_module_exit();
5544                 return ret;
5545         }
5546         tp_features.sensors_pdev_attrs_registered = 1;
5547         tpacpi_hwmon = hwmon_device_register(&tpacpi_sensors_pdev->dev);
5548         if (IS_ERR(tpacpi_hwmon)) {
5549                 ret = PTR_ERR(tpacpi_hwmon);
5550                 tpacpi_hwmon = NULL;
5551                 printk(IBM_ERR "unable to register hwmon device\n");
5552                 thinkpad_acpi_module_exit();
5553                 return ret;
5554         }
5555         mutex_init(&tpacpi_inputdev_send_mutex);
5556         tpacpi_inputdev = input_allocate_device();
5557         if (!tpacpi_inputdev) {
5558                 printk(IBM_ERR "unable to allocate input device\n");
5559                 thinkpad_acpi_module_exit();
5560                 return -ENOMEM;
5561         } else {
5562                 /* Prepare input device, but don't register */
5563                 tpacpi_inputdev->name = "ThinkPad Extra Buttons";
5564                 tpacpi_inputdev->phys = IBM_DRVR_NAME "/input0";
5565                 tpacpi_inputdev->id.bustype = BUS_HOST;
5566                 tpacpi_inputdev->id.vendor = (thinkpad_id.vendor) ?
5567                                                 thinkpad_id.vendor :
5568                                                 PCI_VENDOR_ID_IBM;
5569                 tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT;
5570                 tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION;
5571         }
5572         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
5573                 ret = ibm_init(&ibms_init[i]);
5574                 if (ret >= 0 && *ibms_init[i].param)
5575                         ret = ibms_init[i].data->write(ibms_init[i].param);
5576                 if (ret < 0) {
5577                         thinkpad_acpi_module_exit();
5578                         return ret;
5579                 }
5580         }
5581         ret = input_register_device(tpacpi_inputdev);
5582         if (ret < 0) {
5583                 printk(IBM_ERR "unable to register input device\n");
5584                 thinkpad_acpi_module_exit();
5585                 return ret;
5586         } else {
5587                 tp_features.input_device_registered = 1;
5588         }
5589
5590         tpacpi_lifecycle = TPACPI_LIFE_RUNNING;
5591         return 0;
5592 }
5593
5594 static void thinkpad_acpi_module_exit(void)
5595 {
5596         struct ibm_struct *ibm, *itmp;
5597
5598         tpacpi_lifecycle = TPACPI_LIFE_EXITING;
5599
5600         list_for_each_entry_safe_reverse(ibm, itmp,
5601                                          &tpacpi_all_drivers,
5602                                          all_drivers) {
5603                 ibm_exit(ibm);
5604         }
5605
5606         dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n");
5607
5608         if (tpacpi_inputdev) {
5609                 if (tp_features.input_device_registered)
5610                         input_unregister_device(tpacpi_inputdev);
5611                 else
5612                         input_free_device(tpacpi_inputdev);
5613         }
5614
5615         if (tpacpi_hwmon)
5616                 hwmon_device_unregister(tpacpi_hwmon);
5617
5618         if (tp_features.sensors_pdev_attrs_registered)
5619                 device_remove_file(&tpacpi_sensors_pdev->dev,
5620                                    &dev_attr_thinkpad_acpi_pdev_name);
5621         if (tpacpi_sensors_pdev)
5622                 platform_device_unregister(tpacpi_sensors_pdev);
5623         if (tpacpi_pdev)
5624                 platform_device_unregister(tpacpi_pdev);
5625
5626         if (tp_features.sensors_pdrv_attrs_registered)
5627                 tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver);
5628         if (tp_features.platform_drv_attrs_registered)
5629                 tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver);
5630
5631         if (tp_features.sensors_pdrv_registered)
5632                 platform_driver_unregister(&tpacpi_hwmon_pdriver);
5633
5634         if (tp_features.platform_drv_registered)
5635                 platform_driver_unregister(&tpacpi_pdriver);
5636
5637         if (proc_dir)
5638                 remove_proc_entry(IBM_PROC_DIR, acpi_root_dir);
5639
5640         kfree(thinkpad_id.bios_version_str);
5641         kfree(thinkpad_id.ec_version_str);
5642         kfree(thinkpad_id.model_str);
5643 }
5644
5645 module_init(thinkpad_acpi_module_init);
5646 module_exit(thinkpad_acpi_module_exit);