ACPI / EC: Add support to disallow QR_EC to be issued when SCI_EVT isn't set
[pandora-kernel.git] / drivers / acpi / ec.c
1 /*
2  *  ec.c - ACPI Embedded Controller Driver (v2.1)
3  *
4  *  Copyright (C) 2006-2008 Alexey Starikovskiy <astarikovskiy@suse.de>
5  *  Copyright (C) 2006 Denis Sadykov <denis.m.sadykov@intel.com>
6  *  Copyright (C) 2004 Luming Yu <luming.yu@intel.com>
7  *  Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
8  *  Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
9  *
10  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2 of the License, or (at
15  *  your option) any later version.
16  *
17  *  This program is distributed in the hope that it will be useful, but
18  *  WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  *  General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License along
23  *  with this program; if not, write to the Free Software Foundation, Inc.,
24  *  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
25  *
26  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
27  */
28
29 /* Uncomment next line to get verbose printout */
30 /* #define DEBUG */
31
32 #include <linux/kernel.h>
33 #include <linux/module.h>
34 #include <linux/init.h>
35 #include <linux/types.h>
36 #include <linux/delay.h>
37 #include <linux/interrupt.h>
38 #include <linux/list.h>
39 #include <linux/spinlock.h>
40 #include <linux/slab.h>
41 #include <asm/io.h>
42 #include <acpi/acpi_bus.h>
43 #include <acpi/acpi_drivers.h>
44 #include <linux/dmi.h>
45
46 #include "internal.h"
47
48 #define ACPI_EC_CLASS                   "embedded_controller"
49 #define ACPI_EC_DEVICE_NAME             "Embedded Controller"
50 #define ACPI_EC_FILE_INFO               "info"
51
52 #undef PREFIX
53 #define PREFIX                          "ACPI: EC: "
54
55 /* EC status register */
56 #define ACPI_EC_FLAG_OBF        0x01    /* Output buffer full */
57 #define ACPI_EC_FLAG_IBF        0x02    /* Input buffer full */
58 #define ACPI_EC_FLAG_BURST      0x10    /* burst mode */
59 #define ACPI_EC_FLAG_SCI        0x20    /* EC-SCI occurred */
60
61 /* EC commands */
62 enum ec_command {
63         ACPI_EC_COMMAND_READ = 0x80,
64         ACPI_EC_COMMAND_WRITE = 0x81,
65         ACPI_EC_BURST_ENABLE = 0x82,
66         ACPI_EC_BURST_DISABLE = 0x83,
67         ACPI_EC_COMMAND_QUERY = 0x84,
68 };
69
70 #define ACPI_EC_DELAY           500     /* Wait 500ms max. during EC ops */
71 #define ACPI_EC_UDELAY_GLK      1000    /* Wait 1ms max. to get global lock */
72 #define ACPI_EC_MSI_UDELAY      550     /* Wait 550us for MSI EC */
73 #define ACPI_EC_CLEAR_MAX       100     /* Maximum number of events to query
74                                          * when trying to clear the EC */
75
76 enum {
77         EC_FLAGS_QUERY_PENDING,         /* Query is pending */
78         EC_FLAGS_GPE_STORM,             /* GPE storm detected */
79         EC_FLAGS_HANDLERS_INSTALLED,    /* Handlers for GPE and
80                                          * OpReg are installed */
81         EC_FLAGS_BLOCKED,               /* Transactions are blocked */
82 };
83
84 #define ACPI_EC_COMMAND_POLL            0x01 /* Available for command byte */
85 #define ACPI_EC_COMMAND_COMPLETE        0x02 /* Completed last byte */
86
87 /* ec.c is compiled in acpi namespace so this shows up as acpi.ec_delay param */
88 static unsigned int ec_delay __read_mostly = ACPI_EC_DELAY;
89 module_param(ec_delay, uint, 0644);
90 MODULE_PARM_DESC(ec_delay, "Timeout(ms) waited until an EC command completes");
91
92 /*
93  * If the number of false interrupts per one transaction exceeds
94  * this threshold, will think there is a GPE storm happened and
95  * will disable the GPE for normal transaction.
96  */
97 static unsigned int ec_storm_threshold  __read_mostly = 8;
98 module_param(ec_storm_threshold, uint, 0644);
99 MODULE_PARM_DESC(ec_storm_threshold, "Maxim false GPE numbers not considered as GPE storm");
100
101 /* If we find an EC via the ECDT, we need to keep a ptr to its context */
102 /* External interfaces use first EC only, so remember */
103 typedef int (*acpi_ec_query_func) (void *data);
104
105 struct acpi_ec_query_handler {
106         struct list_head node;
107         acpi_ec_query_func func;
108         acpi_handle handle;
109         void *data;
110         u8 query_bit;
111 };
112
113 struct transaction {
114         const u8 *wdata;
115         u8 *rdata;
116         unsigned short irq_count;
117         u8 command;
118         u8 wi;
119         u8 ri;
120         u8 wlen;
121         u8 rlen;
122         u8 flags;
123 };
124
125 struct acpi_ec *boot_ec, *first_ec;
126 EXPORT_SYMBOL(first_ec);
127
128 static int EC_FLAGS_MSI; /* Out-of-spec MSI controller */
129 static int EC_FLAGS_VALIDATE_ECDT; /* ASUStec ECDTs need to be validated */
130 static int EC_FLAGS_SKIP_DSDT_SCAN; /* Not all BIOS survive early DSDT scan */
131 static int EC_FLAGS_CLEAR_ON_RESUME; /* Needs acpi_ec_clear() on boot/resume */
132
133 /* --------------------------------------------------------------------------
134                              Transaction Management
135    -------------------------------------------------------------------------- */
136
137 static inline u8 acpi_ec_read_status(struct acpi_ec *ec)
138 {
139         u8 x = inb(ec->command_addr);
140         pr_debug(PREFIX "---> status = 0x%2.2x\n", x);
141         return x;
142 }
143
144 static inline u8 acpi_ec_read_data(struct acpi_ec *ec)
145 {
146         u8 x = inb(ec->data_addr);
147         pr_debug(PREFIX "---> data = 0x%2.2x\n", x);
148         return x;
149 }
150
151 static inline void acpi_ec_write_cmd(struct acpi_ec *ec, u8 command)
152 {
153         pr_debug(PREFIX "<--- command = 0x%2.2x\n", command);
154         outb(command, ec->command_addr);
155 }
156
157 static inline void acpi_ec_write_data(struct acpi_ec *ec, u8 data)
158 {
159         pr_debug(PREFIX "<--- data = 0x%2.2x\n", data);
160         outb(data, ec->data_addr);
161 }
162
163 static int ec_transaction_completed(struct acpi_ec *ec)
164 {
165         unsigned long flags;
166         int ret = 0;
167         spin_lock_irqsave(&ec->curr_lock, flags);
168         if (ec->curr && (ec->curr->flags & ACPI_EC_COMMAND_COMPLETE))
169                 ret = 1;
170         spin_unlock_irqrestore(&ec->curr_lock, flags);
171         return ret;
172 }
173
174 static bool advance_transaction(struct acpi_ec *ec)
175 {
176         struct transaction *t;
177         u8 status;
178         bool wakeup = false;
179
180         pr_debug(PREFIX "===== %s =====\n", in_interrupt() ? "IRQ" : "TASK");
181         status = acpi_ec_read_status(ec);
182         t = ec->curr;
183         if (!t)
184                 goto err;
185         if (t->flags & ACPI_EC_COMMAND_POLL) {
186                 if (t->wlen > t->wi) {
187                         if ((status & ACPI_EC_FLAG_IBF) == 0)
188                                 acpi_ec_write_data(ec, t->wdata[t->wi++]);
189                         else
190                                 goto err;
191                 } else if (t->rlen > t->ri) {
192                         if ((status & ACPI_EC_FLAG_OBF) == 1) {
193                                 t->rdata[t->ri++] = acpi_ec_read_data(ec);
194                                 if (t->rlen == t->ri) {
195                                         t->flags |= ACPI_EC_COMMAND_COMPLETE;
196                                         if (t->command == ACPI_EC_COMMAND_QUERY)
197                                                 pr_debug("hardware QR_EC completion\n");
198                                         wakeup = true;
199                                 }
200                         } else
201                                 goto err;
202                 } else if (t->wlen == t->wi &&
203                            (status & ACPI_EC_FLAG_IBF) == 0) {
204                         t->flags |= ACPI_EC_COMMAND_COMPLETE;
205                         wakeup = true;
206                 }
207                 return wakeup;
208         } else {
209                 /*
210                  * There is firmware refusing to respond QR_EC when SCI_EVT
211                  * is not set, for which case, we complete the QR_EC
212                  * without issuing it to the firmware.
213                  * https://bugzilla.kernel.org/show_bug.cgi?id=86211
214                  */
215                 if (!(status & ACPI_EC_FLAG_SCI) &&
216                     (t->command == ACPI_EC_COMMAND_QUERY)) {
217                         t->flags |= ACPI_EC_COMMAND_POLL;
218                         t->rdata[t->ri++] = 0x00;
219                         t->flags |= ACPI_EC_COMMAND_COMPLETE;
220                         pr_debug("software QR_EC completion\n");
221                         wakeup = true;
222                 } else if ((status & ACPI_EC_FLAG_IBF) == 0) {
223                         acpi_ec_write_cmd(ec, t->command);
224                         t->flags |= ACPI_EC_COMMAND_POLL;
225                 } else
226                         goto err;
227                 return wakeup;
228         }
229 err:
230         /*
231          * If SCI bit is set, then don't think it's a false IRQ
232          * otherwise will take a not handled IRQ as a false one.
233          */
234         if (!(status & ACPI_EC_FLAG_SCI)) {
235                 if (in_interrupt() && t)
236                         ++t->irq_count;
237         }
238         return wakeup;
239 }
240
241 static void start_transaction(struct acpi_ec *ec)
242 {
243         ec->curr->irq_count = ec->curr->wi = ec->curr->ri = 0;
244         ec->curr->flags = 0;
245         (void)advance_transaction(ec);
246 }
247
248 static int acpi_ec_sync_query(struct acpi_ec *ec, u8 *data);
249
250 static int ec_check_sci_sync(struct acpi_ec *ec, u8 state)
251 {
252         if (state & ACPI_EC_FLAG_SCI) {
253                 if (!test_and_set_bit(EC_FLAGS_QUERY_PENDING, &ec->flags))
254                         return acpi_ec_sync_query(ec, NULL);
255         }
256         return 0;
257 }
258
259 static int ec_poll(struct acpi_ec *ec)
260 {
261         unsigned long flags;
262         int repeat = 5; /* number of command restarts */
263         while (repeat--) {
264                 unsigned long delay = jiffies +
265                         msecs_to_jiffies(ec_delay);
266                 do {
267                         /* don't sleep with disabled interrupts */
268                         if (EC_FLAGS_MSI || irqs_disabled()) {
269                                 udelay(ACPI_EC_MSI_UDELAY);
270                                 if (ec_transaction_completed(ec))
271                                         return 0;
272                         } else {
273                                 if (wait_event_timeout(ec->wait,
274                                                 ec_transaction_completed(ec),
275                                                 msecs_to_jiffies(1)))
276                                         return 0;
277                         }
278                         spin_lock_irqsave(&ec->curr_lock, flags);
279                         (void)advance_transaction(ec);
280                         spin_unlock_irqrestore(&ec->curr_lock, flags);
281                 } while (time_before(jiffies, delay));
282                 pr_debug(PREFIX "controller reset, restart transaction\n");
283                 spin_lock_irqsave(&ec->curr_lock, flags);
284                 start_transaction(ec);
285                 spin_unlock_irqrestore(&ec->curr_lock, flags);
286         }
287         return -ETIME;
288 }
289
290 static int acpi_ec_transaction_unlocked(struct acpi_ec *ec,
291                                         struct transaction *t)
292 {
293         unsigned long tmp;
294         int ret = 0;
295         if (EC_FLAGS_MSI)
296                 udelay(ACPI_EC_MSI_UDELAY);
297         /* start transaction */
298         spin_lock_irqsave(&ec->curr_lock, tmp);
299         /* following two actions should be kept atomic */
300         ec->curr = t;
301         start_transaction(ec);
302         if (ec->curr->command == ACPI_EC_COMMAND_QUERY)
303                 clear_bit(EC_FLAGS_QUERY_PENDING, &ec->flags);
304         spin_unlock_irqrestore(&ec->curr_lock, tmp);
305         ret = ec_poll(ec);
306         spin_lock_irqsave(&ec->curr_lock, tmp);
307         ec->curr = NULL;
308         spin_unlock_irqrestore(&ec->curr_lock, tmp);
309         return ret;
310 }
311
312 static int acpi_ec_transaction(struct acpi_ec *ec, struct transaction *t)
313 {
314         int status;
315         u32 glk;
316         if (!ec || (!t) || (t->wlen && !t->wdata) || (t->rlen && !t->rdata))
317                 return -EINVAL;
318         if (t->rdata)
319                 memset(t->rdata, 0, t->rlen);
320         mutex_lock(&ec->lock);
321         if (test_bit(EC_FLAGS_BLOCKED, &ec->flags)) {
322                 status = -EINVAL;
323                 goto unlock;
324         }
325         if (ec->global_lock) {
326                 status = acpi_acquire_global_lock(ACPI_EC_UDELAY_GLK, &glk);
327                 if (ACPI_FAILURE(status)) {
328                         status = -ENODEV;
329                         goto unlock;
330                 }
331         }
332         pr_debug(PREFIX "transaction start (cmd=0x%02x, addr=0x%02x)\n",
333                         t->command, t->wdata ? t->wdata[0] : 0);
334         /* disable GPE during transaction if storm is detected */
335         if (test_bit(EC_FLAGS_GPE_STORM, &ec->flags)) {
336                 /* It has to be disabled, so that it doesn't trigger. */
337                 acpi_disable_gpe(NULL, ec->gpe);
338         }
339
340         status = acpi_ec_transaction_unlocked(ec, t);
341
342         /* check if we received SCI during transaction */
343         ec_check_sci_sync(ec, acpi_ec_read_status(ec));
344         if (test_bit(EC_FLAGS_GPE_STORM, &ec->flags)) {
345                 msleep(1);
346                 /* It is safe to enable the GPE outside of the transaction. */
347                 acpi_enable_gpe(NULL, ec->gpe);
348         } else if (t->irq_count > ec_storm_threshold) {
349                 pr_info(PREFIX "GPE storm detected(%d GPEs), "
350                         "transactions will use polling mode\n",
351                         t->irq_count);
352                 set_bit(EC_FLAGS_GPE_STORM, &ec->flags);
353         }
354         pr_debug(PREFIX "transaction end\n");
355         if (ec->global_lock)
356                 acpi_release_global_lock(glk);
357 unlock:
358         mutex_unlock(&ec->lock);
359         return status;
360 }
361
362 static int acpi_ec_burst_enable(struct acpi_ec *ec)
363 {
364         u8 d;
365         struct transaction t = {.command = ACPI_EC_BURST_ENABLE,
366                                 .wdata = NULL, .rdata = &d,
367                                 .wlen = 0, .rlen = 1};
368
369         return acpi_ec_transaction(ec, &t);
370 }
371
372 static int acpi_ec_burst_disable(struct acpi_ec *ec)
373 {
374         struct transaction t = {.command = ACPI_EC_BURST_DISABLE,
375                                 .wdata = NULL, .rdata = NULL,
376                                 .wlen = 0, .rlen = 0};
377
378         return (acpi_ec_read_status(ec) & ACPI_EC_FLAG_BURST) ?
379                                 acpi_ec_transaction(ec, &t) : 0;
380 }
381
382 static int acpi_ec_read(struct acpi_ec *ec, u8 address, u8 * data)
383 {
384         int result;
385         u8 d;
386         struct transaction t = {.command = ACPI_EC_COMMAND_READ,
387                                 .wdata = &address, .rdata = &d,
388                                 .wlen = 1, .rlen = 1};
389
390         result = acpi_ec_transaction(ec, &t);
391         *data = d;
392         return result;
393 }
394
395 static int acpi_ec_write(struct acpi_ec *ec, u8 address, u8 data)
396 {
397         u8 wdata[2] = { address, data };
398         struct transaction t = {.command = ACPI_EC_COMMAND_WRITE,
399                                 .wdata = wdata, .rdata = NULL,
400                                 .wlen = 2, .rlen = 0};
401
402         return acpi_ec_transaction(ec, &t);
403 }
404
405 /*
406  * Externally callable EC access functions. For now, assume 1 EC only
407  */
408 int ec_burst_enable(void)
409 {
410         if (!first_ec)
411                 return -ENODEV;
412         return acpi_ec_burst_enable(first_ec);
413 }
414
415 EXPORT_SYMBOL(ec_burst_enable);
416
417 int ec_burst_disable(void)
418 {
419         if (!first_ec)
420                 return -ENODEV;
421         return acpi_ec_burst_disable(first_ec);
422 }
423
424 EXPORT_SYMBOL(ec_burst_disable);
425
426 int ec_read(u8 addr, u8 *val)
427 {
428         int err;
429         u8 temp_data;
430
431         if (!first_ec)
432                 return -ENODEV;
433
434         err = acpi_ec_read(first_ec, addr, &temp_data);
435
436         if (!err) {
437                 *val = temp_data;
438                 return 0;
439         } else
440                 return err;
441 }
442
443 EXPORT_SYMBOL(ec_read);
444
445 int ec_write(u8 addr, u8 val)
446 {
447         int err;
448
449         if (!first_ec)
450                 return -ENODEV;
451
452         err = acpi_ec_write(first_ec, addr, val);
453
454         return err;
455 }
456
457 EXPORT_SYMBOL(ec_write);
458
459 int ec_transaction(u8 command,
460                    const u8 * wdata, unsigned wdata_len,
461                    u8 * rdata, unsigned rdata_len)
462 {
463         struct transaction t = {.command = command,
464                                 .wdata = wdata, .rdata = rdata,
465                                 .wlen = wdata_len, .rlen = rdata_len};
466         if (!first_ec)
467                 return -ENODEV;
468
469         return acpi_ec_transaction(first_ec, &t);
470 }
471
472 EXPORT_SYMBOL(ec_transaction);
473
474 /*
475  * Process _Q events that might have accumulated in the EC.
476  * Run with locked ec mutex.
477  */
478 static void acpi_ec_clear(struct acpi_ec *ec)
479 {
480         int i, status;
481         u8 value = 0;
482
483         for (i = 0; i < ACPI_EC_CLEAR_MAX; i++) {
484                 status = acpi_ec_sync_query(ec, &value);
485                 if (status || !value)
486                         break;
487         }
488
489         if (unlikely(i == ACPI_EC_CLEAR_MAX))
490                 pr_warn("Warning: Maximum of %d stale EC events cleared\n", i);
491         else
492                 pr_info("%d stale EC events cleared\n", i);
493 }
494
495 void acpi_ec_block_transactions(void)
496 {
497         struct acpi_ec *ec = first_ec;
498
499         if (!ec)
500                 return;
501
502         mutex_lock(&ec->lock);
503         /* Prevent transactions from being carried out */
504         set_bit(EC_FLAGS_BLOCKED, &ec->flags);
505         mutex_unlock(&ec->lock);
506 }
507
508 void acpi_ec_unblock_transactions(void)
509 {
510         struct acpi_ec *ec = first_ec;
511
512         if (!ec)
513                 return;
514
515         mutex_lock(&ec->lock);
516         /* Allow transactions to be carried out again */
517         clear_bit(EC_FLAGS_BLOCKED, &ec->flags);
518
519         if (EC_FLAGS_CLEAR_ON_RESUME)
520                 acpi_ec_clear(ec);
521
522         mutex_unlock(&ec->lock);
523 }
524
525 void acpi_ec_unblock_transactions_early(void)
526 {
527         /*
528          * Allow transactions to happen again (this function is called from
529          * atomic context during wakeup, so we don't need to acquire the mutex).
530          */
531         if (first_ec)
532                 clear_bit(EC_FLAGS_BLOCKED, &first_ec->flags);
533 }
534
535 static int acpi_ec_query_unlocked(struct acpi_ec *ec, u8 * data)
536 {
537         int result;
538         u8 d;
539         struct transaction t = {.command = ACPI_EC_COMMAND_QUERY,
540                                 .wdata = NULL, .rdata = &d,
541                                 .wlen = 0, .rlen = 1};
542         if (!ec || !data)
543                 return -EINVAL;
544         /*
545          * Query the EC to find out which _Qxx method we need to evaluate.
546          * Note that successful completion of the query causes the ACPI_EC_SCI
547          * bit to be cleared (and thus clearing the interrupt source).
548          */
549         result = acpi_ec_transaction_unlocked(ec, &t);
550         if (result)
551                 return result;
552         if (!d)
553                 return -ENODATA;
554         *data = d;
555         return 0;
556 }
557
558 /* --------------------------------------------------------------------------
559                                 Event Management
560    -------------------------------------------------------------------------- */
561 int acpi_ec_add_query_handler(struct acpi_ec *ec, u8 query_bit,
562                               acpi_handle handle, acpi_ec_query_func func,
563                               void *data)
564 {
565         struct acpi_ec_query_handler *handler =
566             kzalloc(sizeof(struct acpi_ec_query_handler), GFP_KERNEL);
567         if (!handler)
568                 return -ENOMEM;
569
570         handler->query_bit = query_bit;
571         handler->handle = handle;
572         handler->func = func;
573         handler->data = data;
574         mutex_lock(&ec->lock);
575         list_add(&handler->node, &ec->list);
576         mutex_unlock(&ec->lock);
577         return 0;
578 }
579
580 EXPORT_SYMBOL_GPL(acpi_ec_add_query_handler);
581
582 void acpi_ec_remove_query_handler(struct acpi_ec *ec, u8 query_bit)
583 {
584         struct acpi_ec_query_handler *handler, *tmp;
585         mutex_lock(&ec->lock);
586         list_for_each_entry_safe(handler, tmp, &ec->list, node) {
587                 if (query_bit == handler->query_bit) {
588                         list_del(&handler->node);
589                         kfree(handler);
590                 }
591         }
592         mutex_unlock(&ec->lock);
593 }
594
595 EXPORT_SYMBOL_GPL(acpi_ec_remove_query_handler);
596
597 static void acpi_ec_run(void *cxt)
598 {
599         struct acpi_ec_query_handler *handler = cxt;
600         if (!handler)
601                 return;
602         pr_debug(PREFIX "start query execution\n");
603         if (handler->func)
604                 handler->func(handler->data);
605         else if (handler->handle)
606                 acpi_evaluate_object(handler->handle, NULL, NULL, NULL);
607         pr_debug(PREFIX "stop query execution\n");
608         kfree(handler);
609 }
610
611 static int acpi_ec_sync_query(struct acpi_ec *ec, u8 *data)
612 {
613         u8 value = 0;
614         int status;
615         struct acpi_ec_query_handler *handler, *copy;
616
617         status = acpi_ec_query_unlocked(ec, &value);
618         if (data)
619                 *data = value;
620         if (status)
621                 return status;
622
623         list_for_each_entry(handler, &ec->list, node) {
624                 if (value == handler->query_bit) {
625                         /* have custom handler for this bit */
626                         copy = kmalloc(sizeof(*handler), GFP_KERNEL);
627                         if (!copy)
628                                 return -ENOMEM;
629                         memcpy(copy, handler, sizeof(*copy));
630                         pr_debug(PREFIX "push query execution (0x%2x) on queue\n", value);
631                         return acpi_os_execute((copy->func) ?
632                                 OSL_NOTIFY_HANDLER : OSL_GPE_HANDLER,
633                                 acpi_ec_run, copy);
634                 }
635         }
636         return 0;
637 }
638
639 static void acpi_ec_gpe_query(void *ec_cxt)
640 {
641         struct acpi_ec *ec = ec_cxt;
642         if (!ec)
643                 return;
644         mutex_lock(&ec->lock);
645         acpi_ec_sync_query(ec, NULL);
646         mutex_unlock(&ec->lock);
647 }
648
649 static int ec_check_sci(struct acpi_ec *ec, u8 state)
650 {
651         if (state & ACPI_EC_FLAG_SCI) {
652                 if (!test_and_set_bit(EC_FLAGS_QUERY_PENDING, &ec->flags)) {
653                         pr_debug(PREFIX "push gpe query to the queue\n");
654                         return acpi_os_execute(OSL_NOTIFY_HANDLER,
655                                 acpi_ec_gpe_query, ec);
656                 }
657         }
658         return 0;
659 }
660
661 static u32 acpi_ec_gpe_handler(acpi_handle gpe_device,
662         u32 gpe_number, void *data)
663 {
664         unsigned long flags;
665         struct acpi_ec *ec = data;
666
667         spin_lock_irqsave(&ec->curr_lock, flags);
668         if (advance_transaction(ec))
669                 wake_up(&ec->wait);
670         spin_unlock_irqrestore(&ec->curr_lock, flags);
671         ec_check_sci(ec, acpi_ec_read_status(ec));
672         return ACPI_INTERRUPT_HANDLED | ACPI_REENABLE_GPE;
673 }
674
675 /* --------------------------------------------------------------------------
676                              Address Space Management
677    -------------------------------------------------------------------------- */
678
679 static acpi_status
680 acpi_ec_space_handler(u32 function, acpi_physical_address address,
681                       u32 bits, u64 *value64,
682                       void *handler_context, void *region_context)
683 {
684         struct acpi_ec *ec = handler_context;
685         int result = 0, i, bytes = bits / 8;
686         u8 *value = (u8 *)value64;
687
688         if ((address > 0xFF) || !value || !handler_context)
689                 return AE_BAD_PARAMETER;
690
691         if (function != ACPI_READ && function != ACPI_WRITE)
692                 return AE_BAD_PARAMETER;
693
694         if (EC_FLAGS_MSI || bits > 8)
695                 acpi_ec_burst_enable(ec);
696
697         for (i = 0; i < bytes; ++i, ++address, ++value)
698                 result = (function == ACPI_READ) ?
699                         acpi_ec_read(ec, address, value) :
700                         acpi_ec_write(ec, address, *value);
701
702         if (EC_FLAGS_MSI || bits > 8)
703                 acpi_ec_burst_disable(ec);
704
705         switch (result) {
706         case -EINVAL:
707                 return AE_BAD_PARAMETER;
708                 break;
709         case -ENODEV:
710                 return AE_NOT_FOUND;
711                 break;
712         case -ETIME:
713                 return AE_TIME;
714                 break;
715         default:
716                 return AE_OK;
717         }
718 }
719
720 /* --------------------------------------------------------------------------
721                                Driver Interface
722    -------------------------------------------------------------------------- */
723 static acpi_status
724 ec_parse_io_ports(struct acpi_resource *resource, void *context);
725
726 static struct acpi_ec *make_acpi_ec(void)
727 {
728         struct acpi_ec *ec = kzalloc(sizeof(struct acpi_ec), GFP_KERNEL);
729         if (!ec)
730                 return NULL;
731         ec->flags = 1 << EC_FLAGS_QUERY_PENDING;
732         mutex_init(&ec->lock);
733         init_waitqueue_head(&ec->wait);
734         INIT_LIST_HEAD(&ec->list);
735         spin_lock_init(&ec->curr_lock);
736         return ec;
737 }
738
739 static acpi_status
740 acpi_ec_register_query_methods(acpi_handle handle, u32 level,
741                                void *context, void **return_value)
742 {
743         char node_name[5];
744         struct acpi_buffer buffer = { sizeof(node_name), node_name };
745         struct acpi_ec *ec = context;
746         int value = 0;
747         acpi_status status;
748
749         status = acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer);
750
751         if (ACPI_SUCCESS(status) && sscanf(node_name, "_Q%x", &value) == 1) {
752                 acpi_ec_add_query_handler(ec, value, handle, NULL, NULL);
753         }
754         return AE_OK;
755 }
756
757 static acpi_status
758 ec_parse_device(acpi_handle handle, u32 Level, void *context, void **retval)
759 {
760         acpi_status status;
761         unsigned long long tmp = 0;
762
763         struct acpi_ec *ec = context;
764
765         /* clear addr values, ec_parse_io_ports depend on it */
766         ec->command_addr = ec->data_addr = 0;
767
768         status = acpi_walk_resources(handle, METHOD_NAME__CRS,
769                                      ec_parse_io_ports, ec);
770         if (ACPI_FAILURE(status))
771                 return status;
772
773         /* Get GPE bit assignment (EC events). */
774         /* TODO: Add support for _GPE returning a package */
775         status = acpi_evaluate_integer(handle, "_GPE", NULL, &tmp);
776         if (ACPI_FAILURE(status))
777                 return status;
778         ec->gpe = tmp;
779         /* Use the global lock for all EC transactions? */
780         tmp = 0;
781         acpi_evaluate_integer(handle, "_GLK", NULL, &tmp);
782         ec->global_lock = tmp;
783         ec->handle = handle;
784         return AE_CTRL_TERMINATE;
785 }
786
787 static int ec_install_handlers(struct acpi_ec *ec)
788 {
789         acpi_status status;
790         if (test_bit(EC_FLAGS_HANDLERS_INSTALLED, &ec->flags))
791                 return 0;
792         status = acpi_install_gpe_handler(NULL, ec->gpe,
793                                   ACPI_GPE_EDGE_TRIGGERED,
794                                   &acpi_ec_gpe_handler, ec);
795         if (ACPI_FAILURE(status))
796                 return -ENODEV;
797
798         acpi_enable_gpe(NULL, ec->gpe);
799         status = acpi_install_address_space_handler(ec->handle,
800                                                     ACPI_ADR_SPACE_EC,
801                                                     &acpi_ec_space_handler,
802                                                     NULL, ec);
803         if (ACPI_FAILURE(status)) {
804                 if (status == AE_NOT_FOUND) {
805                         /*
806                          * Maybe OS fails in evaluating the _REG object.
807                          * The AE_NOT_FOUND error will be ignored and OS
808                          * continue to initialize EC.
809                          */
810                         printk(KERN_ERR "Fail in evaluating the _REG object"
811                                 " of EC device. Broken bios is suspected.\n");
812                 } else {
813                         acpi_remove_gpe_handler(NULL, ec->gpe,
814                                 &acpi_ec_gpe_handler);
815                         acpi_disable_gpe(NULL, ec->gpe);
816                         return -ENODEV;
817                 }
818         }
819
820         set_bit(EC_FLAGS_HANDLERS_INSTALLED, &ec->flags);
821         return 0;
822 }
823
824 static void ec_remove_handlers(struct acpi_ec *ec)
825 {
826         acpi_disable_gpe(NULL, ec->gpe);
827         if (ACPI_FAILURE(acpi_remove_address_space_handler(ec->handle,
828                                 ACPI_ADR_SPACE_EC, &acpi_ec_space_handler)))
829                 pr_err(PREFIX "failed to remove space handler\n");
830         if (ACPI_FAILURE(acpi_remove_gpe_handler(NULL, ec->gpe,
831                                 &acpi_ec_gpe_handler)))
832                 pr_err(PREFIX "failed to remove gpe handler\n");
833         clear_bit(EC_FLAGS_HANDLERS_INSTALLED, &ec->flags);
834 }
835
836 static int acpi_ec_add(struct acpi_device *device)
837 {
838         struct acpi_ec *ec = NULL;
839         int ret;
840
841         strcpy(acpi_device_name(device), ACPI_EC_DEVICE_NAME);
842         strcpy(acpi_device_class(device), ACPI_EC_CLASS);
843
844         /* Check for boot EC */
845         if (boot_ec &&
846             (boot_ec->handle == device->handle ||
847              boot_ec->handle == ACPI_ROOT_OBJECT)) {
848                 ec = boot_ec;
849                 boot_ec = NULL;
850         } else {
851                 ec = make_acpi_ec();
852                 if (!ec)
853                         return -ENOMEM;
854         }
855         if (ec_parse_device(device->handle, 0, ec, NULL) !=
856                 AE_CTRL_TERMINATE) {
857                         kfree(ec);
858                         return -EINVAL;
859         }
860
861         /* Find and register all query methods */
862         acpi_walk_namespace(ACPI_TYPE_METHOD, ec->handle, 1,
863                             acpi_ec_register_query_methods, NULL, ec, NULL);
864
865         if (!first_ec)
866                 first_ec = ec;
867         device->driver_data = ec;
868
869         WARN(!request_region(ec->data_addr, 1, "EC data"),
870              "Could not request EC data io port 0x%lx", ec->data_addr);
871         WARN(!request_region(ec->command_addr, 1, "EC cmd"),
872              "Could not request EC cmd io port 0x%lx", ec->command_addr);
873
874         pr_info(PREFIX "GPE = 0x%lx, I/O: command/status = 0x%lx, data = 0x%lx\n",
875                           ec->gpe, ec->command_addr, ec->data_addr);
876
877         ret = ec_install_handlers(ec);
878
879         /* EC is fully operational, allow queries */
880         clear_bit(EC_FLAGS_QUERY_PENDING, &ec->flags);
881
882         /* Clear stale _Q events if hardware might require that */
883         if (EC_FLAGS_CLEAR_ON_RESUME) {
884                 mutex_lock(&ec->lock);
885                 acpi_ec_clear(ec);
886                 mutex_unlock(&ec->lock);
887         }
888         return ret;
889 }
890
891 static int acpi_ec_remove(struct acpi_device *device, int type)
892 {
893         struct acpi_ec *ec;
894         struct acpi_ec_query_handler *handler, *tmp;
895
896         if (!device)
897                 return -EINVAL;
898
899         ec = acpi_driver_data(device);
900         ec_remove_handlers(ec);
901         mutex_lock(&ec->lock);
902         list_for_each_entry_safe(handler, tmp, &ec->list, node) {
903                 list_del(&handler->node);
904                 kfree(handler);
905         }
906         mutex_unlock(&ec->lock);
907         release_region(ec->data_addr, 1);
908         release_region(ec->command_addr, 1);
909         device->driver_data = NULL;
910         if (ec == first_ec)
911                 first_ec = NULL;
912         kfree(ec);
913         return 0;
914 }
915
916 static acpi_status
917 ec_parse_io_ports(struct acpi_resource *resource, void *context)
918 {
919         struct acpi_ec *ec = context;
920
921         if (resource->type != ACPI_RESOURCE_TYPE_IO)
922                 return AE_OK;
923
924         /*
925          * The first address region returned is the data port, and
926          * the second address region returned is the status/command
927          * port.
928          */
929         if (ec->data_addr == 0)
930                 ec->data_addr = resource->data.io.minimum;
931         else if (ec->command_addr == 0)
932                 ec->command_addr = resource->data.io.minimum;
933         else
934                 return AE_CTRL_TERMINATE;
935
936         return AE_OK;
937 }
938
939 int __init acpi_boot_ec_enable(void)
940 {
941         if (!boot_ec || test_bit(EC_FLAGS_HANDLERS_INSTALLED, &boot_ec->flags))
942                 return 0;
943         if (!ec_install_handlers(boot_ec)) {
944                 first_ec = boot_ec;
945                 return 0;
946         }
947         return -EFAULT;
948 }
949
950 static const struct acpi_device_id ec_device_ids[] = {
951         {"PNP0C09", 0},
952         {"", 0},
953 };
954
955 /* Some BIOS do not survive early DSDT scan, skip it */
956 static int ec_skip_dsdt_scan(const struct dmi_system_id *id)
957 {
958         EC_FLAGS_SKIP_DSDT_SCAN = 1;
959         return 0;
960 }
961
962 /* ASUStek often supplies us with broken ECDT, validate it */
963 static int ec_validate_ecdt(const struct dmi_system_id *id)
964 {
965         EC_FLAGS_VALIDATE_ECDT = 1;
966         return 0;
967 }
968
969 /* MSI EC needs special treatment, enable it */
970 static int ec_flag_msi(const struct dmi_system_id *id)
971 {
972         printk(KERN_DEBUG PREFIX "Detected MSI hardware, enabling workarounds.\n");
973         EC_FLAGS_MSI = 1;
974         EC_FLAGS_VALIDATE_ECDT = 1;
975         return 0;
976 }
977
978 /*
979  * Clevo M720 notebook actually works ok with IRQ mode, if we lifted
980  * the GPE storm threshold back to 20
981  */
982 static int ec_enlarge_storm_threshold(const struct dmi_system_id *id)
983 {
984         pr_debug("Setting the EC GPE storm threshold to 20\n");
985         ec_storm_threshold  = 20;
986         return 0;
987 }
988
989 /*
990  * On some hardware it is necessary to clear events accumulated by the EC during
991  * sleep. These ECs stop reporting GPEs until they are manually polled, if too
992  * many events are accumulated. (e.g. Samsung Series 5/9 notebooks)
993  *
994  * https://bugzilla.kernel.org/show_bug.cgi?id=44161
995  *
996  * Ideally, the EC should also be instructed NOT to accumulate events during
997  * sleep (which Windows seems to do somehow), but the interface to control this
998  * behaviour is not known at this time.
999  *
1000  * Models known to be affected are Samsung 530Uxx/535Uxx/540Uxx/550Pxx/900Xxx,
1001  * however it is very likely that other Samsung models are affected.
1002  *
1003  * On systems which don't accumulate _Q events during sleep, this extra check
1004  * should be harmless.
1005  */
1006 static int ec_clear_on_resume(const struct dmi_system_id *id)
1007 {
1008         pr_debug("Detected system needing EC poll on resume.\n");
1009         EC_FLAGS_CLEAR_ON_RESUME = 1;
1010         return 0;
1011 }
1012
1013 static struct dmi_system_id __initdata ec_dmi_table[] = {
1014         {
1015         ec_skip_dsdt_scan, "Compal JFL92", {
1016         DMI_MATCH(DMI_BIOS_VENDOR, "COMPAL"),
1017         DMI_MATCH(DMI_BOARD_NAME, "JFL92") }, NULL},
1018         {
1019         ec_flag_msi, "MSI hardware", {
1020         DMI_MATCH(DMI_BIOS_VENDOR, "Micro-Star")}, NULL},
1021         {
1022         ec_flag_msi, "MSI hardware", {
1023         DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star")}, NULL},
1024         {
1025         ec_flag_msi, "MSI hardware", {
1026         DMI_MATCH(DMI_CHASSIS_VENDOR, "MICRO-Star")}, NULL},
1027         {
1028         ec_flag_msi, "MSI hardware", {
1029         DMI_MATCH(DMI_CHASSIS_VENDOR, "MICRO-STAR")}, NULL},
1030         {
1031         ec_flag_msi, "Quanta hardware", {
1032         DMI_MATCH(DMI_SYS_VENDOR, "Quanta"),
1033         DMI_MATCH(DMI_PRODUCT_NAME, "TW8/SW8/DW8"),}, NULL},
1034         {
1035         ec_flag_msi, "Quanta hardware", {
1036         DMI_MATCH(DMI_SYS_VENDOR, "Quanta"),
1037         DMI_MATCH(DMI_PRODUCT_NAME, "TW9/SW9"),}, NULL},
1038         {
1039         ec_validate_ecdt, "ASUS hardware", {
1040         DMI_MATCH(DMI_BIOS_VENDOR, "ASUS") }, NULL},
1041         {
1042         ec_validate_ecdt, "ASUS hardware", {
1043         DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer Inc.") }, NULL},
1044         {
1045         ec_enlarge_storm_threshold, "CLEVO hardware", {
1046         DMI_MATCH(DMI_SYS_VENDOR, "CLEVO Co."),
1047         DMI_MATCH(DMI_PRODUCT_NAME, "M720T/M730T"),}, NULL},
1048         {
1049         ec_validate_ecdt, "ASUS hardware", {
1050         DMI_MATCH(DMI_SYS_VENDOR, "ASUSTek Computer Inc."),
1051         DMI_MATCH(DMI_PRODUCT_NAME, "L4R"),}, NULL},
1052         {
1053         ec_clear_on_resume, "Samsung hardware", {
1054         DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD.")}, NULL},
1055         {},
1056 };
1057
1058 int __init acpi_ec_ecdt_probe(void)
1059 {
1060         acpi_status status;
1061         struct acpi_ec *saved_ec = NULL;
1062         struct acpi_table_ecdt *ecdt_ptr;
1063
1064         boot_ec = make_acpi_ec();
1065         if (!boot_ec)
1066                 return -ENOMEM;
1067         /*
1068          * Generate a boot ec context
1069          */
1070         dmi_check_system(ec_dmi_table);
1071         status = acpi_get_table(ACPI_SIG_ECDT, 1,
1072                                 (struct acpi_table_header **)&ecdt_ptr);
1073         if (ACPI_SUCCESS(status)) {
1074                 pr_info(PREFIX "EC description table is found, configuring boot EC\n");
1075                 boot_ec->command_addr = ecdt_ptr->control.address;
1076                 boot_ec->data_addr = ecdt_ptr->data.address;
1077                 boot_ec->gpe = ecdt_ptr->gpe;
1078                 boot_ec->handle = ACPI_ROOT_OBJECT;
1079                 acpi_get_handle(ACPI_ROOT_OBJECT, ecdt_ptr->id, &boot_ec->handle);
1080                 /* Don't trust ECDT, which comes from ASUSTek */
1081                 if (!EC_FLAGS_VALIDATE_ECDT)
1082                         goto install;
1083                 saved_ec = kmemdup(boot_ec, sizeof(struct acpi_ec), GFP_KERNEL);
1084                 if (!saved_ec)
1085                         return -ENOMEM;
1086         /* fall through */
1087         }
1088
1089         if (EC_FLAGS_SKIP_DSDT_SCAN)
1090                 return -ENODEV;
1091
1092         /* This workaround is needed only on some broken machines,
1093          * which require early EC, but fail to provide ECDT */
1094         printk(KERN_DEBUG PREFIX "Look up EC in DSDT\n");
1095         status = acpi_get_devices(ec_device_ids[0].id, ec_parse_device,
1096                                         boot_ec, NULL);
1097         /* Check that acpi_get_devices actually find something */
1098         if (ACPI_FAILURE(status) || !boot_ec->handle)
1099                 goto error;
1100         if (saved_ec) {
1101                 /* try to find good ECDT from ASUSTek */
1102                 if (saved_ec->command_addr != boot_ec->command_addr ||
1103                     saved_ec->data_addr != boot_ec->data_addr ||
1104                     saved_ec->gpe != boot_ec->gpe ||
1105                     saved_ec->handle != boot_ec->handle)
1106                         pr_info(PREFIX "ASUSTek keeps feeding us with broken "
1107                         "ECDT tables, which are very hard to workaround. "
1108                         "Trying to use DSDT EC info instead. Please send "
1109                         "output of acpidump to linux-acpi@vger.kernel.org\n");
1110                 kfree(saved_ec);
1111                 saved_ec = NULL;
1112         } else {
1113                 /* We really need to limit this workaround, the only ASUS,
1114                 * which needs it, has fake EC._INI method, so use it as flag.
1115                 * Keep boot_ec struct as it will be needed soon.
1116                 */
1117                 acpi_handle dummy;
1118                 if (!dmi_name_in_vendors("ASUS") ||
1119                     ACPI_FAILURE(acpi_get_handle(boot_ec->handle, "_INI",
1120                                                         &dummy)))
1121                         return -ENODEV;
1122         }
1123 install:
1124         if (!ec_install_handlers(boot_ec)) {
1125                 first_ec = boot_ec;
1126                 return 0;
1127         }
1128 error:
1129         kfree(boot_ec);
1130         boot_ec = NULL;
1131         return -ENODEV;
1132 }
1133
1134 static struct acpi_driver acpi_ec_driver = {
1135         .name = "ec",
1136         .class = ACPI_EC_CLASS,
1137         .ids = ec_device_ids,
1138         .ops = {
1139                 .add = acpi_ec_add,
1140                 .remove = acpi_ec_remove,
1141                 },
1142 };
1143
1144 int __init acpi_ec_init(void)
1145 {
1146         int result = 0;
1147
1148         /* Now register the driver for the EC */
1149         result = acpi_bus_register_driver(&acpi_ec_driver);
1150         if (result < 0)
1151                 return -ENODEV;
1152
1153         return result;
1154 }
1155
1156 /* EC driver currently not unloadable */
1157 #if 0
1158 static void __exit acpi_ec_exit(void)
1159 {
1160
1161         acpi_bus_unregister_driver(&acpi_ec_driver);
1162         return;
1163 }
1164 #endif  /* 0 */