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