GNU Linux-libre 5.10.153-gnu1
[releases.git] / drivers / acpi / ec.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  ec.c - ACPI Embedded Controller Driver (v3)
4  *
5  *  Copyright (C) 2001-2015 Intel Corporation
6  *    Author: 2014, 2015 Lv Zheng <lv.zheng@intel.com>
7  *            2006, 2007 Alexey Starikovskiy <alexey.y.starikovskiy@intel.com>
8  *            2006       Denis Sadykov <denis.m.sadykov@intel.com>
9  *            2004       Luming Yu <luming.yu@intel.com>
10  *            2001, 2002 Andy Grover <andrew.grover@intel.com>
11  *            2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
12  *  Copyright (C) 2008      Alexey Starikovskiy <astarikovskiy@suse.de>
13  */
14
15 /* Uncomment next line to get verbose printout */
16 /* #define DEBUG */
17 #define pr_fmt(fmt) "ACPI: EC: " fmt
18
19 #include <linux/kernel.h>
20 #include <linux/module.h>
21 #include <linux/init.h>
22 #include <linux/types.h>
23 #include <linux/delay.h>
24 #include <linux/interrupt.h>
25 #include <linux/list.h>
26 #include <linux/spinlock.h>
27 #include <linux/slab.h>
28 #include <linux/suspend.h>
29 #include <linux/acpi.h>
30 #include <linux/dmi.h>
31 #include <asm/io.h>
32
33 #include "internal.h"
34
35 #define ACPI_EC_CLASS                   "embedded_controller"
36 #define ACPI_EC_DEVICE_NAME             "Embedded Controller"
37
38 /* EC status register */
39 #define ACPI_EC_FLAG_OBF        0x01    /* Output buffer full */
40 #define ACPI_EC_FLAG_IBF        0x02    /* Input buffer full */
41 #define ACPI_EC_FLAG_CMD        0x08    /* Input buffer contains a command */
42 #define ACPI_EC_FLAG_BURST      0x10    /* burst mode */
43 #define ACPI_EC_FLAG_SCI        0x20    /* EC-SCI occurred */
44
45 /*
46  * The SCI_EVT clearing timing is not defined by the ACPI specification.
47  * This leads to lots of practical timing issues for the host EC driver.
48  * The following variations are defined (from the target EC firmware's
49  * perspective):
50  * STATUS: After indicating SCI_EVT edge triggered IRQ to the host, the
51  *         target can clear SCI_EVT at any time so long as the host can see
52  *         the indication by reading the status register (EC_SC). So the
53  *         host should re-check SCI_EVT after the first time the SCI_EVT
54  *         indication is seen, which is the same time the query request
55  *         (QR_EC) is written to the command register (EC_CMD). SCI_EVT set
56  *         at any later time could indicate another event. Normally such
57  *         kind of EC firmware has implemented an event queue and will
58  *         return 0x00 to indicate "no outstanding event".
59  * QUERY: After seeing the query request (QR_EC) written to the command
60  *        register (EC_CMD) by the host and having prepared the responding
61  *        event value in the data register (EC_DATA), the target can safely
62  *        clear SCI_EVT because the target can confirm that the current
63  *        event is being handled by the host. The host then should check
64  *        SCI_EVT right after reading the event response from the data
65  *        register (EC_DATA).
66  * EVENT: After seeing the event response read from the data register
67  *        (EC_DATA) by the host, the target can clear SCI_EVT. As the
68  *        target requires time to notice the change in the data register
69  *        (EC_DATA), the host may be required to wait additional guarding
70  *        time before checking the SCI_EVT again. Such guarding may not be
71  *        necessary if the host is notified via another IRQ.
72  */
73 #define ACPI_EC_EVT_TIMING_STATUS       0x00
74 #define ACPI_EC_EVT_TIMING_QUERY        0x01
75 #define ACPI_EC_EVT_TIMING_EVENT        0x02
76
77 /* EC commands */
78 enum ec_command {
79         ACPI_EC_COMMAND_READ = 0x80,
80         ACPI_EC_COMMAND_WRITE = 0x81,
81         ACPI_EC_BURST_ENABLE = 0x82,
82         ACPI_EC_BURST_DISABLE = 0x83,
83         ACPI_EC_COMMAND_QUERY = 0x84,
84 };
85
86 #define ACPI_EC_DELAY           500     /* Wait 500ms max. during EC ops */
87 #define ACPI_EC_UDELAY_GLK      1000    /* Wait 1ms max. to get global lock */
88 #define ACPI_EC_UDELAY_POLL     550     /* Wait 1ms for EC transaction polling */
89 #define ACPI_EC_CLEAR_MAX       100     /* Maximum number of events to query
90                                          * when trying to clear the EC */
91 #define ACPI_EC_MAX_QUERIES     16      /* Maximum number of parallel queries */
92
93 enum {
94         EC_FLAGS_QUERY_ENABLED,         /* Query is enabled */
95         EC_FLAGS_QUERY_PENDING,         /* Query is pending */
96         EC_FLAGS_QUERY_GUARDING,        /* Guard for SCI_EVT check */
97         EC_FLAGS_EVENT_HANDLER_INSTALLED,       /* Event handler installed */
98         EC_FLAGS_EC_HANDLER_INSTALLED,  /* OpReg handler installed */
99         EC_FLAGS_QUERY_METHODS_INSTALLED, /* _Qxx handlers installed */
100         EC_FLAGS_STARTED,               /* Driver is started */
101         EC_FLAGS_STOPPED,               /* Driver is stopped */
102         EC_FLAGS_EVENTS_MASKED,         /* Events masked */
103 };
104
105 #define ACPI_EC_COMMAND_POLL            0x01 /* Available for command byte */
106 #define ACPI_EC_COMMAND_COMPLETE        0x02 /* Completed last byte */
107
108 /* ec.c is compiled in acpi namespace so this shows up as acpi.ec_delay param */
109 static unsigned int ec_delay __read_mostly = ACPI_EC_DELAY;
110 module_param(ec_delay, uint, 0644);
111 MODULE_PARM_DESC(ec_delay, "Timeout(ms) waited until an EC command completes");
112
113 static unsigned int ec_max_queries __read_mostly = ACPI_EC_MAX_QUERIES;
114 module_param(ec_max_queries, uint, 0644);
115 MODULE_PARM_DESC(ec_max_queries, "Maximum parallel _Qxx evaluations");
116
117 static bool ec_busy_polling __read_mostly;
118 module_param(ec_busy_polling, bool, 0644);
119 MODULE_PARM_DESC(ec_busy_polling, "Use busy polling to advance EC transaction");
120
121 static unsigned int ec_polling_guard __read_mostly = ACPI_EC_UDELAY_POLL;
122 module_param(ec_polling_guard, uint, 0644);
123 MODULE_PARM_DESC(ec_polling_guard, "Guard time(us) between EC accesses in polling modes");
124
125 static unsigned int ec_event_clearing __read_mostly = ACPI_EC_EVT_TIMING_QUERY;
126
127 /*
128  * If the number of false interrupts per one transaction exceeds
129  * this threshold, will think there is a GPE storm happened and
130  * will disable the GPE for normal transaction.
131  */
132 static unsigned int ec_storm_threshold  __read_mostly = 8;
133 module_param(ec_storm_threshold, uint, 0644);
134 MODULE_PARM_DESC(ec_storm_threshold, "Maxim false GPE numbers not considered as GPE storm");
135
136 static bool ec_freeze_events __read_mostly = false;
137 module_param(ec_freeze_events, bool, 0644);
138 MODULE_PARM_DESC(ec_freeze_events, "Disabling event handling during suspend/resume");
139
140 static bool ec_no_wakeup __read_mostly;
141 module_param(ec_no_wakeup, bool, 0644);
142 MODULE_PARM_DESC(ec_no_wakeup, "Do not wake up from suspend-to-idle");
143
144 struct acpi_ec_query_handler {
145         struct list_head node;
146         acpi_ec_query_func func;
147         acpi_handle handle;
148         void *data;
149         u8 query_bit;
150         struct kref kref;
151 };
152
153 struct transaction {
154         const u8 *wdata;
155         u8 *rdata;
156         unsigned short irq_count;
157         u8 command;
158         u8 wi;
159         u8 ri;
160         u8 wlen;
161         u8 rlen;
162         u8 flags;
163 };
164
165 struct acpi_ec_query {
166         struct transaction transaction;
167         struct work_struct work;
168         struct acpi_ec_query_handler *handler;
169         struct acpi_ec *ec;
170 };
171
172 static int acpi_ec_query(struct acpi_ec *ec, u8 *data);
173 static void advance_transaction(struct acpi_ec *ec);
174 static void acpi_ec_event_handler(struct work_struct *work);
175 static void acpi_ec_event_processor(struct work_struct *work);
176
177 struct acpi_ec *first_ec;
178 EXPORT_SYMBOL(first_ec);
179
180 static struct acpi_ec *boot_ec;
181 static bool boot_ec_is_ecdt = false;
182 static struct workqueue_struct *ec_wq;
183 static struct workqueue_struct *ec_query_wq;
184
185 static int EC_FLAGS_CORRECT_ECDT; /* Needs ECDT port address correction */
186 static int EC_FLAGS_TRUST_DSDT_GPE; /* Needs DSDT GPE as correction setting */
187 static int EC_FLAGS_CLEAR_ON_RESUME; /* Needs acpi_ec_clear() on boot/resume */
188
189 /* --------------------------------------------------------------------------
190  *                           Logging/Debugging
191  * -------------------------------------------------------------------------- */
192
193 /*
194  * Splitters used by the developers to track the boundary of the EC
195  * handling processes.
196  */
197 #ifdef DEBUG
198 #define EC_DBG_SEP      " "
199 #define EC_DBG_DRV      "+++++"
200 #define EC_DBG_STM      "====="
201 #define EC_DBG_REQ      "*****"
202 #define EC_DBG_EVT      "#####"
203 #else
204 #define EC_DBG_SEP      ""
205 #define EC_DBG_DRV
206 #define EC_DBG_STM
207 #define EC_DBG_REQ
208 #define EC_DBG_EVT
209 #endif
210
211 #define ec_log_raw(fmt, ...) \
212         pr_info(fmt "\n", ##__VA_ARGS__)
213 #define ec_dbg_raw(fmt, ...) \
214         pr_debug(fmt "\n", ##__VA_ARGS__)
215 #define ec_log(filter, fmt, ...) \
216         ec_log_raw(filter EC_DBG_SEP fmt EC_DBG_SEP filter, ##__VA_ARGS__)
217 #define ec_dbg(filter, fmt, ...) \
218         ec_dbg_raw(filter EC_DBG_SEP fmt EC_DBG_SEP filter, ##__VA_ARGS__)
219
220 #define ec_log_drv(fmt, ...) \
221         ec_log(EC_DBG_DRV, fmt, ##__VA_ARGS__)
222 #define ec_dbg_drv(fmt, ...) \
223         ec_dbg(EC_DBG_DRV, fmt, ##__VA_ARGS__)
224 #define ec_dbg_stm(fmt, ...) \
225         ec_dbg(EC_DBG_STM, fmt, ##__VA_ARGS__)
226 #define ec_dbg_req(fmt, ...) \
227         ec_dbg(EC_DBG_REQ, fmt, ##__VA_ARGS__)
228 #define ec_dbg_evt(fmt, ...) \
229         ec_dbg(EC_DBG_EVT, fmt, ##__VA_ARGS__)
230 #define ec_dbg_ref(ec, fmt, ...) \
231         ec_dbg_raw("%lu: " fmt, ec->reference_count, ## __VA_ARGS__)
232
233 /* --------------------------------------------------------------------------
234  *                           Device Flags
235  * -------------------------------------------------------------------------- */
236
237 static bool acpi_ec_started(struct acpi_ec *ec)
238 {
239         return test_bit(EC_FLAGS_STARTED, &ec->flags) &&
240                !test_bit(EC_FLAGS_STOPPED, &ec->flags);
241 }
242
243 static bool acpi_ec_event_enabled(struct acpi_ec *ec)
244 {
245         /*
246          * There is an OSPM early stage logic. During the early stages
247          * (boot/resume), OSPMs shouldn't enable the event handling, only
248          * the EC transactions are allowed to be performed.
249          */
250         if (!test_bit(EC_FLAGS_QUERY_ENABLED, &ec->flags))
251                 return false;
252         /*
253          * However, disabling the event handling is experimental for late
254          * stage (suspend), and is controlled by the boot parameter of
255          * "ec_freeze_events":
256          * 1. true:  The EC event handling is disabled before entering
257          *           the noirq stage.
258          * 2. false: The EC event handling is automatically disabled as
259          *           soon as the EC driver is stopped.
260          */
261         if (ec_freeze_events)
262                 return acpi_ec_started(ec);
263         else
264                 return test_bit(EC_FLAGS_STARTED, &ec->flags);
265 }
266
267 static bool acpi_ec_flushed(struct acpi_ec *ec)
268 {
269         return ec->reference_count == 1;
270 }
271
272 /* --------------------------------------------------------------------------
273  *                           EC Registers
274  * -------------------------------------------------------------------------- */
275
276 static inline u8 acpi_ec_read_status(struct acpi_ec *ec)
277 {
278         u8 x = inb(ec->command_addr);
279
280         ec_dbg_raw("EC_SC(R) = 0x%2.2x "
281                    "SCI_EVT=%d BURST=%d CMD=%d IBF=%d OBF=%d",
282                    x,
283                    !!(x & ACPI_EC_FLAG_SCI),
284                    !!(x & ACPI_EC_FLAG_BURST),
285                    !!(x & ACPI_EC_FLAG_CMD),
286                    !!(x & ACPI_EC_FLAG_IBF),
287                    !!(x & ACPI_EC_FLAG_OBF));
288         return x;
289 }
290
291 static inline u8 acpi_ec_read_data(struct acpi_ec *ec)
292 {
293         u8 x = inb(ec->data_addr);
294
295         ec->timestamp = jiffies;
296         ec_dbg_raw("EC_DATA(R) = 0x%2.2x", x);
297         return x;
298 }
299
300 static inline void acpi_ec_write_cmd(struct acpi_ec *ec, u8 command)
301 {
302         ec_dbg_raw("EC_SC(W) = 0x%2.2x", command);
303         outb(command, ec->command_addr);
304         ec->timestamp = jiffies;
305 }
306
307 static inline void acpi_ec_write_data(struct acpi_ec *ec, u8 data)
308 {
309         ec_dbg_raw("EC_DATA(W) = 0x%2.2x", data);
310         outb(data, ec->data_addr);
311         ec->timestamp = jiffies;
312 }
313
314 #if defined(DEBUG) || defined(CONFIG_DYNAMIC_DEBUG)
315 static const char *acpi_ec_cmd_string(u8 cmd)
316 {
317         switch (cmd) {
318         case 0x80:
319                 return "RD_EC";
320         case 0x81:
321                 return "WR_EC";
322         case 0x82:
323                 return "BE_EC";
324         case 0x83:
325                 return "BD_EC";
326         case 0x84:
327                 return "QR_EC";
328         }
329         return "UNKNOWN";
330 }
331 #else
332 #define acpi_ec_cmd_string(cmd)         "UNDEF"
333 #endif
334
335 /* --------------------------------------------------------------------------
336  *                           GPE Registers
337  * -------------------------------------------------------------------------- */
338
339 static inline bool acpi_ec_is_gpe_raised(struct acpi_ec *ec)
340 {
341         acpi_event_status gpe_status = 0;
342
343         (void)acpi_get_gpe_status(NULL, ec->gpe, &gpe_status);
344         return (gpe_status & ACPI_EVENT_FLAG_STATUS_SET) ? true : false;
345 }
346
347 static inline void acpi_ec_enable_gpe(struct acpi_ec *ec, bool open)
348 {
349         if (open)
350                 acpi_enable_gpe(NULL, ec->gpe);
351         else {
352                 BUG_ON(ec->reference_count < 1);
353                 acpi_set_gpe(NULL, ec->gpe, ACPI_GPE_ENABLE);
354         }
355         if (acpi_ec_is_gpe_raised(ec)) {
356                 /*
357                  * On some platforms, EN=1 writes cannot trigger GPE. So
358                  * software need to manually trigger a pseudo GPE event on
359                  * EN=1 writes.
360                  */
361                 ec_dbg_raw("Polling quirk");
362                 advance_transaction(ec);
363         }
364 }
365
366 static inline void acpi_ec_disable_gpe(struct acpi_ec *ec, bool close)
367 {
368         if (close)
369                 acpi_disable_gpe(NULL, ec->gpe);
370         else {
371                 BUG_ON(ec->reference_count < 1);
372                 acpi_set_gpe(NULL, ec->gpe, ACPI_GPE_DISABLE);
373         }
374 }
375
376 static inline void acpi_ec_clear_gpe(struct acpi_ec *ec)
377 {
378         /*
379          * GPE STS is a W1C register, which means:
380          * 1. Software can clear it without worrying about clearing other
381          *    GPEs' STS bits when the hardware sets them in parallel.
382          * 2. As long as software can ensure only clearing it when it is
383          *    set, hardware won't set it in parallel.
384          * So software can clear GPE in any contexts.
385          * Warning: do not move the check into advance_transaction() as the
386          * EC commands will be sent without GPE raised.
387          */
388         if (!acpi_ec_is_gpe_raised(ec))
389                 return;
390         acpi_clear_gpe(NULL, ec->gpe);
391 }
392
393 /* --------------------------------------------------------------------------
394  *                           Transaction Management
395  * -------------------------------------------------------------------------- */
396
397 static void acpi_ec_submit_request(struct acpi_ec *ec)
398 {
399         ec->reference_count++;
400         if (test_bit(EC_FLAGS_EVENT_HANDLER_INSTALLED, &ec->flags) &&
401             ec->gpe >= 0 && ec->reference_count == 1)
402                 acpi_ec_enable_gpe(ec, true);
403 }
404
405 static void acpi_ec_complete_request(struct acpi_ec *ec)
406 {
407         bool flushed = false;
408
409         ec->reference_count--;
410         if (test_bit(EC_FLAGS_EVENT_HANDLER_INSTALLED, &ec->flags) &&
411             ec->gpe >= 0 && ec->reference_count == 0)
412                 acpi_ec_disable_gpe(ec, true);
413         flushed = acpi_ec_flushed(ec);
414         if (flushed)
415                 wake_up(&ec->wait);
416 }
417
418 static void acpi_ec_mask_events(struct acpi_ec *ec)
419 {
420         if (!test_bit(EC_FLAGS_EVENTS_MASKED, &ec->flags)) {
421                 if (ec->gpe >= 0)
422                         acpi_ec_disable_gpe(ec, false);
423                 else
424                         disable_irq_nosync(ec->irq);
425
426                 ec_dbg_drv("Polling enabled");
427                 set_bit(EC_FLAGS_EVENTS_MASKED, &ec->flags);
428         }
429 }
430
431 static void acpi_ec_unmask_events(struct acpi_ec *ec)
432 {
433         if (test_bit(EC_FLAGS_EVENTS_MASKED, &ec->flags)) {
434                 clear_bit(EC_FLAGS_EVENTS_MASKED, &ec->flags);
435                 if (ec->gpe >= 0)
436                         acpi_ec_enable_gpe(ec, false);
437                 else
438                         enable_irq(ec->irq);
439
440                 ec_dbg_drv("Polling disabled");
441         }
442 }
443
444 /*
445  * acpi_ec_submit_flushable_request() - Increase the reference count unless
446  *                                      the flush operation is not in
447  *                                      progress
448  * @ec: the EC device
449  *
450  * This function must be used before taking a new action that should hold
451  * the reference count.  If this function returns false, then the action
452  * must be discarded or it will prevent the flush operation from being
453  * completed.
454  */
455 static bool acpi_ec_submit_flushable_request(struct acpi_ec *ec)
456 {
457         if (!acpi_ec_started(ec))
458                 return false;
459         acpi_ec_submit_request(ec);
460         return true;
461 }
462
463 static void acpi_ec_submit_query(struct acpi_ec *ec)
464 {
465         acpi_ec_mask_events(ec);
466         if (!acpi_ec_event_enabled(ec))
467                 return;
468         if (!test_and_set_bit(EC_FLAGS_QUERY_PENDING, &ec->flags)) {
469                 ec_dbg_evt("Command(%s) submitted/blocked",
470                            acpi_ec_cmd_string(ACPI_EC_COMMAND_QUERY));
471                 ec->nr_pending_queries++;
472                 ec->events_in_progress++;
473                 queue_work(ec_wq, &ec->work);
474         }
475 }
476
477 static void acpi_ec_complete_query(struct acpi_ec *ec)
478 {
479         if (test_and_clear_bit(EC_FLAGS_QUERY_PENDING, &ec->flags))
480                 ec_dbg_evt("Command(%s) unblocked",
481                            acpi_ec_cmd_string(ACPI_EC_COMMAND_QUERY));
482         acpi_ec_unmask_events(ec);
483 }
484
485 static inline void __acpi_ec_enable_event(struct acpi_ec *ec)
486 {
487         if (!test_and_set_bit(EC_FLAGS_QUERY_ENABLED, &ec->flags))
488                 ec_log_drv("event unblocked");
489         /*
490          * Unconditionally invoke this once after enabling the event
491          * handling mechanism to detect the pending events.
492          */
493         advance_transaction(ec);
494 }
495
496 static inline void __acpi_ec_disable_event(struct acpi_ec *ec)
497 {
498         if (test_and_clear_bit(EC_FLAGS_QUERY_ENABLED, &ec->flags))
499                 ec_log_drv("event blocked");
500 }
501
502 /*
503  * Process _Q events that might have accumulated in the EC.
504  * Run with locked ec mutex.
505  */
506 static void acpi_ec_clear(struct acpi_ec *ec)
507 {
508         int i, status;
509         u8 value = 0;
510
511         for (i = 0; i < ACPI_EC_CLEAR_MAX; i++) {
512                 status = acpi_ec_query(ec, &value);
513                 if (status || !value)
514                         break;
515         }
516         if (unlikely(i == ACPI_EC_CLEAR_MAX))
517                 pr_warn("Warning: Maximum of %d stale EC events cleared\n", i);
518         else
519                 pr_info("%d stale EC events cleared\n", i);
520 }
521
522 static void acpi_ec_enable_event(struct acpi_ec *ec)
523 {
524         unsigned long flags;
525
526         spin_lock_irqsave(&ec->lock, flags);
527         if (acpi_ec_started(ec))
528                 __acpi_ec_enable_event(ec);
529         spin_unlock_irqrestore(&ec->lock, flags);
530
531         /* Drain additional events if hardware requires that */
532         if (EC_FLAGS_CLEAR_ON_RESUME)
533                 acpi_ec_clear(ec);
534 }
535
536 #ifdef CONFIG_PM_SLEEP
537 static void __acpi_ec_flush_work(void)
538 {
539         flush_workqueue(ec_wq); /* flush ec->work */
540         flush_workqueue(ec_query_wq); /* flush queries */
541 }
542
543 static void acpi_ec_disable_event(struct acpi_ec *ec)
544 {
545         unsigned long flags;
546
547         spin_lock_irqsave(&ec->lock, flags);
548         __acpi_ec_disable_event(ec);
549         spin_unlock_irqrestore(&ec->lock, flags);
550
551         /*
552          * When ec_freeze_events is true, we need to flush events in
553          * the proper position before entering the noirq stage.
554          */
555         __acpi_ec_flush_work();
556 }
557
558 void acpi_ec_flush_work(void)
559 {
560         /* Without ec_wq there is nothing to flush. */
561         if (!ec_wq)
562                 return;
563
564         __acpi_ec_flush_work();
565 }
566 #endif /* CONFIG_PM_SLEEP */
567
568 static bool acpi_ec_guard_event(struct acpi_ec *ec)
569 {
570         bool guarded = true;
571         unsigned long flags;
572
573         spin_lock_irqsave(&ec->lock, flags);
574         /*
575          * If firmware SCI_EVT clearing timing is "event", we actually
576          * don't know when the SCI_EVT will be cleared by firmware after
577          * evaluating _Qxx, so we need to re-check SCI_EVT after waiting an
578          * acceptable period.
579          *
580          * The guarding period begins when EC_FLAGS_QUERY_PENDING is
581          * flagged, which means SCI_EVT check has just been performed.
582          * But if the current transaction is ACPI_EC_COMMAND_QUERY, the
583          * guarding should have already been performed (via
584          * EC_FLAGS_QUERY_GUARDING) and should not be applied so that the
585          * ACPI_EC_COMMAND_QUERY transaction can be transitioned into
586          * ACPI_EC_COMMAND_POLL state immediately.
587          */
588         if (ec_event_clearing == ACPI_EC_EVT_TIMING_STATUS ||
589             ec_event_clearing == ACPI_EC_EVT_TIMING_QUERY ||
590             !test_bit(EC_FLAGS_QUERY_PENDING, &ec->flags) ||
591             (ec->curr && ec->curr->command == ACPI_EC_COMMAND_QUERY))
592                 guarded = false;
593         spin_unlock_irqrestore(&ec->lock, flags);
594         return guarded;
595 }
596
597 static int ec_transaction_polled(struct acpi_ec *ec)
598 {
599         unsigned long flags;
600         int ret = 0;
601
602         spin_lock_irqsave(&ec->lock, flags);
603         if (ec->curr && (ec->curr->flags & ACPI_EC_COMMAND_POLL))
604                 ret = 1;
605         spin_unlock_irqrestore(&ec->lock, flags);
606         return ret;
607 }
608
609 static int ec_transaction_completed(struct acpi_ec *ec)
610 {
611         unsigned long flags;
612         int ret = 0;
613
614         spin_lock_irqsave(&ec->lock, flags);
615         if (ec->curr && (ec->curr->flags & ACPI_EC_COMMAND_COMPLETE))
616                 ret = 1;
617         spin_unlock_irqrestore(&ec->lock, flags);
618         return ret;
619 }
620
621 static inline void ec_transaction_transition(struct acpi_ec *ec, unsigned long flag)
622 {
623         ec->curr->flags |= flag;
624         if (ec->curr->command == ACPI_EC_COMMAND_QUERY) {
625                 if (ec_event_clearing == ACPI_EC_EVT_TIMING_STATUS &&
626                     flag == ACPI_EC_COMMAND_POLL)
627                         acpi_ec_complete_query(ec);
628                 if (ec_event_clearing == ACPI_EC_EVT_TIMING_QUERY &&
629                     flag == ACPI_EC_COMMAND_COMPLETE)
630                         acpi_ec_complete_query(ec);
631                 if (ec_event_clearing == ACPI_EC_EVT_TIMING_EVENT &&
632                     flag == ACPI_EC_COMMAND_COMPLETE)
633                         set_bit(EC_FLAGS_QUERY_GUARDING, &ec->flags);
634         }
635 }
636
637 static void advance_transaction(struct acpi_ec *ec)
638 {
639         struct transaction *t;
640         u8 status;
641         bool wakeup = false;
642
643         ec_dbg_stm("%s (%d)", in_interrupt() ? "IRQ" : "TASK",
644                    smp_processor_id());
645         /*
646          * By always clearing STS before handling all indications, we can
647          * ensure a hardware STS 0->1 change after this clearing can always
648          * trigger a GPE interrupt.
649          */
650         if (ec->gpe >= 0)
651                 acpi_ec_clear_gpe(ec);
652
653         status = acpi_ec_read_status(ec);
654         t = ec->curr;
655         /*
656          * Another IRQ or a guarded polling mode advancement is detected,
657          * the next QR_EC submission is then allowed.
658          */
659         if (!t || !(t->flags & ACPI_EC_COMMAND_POLL)) {
660                 if (ec_event_clearing == ACPI_EC_EVT_TIMING_EVENT &&
661                     (!ec->nr_pending_queries ||
662                      test_bit(EC_FLAGS_QUERY_GUARDING, &ec->flags))) {
663                         clear_bit(EC_FLAGS_QUERY_GUARDING, &ec->flags);
664                         acpi_ec_complete_query(ec);
665                 }
666         }
667         if (!t)
668                 goto err;
669         if (t->flags & ACPI_EC_COMMAND_POLL) {
670                 if (t->wlen > t->wi) {
671                         if ((status & ACPI_EC_FLAG_IBF) == 0)
672                                 acpi_ec_write_data(ec, t->wdata[t->wi++]);
673                         else
674                                 goto err;
675                 } else if (t->rlen > t->ri) {
676                         if ((status & ACPI_EC_FLAG_OBF) == 1) {
677                                 t->rdata[t->ri++] = acpi_ec_read_data(ec);
678                                 if (t->rlen == t->ri) {
679                                         ec_transaction_transition(ec, ACPI_EC_COMMAND_COMPLETE);
680                                         if (t->command == ACPI_EC_COMMAND_QUERY)
681                                                 ec_dbg_evt("Command(%s) completed by hardware",
682                                                            acpi_ec_cmd_string(ACPI_EC_COMMAND_QUERY));
683                                         wakeup = true;
684                                 }
685                         } else
686                                 goto err;
687                 } else if (t->wlen == t->wi &&
688                            (status & ACPI_EC_FLAG_IBF) == 0) {
689                         ec_transaction_transition(ec, ACPI_EC_COMMAND_COMPLETE);
690                         wakeup = true;
691                 }
692                 goto out;
693         } else if (!(status & ACPI_EC_FLAG_IBF)) {
694                 acpi_ec_write_cmd(ec, t->command);
695                 ec_transaction_transition(ec, ACPI_EC_COMMAND_POLL);
696                 goto out;
697         }
698 err:
699         /*
700          * If SCI bit is set, then don't think it's a false IRQ
701          * otherwise will take a not handled IRQ as a false one.
702          */
703         if (!(status & ACPI_EC_FLAG_SCI)) {
704                 if (in_interrupt() && t) {
705                         if (t->irq_count < ec_storm_threshold)
706                                 ++t->irq_count;
707                         /* Allow triggering on 0 threshold */
708                         if (t->irq_count == ec_storm_threshold)
709                                 acpi_ec_mask_events(ec);
710                 }
711         }
712 out:
713         if (status & ACPI_EC_FLAG_SCI)
714                 acpi_ec_submit_query(ec);
715         if (wakeup && in_interrupt())
716                 wake_up(&ec->wait);
717 }
718
719 static void start_transaction(struct acpi_ec *ec)
720 {
721         ec->curr->irq_count = ec->curr->wi = ec->curr->ri = 0;
722         ec->curr->flags = 0;
723 }
724
725 static int ec_guard(struct acpi_ec *ec)
726 {
727         unsigned long guard = usecs_to_jiffies(ec->polling_guard);
728         unsigned long timeout = ec->timestamp + guard;
729
730         /* Ensure guarding period before polling EC status */
731         do {
732                 if (ec->busy_polling) {
733                         /* Perform busy polling */
734                         if (ec_transaction_completed(ec))
735                                 return 0;
736                         udelay(jiffies_to_usecs(guard));
737                 } else {
738                         /*
739                          * Perform wait polling
740                          * 1. Wait the transaction to be completed by the
741                          *    GPE handler after the transaction enters
742                          *    ACPI_EC_COMMAND_POLL state.
743                          * 2. A special guarding logic is also required
744                          *    for event clearing mode "event" before the
745                          *    transaction enters ACPI_EC_COMMAND_POLL
746                          *    state.
747                          */
748                         if (!ec_transaction_polled(ec) &&
749                             !acpi_ec_guard_event(ec))
750                                 break;
751                         if (wait_event_timeout(ec->wait,
752                                                ec_transaction_completed(ec),
753                                                guard))
754                                 return 0;
755                 }
756         } while (time_before(jiffies, timeout));
757         return -ETIME;
758 }
759
760 static int ec_poll(struct acpi_ec *ec)
761 {
762         unsigned long flags;
763         int repeat = 5; /* number of command restarts */
764
765         while (repeat--) {
766                 unsigned long delay = jiffies +
767                         msecs_to_jiffies(ec_delay);
768                 do {
769                         if (!ec_guard(ec))
770                                 return 0;
771                         spin_lock_irqsave(&ec->lock, flags);
772                         advance_transaction(ec);
773                         spin_unlock_irqrestore(&ec->lock, flags);
774                 } while (time_before(jiffies, delay));
775                 pr_debug("controller reset, restart transaction\n");
776                 spin_lock_irqsave(&ec->lock, flags);
777                 start_transaction(ec);
778                 spin_unlock_irqrestore(&ec->lock, flags);
779         }
780         return -ETIME;
781 }
782
783 static int acpi_ec_transaction_unlocked(struct acpi_ec *ec,
784                                         struct transaction *t)
785 {
786         unsigned long tmp;
787         int ret = 0;
788
789         /* start transaction */
790         spin_lock_irqsave(&ec->lock, tmp);
791         /* Enable GPE for command processing (IBF=0/OBF=1) */
792         if (!acpi_ec_submit_flushable_request(ec)) {
793                 ret = -EINVAL;
794                 goto unlock;
795         }
796         ec_dbg_ref(ec, "Increase command");
797         /* following two actions should be kept atomic */
798         ec->curr = t;
799         ec_dbg_req("Command(%s) started", acpi_ec_cmd_string(t->command));
800         start_transaction(ec);
801         spin_unlock_irqrestore(&ec->lock, tmp);
802
803         ret = ec_poll(ec);
804
805         spin_lock_irqsave(&ec->lock, tmp);
806         if (t->irq_count == ec_storm_threshold)
807                 acpi_ec_unmask_events(ec);
808         ec_dbg_req("Command(%s) stopped", acpi_ec_cmd_string(t->command));
809         ec->curr = NULL;
810         /* Disable GPE for command processing (IBF=0/OBF=1) */
811         acpi_ec_complete_request(ec);
812         ec_dbg_ref(ec, "Decrease command");
813 unlock:
814         spin_unlock_irqrestore(&ec->lock, tmp);
815         return ret;
816 }
817
818 static int acpi_ec_transaction(struct acpi_ec *ec, struct transaction *t)
819 {
820         int status;
821         u32 glk;
822
823         if (!ec || (!t) || (t->wlen && !t->wdata) || (t->rlen && !t->rdata))
824                 return -EINVAL;
825         if (t->rdata)
826                 memset(t->rdata, 0, t->rlen);
827
828         mutex_lock(&ec->mutex);
829         if (ec->global_lock) {
830                 status = acpi_acquire_global_lock(ACPI_EC_UDELAY_GLK, &glk);
831                 if (ACPI_FAILURE(status)) {
832                         status = -ENODEV;
833                         goto unlock;
834                 }
835         }
836
837         status = acpi_ec_transaction_unlocked(ec, t);
838
839         if (ec->global_lock)
840                 acpi_release_global_lock(glk);
841 unlock:
842         mutex_unlock(&ec->mutex);
843         return status;
844 }
845
846 static int acpi_ec_burst_enable(struct acpi_ec *ec)
847 {
848         u8 d;
849         struct transaction t = {.command = ACPI_EC_BURST_ENABLE,
850                                 .wdata = NULL, .rdata = &d,
851                                 .wlen = 0, .rlen = 1};
852
853         return acpi_ec_transaction(ec, &t);
854 }
855
856 static int acpi_ec_burst_disable(struct acpi_ec *ec)
857 {
858         struct transaction t = {.command = ACPI_EC_BURST_DISABLE,
859                                 .wdata = NULL, .rdata = NULL,
860                                 .wlen = 0, .rlen = 0};
861
862         return (acpi_ec_read_status(ec) & ACPI_EC_FLAG_BURST) ?
863                                 acpi_ec_transaction(ec, &t) : 0;
864 }
865
866 static int acpi_ec_read(struct acpi_ec *ec, u8 address, u8 *data)
867 {
868         int result;
869         u8 d;
870         struct transaction t = {.command = ACPI_EC_COMMAND_READ,
871                                 .wdata = &address, .rdata = &d,
872                                 .wlen = 1, .rlen = 1};
873
874         result = acpi_ec_transaction(ec, &t);
875         *data = d;
876         return result;
877 }
878
879 static int acpi_ec_write(struct acpi_ec *ec, u8 address, u8 data)
880 {
881         u8 wdata[2] = { address, data };
882         struct transaction t = {.command = ACPI_EC_COMMAND_WRITE,
883                                 .wdata = wdata, .rdata = NULL,
884                                 .wlen = 2, .rlen = 0};
885
886         return acpi_ec_transaction(ec, &t);
887 }
888
889 int ec_read(u8 addr, u8 *val)
890 {
891         int err;
892         u8 temp_data;
893
894         if (!first_ec)
895                 return -ENODEV;
896
897         err = acpi_ec_read(first_ec, addr, &temp_data);
898
899         if (!err) {
900                 *val = temp_data;
901                 return 0;
902         }
903         return err;
904 }
905 EXPORT_SYMBOL(ec_read);
906
907 int ec_write(u8 addr, u8 val)
908 {
909         int err;
910
911         if (!first_ec)
912                 return -ENODEV;
913
914         err = acpi_ec_write(first_ec, addr, val);
915
916         return err;
917 }
918 EXPORT_SYMBOL(ec_write);
919
920 int ec_transaction(u8 command,
921                    const u8 *wdata, unsigned wdata_len,
922                    u8 *rdata, unsigned rdata_len)
923 {
924         struct transaction t = {.command = command,
925                                 .wdata = wdata, .rdata = rdata,
926                                 .wlen = wdata_len, .rlen = rdata_len};
927
928         if (!first_ec)
929                 return -ENODEV;
930
931         return acpi_ec_transaction(first_ec, &t);
932 }
933 EXPORT_SYMBOL(ec_transaction);
934
935 /* Get the handle to the EC device */
936 acpi_handle ec_get_handle(void)
937 {
938         if (!first_ec)
939                 return NULL;
940         return first_ec->handle;
941 }
942 EXPORT_SYMBOL(ec_get_handle);
943
944 static void acpi_ec_start(struct acpi_ec *ec, bool resuming)
945 {
946         unsigned long flags;
947
948         spin_lock_irqsave(&ec->lock, flags);
949         if (!test_and_set_bit(EC_FLAGS_STARTED, &ec->flags)) {
950                 ec_dbg_drv("Starting EC");
951                 /* Enable GPE for event processing (SCI_EVT=1) */
952                 if (!resuming) {
953                         acpi_ec_submit_request(ec);
954                         ec_dbg_ref(ec, "Increase driver");
955                 }
956                 ec_log_drv("EC started");
957         }
958         spin_unlock_irqrestore(&ec->lock, flags);
959 }
960
961 static bool acpi_ec_stopped(struct acpi_ec *ec)
962 {
963         unsigned long flags;
964         bool flushed;
965
966         spin_lock_irqsave(&ec->lock, flags);
967         flushed = acpi_ec_flushed(ec);
968         spin_unlock_irqrestore(&ec->lock, flags);
969         return flushed;
970 }
971
972 static void acpi_ec_stop(struct acpi_ec *ec, bool suspending)
973 {
974         unsigned long flags;
975
976         spin_lock_irqsave(&ec->lock, flags);
977         if (acpi_ec_started(ec)) {
978                 ec_dbg_drv("Stopping EC");
979                 set_bit(EC_FLAGS_STOPPED, &ec->flags);
980                 spin_unlock_irqrestore(&ec->lock, flags);
981                 wait_event(ec->wait, acpi_ec_stopped(ec));
982                 spin_lock_irqsave(&ec->lock, flags);
983                 /* Disable GPE for event processing (SCI_EVT=1) */
984                 if (!suspending) {
985                         acpi_ec_complete_request(ec);
986                         ec_dbg_ref(ec, "Decrease driver");
987                 } else if (!ec_freeze_events)
988                         __acpi_ec_disable_event(ec);
989                 clear_bit(EC_FLAGS_STARTED, &ec->flags);
990                 clear_bit(EC_FLAGS_STOPPED, &ec->flags);
991                 ec_log_drv("EC stopped");
992         }
993         spin_unlock_irqrestore(&ec->lock, flags);
994 }
995
996 static void acpi_ec_enter_noirq(struct acpi_ec *ec)
997 {
998         unsigned long flags;
999
1000         spin_lock_irqsave(&ec->lock, flags);
1001         ec->busy_polling = true;
1002         ec->polling_guard = 0;
1003         ec_log_drv("interrupt blocked");
1004         spin_unlock_irqrestore(&ec->lock, flags);
1005 }
1006
1007 static void acpi_ec_leave_noirq(struct acpi_ec *ec)
1008 {
1009         unsigned long flags;
1010
1011         spin_lock_irqsave(&ec->lock, flags);
1012         ec->busy_polling = ec_busy_polling;
1013         ec->polling_guard = ec_polling_guard;
1014         ec_log_drv("interrupt unblocked");
1015         spin_unlock_irqrestore(&ec->lock, flags);
1016 }
1017
1018 void acpi_ec_block_transactions(void)
1019 {
1020         struct acpi_ec *ec = first_ec;
1021
1022         if (!ec)
1023                 return;
1024
1025         mutex_lock(&ec->mutex);
1026         /* Prevent transactions from being carried out */
1027         acpi_ec_stop(ec, true);
1028         mutex_unlock(&ec->mutex);
1029 }
1030
1031 void acpi_ec_unblock_transactions(void)
1032 {
1033         /*
1034          * Allow transactions to happen again (this function is called from
1035          * atomic context during wakeup, so we don't need to acquire the mutex).
1036          */
1037         if (first_ec)
1038                 acpi_ec_start(first_ec, true);
1039 }
1040
1041 /* --------------------------------------------------------------------------
1042                                 Event Management
1043    -------------------------------------------------------------------------- */
1044 static struct acpi_ec_query_handler *
1045 acpi_ec_get_query_handler_by_value(struct acpi_ec *ec, u8 value)
1046 {
1047         struct acpi_ec_query_handler *handler;
1048
1049         mutex_lock(&ec->mutex);
1050         list_for_each_entry(handler, &ec->list, node) {
1051                 if (value == handler->query_bit) {
1052                         kref_get(&handler->kref);
1053                         mutex_unlock(&ec->mutex);
1054                         return handler;
1055                 }
1056         }
1057         mutex_unlock(&ec->mutex);
1058         return NULL;
1059 }
1060
1061 static void acpi_ec_query_handler_release(struct kref *kref)
1062 {
1063         struct acpi_ec_query_handler *handler =
1064                 container_of(kref, struct acpi_ec_query_handler, kref);
1065
1066         kfree(handler);
1067 }
1068
1069 static void acpi_ec_put_query_handler(struct acpi_ec_query_handler *handler)
1070 {
1071         kref_put(&handler->kref, acpi_ec_query_handler_release);
1072 }
1073
1074 int acpi_ec_add_query_handler(struct acpi_ec *ec, u8 query_bit,
1075                               acpi_handle handle, acpi_ec_query_func func,
1076                               void *data)
1077 {
1078         struct acpi_ec_query_handler *handler =
1079             kzalloc(sizeof(struct acpi_ec_query_handler), GFP_KERNEL);
1080
1081         if (!handler)
1082                 return -ENOMEM;
1083
1084         handler->query_bit = query_bit;
1085         handler->handle = handle;
1086         handler->func = func;
1087         handler->data = data;
1088         mutex_lock(&ec->mutex);
1089         kref_init(&handler->kref);
1090         list_add(&handler->node, &ec->list);
1091         mutex_unlock(&ec->mutex);
1092         return 0;
1093 }
1094 EXPORT_SYMBOL_GPL(acpi_ec_add_query_handler);
1095
1096 static void acpi_ec_remove_query_handlers(struct acpi_ec *ec,
1097                                           bool remove_all, u8 query_bit)
1098 {
1099         struct acpi_ec_query_handler *handler, *tmp;
1100         LIST_HEAD(free_list);
1101
1102         mutex_lock(&ec->mutex);
1103         list_for_each_entry_safe(handler, tmp, &ec->list, node) {
1104                 if (remove_all || query_bit == handler->query_bit) {
1105                         list_del_init(&handler->node);
1106                         list_add(&handler->node, &free_list);
1107                 }
1108         }
1109         mutex_unlock(&ec->mutex);
1110         list_for_each_entry_safe(handler, tmp, &free_list, node)
1111                 acpi_ec_put_query_handler(handler);
1112 }
1113
1114 void acpi_ec_remove_query_handler(struct acpi_ec *ec, u8 query_bit)
1115 {
1116         acpi_ec_remove_query_handlers(ec, false, query_bit);
1117 }
1118 EXPORT_SYMBOL_GPL(acpi_ec_remove_query_handler);
1119
1120 static struct acpi_ec_query *acpi_ec_create_query(struct acpi_ec *ec, u8 *pval)
1121 {
1122         struct acpi_ec_query *q;
1123         struct transaction *t;
1124
1125         q = kzalloc(sizeof (struct acpi_ec_query), GFP_KERNEL);
1126         if (!q)
1127                 return NULL;
1128
1129         INIT_WORK(&q->work, acpi_ec_event_processor);
1130         t = &q->transaction;
1131         t->command = ACPI_EC_COMMAND_QUERY;
1132         t->rdata = pval;
1133         t->rlen = 1;
1134         q->ec = ec;
1135         return q;
1136 }
1137
1138 static void acpi_ec_delete_query(struct acpi_ec_query *q)
1139 {
1140         if (q) {
1141                 if (q->handler)
1142                         acpi_ec_put_query_handler(q->handler);
1143                 kfree(q);
1144         }
1145 }
1146
1147 static void acpi_ec_event_processor(struct work_struct *work)
1148 {
1149         struct acpi_ec_query *q = container_of(work, struct acpi_ec_query, work);
1150         struct acpi_ec_query_handler *handler = q->handler;
1151         struct acpi_ec *ec = q->ec;
1152
1153         ec_dbg_evt("Query(0x%02x) started", handler->query_bit);
1154
1155         if (handler->func)
1156                 handler->func(handler->data);
1157         else if (handler->handle)
1158                 acpi_evaluate_object(handler->handle, NULL, NULL, NULL);
1159
1160         ec_dbg_evt("Query(0x%02x) stopped", handler->query_bit);
1161
1162         spin_lock_irq(&ec->lock);
1163         ec->queries_in_progress--;
1164         spin_unlock_irq(&ec->lock);
1165
1166         acpi_ec_delete_query(q);
1167 }
1168
1169 static int acpi_ec_query(struct acpi_ec *ec, u8 *data)
1170 {
1171         u8 value = 0;
1172         int result;
1173         struct acpi_ec_query *q;
1174
1175         q = acpi_ec_create_query(ec, &value);
1176         if (!q)
1177                 return -ENOMEM;
1178
1179         /*
1180          * Query the EC to find out which _Qxx method we need to evaluate.
1181          * Note that successful completion of the query causes the ACPI_EC_SCI
1182          * bit to be cleared (and thus clearing the interrupt source).
1183          */
1184         result = acpi_ec_transaction(ec, &q->transaction);
1185         if (!value)
1186                 result = -ENODATA;
1187         if (result)
1188                 goto err_exit;
1189
1190         q->handler = acpi_ec_get_query_handler_by_value(ec, value);
1191         if (!q->handler) {
1192                 result = -ENODATA;
1193                 goto err_exit;
1194         }
1195
1196         /*
1197          * It is reported that _Qxx are evaluated in a parallel way on Windows:
1198          * https://bugzilla.kernel.org/show_bug.cgi?id=94411
1199          *
1200          * Put this log entry before queue_work() to make it appear in the log
1201          * before any other messages emitted during workqueue handling.
1202          */
1203         ec_dbg_evt("Query(0x%02x) scheduled", value);
1204
1205         spin_lock_irq(&ec->lock);
1206
1207         ec->queries_in_progress++;
1208         queue_work(ec_query_wq, &q->work);
1209
1210         spin_unlock_irq(&ec->lock);
1211
1212 err_exit:
1213         if (result)
1214                 acpi_ec_delete_query(q);
1215         if (data)
1216                 *data = value;
1217         return result;
1218 }
1219
1220 static void acpi_ec_check_event(struct acpi_ec *ec)
1221 {
1222         unsigned long flags;
1223
1224         if (ec_event_clearing == ACPI_EC_EVT_TIMING_EVENT) {
1225                 if (ec_guard(ec)) {
1226                         spin_lock_irqsave(&ec->lock, flags);
1227                         /*
1228                          * Take care of the SCI_EVT unless no one else is
1229                          * taking care of it.
1230                          */
1231                         if (!ec->curr)
1232                                 advance_transaction(ec);
1233                         spin_unlock_irqrestore(&ec->lock, flags);
1234                 }
1235         }
1236 }
1237
1238 static void acpi_ec_event_handler(struct work_struct *work)
1239 {
1240         unsigned long flags;
1241         struct acpi_ec *ec = container_of(work, struct acpi_ec, work);
1242
1243         ec_dbg_evt("Event started");
1244
1245         spin_lock_irqsave(&ec->lock, flags);
1246         while (ec->nr_pending_queries) {
1247                 spin_unlock_irqrestore(&ec->lock, flags);
1248                 (void)acpi_ec_query(ec, NULL);
1249                 spin_lock_irqsave(&ec->lock, flags);
1250                 ec->nr_pending_queries--;
1251                 /*
1252                  * Before exit, make sure that this work item can be
1253                  * scheduled again. There might be QR_EC failures, leaving
1254                  * EC_FLAGS_QUERY_PENDING uncleared and preventing this work
1255                  * item from being scheduled again.
1256                  */
1257                 if (!ec->nr_pending_queries) {
1258                         if (ec_event_clearing == ACPI_EC_EVT_TIMING_STATUS ||
1259                             ec_event_clearing == ACPI_EC_EVT_TIMING_QUERY)
1260                                 acpi_ec_complete_query(ec);
1261                 }
1262         }
1263         spin_unlock_irqrestore(&ec->lock, flags);
1264
1265         ec_dbg_evt("Event stopped");
1266
1267         acpi_ec_check_event(ec);
1268
1269         spin_lock_irqsave(&ec->lock, flags);
1270         ec->events_in_progress--;
1271         spin_unlock_irqrestore(&ec->lock, flags);
1272 }
1273
1274 static void acpi_ec_handle_interrupt(struct acpi_ec *ec)
1275 {
1276         unsigned long flags;
1277
1278         spin_lock_irqsave(&ec->lock, flags);
1279         advance_transaction(ec);
1280         spin_unlock_irqrestore(&ec->lock, flags);
1281 }
1282
1283 static u32 acpi_ec_gpe_handler(acpi_handle gpe_device,
1284                                u32 gpe_number, void *data)
1285 {
1286         acpi_ec_handle_interrupt(data);
1287         return ACPI_INTERRUPT_HANDLED;
1288 }
1289
1290 static irqreturn_t acpi_ec_irq_handler(int irq, void *data)
1291 {
1292         acpi_ec_handle_interrupt(data);
1293         return IRQ_HANDLED;
1294 }
1295
1296 /* --------------------------------------------------------------------------
1297  *                           Address Space Management
1298  * -------------------------------------------------------------------------- */
1299
1300 static acpi_status
1301 acpi_ec_space_handler(u32 function, acpi_physical_address address,
1302                       u32 bits, u64 *value64,
1303                       void *handler_context, void *region_context)
1304 {
1305         struct acpi_ec *ec = handler_context;
1306         int result = 0, i, bytes = bits / 8;
1307         u8 *value = (u8 *)value64;
1308
1309         if ((address > 0xFF) || !value || !handler_context)
1310                 return AE_BAD_PARAMETER;
1311
1312         if (function != ACPI_READ && function != ACPI_WRITE)
1313                 return AE_BAD_PARAMETER;
1314
1315         if (ec->busy_polling || bits > 8)
1316                 acpi_ec_burst_enable(ec);
1317
1318         for (i = 0; i < bytes; ++i, ++address, ++value)
1319                 result = (function == ACPI_READ) ?
1320                         acpi_ec_read(ec, address, value) :
1321                         acpi_ec_write(ec, address, *value);
1322
1323         if (ec->busy_polling || bits > 8)
1324                 acpi_ec_burst_disable(ec);
1325
1326         switch (result) {
1327         case -EINVAL:
1328                 return AE_BAD_PARAMETER;
1329         case -ENODEV:
1330                 return AE_NOT_FOUND;
1331         case -ETIME:
1332                 return AE_TIME;
1333         default:
1334                 return AE_OK;
1335         }
1336 }
1337
1338 /* --------------------------------------------------------------------------
1339  *                             Driver Interface
1340  * -------------------------------------------------------------------------- */
1341
1342 static acpi_status
1343 ec_parse_io_ports(struct acpi_resource *resource, void *context);
1344
1345 static void acpi_ec_free(struct acpi_ec *ec)
1346 {
1347         if (first_ec == ec)
1348                 first_ec = NULL;
1349         if (boot_ec == ec)
1350                 boot_ec = NULL;
1351         kfree(ec);
1352 }
1353
1354 static struct acpi_ec *acpi_ec_alloc(void)
1355 {
1356         struct acpi_ec *ec = kzalloc(sizeof(struct acpi_ec), GFP_KERNEL);
1357
1358         if (!ec)
1359                 return NULL;
1360         mutex_init(&ec->mutex);
1361         init_waitqueue_head(&ec->wait);
1362         INIT_LIST_HEAD(&ec->list);
1363         spin_lock_init(&ec->lock);
1364         INIT_WORK(&ec->work, acpi_ec_event_handler);
1365         ec->timestamp = jiffies;
1366         ec->busy_polling = true;
1367         ec->polling_guard = 0;
1368         ec->gpe = -1;
1369         ec->irq = -1;
1370         return ec;
1371 }
1372
1373 static acpi_status
1374 acpi_ec_register_query_methods(acpi_handle handle, u32 level,
1375                                void *context, void **return_value)
1376 {
1377         char node_name[5];
1378         struct acpi_buffer buffer = { sizeof(node_name), node_name };
1379         struct acpi_ec *ec = context;
1380         int value = 0;
1381         acpi_status status;
1382
1383         status = acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer);
1384
1385         if (ACPI_SUCCESS(status) && sscanf(node_name, "_Q%x", &value) == 1)
1386                 acpi_ec_add_query_handler(ec, value, handle, NULL, NULL);
1387         return AE_OK;
1388 }
1389
1390 static acpi_status
1391 ec_parse_device(acpi_handle handle, u32 Level, void *context, void **retval)
1392 {
1393         acpi_status status;
1394         unsigned long long tmp = 0;
1395         struct acpi_ec *ec = context;
1396
1397         /* clear addr values, ec_parse_io_ports depend on it */
1398         ec->command_addr = ec->data_addr = 0;
1399
1400         status = acpi_walk_resources(handle, METHOD_NAME__CRS,
1401                                      ec_parse_io_ports, ec);
1402         if (ACPI_FAILURE(status))
1403                 return status;
1404         if (ec->data_addr == 0 || ec->command_addr == 0)
1405                 return AE_OK;
1406
1407         /* Get GPE bit assignment (EC events). */
1408         /* TODO: Add support for _GPE returning a package */
1409         status = acpi_evaluate_integer(handle, "_GPE", NULL, &tmp);
1410         if (ACPI_SUCCESS(status))
1411                 ec->gpe = tmp;
1412         /*
1413          * Errors are non-fatal, allowing for ACPI Reduced Hardware
1414          * platforms which use GpioInt instead of GPE.
1415          */
1416
1417         /* Use the global lock for all EC transactions? */
1418         tmp = 0;
1419         acpi_evaluate_integer(handle, "_GLK", NULL, &tmp);
1420         ec->global_lock = tmp;
1421         ec->handle = handle;
1422         return AE_CTRL_TERMINATE;
1423 }
1424
1425 static bool install_gpe_event_handler(struct acpi_ec *ec)
1426 {
1427         acpi_status status;
1428
1429         status = acpi_install_gpe_raw_handler(NULL, ec->gpe,
1430                                               ACPI_GPE_EDGE_TRIGGERED,
1431                                               &acpi_ec_gpe_handler, ec);
1432         if (ACPI_FAILURE(status))
1433                 return false;
1434
1435         if (test_bit(EC_FLAGS_STARTED, &ec->flags) && ec->reference_count >= 1)
1436                 acpi_ec_enable_gpe(ec, true);
1437
1438         return true;
1439 }
1440
1441 static bool install_gpio_irq_event_handler(struct acpi_ec *ec)
1442 {
1443         return request_irq(ec->irq, acpi_ec_irq_handler, IRQF_SHARED,
1444                            "ACPI EC", ec) >= 0;
1445 }
1446
1447 /**
1448  * ec_install_handlers - Install service callbacks and register query methods.
1449  * @ec: Target EC.
1450  * @device: ACPI device object corresponding to @ec.
1451  *
1452  * Install a handler for the EC address space type unless it has been installed
1453  * already.  If @device is not NULL, also look for EC query methods in the
1454  * namespace and register them, and install an event (either GPE or GPIO IRQ)
1455  * handler for the EC, if possible.
1456  *
1457  * Return:
1458  * -ENODEV if the address space handler cannot be installed, which means
1459  *  "unable to handle transactions",
1460  * -EPROBE_DEFER if GPIO IRQ acquisition needs to be deferred,
1461  * or 0 (success) otherwise.
1462  */
1463 static int ec_install_handlers(struct acpi_ec *ec, struct acpi_device *device)
1464 {
1465         acpi_status status;
1466
1467         acpi_ec_start(ec, false);
1468
1469         if (!test_bit(EC_FLAGS_EC_HANDLER_INSTALLED, &ec->flags)) {
1470                 acpi_ec_enter_noirq(ec);
1471                 status = acpi_install_address_space_handler(ec->handle,
1472                                                             ACPI_ADR_SPACE_EC,
1473                                                             &acpi_ec_space_handler,
1474                                                             NULL, ec);
1475                 if (ACPI_FAILURE(status)) {
1476                         acpi_ec_stop(ec, false);
1477                         return -ENODEV;
1478                 }
1479                 set_bit(EC_FLAGS_EC_HANDLER_INSTALLED, &ec->flags);
1480         }
1481
1482         if (!device)
1483                 return 0;
1484
1485         if (ec->gpe < 0) {
1486                 /* ACPI reduced hardware platforms use a GpioInt from _CRS. */
1487                 int irq = acpi_dev_gpio_irq_get(device, 0);
1488                 /*
1489                  * Bail out right away for deferred probing or complete the
1490                  * initialization regardless of any other errors.
1491                  */
1492                 if (irq == -EPROBE_DEFER)
1493                         return -EPROBE_DEFER;
1494                 else if (irq >= 0)
1495                         ec->irq = irq;
1496         }
1497
1498         if (!test_bit(EC_FLAGS_QUERY_METHODS_INSTALLED, &ec->flags)) {
1499                 /* Find and register all query methods */
1500                 acpi_walk_namespace(ACPI_TYPE_METHOD, ec->handle, 1,
1501                                     acpi_ec_register_query_methods,
1502                                     NULL, ec, NULL);
1503                 set_bit(EC_FLAGS_QUERY_METHODS_INSTALLED, &ec->flags);
1504         }
1505         if (!test_bit(EC_FLAGS_EVENT_HANDLER_INSTALLED, &ec->flags)) {
1506                 bool ready = false;
1507
1508                 if (ec->gpe >= 0)
1509                         ready = install_gpe_event_handler(ec);
1510                 else if (ec->irq >= 0)
1511                         ready = install_gpio_irq_event_handler(ec);
1512
1513                 if (ready) {
1514                         set_bit(EC_FLAGS_EVENT_HANDLER_INSTALLED, &ec->flags);
1515                         acpi_ec_leave_noirq(ec);
1516                 }
1517                 /*
1518                  * Failures to install an event handler are not fatal, because
1519                  * the EC can be polled for events.
1520                  */
1521         }
1522         /* EC is fully operational, allow queries */
1523         acpi_ec_enable_event(ec);
1524
1525         return 0;
1526 }
1527
1528 static void ec_remove_handlers(struct acpi_ec *ec)
1529 {
1530         if (test_bit(EC_FLAGS_EC_HANDLER_INSTALLED, &ec->flags)) {
1531                 if (ACPI_FAILURE(acpi_remove_address_space_handler(ec->handle,
1532                                         ACPI_ADR_SPACE_EC, &acpi_ec_space_handler)))
1533                         pr_err("failed to remove space handler\n");
1534                 clear_bit(EC_FLAGS_EC_HANDLER_INSTALLED, &ec->flags);
1535         }
1536
1537         /*
1538          * Stops handling the EC transactions after removing the operation
1539          * region handler. This is required because _REG(DISCONNECT)
1540          * invoked during the removal can result in new EC transactions.
1541          *
1542          * Flushes the EC requests and thus disables the GPE before
1543          * removing the GPE handler. This is required by the current ACPICA
1544          * GPE core. ACPICA GPE core will automatically disable a GPE when
1545          * it is indicated but there is no way to handle it. So the drivers
1546          * must disable the GPEs prior to removing the GPE handlers.
1547          */
1548         acpi_ec_stop(ec, false);
1549
1550         if (test_bit(EC_FLAGS_EVENT_HANDLER_INSTALLED, &ec->flags)) {
1551                 if (ec->gpe >= 0 &&
1552                     ACPI_FAILURE(acpi_remove_gpe_handler(NULL, ec->gpe,
1553                                  &acpi_ec_gpe_handler)))
1554                         pr_err("failed to remove gpe handler\n");
1555
1556                 if (ec->irq >= 0)
1557                         free_irq(ec->irq, ec);
1558
1559                 clear_bit(EC_FLAGS_EVENT_HANDLER_INSTALLED, &ec->flags);
1560         }
1561         if (test_bit(EC_FLAGS_QUERY_METHODS_INSTALLED, &ec->flags)) {
1562                 acpi_ec_remove_query_handlers(ec, true, 0);
1563                 clear_bit(EC_FLAGS_QUERY_METHODS_INSTALLED, &ec->flags);
1564         }
1565 }
1566
1567 static int acpi_ec_setup(struct acpi_ec *ec, struct acpi_device *device)
1568 {
1569         int ret;
1570
1571         ret = ec_install_handlers(ec, device);
1572         if (ret)
1573                 return ret;
1574
1575         /* First EC capable of handling transactions */
1576         if (!first_ec)
1577                 first_ec = ec;
1578
1579         pr_info("EC_CMD/EC_SC=0x%lx, EC_DATA=0x%lx\n", ec->command_addr,
1580                 ec->data_addr);
1581
1582         if (test_bit(EC_FLAGS_EVENT_HANDLER_INSTALLED, &ec->flags)) {
1583                 if (ec->gpe >= 0)
1584                         pr_info("GPE=0x%x\n", ec->gpe);
1585                 else
1586                         pr_info("IRQ=%d\n", ec->irq);
1587         }
1588
1589         return ret;
1590 }
1591
1592 static int acpi_ec_add(struct acpi_device *device)
1593 {
1594         struct acpi_ec *ec;
1595         int ret;
1596
1597         strcpy(acpi_device_name(device), ACPI_EC_DEVICE_NAME);
1598         strcpy(acpi_device_class(device), ACPI_EC_CLASS);
1599
1600         if (boot_ec && (boot_ec->handle == device->handle ||
1601             !strcmp(acpi_device_hid(device), ACPI_ECDT_HID))) {
1602                 /* Fast path: this device corresponds to the boot EC. */
1603                 ec = boot_ec;
1604         } else {
1605                 acpi_status status;
1606
1607                 ec = acpi_ec_alloc();
1608                 if (!ec)
1609                         return -ENOMEM;
1610
1611                 status = ec_parse_device(device->handle, 0, ec, NULL);
1612                 if (status != AE_CTRL_TERMINATE) {
1613                         ret = -EINVAL;
1614                         goto err;
1615                 }
1616
1617                 if (boot_ec && ec->command_addr == boot_ec->command_addr &&
1618                     ec->data_addr == boot_ec->data_addr &&
1619                     !EC_FLAGS_TRUST_DSDT_GPE) {
1620                         /*
1621                          * Trust PNP0C09 namespace location rather than
1622                          * ECDT ID. But trust ECDT GPE rather than _GPE
1623                          * because of ASUS quirks, so do not change
1624                          * boot_ec->gpe to ec->gpe.
1625                          */
1626                         boot_ec->handle = ec->handle;
1627                         acpi_handle_debug(ec->handle, "duplicated.\n");
1628                         acpi_ec_free(ec);
1629                         ec = boot_ec;
1630                 }
1631         }
1632
1633         ret = acpi_ec_setup(ec, device);
1634         if (ret)
1635                 goto err;
1636
1637         if (ec == boot_ec)
1638                 acpi_handle_info(boot_ec->handle,
1639                                  "Boot %s EC initialization complete\n",
1640                                  boot_ec_is_ecdt ? "ECDT" : "DSDT");
1641
1642         acpi_handle_info(ec->handle,
1643                          "EC: Used to handle transactions and events\n");
1644
1645         device->driver_data = ec;
1646
1647         ret = !!request_region(ec->data_addr, 1, "EC data");
1648         WARN(!ret, "Could not request EC data io port 0x%lx", ec->data_addr);
1649         ret = !!request_region(ec->command_addr, 1, "EC cmd");
1650         WARN(!ret, "Could not request EC cmd io port 0x%lx", ec->command_addr);
1651
1652         /* Reprobe devices depending on the EC */
1653         acpi_walk_dep_device_list(ec->handle);
1654
1655         acpi_handle_debug(ec->handle, "enumerated.\n");
1656         return 0;
1657
1658 err:
1659         if (ec != boot_ec)
1660                 acpi_ec_free(ec);
1661
1662         return ret;
1663 }
1664
1665 static int acpi_ec_remove(struct acpi_device *device)
1666 {
1667         struct acpi_ec *ec;
1668
1669         if (!device)
1670                 return -EINVAL;
1671
1672         ec = acpi_driver_data(device);
1673         release_region(ec->data_addr, 1);
1674         release_region(ec->command_addr, 1);
1675         device->driver_data = NULL;
1676         if (ec != boot_ec) {
1677                 ec_remove_handlers(ec);
1678                 acpi_ec_free(ec);
1679         }
1680         return 0;
1681 }
1682
1683 static acpi_status
1684 ec_parse_io_ports(struct acpi_resource *resource, void *context)
1685 {
1686         struct acpi_ec *ec = context;
1687
1688         if (resource->type != ACPI_RESOURCE_TYPE_IO)
1689                 return AE_OK;
1690
1691         /*
1692          * The first address region returned is the data port, and
1693          * the second address region returned is the status/command
1694          * port.
1695          */
1696         if (ec->data_addr == 0)
1697                 ec->data_addr = resource->data.io.minimum;
1698         else if (ec->command_addr == 0)
1699                 ec->command_addr = resource->data.io.minimum;
1700         else
1701                 return AE_CTRL_TERMINATE;
1702
1703         return AE_OK;
1704 }
1705
1706 static const struct acpi_device_id ec_device_ids[] = {
1707         {"PNP0C09", 0},
1708         {ACPI_ECDT_HID, 0},
1709         {"", 0},
1710 };
1711
1712 /*
1713  * This function is not Windows-compatible as Windows never enumerates the
1714  * namespace EC before the main ACPI device enumeration process. It is
1715  * retained for historical reason and will be deprecated in the future.
1716  */
1717 void __init acpi_ec_dsdt_probe(void)
1718 {
1719         struct acpi_ec *ec;
1720         acpi_status status;
1721         int ret;
1722
1723         /*
1724          * If a platform has ECDT, there is no need to proceed as the
1725          * following probe is not a part of the ACPI device enumeration,
1726          * executing _STA is not safe, and thus this probe may risk of
1727          * picking up an invalid EC device.
1728          */
1729         if (boot_ec)
1730                 return;
1731
1732         ec = acpi_ec_alloc();
1733         if (!ec)
1734                 return;
1735
1736         /*
1737          * At this point, the namespace is initialized, so start to find
1738          * the namespace objects.
1739          */
1740         status = acpi_get_devices(ec_device_ids[0].id, ec_parse_device, ec, NULL);
1741         if (ACPI_FAILURE(status) || !ec->handle) {
1742                 acpi_ec_free(ec);
1743                 return;
1744         }
1745
1746         /*
1747          * When the DSDT EC is available, always re-configure boot EC to
1748          * have _REG evaluated. _REG can only be evaluated after the
1749          * namespace initialization.
1750          * At this point, the GPE is not fully initialized, so do not to
1751          * handle the events.
1752          */
1753         ret = acpi_ec_setup(ec, NULL);
1754         if (ret) {
1755                 acpi_ec_free(ec);
1756                 return;
1757         }
1758
1759         boot_ec = ec;
1760
1761         acpi_handle_info(ec->handle,
1762                          "Boot DSDT EC used to handle transactions\n");
1763 }
1764
1765 /*
1766  * acpi_ec_ecdt_start - Finalize the boot ECDT EC initialization.
1767  *
1768  * First, look for an ACPI handle for the boot ECDT EC if acpi_ec_add() has not
1769  * found a matching object in the namespace.
1770  *
1771  * Next, in case the DSDT EC is not functioning, it is still necessary to
1772  * provide a functional ECDT EC to handle events, so add an extra device object
1773  * to represent it (see https://bugzilla.kernel.org/show_bug.cgi?id=115021).
1774  *
1775  * This is useful on platforms with valid ECDT and invalid DSDT EC settings,
1776  * like ASUS X550ZE (see https://bugzilla.kernel.org/show_bug.cgi?id=196847).
1777  */
1778 static void __init acpi_ec_ecdt_start(void)
1779 {
1780         struct acpi_table_ecdt *ecdt_ptr;
1781         acpi_handle handle;
1782         acpi_status status;
1783
1784         /* Bail out if a matching EC has been found in the namespace. */
1785         if (!boot_ec || boot_ec->handle != ACPI_ROOT_OBJECT)
1786                 return;
1787
1788         /* Look up the object pointed to from the ECDT in the namespace. */
1789         status = acpi_get_table(ACPI_SIG_ECDT, 1,
1790                                 (struct acpi_table_header **)&ecdt_ptr);
1791         if (ACPI_FAILURE(status))
1792                 return;
1793
1794         status = acpi_get_handle(NULL, ecdt_ptr->id, &handle);
1795         if (ACPI_SUCCESS(status)) {
1796                 boot_ec->handle = handle;
1797
1798                 /* Add a special ACPI device object to represent the boot EC. */
1799                 acpi_bus_register_early_device(ACPI_BUS_TYPE_ECDT_EC);
1800         }
1801
1802         acpi_put_table((struct acpi_table_header *)ecdt_ptr);
1803 }
1804
1805 /*
1806  * On some hardware it is necessary to clear events accumulated by the EC during
1807  * sleep. These ECs stop reporting GPEs until they are manually polled, if too
1808  * many events are accumulated. (e.g. Samsung Series 5/9 notebooks)
1809  *
1810  * https://bugzilla.kernel.org/show_bug.cgi?id=44161
1811  *
1812  * Ideally, the EC should also be instructed NOT to accumulate events during
1813  * sleep (which Windows seems to do somehow), but the interface to control this
1814  * behaviour is not known at this time.
1815  *
1816  * Models known to be affected are Samsung 530Uxx/535Uxx/540Uxx/550Pxx/900Xxx,
1817  * however it is very likely that other Samsung models are affected.
1818  *
1819  * On systems which don't accumulate _Q events during sleep, this extra check
1820  * should be harmless.
1821  */
1822 static int ec_clear_on_resume(const struct dmi_system_id *id)
1823 {
1824         pr_debug("Detected system needing EC poll on resume.\n");
1825         EC_FLAGS_CLEAR_ON_RESUME = 1;
1826         ec_event_clearing = ACPI_EC_EVT_TIMING_STATUS;
1827         return 0;
1828 }
1829
1830 /*
1831  * Some ECDTs contain wrong register addresses.
1832  * MSI MS-171F
1833  * https://bugzilla.kernel.org/show_bug.cgi?id=12461
1834  */
1835 static int ec_correct_ecdt(const struct dmi_system_id *id)
1836 {
1837         pr_debug("Detected system needing ECDT address correction.\n");
1838         EC_FLAGS_CORRECT_ECDT = 1;
1839         return 0;
1840 }
1841
1842 /*
1843  * Some ECDTs contain wrong GPE setting, but they share the same port addresses
1844  * with DSDT EC, don't duplicate the DSDT EC with ECDT EC in this case.
1845  * https://bugzilla.kernel.org/show_bug.cgi?id=209989
1846  */
1847 static int ec_honor_dsdt_gpe(const struct dmi_system_id *id)
1848 {
1849         pr_debug("Detected system needing DSDT GPE setting.\n");
1850         EC_FLAGS_TRUST_DSDT_GPE = 1;
1851         return 0;
1852 }
1853
1854 static const struct dmi_system_id ec_dmi_table[] __initconst = {
1855         {
1856         ec_correct_ecdt, "MSI MS-171F", {
1857         DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star"),
1858         DMI_MATCH(DMI_PRODUCT_NAME, "MS-171F"),}, NULL},
1859         {
1860         /* https://bugzilla.kernel.org/show_bug.cgi?id=209989 */
1861         ec_honor_dsdt_gpe, "HP Pavilion Gaming Laptop 15-cx0xxx", {
1862         DMI_MATCH(DMI_SYS_VENDOR, "HP"),
1863         DMI_MATCH(DMI_PRODUCT_NAME, "HP Pavilion Gaming Laptop 15-cx0xxx"),}, NULL},
1864         {
1865         ec_clear_on_resume, "Samsung hardware", {
1866         DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD.")}, NULL},
1867         {},
1868 };
1869
1870 void __init acpi_ec_ecdt_probe(void)
1871 {
1872         struct acpi_table_ecdt *ecdt_ptr;
1873         struct acpi_ec *ec;
1874         acpi_status status;
1875         int ret;
1876
1877         /* Generate a boot ec context. */
1878         dmi_check_system(ec_dmi_table);
1879         status = acpi_get_table(ACPI_SIG_ECDT, 1,
1880                                 (struct acpi_table_header **)&ecdt_ptr);
1881         if (ACPI_FAILURE(status))
1882                 return;
1883
1884         if (!ecdt_ptr->control.address || !ecdt_ptr->data.address) {
1885                 /*
1886                  * Asus X50GL:
1887                  * https://bugzilla.kernel.org/show_bug.cgi?id=11880
1888                  */
1889                 goto out;
1890         }
1891
1892         ec = acpi_ec_alloc();
1893         if (!ec)
1894                 goto out;
1895
1896         if (EC_FLAGS_CORRECT_ECDT) {
1897                 ec->command_addr = ecdt_ptr->data.address;
1898                 ec->data_addr = ecdt_ptr->control.address;
1899         } else {
1900                 ec->command_addr = ecdt_ptr->control.address;
1901                 ec->data_addr = ecdt_ptr->data.address;
1902         }
1903
1904         /*
1905          * Ignore the GPE value on Reduced Hardware platforms.
1906          * Some products have this set to an erroneous value.
1907          */
1908         if (!acpi_gbl_reduced_hardware)
1909                 ec->gpe = ecdt_ptr->gpe;
1910
1911         ec->handle = ACPI_ROOT_OBJECT;
1912
1913         /*
1914          * At this point, the namespace is not initialized, so do not find
1915          * the namespace objects, or handle the events.
1916          */
1917         ret = acpi_ec_setup(ec, NULL);
1918         if (ret) {
1919                 acpi_ec_free(ec);
1920                 goto out;
1921         }
1922
1923         boot_ec = ec;
1924         boot_ec_is_ecdt = true;
1925
1926         pr_info("Boot ECDT EC used to handle transactions\n");
1927
1928 out:
1929         acpi_put_table((struct acpi_table_header *)ecdt_ptr);
1930 }
1931
1932 #ifdef CONFIG_PM_SLEEP
1933 static int acpi_ec_suspend(struct device *dev)
1934 {
1935         struct acpi_ec *ec =
1936                 acpi_driver_data(to_acpi_device(dev));
1937
1938         if (!pm_suspend_no_platform() && ec_freeze_events)
1939                 acpi_ec_disable_event(ec);
1940         return 0;
1941 }
1942
1943 static int acpi_ec_suspend_noirq(struct device *dev)
1944 {
1945         struct acpi_ec *ec = acpi_driver_data(to_acpi_device(dev));
1946
1947         /*
1948          * The SCI handler doesn't run at this point, so the GPE can be
1949          * masked at the low level without side effects.
1950          */
1951         if (ec_no_wakeup && test_bit(EC_FLAGS_STARTED, &ec->flags) &&
1952             ec->gpe >= 0 && ec->reference_count >= 1)
1953                 acpi_set_gpe(NULL, ec->gpe, ACPI_GPE_DISABLE);
1954
1955         acpi_ec_enter_noirq(ec);
1956
1957         return 0;
1958 }
1959
1960 static int acpi_ec_resume_noirq(struct device *dev)
1961 {
1962         struct acpi_ec *ec = acpi_driver_data(to_acpi_device(dev));
1963
1964         acpi_ec_leave_noirq(ec);
1965
1966         if (ec_no_wakeup && test_bit(EC_FLAGS_STARTED, &ec->flags) &&
1967             ec->gpe >= 0 && ec->reference_count >= 1)
1968                 acpi_set_gpe(NULL, ec->gpe, ACPI_GPE_ENABLE);
1969
1970         return 0;
1971 }
1972
1973 static int acpi_ec_resume(struct device *dev)
1974 {
1975         struct acpi_ec *ec =
1976                 acpi_driver_data(to_acpi_device(dev));
1977
1978         acpi_ec_enable_event(ec);
1979         return 0;
1980 }
1981
1982 void acpi_ec_mark_gpe_for_wake(void)
1983 {
1984         if (first_ec && !ec_no_wakeup)
1985                 acpi_mark_gpe_for_wake(NULL, first_ec->gpe);
1986 }
1987 EXPORT_SYMBOL_GPL(acpi_ec_mark_gpe_for_wake);
1988
1989 void acpi_ec_set_gpe_wake_mask(u8 action)
1990 {
1991         if (pm_suspend_no_platform() && first_ec && !ec_no_wakeup)
1992                 acpi_set_gpe_wake_mask(NULL, first_ec->gpe, action);
1993 }
1994
1995 bool acpi_ec_dispatch_gpe(void)
1996 {
1997         bool work_in_progress;
1998         u32 ret;
1999
2000         if (!first_ec)
2001                 return acpi_any_gpe_status_set(U32_MAX);
2002
2003         /*
2004          * Report wakeup if the status bit is set for any enabled GPE other
2005          * than the EC one.
2006          */
2007         if (acpi_any_gpe_status_set(first_ec->gpe))
2008                 return true;
2009
2010         /*
2011          * Dispatch the EC GPE in-band, but do not report wakeup in any case
2012          * to allow the caller to process events properly after that.
2013          */
2014         ret = acpi_dispatch_gpe(NULL, first_ec->gpe);
2015         if (ret == ACPI_INTERRUPT_HANDLED)
2016                 pm_pr_dbg("ACPI EC GPE dispatched\n");
2017
2018         /* Drain EC work. */
2019         do {
2020                 acpi_ec_flush_work();
2021
2022                 pm_pr_dbg("ACPI EC work flushed\n");
2023
2024                 spin_lock_irq(&first_ec->lock);
2025
2026                 work_in_progress = first_ec->events_in_progress +
2027                         first_ec->queries_in_progress > 0;
2028
2029                 spin_unlock_irq(&first_ec->lock);
2030         } while (work_in_progress && !pm_wakeup_pending());
2031
2032         return false;
2033 }
2034 #endif /* CONFIG_PM_SLEEP */
2035
2036 static const struct dev_pm_ops acpi_ec_pm = {
2037         SET_NOIRQ_SYSTEM_SLEEP_PM_OPS(acpi_ec_suspend_noirq, acpi_ec_resume_noirq)
2038         SET_SYSTEM_SLEEP_PM_OPS(acpi_ec_suspend, acpi_ec_resume)
2039 };
2040
2041 static int param_set_event_clearing(const char *val,
2042                                     const struct kernel_param *kp)
2043 {
2044         int result = 0;
2045
2046         if (!strncmp(val, "status", sizeof("status") - 1)) {
2047                 ec_event_clearing = ACPI_EC_EVT_TIMING_STATUS;
2048                 pr_info("Assuming SCI_EVT clearing on EC_SC accesses\n");
2049         } else if (!strncmp(val, "query", sizeof("query") - 1)) {
2050                 ec_event_clearing = ACPI_EC_EVT_TIMING_QUERY;
2051                 pr_info("Assuming SCI_EVT clearing on QR_EC writes\n");
2052         } else if (!strncmp(val, "event", sizeof("event") - 1)) {
2053                 ec_event_clearing = ACPI_EC_EVT_TIMING_EVENT;
2054                 pr_info("Assuming SCI_EVT clearing on event reads\n");
2055         } else
2056                 result = -EINVAL;
2057         return result;
2058 }
2059
2060 static int param_get_event_clearing(char *buffer,
2061                                     const struct kernel_param *kp)
2062 {
2063         switch (ec_event_clearing) {
2064         case ACPI_EC_EVT_TIMING_STATUS:
2065                 return sprintf(buffer, "status\n");
2066         case ACPI_EC_EVT_TIMING_QUERY:
2067                 return sprintf(buffer, "query\n");
2068         case ACPI_EC_EVT_TIMING_EVENT:
2069                 return sprintf(buffer, "event\n");
2070         default:
2071                 return sprintf(buffer, "invalid\n");
2072         }
2073         return 0;
2074 }
2075
2076 module_param_call(ec_event_clearing, param_set_event_clearing, param_get_event_clearing,
2077                   NULL, 0644);
2078 MODULE_PARM_DESC(ec_event_clearing, "Assumed SCI_EVT clearing timing");
2079
2080 static struct acpi_driver acpi_ec_driver = {
2081         .name = "ec",
2082         .class = ACPI_EC_CLASS,
2083         .ids = ec_device_ids,
2084         .ops = {
2085                 .add = acpi_ec_add,
2086                 .remove = acpi_ec_remove,
2087                 },
2088         .drv.pm = &acpi_ec_pm,
2089 };
2090
2091 static void acpi_ec_destroy_workqueues(void)
2092 {
2093         if (ec_wq) {
2094                 destroy_workqueue(ec_wq);
2095                 ec_wq = NULL;
2096         }
2097         if (ec_query_wq) {
2098                 destroy_workqueue(ec_query_wq);
2099                 ec_query_wq = NULL;
2100         }
2101 }
2102
2103 static int acpi_ec_init_workqueues(void)
2104 {
2105         if (!ec_wq)
2106                 ec_wq = alloc_ordered_workqueue("kec", 0);
2107
2108         if (!ec_query_wq)
2109                 ec_query_wq = alloc_workqueue("kec_query", 0, ec_max_queries);
2110
2111         if (!ec_wq || !ec_query_wq) {
2112                 acpi_ec_destroy_workqueues();
2113                 return -ENODEV;
2114         }
2115         return 0;
2116 }
2117
2118 static const struct dmi_system_id acpi_ec_no_wakeup[] = {
2119         {
2120                 .ident = "Thinkpad X1 Carbon 6th",
2121                 .matches = {
2122                         DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
2123                         DMI_MATCH(DMI_PRODUCT_FAMILY, "Thinkpad X1 Carbon 6th"),
2124                 },
2125         },
2126         {
2127                 .ident = "ThinkPad X1 Yoga 3rd",
2128                 .matches = {
2129                         DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
2130                         DMI_MATCH(DMI_PRODUCT_FAMILY, "ThinkPad X1 Yoga 3rd"),
2131                 },
2132         },
2133         { },
2134 };
2135
2136 void __init acpi_ec_init(void)
2137 {
2138         int result;
2139
2140         result = acpi_ec_init_workqueues();
2141         if (result)
2142                 return;
2143
2144         /*
2145          * Disable EC wakeup on following systems to prevent periodic
2146          * wakeup from EC GPE.
2147          */
2148         if (dmi_check_system(acpi_ec_no_wakeup)) {
2149                 ec_no_wakeup = true;
2150                 pr_debug("Disabling EC wakeup on suspend-to-idle\n");
2151         }
2152
2153         /* Driver must be registered after acpi_ec_init_workqueues(). */
2154         acpi_bus_register_driver(&acpi_ec_driver);
2155
2156         acpi_ec_ecdt_start();
2157 }
2158
2159 /* EC driver currently not unloadable */
2160 #if 0
2161 static void __exit acpi_ec_exit(void)
2162 {
2163
2164         acpi_bus_unregister_driver(&acpi_ec_driver);
2165         acpi_ec_destroy_workqueues();
2166 }
2167 #endif  /* 0 */