1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * ACPI event handling for Wilco Embedded Controller
4  *
5  * Copyright 2019 Google LLC
6  *
7  * The Wilco Embedded Controller can create custom events that
8  * are not handled as standard ACPI objects. These events can
9  * contain information about changes in EC controlled features,
10  * such as errors and events in the dock or display. For example,
11  * an event is triggered if the dock is plugged into a display
12  * incorrectly. These events are needed for telemetry and
13  * diagnostics reasons, and for possibly alerting the user.
14 
15  * These events are triggered by the EC with an ACPI Notify(0x90),
16  * and then the BIOS reads the event buffer from EC RAM via an
17  * ACPI method. When the OS receives these events via ACPI,
18  * it passes them along to this driver. The events are put into
19  * a queue which can be read by a userspace daemon via a char device
20  * that implements read() and poll(). The event queue acts as a
21  * circular buffer of size 64, so if there are no userspace consumers
22  * the kernel will not run out of memory. The char device will appear at
23  * /dev/wilco_event{n}, where n is some small non-negative integer,
24  * starting from 0. Standard ACPI events such as the battery getting
25  * plugged/unplugged can also come through this path, but they are
26  * dealt with via other paths, and are ignored here.
27 
28  * To test, you can tail the binary data with
29  * $ cat /dev/wilco_event0 | hexdump -ve '1/1 "%x\n"'
30  * and then create an event by plugging/unplugging the battery.
31  */
32 
33 #include <linux/acpi.h>
34 #include <linux/cdev.h>
35 #include <linux/device.h>
36 #include <linux/fs.h>
37 #include <linux/idr.h>
38 #include <linux/io.h>
39 #include <linux/list.h>
40 #include <linux/module.h>
41 #include <linux/poll.h>
42 #include <linux/spinlock.h>
43 #include <linux/uaccess.h>
44 #include <linux/wait.h>
45 
46 /* ACPI Notify event code indicating event data is available. */
47 #define EC_ACPI_NOTIFY_EVENT		0x90
48 /* ACPI Method to execute to retrieve event data buffer from the EC. */
49 #define EC_ACPI_GET_EVENT		"QSET"
50 /* Maximum number of words in event data returned by the EC. */
51 #define EC_ACPI_MAX_EVENT_WORDS		6
52 #define EC_ACPI_MAX_EVENT_SIZE \
53 	(sizeof(struct ec_event) + (EC_ACPI_MAX_EVENT_WORDS) * sizeof(u16))
54 
55 /* Node will appear in /dev/EVENT_DEV_NAME */
56 #define EVENT_DEV_NAME		"wilco_event"
57 #define EVENT_CLASS_NAME	EVENT_DEV_NAME
58 #define DRV_NAME		EVENT_DEV_NAME
59 #define EVENT_DEV_NAME_FMT	(EVENT_DEV_NAME "%d")
60 static struct class event_class = {
61 	.owner	= THIS_MODULE,
62 	.name	= EVENT_CLASS_NAME,
63 };
64 
65 /* Keep track of all the device numbers used. */
66 #define EVENT_MAX_DEV 128
67 static int event_major;
68 static DEFINE_IDA(event_ida);
69 
70 /* Size of circular queue of events. */
71 #define MAX_NUM_EVENTS 64
72 
73 /**
74  * struct ec_event - Extended event returned by the EC.
75  * @size: Number of 16bit words in structure after the size word.
76  * @type: Extended event type, meaningless for us.
77  * @event: Event data words.  Max count is %EC_ACPI_MAX_EVENT_WORDS.
78  */
79 struct ec_event {
80 	u16 size;
81 	u16 type;
82 	u16 event[];
83 } __packed;
84 
85 #define ec_event_num_words(ev) (ev->size - 1)
86 #define ec_event_size(ev) (sizeof(*ev) + (ec_event_num_words(ev) * sizeof(u16)))
87 
88 /**
89  * struct ec_event_queue - Circular queue for events.
90  * @capacity: Number of elements the queue can hold.
91  * @head: Next index to write to.
92  * @tail: Next index to read from.
93  * @entries: Array of events.
94  */
95 struct ec_event_queue {
96 	int capacity;
97 	int head;
98 	int tail;
99 	struct ec_event *entries[];
100 };
101 
102 /* Maximum number of events to store in ec_event_queue */
103 static int queue_size = 64;
104 module_param(queue_size, int, 0644);
105 
event_queue_new(int capacity)106 static struct ec_event_queue *event_queue_new(int capacity)
107 {
108 	struct ec_event_queue *q;
109 
110 	q = kzalloc(struct_size(q, entries, capacity), GFP_KERNEL);
111 	if (!q)
112 		return NULL;
113 
114 	q->capacity = capacity;
115 
116 	return q;
117 }
118 
event_queue_empty(struct ec_event_queue * q)119 static inline bool event_queue_empty(struct ec_event_queue *q)
120 {
121 	/* head==tail when both full and empty, but head==NULL when empty */
122 	return q->head == q->tail && !q->entries[q->head];
123 }
124 
event_queue_full(struct ec_event_queue * q)125 static inline bool event_queue_full(struct ec_event_queue *q)
126 {
127 	/* head==tail when both full and empty, but head!=NULL when full */
128 	return q->head == q->tail && q->entries[q->head];
129 }
130 
event_queue_pop(struct ec_event_queue * q)131 static struct ec_event *event_queue_pop(struct ec_event_queue *q)
132 {
133 	struct ec_event *ev;
134 
135 	if (event_queue_empty(q))
136 		return NULL;
137 
138 	ev = q->entries[q->tail];
139 	q->entries[q->tail] = NULL;
140 	q->tail = (q->tail + 1) % q->capacity;
141 
142 	return ev;
143 }
144 
145 /*
146  * If full, overwrite the oldest event and return it so the caller
147  * can kfree it. If not full, return NULL.
148  */
event_queue_push(struct ec_event_queue * q,struct ec_event * ev)149 static struct ec_event *event_queue_push(struct ec_event_queue *q,
150 					 struct ec_event *ev)
151 {
152 	struct ec_event *popped = NULL;
153 
154 	if (event_queue_full(q))
155 		popped = event_queue_pop(q);
156 	q->entries[q->head] = ev;
157 	q->head = (q->head + 1) % q->capacity;
158 
159 	return popped;
160 }
161 
event_queue_free(struct ec_event_queue * q)162 static void event_queue_free(struct ec_event_queue *q)
163 {
164 	struct ec_event *event;
165 
166 	while ((event = event_queue_pop(q)) != NULL)
167 		kfree(event);
168 
169 	kfree(q);
170 }
171 
172 /**
173  * struct event_device_data - Data for a Wilco EC device that responds to ACPI.
174  * @events: Circular queue of EC events to be provided to userspace.
175  * @queue_lock: Protect the queue from simultaneous read/writes.
176  * @wq: Wait queue to notify processes when events are available or the
177  *	device has been removed.
178  * @cdev: Char dev that userspace reads() and polls() from.
179  * @dev: Device associated with the %cdev.
180  * @exist: Has the device been not been removed? Once a device has been removed,
181  *	   writes, reads, and new opens will fail.
182  * @available: Guarantee only one client can open() file and read from queue.
183  *
184  * There will be one of these structs for each ACPI device registered. This data
185  * is the queue of events received from ACPI that still need to be read from
186  * userspace, the device and char device that userspace is using, a wait queue
187  * used to notify different threads when something has changed, plus a flag
188  * on whether the ACPI device has been removed.
189  */
190 struct event_device_data {
191 	struct ec_event_queue *events;
192 	spinlock_t queue_lock;
193 	wait_queue_head_t wq;
194 	struct device dev;
195 	struct cdev cdev;
196 	bool exist;
197 	atomic_t available;
198 };
199 
200 /**
201  * enqueue_events() - Place EC events in queue to be read by userspace.
202  * @adev: Device the events came from.
203  * @buf: Buffer of event data.
204  * @length: Length of event data buffer.
205  *
206  * %buf contains a number of ec_event's, packed one after the other.
207  * Each ec_event is of variable length. Start with the first event, copy it
208  * into a persistent ec_event, store that entry in the queue, move on
209  * to the next ec_event in buf, and repeat.
210  *
211  * Return: 0 on success or negative error code on failure.
212  */
enqueue_events(struct acpi_device * adev,const u8 * buf,u32 length)213 static int enqueue_events(struct acpi_device *adev, const u8 *buf, u32 length)
214 {
215 	struct event_device_data *dev_data = adev->driver_data;
216 	struct ec_event *event, *queue_event, *old_event;
217 	size_t num_words, event_size;
218 	u32 offset = 0;
219 
220 	while (offset < length) {
221 		event = (struct ec_event *)(buf + offset);
222 
223 		num_words = ec_event_num_words(event);
224 		event_size = ec_event_size(event);
225 		if (num_words > EC_ACPI_MAX_EVENT_WORDS) {
226 			dev_err(&adev->dev, "Too many event words: %zu > %d\n",
227 				num_words, EC_ACPI_MAX_EVENT_WORDS);
228 			return -EOVERFLOW;
229 		}
230 
231 		/* Ensure event does not overflow the available buffer */
232 		if ((offset + event_size) > length) {
233 			dev_err(&adev->dev, "Event exceeds buffer: %zu > %d\n",
234 				offset + event_size, length);
235 			return -EOVERFLOW;
236 		}
237 
238 		/* Point to the next event in the buffer */
239 		offset += event_size;
240 
241 		/* Copy event into the queue */
242 		queue_event = kmemdup(event, event_size, GFP_KERNEL);
243 		if (!queue_event)
244 			return -ENOMEM;
245 		spin_lock(&dev_data->queue_lock);
246 		old_event = event_queue_push(dev_data->events, queue_event);
247 		spin_unlock(&dev_data->queue_lock);
248 		kfree(old_event);
249 		wake_up_interruptible(&dev_data->wq);
250 	}
251 
252 	return 0;
253 }
254 
255 /**
256  * event_device_notify() - Callback when EC generates an event over ACPI.
257  * @adev: The device that the event is coming from.
258  * @value: Value passed to Notify() in ACPI.
259  *
260  * This function will read the events from the device and enqueue them.
261  */
event_device_notify(struct acpi_device * adev,u32 value)262 static void event_device_notify(struct acpi_device *adev, u32 value)
263 {
264 	struct acpi_buffer event_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
265 	union acpi_object *obj;
266 	acpi_status status;
267 
268 	if (value != EC_ACPI_NOTIFY_EVENT) {
269 		dev_err(&adev->dev, "Invalid event: 0x%08x\n", value);
270 		return;
271 	}
272 
273 	/* Execute ACPI method to get event data buffer. */
274 	status = acpi_evaluate_object(adev->handle, EC_ACPI_GET_EVENT,
275 				      NULL, &event_buffer);
276 	if (ACPI_FAILURE(status)) {
277 		dev_err(&adev->dev, "Error executing ACPI method %s()\n",
278 			EC_ACPI_GET_EVENT);
279 		return;
280 	}
281 
282 	obj = (union acpi_object *)event_buffer.pointer;
283 	if (!obj) {
284 		dev_err(&adev->dev, "Nothing returned from %s()\n",
285 			EC_ACPI_GET_EVENT);
286 		return;
287 	}
288 	if (obj->type != ACPI_TYPE_BUFFER) {
289 		dev_err(&adev->dev, "Invalid object returned from %s()\n",
290 			EC_ACPI_GET_EVENT);
291 		kfree(obj);
292 		return;
293 	}
294 	if (obj->buffer.length < sizeof(struct ec_event)) {
295 		dev_err(&adev->dev, "Invalid buffer length %d from %s()\n",
296 			obj->buffer.length, EC_ACPI_GET_EVENT);
297 		kfree(obj);
298 		return;
299 	}
300 
301 	enqueue_events(adev, obj->buffer.pointer, obj->buffer.length);
302 	kfree(obj);
303 }
304 
event_open(struct inode * inode,struct file * filp)305 static int event_open(struct inode *inode, struct file *filp)
306 {
307 	struct event_device_data *dev_data;
308 
309 	dev_data = container_of(inode->i_cdev, struct event_device_data, cdev);
310 	if (!dev_data->exist)
311 		return -ENODEV;
312 
313 	if (atomic_cmpxchg(&dev_data->available, 1, 0) == 0)
314 		return -EBUSY;
315 
316 	/* Increase refcount on device so dev_data is not freed */
317 	get_device(&dev_data->dev);
318 	stream_open(inode, filp);
319 	filp->private_data = dev_data;
320 
321 	return 0;
322 }
323 
event_poll(struct file * filp,poll_table * wait)324 static __poll_t event_poll(struct file *filp, poll_table *wait)
325 {
326 	struct event_device_data *dev_data = filp->private_data;
327 	__poll_t mask = 0;
328 
329 	poll_wait(filp, &dev_data->wq, wait);
330 	if (!dev_data->exist)
331 		return EPOLLHUP;
332 	if (!event_queue_empty(dev_data->events))
333 		mask |= EPOLLIN | EPOLLRDNORM | EPOLLPRI;
334 	return mask;
335 }
336 
337 /**
338  * event_read() - Callback for passing event data to userspace via read().
339  * @filp: The file we are reading from.
340  * @buf: Pointer to userspace buffer to fill with one event.
341  * @count: Number of bytes requested. Must be at least EC_ACPI_MAX_EVENT_SIZE.
342  * @pos: File position pointer, irrelevant since we don't support seeking.
343  *
344  * Removes the first event from the queue, places it in the passed buffer.
345  *
346  * If there are no events in the the queue, then one of two things happens,
347  * depending on if the file was opened in nonblocking mode: If in nonblocking
348  * mode, then return -EAGAIN to say there's no data. If in blocking mode, then
349  * block until an event is available.
350  *
351  * Return: Number of bytes placed in buffer, negative error code on failure.
352  */
event_read(struct file * filp,char __user * buf,size_t count,loff_t * pos)353 static ssize_t event_read(struct file *filp, char __user *buf, size_t count,
354 			  loff_t *pos)
355 {
356 	struct event_device_data *dev_data = filp->private_data;
357 	struct ec_event *event;
358 	ssize_t n_bytes_written = 0;
359 	int err;
360 
361 	/* We only will give them the entire event at once */
362 	if (count != 0 && count < EC_ACPI_MAX_EVENT_SIZE)
363 		return -EINVAL;
364 
365 	spin_lock(&dev_data->queue_lock);
366 	while (event_queue_empty(dev_data->events)) {
367 		spin_unlock(&dev_data->queue_lock);
368 		if (filp->f_flags & O_NONBLOCK)
369 			return -EAGAIN;
370 
371 		err = wait_event_interruptible(dev_data->wq,
372 					!event_queue_empty(dev_data->events) ||
373 					!dev_data->exist);
374 		if (err)
375 			return err;
376 
377 		/* Device was removed as we waited? */
378 		if (!dev_data->exist)
379 			return -ENODEV;
380 		spin_lock(&dev_data->queue_lock);
381 	}
382 	event = event_queue_pop(dev_data->events);
383 	spin_unlock(&dev_data->queue_lock);
384 	n_bytes_written = ec_event_size(event);
385 	if (copy_to_user(buf, event, n_bytes_written))
386 		n_bytes_written = -EFAULT;
387 	kfree(event);
388 
389 	return n_bytes_written;
390 }
391 
event_release(struct inode * inode,struct file * filp)392 static int event_release(struct inode *inode, struct file *filp)
393 {
394 	struct event_device_data *dev_data = filp->private_data;
395 
396 	atomic_set(&dev_data->available, 1);
397 	put_device(&dev_data->dev);
398 
399 	return 0;
400 }
401 
402 static const struct file_operations event_fops = {
403 	.open = event_open,
404 	.poll  = event_poll,
405 	.read = event_read,
406 	.release = event_release,
407 	.llseek = no_llseek,
408 	.owner = THIS_MODULE,
409 };
410 
411 /**
412  * free_device_data() - Callback to free the event_device_data structure.
413  * @d: The device embedded in our device data, which we have been ref counting.
414  *
415  * This is called only after event_device_remove() has been called and all
416  * userspace programs have called event_release() on all the open file
417  * descriptors.
418  */
free_device_data(struct device * d)419 static void free_device_data(struct device *d)
420 {
421 	struct event_device_data *dev_data;
422 
423 	dev_data = container_of(d, struct event_device_data, dev);
424 	event_queue_free(dev_data->events);
425 	kfree(dev_data);
426 }
427 
hangup_device(struct event_device_data * dev_data)428 static void hangup_device(struct event_device_data *dev_data)
429 {
430 	dev_data->exist = false;
431 	/* Wake up the waiting processes so they can close. */
432 	wake_up_interruptible(&dev_data->wq);
433 	put_device(&dev_data->dev);
434 }
435 
436 /**
437  * event_device_add() - Callback when creating a new device.
438  * @adev: ACPI device that we will be receiving events from.
439  *
440  * This finds a free minor number for the device, allocates and initializes
441  * some device data, and creates a new device and char dev node.
442  *
443  * The device data is freed in free_device_data(), which is called when
444  * %dev_data->dev is release()ed. This happens after all references to
445  * %dev_data->dev are dropped, which happens once both event_device_remove()
446  * has been called and every open()ed file descriptor has been release()ed.
447  *
448  * Return: 0 on success, negative error code on failure.
449  */
event_device_add(struct acpi_device * adev)450 static int event_device_add(struct acpi_device *adev)
451 {
452 	struct event_device_data *dev_data;
453 	int error, minor;
454 
455 	minor = ida_alloc_max(&event_ida, EVENT_MAX_DEV-1, GFP_KERNEL);
456 	if (minor < 0) {
457 		error = minor;
458 		dev_err(&adev->dev, "Failed to find minor number: %d\n", error);
459 		return error;
460 	}
461 
462 	dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
463 	if (!dev_data) {
464 		error = -ENOMEM;
465 		goto free_minor;
466 	}
467 
468 	/* Initialize the device data. */
469 	adev->driver_data = dev_data;
470 	dev_data->events = event_queue_new(queue_size);
471 	if (!dev_data->events) {
472 		kfree(dev_data);
473 		error = -ENOMEM;
474 		goto free_minor;
475 	}
476 	spin_lock_init(&dev_data->queue_lock);
477 	init_waitqueue_head(&dev_data->wq);
478 	dev_data->exist = true;
479 	atomic_set(&dev_data->available, 1);
480 
481 	/* Initialize the device. */
482 	dev_data->dev.devt = MKDEV(event_major, minor);
483 	dev_data->dev.class = &event_class;
484 	dev_data->dev.release = free_device_data;
485 	dev_set_name(&dev_data->dev, EVENT_DEV_NAME_FMT, minor);
486 	device_initialize(&dev_data->dev);
487 
488 	/* Initialize the character device, and add it to userspace. */
489 	cdev_init(&dev_data->cdev, &event_fops);
490 	error = cdev_device_add(&dev_data->cdev, &dev_data->dev);
491 	if (error)
492 		goto free_dev_data;
493 
494 	return 0;
495 
496 free_dev_data:
497 	hangup_device(dev_data);
498 free_minor:
499 	ida_simple_remove(&event_ida, minor);
500 	return error;
501 }
502 
event_device_remove(struct acpi_device * adev)503 static int event_device_remove(struct acpi_device *adev)
504 {
505 	struct event_device_data *dev_data = adev->driver_data;
506 
507 	cdev_device_del(&dev_data->cdev, &dev_data->dev);
508 	ida_simple_remove(&event_ida, MINOR(dev_data->dev.devt));
509 	hangup_device(dev_data);
510 
511 	return 0;
512 }
513 
514 static const struct acpi_device_id event_acpi_ids[] = {
515 	{ "GOOG000D", 0 },
516 	{ }
517 };
518 MODULE_DEVICE_TABLE(acpi, event_acpi_ids);
519 
520 static struct acpi_driver event_driver = {
521 	.name = DRV_NAME,
522 	.class = DRV_NAME,
523 	.ids = event_acpi_ids,
524 	.ops = {
525 		.add = event_device_add,
526 		.notify = event_device_notify,
527 		.remove = event_device_remove,
528 	},
529 	.owner = THIS_MODULE,
530 };
531 
event_module_init(void)532 static int __init event_module_init(void)
533 {
534 	dev_t dev_num = 0;
535 	int ret;
536 
537 	ret = class_register(&event_class);
538 	if (ret) {
539 		pr_err(DRV_NAME ": Failed registering class: %d\n", ret);
540 		return ret;
541 	}
542 
543 	/* Request device numbers, starting with minor=0. Save the major num. */
544 	ret = alloc_chrdev_region(&dev_num, 0, EVENT_MAX_DEV, EVENT_DEV_NAME);
545 	if (ret) {
546 		pr_err(DRV_NAME ": Failed allocating dev numbers: %d\n", ret);
547 		goto destroy_class;
548 	}
549 	event_major = MAJOR(dev_num);
550 
551 	ret = acpi_bus_register_driver(&event_driver);
552 	if (ret < 0) {
553 		pr_err(DRV_NAME ": Failed registering driver: %d\n", ret);
554 		goto unregister_region;
555 	}
556 
557 	return 0;
558 
559 unregister_region:
560 	unregister_chrdev_region(MKDEV(event_major, 0), EVENT_MAX_DEV);
561 destroy_class:
562 	class_unregister(&event_class);
563 	ida_destroy(&event_ida);
564 	return ret;
565 }
566 
event_module_exit(void)567 static void __exit event_module_exit(void)
568 {
569 	acpi_bus_unregister_driver(&event_driver);
570 	unregister_chrdev_region(MKDEV(event_major, 0), EVENT_MAX_DEV);
571 	class_unregister(&event_class);
572 	ida_destroy(&event_ida);
573 }
574 
575 module_init(event_module_init);
576 module_exit(event_module_exit);
577 
578 MODULE_AUTHOR("Nick Crews <ncrews@chromium.org>");
579 MODULE_DESCRIPTION("Wilco EC ACPI event driver");
580 MODULE_LICENSE("GPL");
581 MODULE_ALIAS("platform:" DRV_NAME);
582