diff --git a/drivers/hid/ipts/cmd.h b/drivers/hid/ipts/cmd.h index 2b4079075b642..84cf8278287b5 100644 --- a/drivers/hid/ipts/cmd.h +++ b/drivers/hid/ipts/cmd.h @@ -25,7 +25,7 @@ * @rsp: The address that the received response will be copied to. * @timeout: How many milliseconds the function will wait at most. * - * A negative timeout means to wait forever. + * A timeout of 0 means to check once and return. * * Returns: 0 on success, <0 on error, -EAGAIN if no response has been received. */ diff --git a/drivers/hid/ipts/context.h b/drivers/hid/ipts/context.h index ba33259f1f7c5..4157361aa9574 100644 --- a/drivers/hid/ipts/context.h +++ b/drivers/hid/ipts/context.h @@ -8,13 +8,17 @@ #ifndef IPTS_CONTEXT_H #define IPTS_CONTEXT_H +#include #include #include #include +#include #include #include #include #include +#include +#include #include "mei.h" #include "resources.h" @@ -33,6 +37,13 @@ struct ipts_context { struct mutex feature_lock; struct completion feature_event; + /* + * Allows one FEEDBACK command at a time, held from the send until its reply is taken, + * and guards the hid2me buffer a hid2me FEEDBACK hands to the device. GET_FEATURE takes + * it while holding feature_lock; never take feature_lock while holding it. + */ + struct mutex feedback_lock; + /* * These are not inside of struct ipts_resources * because they don't own the memory they point to. @@ -43,10 +54,92 @@ struct ipts_context { bool hid_active; struct hid_device *hid; + /* + * Number of HID callbacks currently running driver code. Stopping waits, bounded, + * until it drops to 0. + */ + atomic_t hid_users; + wait_queue_head_t hid_users_wq; + + /* + * Serializes a restart with remove. Restarts requested from a HID callback (the EDS1 + * mode switch) run from restart_work, never inside the callback. + */ + struct mutex ctl_lock; + struct delayed_work restart_work; + bool removing; + + /* + * When a restart fails to start the device again: how many restarts were tried. + * Retries run from restart_work, too. + */ + unsigned int restart_attempts; + + /* + * EDS1: the mode that the last mode switch asked for. restart_work applies it to mode + * under ctl_lock, so a switch that arrives during a restart does not change the mode + * under a start that is running. + */ + enum ipts_mode requested_mode; + + /* + * Set when a stop for a restart failed or leaked the buffers: the device must not be + * started again, and mode switches are refused, until the next probe. + */ + bool restart_blocked; + + /* + * Freed when the last reference is dropped. Probe holds one (dropped by devres), and the + * receiver thread, the HID device, every holder of message_lock and a queued restart + * hold one each. + */ + struct kref refcount; + + /* + * Users other than probe. ipts_remove() waits, bounded, for this to reach zero. That + * narrows the window in which the module code is freed under a user that is about to + * return, but does not close it: the last user wakes remove from inside its own put. + */ + atomic_t users; + wait_queue_head_t users_wq; + struct ipts_device_info info; struct ipts_resources resources; + /* + * Set by a stop whose wait for running HID callbacks timed out: a callback that outlived + * the wait may have sent the device a command after it confirmed the stop. The buffers + * are then leaked instead of freed, by that stop or, if it kept everything, by the next. + */ + bool buffers_unconfirmed; + struct ipts_thread receiver_loop; }; +void ipts_context_release(struct kref *refcount); + +/* + * Every user of the context (the receiver thread, the HID device, a holder of message_lock, a + * queued restart) takes a reference, so the context is freed only after the last user is gone. + */ +static inline void ipts_context_get(struct ipts_context *ipts) +{ + if (!ipts) + return; + + kref_get(&ipts->refcount); + atomic_inc(&ipts->users); +} + +static inline void ipts_context_put(struct ipts_context *ipts) +{ + if (!ipts) + return; + + if (atomic_dec_and_test(&ipts->users)) + wake_up_all(&ipts->users_wq); + + kref_put(&ipts->refcount, ipts_context_release); +} + #endif /* IPTS_CONTEXT_H */ diff --git a/drivers/hid/ipts/control.c b/drivers/hid/ipts/control.c index 5360842d260ba..cde37cde3603c 100644 --- a/drivers/hid/ipts/control.c +++ b/drivers/hid/ipts/control.c @@ -8,9 +8,15 @@ #include #include #include +#include #include #include +#include +#include +#include #include +#include +#include #include "cmd.h" #include "context.h" @@ -22,6 +28,9 @@ #include "spec-data.h" #include "spec-device.h" +#define IPTS_RESTART_DELAY_MS 2000 +#define IPTS_RESTART_MAX_ATTEMPTS 5 + static int ipts_control_get_device_info(struct ipts_context *ipts, struct ipts_device_info *info) { int ret = 0; @@ -276,14 +285,28 @@ int ipts_control_wait_data(struct ipts_context *ipts, bool shutdown) return 0; } -int ipts_control_send_feedback(struct ipts_context *ipts, u32 buffer) +static int ipts_control_send_feedback_locked(struct ipts_context *ipts, u32 buffer) { int ret = 0; + int late = 0; + long left = 0; + u32 answered = 0; + unsigned long end = 0; struct ipts_feedback cmd = { 0 }; struct ipts_response rsp = { 0 }; - if (!ipts) - return -EFAULT; + lockdep_assert_held(&ipts->feedback_lock); + + /* + * No other FEEDBACK is in flight while the lock is held, so a FEEDBACK reply that is + * already queued answers one whose sender gave up waiting. Drop it, or this send would + * take it as its own. + */ + while (!ipts_cmd_recv_timeout(ipts, IPTS_CMD_FEEDBACK, &rsp, 0)) + late++; + + if (late) + dev_warn(ipts->dev, "FEEDBACK: dropped %d late replies\n", late); cmd.buffer = buffer; @@ -293,11 +316,29 @@ int ipts_control_send_feedback(struct ipts_context *ipts, u32 buffer) return ret; } - ret = ipts_cmd_recv(ipts, IPTS_CMD_FEEDBACK, &rsp); - if (ret) { - dev_err(ipts->dev, "FEEDBACK: recv failed: %d\n", ret); - return ret; - } + /* + * The first word of a FEEDBACK reply's payload echoes the buffer index of the command it + * answers. A reply for another buffer answers a sender that gave up after the drop above + * ran: drop it too and keep waiting for ours, within the usual time limit. Two hid2me + * replies look alike, but the lock allows one hid2me FEEDBACK at a time. + */ + end = jiffies + msecs_to_jiffies(IPTS_CMD_DEFAULT_TIMEOUT); + + do { + left = (long)(end - jiffies); + + ret = ipts_cmd_recv_timeout(ipts, IPTS_CMD_FEEDBACK, &rsp, + left > 0 ? jiffies_to_msecs(left) : 0); + if (ret) { + dev_err(ipts->dev, "FEEDBACK: recv failed: %d\n", ret); + return ret; + } + + answered = get_unaligned_le32(rsp.payload); + if (answered != buffer) + dev_warn(ipts->dev, "FEEDBACK: dropped a reply for buffer %u, waiting for %u\n", + answered, buffer); + } while (answered != buffer); /* * We don't know what feedback data looks like so we are sending zeros. @@ -314,9 +355,34 @@ int ipts_control_send_feedback(struct ipts_context *ipts, u32 buffer) return 0; } +/* + * The receiver loop and HID feature requests both send FEEDBACK, and a reply is matched to + * its sender by the command code only. With several FEEDBACKs in flight, a sender can take + * the reply to another one and return while its own command is still pending. The device + * then stays a reply behind, holding its newest reply until the next command, and never + * confirms a QUIESCE_IO sent in that state. One FEEDBACK at a time, dropping a reply that + * arrived after its sender gave up, and taking only the reply that names the sender's buffer + * keep each reply with its sender. The lock is held for a bounded time: the send and the + * reply wait are both bounded. + */ +int ipts_control_send_feedback(struct ipts_context *ipts, u32 buffer) +{ + int ret = 0; + + if (!ipts) + return -EFAULT; + + mutex_lock(&ipts->feedback_lock); + ret = ipts_control_send_feedback_locked(ipts, buffer); + mutex_unlock(&ipts->feedback_lock); + + return ret; +} + int ipts_control_hid2me_feedback(struct ipts_context *ipts, enum ipts_feedback_cmd_type cmd, enum ipts_feedback_data_type type, void *data, size_t size) { + int ret = 0; struct ipts_feedback_header *header = NULL; if (!ipts) @@ -325,6 +391,15 @@ int ipts_control_hid2me_feedback(struct ipts_context *ipts, enum ipts_feedback_c if (!ipts->resources.hid2me.address) return -EFAULT; + /* + * There is one hid2me buffer. Fill it under the lock, which is held until the device + * answered this FEEDBACK, so a second request cannot overwrite it before then. (That the + * device is done reading the buffer once it answered is assumed, not known.) + * GET_FEATURE waits for its report only after this returns, with the lock released, + * because the receiver loop needs the lock to give back the buffer the report is in. + */ + mutex_lock(&ipts->feedback_lock); + memset(ipts->resources.hid2me.address, 0, ipts->resources.hid2me.size); header = (struct ipts_feedback_header *)ipts->resources.hid2me.address; @@ -333,18 +408,39 @@ int ipts_control_hid2me_feedback(struct ipts_context *ipts, enum ipts_feedback_c header->size = size; header->buffer = IPTS_HID2ME_BUFFER; - if (size + sizeof(*header) > ipts->resources.hid2me.size) - return -EINVAL; + if (size + sizeof(*header) > ipts->resources.hid2me.size) { + ret = -EINVAL; + goto out; + } if (data && size > 0) memcpy(header->payload, data, size); - return ipts_control_send_feedback(ipts, IPTS_HID2ME_BUFFER); + ret = ipts_control_send_feedback_locked(ipts, IPTS_HID2ME_BUFFER); + +out: + mutex_unlock(&ipts->feedback_lock); + return ret; +} + +/* + * The device was never told to stop, or never confirmed it, so it may still write to its + * DMA buffers. They are never freed; the next start allocates new ones. The report buffer + * is driver memory only and is freed. + */ +static void ipts_control_leak_buffers(struct ipts_context *ipts) +{ + dev_warn(ipts->dev, "Device stop not confirmed, leaking its DMA buffers\n"); + + kfree(ipts->resources.report.address); + memset(&ipts->resources, 0, sizeof(ipts->resources)); + ipts->buffers_unconfirmed = false; } int ipts_control_start(struct ipts_context *ipts) { int ret = 0; + size_t stale = 0; struct ipts_device_info info = { 0 }; if (!ipts) @@ -352,6 +448,15 @@ int ipts_control_start(struct ipts_context *ipts) dev_info(ipts->dev, "Starting IPTS\n"); + /* + * Responses to commands that were interrupted while sending (or that timed out) can + * still arrive later. Drop them, so that they are not mistaken for responses to the + * commands sent below. + */ + stale = ipts_mei_flush(&ipts->mei); + if (stale) + dev_dbg(ipts->dev, "Dropped %zu stale responses\n", stale); + ret = ipts_control_get_device_info(ipts, &info); if (ret) { dev_err(ipts->dev, "Failed to get device info: %d\n", ret); @@ -379,7 +484,15 @@ int ipts_control_start(struct ipts_context *ipts) ret = ipts_control_get_descriptor(ipts); if (ret) { dev_err(ipts->dev, "Failed to fetch HID descriptor: %d\n", ret); - return ret; + + /* + * Unless the device replied, it may still write the descriptor into its + * buffer. + */ + if (ret == -EBADR || ret == -ENODATA) + goto err_free_resources; + + goto err_leak_resources; } /* @@ -391,25 +504,25 @@ int ipts_control_start(struct ipts_context *ipts) ret = ipts_control_set_mode(ipts, ipts->mode); if (ret) { dev_err(ipts->dev, "Failed to set mode: %d\n", ret); - return ret; + goto err_free_resources; } ret = ipts_control_set_mem_window(ipts, &ipts->resources); if (ret) { dev_err(ipts->dev, "Failed to set memory window: %d\n", ret); - return ret; + goto err_leak_resources; } ret = ipts_receiver_start(ipts); if (ret) { dev_err(ipts->dev, "Failed to start receiver: %d\n", ret); - return ret; + goto err_leak_resources; } ret = ipts_control_request_data(ipts); if (ret) { dev_err(ipts->dev, "Failed to request data: %d\n", ret); - return ret; + goto err_stop; } ipts_hid_enable(ipts); @@ -417,70 +530,317 @@ int ipts_control_start(struct ipts_context *ipts) ret = ipts_hid_init(ipts, info); if (ret) { dev_err(ipts->dev, "Failed to initialize HID device: %d\n", ret); - return ret; + goto err_stop; } return 0; + +err_stop: + /* + * The receiver is running: stop it through the normal stop path, which keeps whatever + * a receiver thread that does not stop can still use. + */ + ipts_control_stop(ipts); + return ret; + +err_leak_resources: + /* + * The device may already have been given these buffers and was never told to stop. + */ + ipts_control_leak_buffers(ipts); + return ret; + +err_free_resources: + ipts_resources_free(&ipts->resources); + return ret; } +/* + * Returned by _ipts_control_stop() when the receiver thread is gone, but the device did not + * confirm its stop, or a HID request overlapped it: its DMA buffers were leaked, and it must + * not be started again. + */ +#define IPTS_STOP_LEAKED 1 + static int _ipts_control_stop(struct ipts_context *ipts) { int ret = 0; + bool busy = false; if (!ipts) return -EFAULT; - ipts_hid_disable(ipts); dev_info(ipts->dev, "Stopping IPTS\n"); + busy = ipts_hid_quiesce(ipts, IPTS_HID_QUIESCE_TIMEOUT_MS) == -ETIMEDOUT; + + /* + * A HID callback that outlives the wait may send the device a command after it confirmed + * the stop below, and the device may answer by writing to the buffers again. They are + * leaked then, by this stop or, if it keeps everything, by a later one. + */ + if (busy) + ipts->buffers_unconfirmed = true; + + /* + * The receiver is asked to stop in any case. A HID callback that was only slow may + * return meanwhile; once the count is zero, no new one starts, since HID input is off. + */ ret = ipts_receiver_stop(ipts); - if (ret) { - dev_err(ipts->dev, "Failed to stop receiver: %d\n", ret); + + if (busy && atomic_read(&ipts->hid_users) == 0) + busy = false; + + if (busy) { + /* + * A HID request, or the receiver's HID input, is stuck in driver code, most + * likely in a task that died inside it. It can still touch the buffers, and + * destroying the HID device could block forever on HID core locks that task + * holds, so nothing is freed. A later stop must not free the buffers either, + * although it finds no thread anymore. + */ + dev_err(ipts->dev, "A HID request did not return (%d still running)\n", + atomic_read(&ipts->hid_users)); + return -EBUSY; + } + + if (ret == -ETIMEDOUT) { + /* + * The thread is still running and can still touch the buffers, so they are + * kept. It can no longer reach the HID device: its HID input is counted, and + * nothing counted is running anymore. + */ + dev_err(ipts->dev, "Receiver thread did not stop\n"); return ret; } - ret = ipts_resources_free(&ipts->resources); if (ret) { - dev_err(ipts->dev, "Failed to free resources: %d\n", ret); - return ret; + dev_err(ipts->dev, "Receiver thread died without stopping the device: %d\n", ret); + ipts_control_leak_buffers(ipts); + return IPTS_STOP_LEAKED; + } + + if (ipts->receiver_loop.exit_code) { + dev_err(ipts->dev, "Failed to stop the device: %d\n", + ipts->receiver_loop.exit_code); + ipts_control_leak_buffers(ipts); + return IPTS_STOP_LEAKED; + } + + if (ipts->buffers_unconfirmed) { + dev_err(ipts->dev, "Device may still use its buffers, leaking them\n"); + ipts_control_leak_buffers(ipts); + return IPTS_STOP_LEAKED; } + ret = ipts_resources_free(&ipts->resources); + if (ret) + dev_err(ipts->dev, "Failed to free resources: %d\n", ret); + return 0; } int ipts_control_stop(struct ipts_context *ipts) { int ret = 0; + int err = 0; + + if (!ipts) + return -EFAULT; + /* + * The HID device must be gone before the module can unload, or opening its hidraw node + * later runs freed module code. Once no HID callback and no HID input of the receiver + * runs, and none can start, it is destroyed, even when the receiver thread did not stop. + * It is kept only while a HID callback is stuck. + */ ret = _ipts_control_stop(ipts); + + /* + * As after a failed stop for a restart: a failed start stops the device through here, + * and the restart retry must not start a device that did not stop or confirm its stop. + */ if (ret) - return ret; + WRITE_ONCE(ipts->restart_blocked, true); - ret = ipts_hid_free(ipts); - if (ret) { - dev_err(ipts->dev, "Failed to free HID device: %d\n", ret); + if (ret == -EBUSY) return ret; - } - return 0; + err = ipts_hid_free(ipts); + if (err) + dev_err(ipts->dev, "Failed to free HID device: %d\n", err); + + /* + * Leaked buffers are not an error for the callers. + */ + if (ret == IPTS_STOP_LEAKED) + return 0; + + return ret; } -int ipts_control_restart(struct ipts_context *ipts) +static void ipts_control_restart_work(struct work_struct *work) { int ret = 0; + struct ipts_context *ipts = + container_of(to_delayed_work(work), struct ipts_context, restart_work); + mutex_lock(&ipts->ctl_lock); + + if (READ_ONCE(ipts->removing)) + goto out; + + /* + * A mode switch can queue this again while a stop that leaked the buffers runs, before + * that stop sets restart_blocked. The device must not be started again until the next + * probe, so a run queued that way does nothing. + */ + if (READ_ONCE(ipts->restart_blocked)) + goto out; + + /* + * A mode switch that arrived while the previous restart ran queues another one. If that + * restart already applied the mode and the device runs, there is nothing to do. + */ + if (!ipts->restart_attempts && READ_ONCE(ipts->hid_active) && + ipts->mode == READ_ONCE(ipts->requested_mode)) + goto out; + + ipts->mode = READ_ONCE(ipts->requested_mode); + + /* + * Also on a retry, although the failed start left the device stopped: on a stopped device + * this does nothing, but if the start failed after it started the receiver and that did + * not stop, it keeps the device from being started again, as for any other restart. If + * the device did not confirm the failed start's stop, that stop set restart_blocked and + * the retry ended above. + */ ret = _ipts_control_stop(ipts); - if (ret) - return ret; + if (ret == IPTS_STOP_LEAKED) { + /* + * The device did not confirm its stop, or a HID request may have sent it a + * command after it did. Starting it again can leave its firmware unresponsive + * until the next boot. + */ + dev_err(ipts->dev, "Device may not have stopped, not restarting IPTS\n"); + goto blocked; + } + + if (ret) { + dev_err(ipts->dev, "Failed to stop IPTS for a restart: %d\n", ret); + goto blocked; + } + + if (ipts->restart_attempts) { + dev_info(ipts->dev, "Restarting IPTS after a failed mode switch\n"); + + /* + * After a timeout, every response from the ME can arrive only when the next + * command is sent, which makes all further commands time out as well. Waiting + * doesn't help, but reconnecting does. + */ + ret = ipts_mei_reconnect(&ipts->mei); + if (ret) { + dev_err(ipts->dev, "Failed to reconnect to the ME: %d\n", ret); + goto failed; + } + } /* * Wait a second to give the sensor time to fully shut down. */ msleep(1000); + /* + * A remove that started meanwhile waits for this, and stops the device anyway. + */ + if (READ_ONCE(ipts->removing)) + goto out; + ret = ipts_control_start(ipts); - if (ret) - return ret; + if (!ret) { + ipts->restart_attempts = 0; + goto out; + } + + dev_err(ipts->dev, "Failed to restart IPTS: %d\n", ret); + +failed: + if (++ipts->restart_attempts >= IPTS_RESTART_MAX_ATTEMPTS) { + dev_err(ipts->dev, "Giving up restarting IPTS: %d\n", ret); + ipts->restart_attempts = 0; + goto out; + } + + if (READ_ONCE(ipts->removing)) + goto out; + + /* + * The device is stopped, and the HID device is inactive, so userspace cannot retry. + * Retry in the mode that was asked for: the HID request that asked for it returned + * before the restart ran, so its sender expects that mode. The retry holds its own + * reference. + */ + ipts_context_get(ipts); + if (!schedule_delayed_work(&ipts->restart_work, msecs_to_jiffies(IPTS_RESTART_DELAY_MS))) + ipts_context_put(ipts); + + goto out; + +blocked: + /* + * Refuse further mode switches, which would only queue another restart. + */ + WRITE_ONCE(ipts->restart_blocked, true); + ipts->restart_attempts = 0; + +out: + mutex_unlock(&ipts->ctl_lock); + + /* + * Drop the reference that ipts_control_restart() took for this run. + */ + ipts_context_put(ipts); +} + +void ipts_control_init(struct ipts_context *ipts) +{ + mutex_init(&ipts->ctl_lock); + INIT_DELAYED_WORK(&ipts->restart_work, ipts_control_restart_work); + ipts->restart_attempts = 0; + ipts->restart_blocked = false; + ipts->removing = false; +} + +int ipts_control_restart(struct ipts_context *ipts) +{ + if (!ipts) + return -EFAULT; + + /* + * Called from a HID callback, which the stop has to wait for, so the restart itself + * runs from a work item. + */ + if (READ_ONCE(ipts->removing)) + return -ENODEV; + + /* + * A queued restart holds a reference until it ran or was cancelled. If one is queued + * already, it holds its own. + */ + ipts_context_get(ipts); + if (!schedule_delayed_work(&ipts->restart_work, 0)) + ipts_context_put(ipts); return 0; } + +void ipts_control_cancel_restart(struct ipts_context *ipts) +{ + /* + * Never waits: a restart that is running holds ctl_lock, which remove waits for with a + * bound. A queued one that is cancelled drops its reference here. + */ + if (cancel_delayed_work(&ipts->restart_work)) + ipts_context_put(ipts); +} diff --git a/drivers/hid/ipts/control.h b/drivers/hid/ipts/control.h index 26629c5144edb..ca7e8ba68a912 100644 --- a/drivers/hid/ipts/control.h +++ b/drivers/hid/ipts/control.h @@ -11,6 +11,8 @@ #include #include "context.h" +#include "mei.h" +#include "receiver.h" #include "spec-data.h" #include "spec-device.h" @@ -99,10 +101,34 @@ static inline int ipts_control_refill_buffer(struct ipts_context *ipts, u32 buff return ipts_control_send_feedback(ipts, buffer); } +/* + * The longest ipts_control_start() takes on a restart. Only EDS1 devices restart. They send + * three commands that wait for their reply (GET_DEVICE_INFO, SET_MODE and SET_MEM_WINDOW) and + * READY_FOR_DATA, which is only sent. GET_DESCRIPTOR is sent only to newer devices, since the + * EDS1 HID descriptor is built into the driver, and the rest of a start sends no command. The + * bound still counts four replies; the fourth is margin. + */ +#define IPTS_CONTROL_START_TIMEOUT_MS (4 * IPTS_RECEIVER_CMD_MS + IPTS_MEI_SEND_TIMEOUT_MS) + +/* + * How long stopping waits for running HID callbacks. The longest of them, a GET_FEATURE + * request, is released at once by ipts_hid_quiesce(). + */ +#define IPTS_HID_QUIESCE_TIMEOUT_MS 12000 + +/* + * The longest a stop takes: the wait for running HID callbacks, then the stop of the receiver + * thread. + */ +#define IPTS_CONTROL_STOP_TIMEOUT_MS (IPTS_HID_QUIESCE_TIMEOUT_MS + IPTS_RECEIVER_STOP_TIMEOUT_MS) + /** * ipts_control_start() - Initialized the device and starts the data flow. * @ipts: The IPTS driver context. * + * On failure, what it set up is torn down again, except what the device or a receiver thread + * that does not stop may still use: DMA buffers the device may have been given are leaked. + * * Returns: 0 on success, <0 on error. */ int ipts_control_start(struct ipts_context *ipts); @@ -111,16 +137,31 @@ int ipts_control_start(struct ipts_context *ipts); * ipts_control_stop() - Stops the data flow and resets the device. * @ipts: The IPTS driver context. * - * Returns: 0 on success, <0 on error. + * Returns: 0 if the receiver thread stopped (the DMA buffers are leaked if the device did not + * confirm the stop, or a HID callback outlived the wait for it), -ETIMEDOUT if it is still + * running (the HID device is destroyed, the buffers are kept), -EBUSY if a HID callback did + * not return (everything is kept), <0 on other errors. */ int ipts_control_stop(struct ipts_context *ipts); /** - * ipts_control_restart() - Stops the device and starts it again. + * ipts_control_restart() - Schedules a stop and start of the device. * @ipts: The IPTS driver context. * - * Returns: 0 on success, <0 on error. + * Returns: 0 if the restart was scheduled, <0 on error. */ int ipts_control_restart(struct ipts_context *ipts); +/** + * ipts_control_cancel_restart() - Cancels a restart that is queued but not running yet. + * @ipts: The IPTS driver context. + */ +void ipts_control_cancel_restart(struct ipts_context *ipts); + +/** + * ipts_control_init() - Initializes the lock and the work item of the context. + * @ipts: The IPTS driver context. + */ +void ipts_control_init(struct ipts_context *ipts); + #endif /* IPTS_CONTROL_H */ diff --git a/drivers/hid/ipts/eds1.c b/drivers/hid/ipts/eds1.c index 7b9f54388a9f6..f677e00ab334a 100644 --- a/drivers/hid/ipts/eds1.c +++ b/drivers/hid/ipts/eds1.c @@ -54,10 +54,29 @@ static int ipts_eds1_switch_mode(struct ipts_context *ipts, enum ipts_mode mode) if (!ipts) return -EFAULT; - if (ipts->mode == mode) + /* + * The value comes from userspace, and every restart retry applies it. + */ + if (mode != IPTS_MODE_EVENT && mode != IPTS_MODE_POLL) + return -EINVAL; + + /* + * After a failed stop the device must not be started again until the next probe. The + * device can still be running then, if a restart queued before the flag was set + * started it. + */ + if (READ_ONCE(ipts->restart_blocked)) + return -ENODEV; + + /* + * Only recorded here: restart_work applies it, also when this arrives during a restart. + * The same mode again restarts a device that is not running, for example after the + * restart retries gave up; restart_work does nothing if it runs by then. + */ + if (READ_ONCE(ipts->requested_mode) == mode && READ_ONCE(ipts->hid_active)) return 0; - ipts->mode = mode; + WRITE_ONCE(ipts->requested_mode, mode); ret = ipts_control_restart(ipts); if (ret) @@ -93,7 +112,7 @@ int ipts_eds1_raw_request(struct ipts_context *ipts, u8 *buffer, size_t size, u8 if (request_type == HID_REQ_GET_REPORT) { memset(buffer, 0, size); buffer[0] = report_id; - buffer[1] = ipts->mode; + buffer[1] = READ_ONCE(ipts->requested_mode); } else if (request_type == HID_REQ_SET_REPORT) { return ipts_eds1_switch_mode(ipts, buffer[1]); } else { diff --git a/drivers/hid/ipts/eds2.c b/drivers/hid/ipts/eds2.c index 639940794615d..af00ca9d435b9 100644 --- a/drivers/hid/ipts/eds2.c +++ b/drivers/hid/ipts/eds2.c @@ -67,6 +67,16 @@ static int ipts_eds2_get_feature(struct ipts_context *ipts, u8 *buffer, size_t s memset(&ipts->feature_report, 0, sizeof(ipts->feature_report)); reinit_completion(&ipts->feature_event); + /* + * A stop that started before the reinit above already released the completion, so + * do not wait for a reply that will not come. + */ + smp_mb(); + if (!READ_ONCE(ipts->hid_active)) { + ret = -ENODEV; + goto out; + } + ret = ipts_control_hid2me_feedback(ipts, IPTS_FEEDBACK_CMD_TYPE_NONE, type, buffer, size); if (ret) { dev_err(ipts->dev, "Failed to send hid2me feedback: %d\n", ret); diff --git a/drivers/hid/ipts/hid.c b/drivers/hid/ipts/hid.c index e34a1a4f9fa77..8a0e2a830946b 100644 --- a/drivers/hid/ipts/hid.c +++ b/drivers/hid/ipts/hid.c @@ -31,6 +31,54 @@ void ipts_hid_disable(struct ipts_context *ipts) WRITE_ONCE(ipts->hid_active, false); } +static void ipts_hid_exit(struct ipts_context *ipts) +{ + if (atomic_dec_and_test(&ipts->hid_users)) + wake_up_all(&ipts->hid_users_wq); +} + +/* + * Every HID callback that runs driver code, and the receiver's HID input, is counted, so that + * stopping can wait until none of them can touch the buffers or the HID device anymore. + */ +static bool ipts_hid_enter(struct ipts_context *ipts) +{ + atomic_inc(&ipts->hid_users); + /* + * Order the count above before reading hid_active, so a stop that cleared it cannot + * miss this callback. + */ + smp_mb__after_atomic(); + + if (!READ_ONCE(ipts->hid_active)) { + ipts_hid_exit(ipts); + return false; + } + + return true; +} + +int ipts_hid_quiesce(struct ipts_context *ipts, unsigned int timeout_ms) +{ + ipts_hid_disable(ipts); + /* + * Order the disable above before releasing the completion, so a callback that passed the + * check before it does not wait for a reply that will not come. + */ + smp_mb(); + + /* + * Release a GET_FEATURE request that waits for a reply which will not come anymore. + */ + complete_all(&ipts->feature_event); + + if (!wait_event_timeout(ipts->hid_users_wq, atomic_read(&ipts->hid_users) == 0, + msecs_to_jiffies(timeout_ms))) + return -ETIMEDOUT; + + return 0; +} + static int ipts_hid_start(struct hid_device *hid) { return 0; @@ -56,7 +104,7 @@ static int ipts_hid_parse(struct hid_device *hid) if (!ipts) return -EFAULT; - if (!READ_ONCE(ipts->hid_active)) + if (!ipts_hid_enter(ipts)) return -ENODEV; if (ipts->info.intf_eds == 1) @@ -64,6 +112,8 @@ static int ipts_hid_parse(struct hid_device *hid) else ret = ipts_eds2_get_descriptor(ipts, &buffer, &size); + ipts_hid_exit(ipts); + if (ret) { dev_err(ipts->dev, "Failed to allocate HID descriptor: %d\n", ret); return ret; @@ -80,9 +130,36 @@ static int ipts_hid_parse(struct hid_device *hid) return 0; } +/* + * On EDS1, a mode switch restarts the device from a work item, and the HID device is inactive + * until the restart is done. When iptsd is restarted, the old instance switches back to event + * mode as it exits, and the switch of the new one arrives during that restart. Refusing it + * would make the new iptsd exit, with touch input left in event mode. The EDS1 mode report + * only records the requested mode and queues a restart, and touches neither the device nor + * its buffers, so it is let through while the device restarts. It is still counted, so that a + * stop waits for it, and refused once remove started or after a failed stop. + */ +static bool ipts_hid_enter_restarting(struct ipts_context *ipts) +{ + atomic_inc(&ipts->hid_users); + /* + * Order the count above before reading removing, so a remove that set it cannot miss + * this callback: its stop orders that write before reading the count. + */ + smp_mb__after_atomic(); + + if (READ_ONCE(ipts->removing) || READ_ONCE(ipts->restart_blocked)) { + ipts_hid_exit(ipts); + return false; + } + + return true; +} + static int ipts_hid_raw_request(struct hid_device *hid, unsigned char report_id, __u8 *buffer, size_t size, unsigned char report_type, int request_type) { + int ret = 0; struct ipts_context *ipts = NULL; if (!hid) @@ -93,16 +170,20 @@ static int ipts_hid_raw_request(struct hid_device *hid, unsigned char report_id, if (!ipts) return -EFAULT; - if (!READ_ONCE(ipts->hid_active)) + if (!ipts_hid_enter(ipts) && + (ipts->info.intf_eds != 1 || !ipts_hid_enter_restarting(ipts))) return -ENODEV; if (ipts->info.intf_eds == 1) { - return ipts_eds1_raw_request(ipts, buffer, size, report_id, report_type, - request_type); + ret = ipts_eds1_raw_request(ipts, buffer, size, report_id, report_type, + request_type); } else { - return ipts_eds2_raw_request(ipts, buffer, size, report_id, report_type, - request_type); + ret = ipts_eds2_raw_request(ipts, buffer, size, report_id, report_type, + request_type); } + + ipts_hid_exit(ipts); + return ret; } static struct hid_ll_driver ipts_hid_driver = { @@ -114,19 +195,18 @@ static struct hid_ll_driver ipts_hid_driver = { .raw_request = ipts_hid_raw_request, }; -int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer) +static int ipts_hid_handle_data(struct ipts_context *ipts, u32 buffer) { u8 *temp = NULL; + struct hid_device *hid = NULL; struct ipts_hid_header *frame = NULL; struct ipts_data_header *header = NULL; - if (!ipts) - return -EFAULT; - - if (!ipts->hid) - return -ENODEV; - - if (!READ_ONCE(ipts->hid_active)) + /* + * Set by ipts_hid_init() while this thread is already running. + */ + hid = READ_ONCE(ipts->hid); + if (!hid) return -ENODEV; header = (struct ipts_data_header *)ipts->resources.data[buffer].address; @@ -141,7 +221,7 @@ int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer) return 0; if (header->type == IPTS_DATA_TYPE_HID) - return hid_input_report(ipts->hid, HID_INPUT_REPORT, header->data, header->size, 1); + return hid_input_report(hid, HID_INPUT_REPORT, header->data, header->size, 1); if (header->type == IPTS_DATA_TYPE_GET_FEATURES) { ipts->feature_report.address = header->data; @@ -168,12 +248,33 @@ int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer) memcpy(frame->data, header->data, header->size); - return hid_input_report(ipts->hid, HID_INPUT_REPORT, temp, IPTS_HID_REPORT_DATA_SIZE, 1); + return hid_input_report(hid, HID_INPUT_REPORT, temp, IPTS_HID_REPORT_DATA_SIZE, 1); +} + +int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer) +{ + int ret = 0; + + if (!ipts) + return -EFAULT; + + /* + * Counted like a HID callback. Once a stop has seen no callback running, the receiver + * thread can no longer reach the HID device, even if the thread itself does not stop. + */ + if (!ipts_hid_enter(ipts)) + return -ENODEV; + + ret = ipts_hid_handle_data(ipts, buffer); + ipts_hid_exit(ipts); + + return ret; } int ipts_hid_init(struct ipts_context *ipts, struct ipts_device_info info) { int ret = 0; + struct hid_device *hid = NULL; if (!ipts) return -EFAULT; @@ -181,29 +282,43 @@ int ipts_hid_init(struct ipts_context *ipts, struct ipts_device_info info) if (ipts->hid) return 0; - ipts->hid = hid_allocate_device(); - if (IS_ERR(ipts->hid)) { - int err = PTR_ERR(ipts->hid); - - dev_err(ipts->dev, "Failed to allocate HID device: %d\n", err); - return err; + hid = hid_allocate_device(); + if (IS_ERR(hid)) { + ret = PTR_ERR(hid); + dev_err(ipts->dev, "Failed to allocate HID device: %d\n", ret); + return ret; } - ipts->hid->driver_data = ipts; - ipts->hid->dev.parent = ipts->dev; - ipts->hid->ll_driver = &ipts_hid_driver; + /* + * The HID device uses the context in its callbacks until it is destroyed: hold a + * reference for its whole life, also when hid_add_device() fails and it is left for + * ipts_control_stop() to destroy. + */ + ipts_context_get(ipts); + + hid->driver_data = ipts; + hid->dev.parent = ipts->dev; + hid->ll_driver = &ipts_hid_driver; - ipts->hid->vendor = info.vendor; - ipts->hid->product = info.product; - ipts->hid->group = HID_GROUP_GENERIC; + hid->vendor = info.vendor; + hid->product = info.product; + hid->group = HID_GROUP_GENERIC; - snprintf(ipts->hid->name, sizeof(ipts->hid->name), "IPTS %04X:%04X", info.vendor, - info.product); + snprintf(hid->name, sizeof(hid->name), "IPTS %04X:%04X", info.vendor, info.product); - ret = hid_add_device(ipts->hid); + /* + * The receiver thread is already running and reads ipts->hid, so the device is published + * only once it is set up. The release orders the setup before the pointer. + */ + smp_store_release(&ipts->hid, hid); + + /* + * On failure ipts->hid stays set: the receiver thread may already be using it, so it + * is destroyed by ipts_control_stop() once HID input has stopped. + */ + ret = hid_add_device(hid); if (ret) { dev_err(ipts->dev, "Failed to add HID device: %d\n", ret); - ipts_hid_free(ipts); return ret; } @@ -221,5 +336,10 @@ int ipts_hid_free(struct ipts_context *ipts) hid_destroy_device(ipts->hid); ipts->hid = NULL; + /* + * Drop the reference taken by ipts_hid_init(). + */ + ipts_context_put(ipts); + return 0; } diff --git a/drivers/hid/ipts/hid.h b/drivers/hid/ipts/hid.h index 1ebe77447903a..d3e89e412f179 100644 --- a/drivers/hid/ipts/hid.h +++ b/drivers/hid/ipts/hid.h @@ -16,6 +16,15 @@ void ipts_hid_enable(struct ipts_context *ipts); void ipts_hid_disable(struct ipts_context *ipts); +/** + * ipts_hid_quiesce() - Disables HID callbacks and waits for running ones to return. + * @ipts: The IPTS driver context. + * @timeout_ms: How long to wait at most. + * + * Returns: 0 when no callback is running anymore, -ETIMEDOUT if one did not return. + */ +int ipts_hid_quiesce(struct ipts_context *ipts, unsigned int timeout_ms); + int ipts_hid_input_data(struct ipts_context *ipts, u32 buffer); int ipts_hid_init(struct ipts_context *ipts, struct ipts_device_info info); diff --git a/drivers/hid/ipts/main.c b/drivers/hid/ipts/main.c index fb5b5c13ee3ea..8e7e0b5682c75 100644 --- a/drivers/hid/ipts/main.c +++ b/drivers/hid/ipts/main.c @@ -9,6 +9,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -16,6 +19,7 @@ #include #include #include +#include #include "context.h" #include "control.h" @@ -39,6 +43,27 @@ static int ipts_set_dma_mask(struct mei_cl_device *cldev) return dma_coerce_mask_and_coherent(&cldev->dev, DMA_BIT_MASK(32)); } +void ipts_context_release(struct kref *refcount) +{ + struct ipts_context *ipts = container_of(refcount, struct ipts_context, refcount); + struct mei_cl_device *cldev = ipts->mei.cldev; + + ipts_mei_free_messages(&ipts->mei); + kfree(ipts); + + /* + * Drop the reference to the MEI device that probe took for the context. + */ + put_device(&cldev->dev); +} + +static void ipts_context_drop_probe(void *data) +{ + struct ipts_context *ipts = data; + + kref_put(&ipts->refcount, ipts_context_release); +} + static int ipts_probe(struct mei_cl_device *cldev, const struct mei_cl_device_id *id) { int ret = 0; @@ -59,33 +84,106 @@ static int ipts_probe(struct mei_cl_device *cldev, const struct mei_cl_device_id return ret; } - ipts = devm_kzalloc(&cldev->dev, sizeof(*ipts), GFP_KERNEL); + /* + * The context is freed by its kref once every user dropped its reference. It must not be + * tied to the device lifetime: a receiver thread or HID device that is still there after + * a failed stop keeps using it after the device is gone. + */ + ipts = kzalloc(sizeof(*ipts), GFP_KERNEL); if (!ipts) { - mei_cldev_disable(cldev); - return -ENOMEM; + ret = -ENOMEM; + goto err_disable; } + /* + * Such a user also keeps sending through the MEI device and logging against it after + * remove returned, so the context holds a reference to it until it is freed. + */ + get_device(&cldev->dev); + + kref_init(&ipts->refcount); + atomic_set(&ipts->users, 0); + init_waitqueue_head(&ipts->users_wq); + + /* + * Before the release function can run: it frees the message list. + */ ret = ipts_mei_init(&ipts->mei, cldev); if (ret) { dev_err(&cldev->dev, "Failed to init MEI bus logic: %d\n", ret); - return ret; + put_device(&cldev->dev); + kfree(ipts); + goto err_disable; } + /* + * Drop the probe reference when the device is released. Remove and every later probe + * failure disable the MEI device before that, which cancels its receive callback, so no + * message arrives while the context is being freed. If adding the action fails, the + * context is freed at once, before the MEI device is disabled: the receive callback finds + * no context then, because drvdata is not set yet. + */ + ret = devm_add_action_or_reset(&cldev->dev, ipts_context_drop_probe, ipts); + if (ret) + goto err_disable; + ipts->dev = &cldev->dev; ipts->mode = IPTS_MODE_EVENT; + ipts->requested_mode = IPTS_MODE_EVENT; mutex_init(&ipts->feature_lock); + mutex_init(&ipts->feedback_lock); init_completion(&ipts->feature_event); + ipts_control_init(ipts); + + atomic_set(&ipts->hid_users, 0); + init_waitqueue_head(&ipts->hid_users_wq); mei_cldev_set_drvdata(cldev, ipts); ret = ipts_control_start(ipts); if (ret) { dev_err(&cldev->dev, "Failed to start IPTS: %d\n", ret); - return ret; + goto err_disable; } return 0; + +err_disable: + mei_cldev_disable(cldev); + return ret; +} + +/* + * How long ipts_remove() waits for the last user of the context to return. One that does not + * return keeps the context alive, so it is never freed under it. + */ +#define IPTS_REMOVE_TIMEOUT_MS 12000 + +/* + * How long ipts_remove() waits for a running restart to release ctl_lock: the longest a + * restart can still hold it once removing is set. Before its last check of removing, that is + * the rest of a stop, a reconnect to the ME on a retry, and the one-second pause; after it, a + * start, and a stop if the start fails. The sum of a start, a stop and a reconnect covers + * either. One second more covers scheduling. A restart that holds the lock for longer is stuck. + */ +#define IPTS_REMOVE_LOCK_TIMEOUT_MS \ + (IPTS_CONTROL_START_TIMEOUT_MS + IPTS_CONTROL_STOP_TIMEOUT_MS + \ + IPTS_MEI_RECONNECT_TIMEOUT_MS + 1000) +#define IPTS_REMOVE_LOCK_POLL_MS 10 + +static bool ipts_remove_lock(struct ipts_context *ipts) +{ + unsigned long end = jiffies + msecs_to_jiffies(IPTS_REMOVE_LOCK_TIMEOUT_MS); + + while (!mutex_trylock(&ipts->ctl_lock)) { + if (time_after(jiffies, end)) + return false; + + msleep(IPTS_REMOVE_LOCK_POLL_MS); + } + + return true; } static void ipts_remove(struct mei_cl_device *cldev) @@ -100,11 +198,52 @@ static void ipts_remove(struct mei_cl_device *cldev) ipts = mei_cldev_get_drvdata(cldev); + /* + * No new restarts, and cancel a queued one. A restart that is already running sees + * removing before it starts the device again, and is waited for, bounded, through + * ctl_lock. One scheduled by a HID callback that raced with this is cancelled after the + * stop, or sees removing and does nothing. + */ + WRITE_ONCE(ipts->removing, true); + ipts_control_cancel_restart(ipts); + + if (!ipts_remove_lock(ipts)) { + /* + * A restart is stuck with the device half stopped or started. Nothing it uses + * may be freed, so the stop is skipped. + */ + dev_err(&cldev->dev, "A restart of IPTS did not finish, not stopping it\n"); + mei_cldev_disable(cldev); + return; + } + ret = ipts_control_stop(ipts); + mutex_unlock(&ipts->ctl_lock); + + ipts_control_cancel_restart(ipts); + if (ret) dev_err(&cldev->dev, "Failed to stop IPTS: %d\n", ret); mei_cldev_disable(cldev); + + /* + * A failed stop keeps the receiver thread or the HID device, and their references, on + * purpose, so there is nothing to wait for. + */ + if (ret) + return; + + /* + * Wait, bounded, for the remaining users of the context to return, so the module code is + * not freed while they still run it. That narrows the window, but does not close it: the + * last user wakes this from inside its own put, before it has left the module code. The + * probe reference is dropped by devres after this, and the context is freed after its + * last user. + */ + if (!wait_event_timeout(ipts->users_wq, atomic_read(&ipts->users) == 0, + msecs_to_jiffies(IPTS_REMOVE_TIMEOUT_MS))) + dev_err(&cldev->dev, "A user of the IPTS context did not return\n"); } static struct mei_cl_device_id ipts_device_id_table[] = { diff --git a/drivers/hid/ipts/mei.c b/drivers/hid/ipts/mei.c index 1e0395ceae4a4..8b753406e4a16 100644 --- a/drivers/hid/ipts/mei.c +++ b/drivers/hid/ipts/mei.c @@ -5,73 +5,146 @@ * Linux driver for Intel Precise Touch & Stylus */ +#include #include #include #include +#include #include #include #include #include +#include #include #include #include "context.h" #include "mei.h" -static void locked_list_add(struct list_head *new, struct list_head *head, - struct rw_semaphore *lock) +/* + * The message lock is only ever held around a list add or delete. A holder that keeps it + * for longer died or is stuck, and waiting for it must never block forever: ipts_remove() + * runs on reboot and suspend, too. + */ +static bool ipts_mei_trylock(struct ipts_mei *mei) { - down_write(lock); - list_add(new, head); - up_write(lock); + struct ipts_context *ipts = container_of(mei, struct ipts_context, mei); + + if (!down_write_trylock(&mei->message_lock)) + return false; + + /* + * Hold the context while the lock is held, so a holder that never releases the lock (a + * dead or stuck task) keeps the context alive instead of freeing it under itself. + */ + ipts_context_get(ipts); + + return true; } -static void locked_list_del(struct list_head *entry, struct rw_semaphore *lock) +static bool ipts_mei_lock_timeout(struct ipts_mei *mei, unsigned int timeout_ms) { - down_write(lock); - list_del(entry); - up_write(lock); + unsigned long end = jiffies + msecs_to_jiffies(timeout_ms); + + while (!ipts_mei_trylock(mei)) { + if (time_after(jiffies, end)) + return false; + + usleep_range(IPTS_MEI_LOCK_POLL_US, 2 * IPTS_MEI_LOCK_POLL_US); + } + + return true; } -static void ipts_mei_incoming(struct mei_cl_device *cldev) +static void ipts_mei_unlock(struct ipts_mei *mei) { - ssize_t ret = 0; - struct ipts_mei_message *entry = NULL; - struct ipts_context *ipts = NULL; + struct ipts_context *ipts = container_of(mei, struct ipts_context, mei); - if (!cldev) { - pr_err("MEI device is NULL!"); - return; - } + /* + * Release the lock before the reference: if this is the last one, the release function + * frees the context, and takes the lock itself to free the messages. + */ + up_write(&mei->message_lock); + ipts_context_put(ipts); +} - ipts = mei_cldev_get_drvdata(cldev); - if (!ipts) { - pr_err("IPTS driver context is NULL!"); - return; - } +/* + * Read one response from the bus and queue it. Returns false if none was ready within + * IPTS_MEI_RECV_MORE_MS or reading it failed. + */ +static bool ipts_mei_receive(struct ipts_context *ipts, struct mei_cl_device *cldev) +{ + ssize_t ret = 0; + struct ipts_mei_message *entry = NULL; - entry = devm_kzalloc(ipts->dev, sizeof(*entry), GFP_KERNEL); + entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (!entry) - return; + return false; INIT_LIST_HEAD(&entry->list); do { - ret = mei_cldev_recv(cldev, (u8 *)&entry->rsp, sizeof(entry->rsp)); + ret = mei_cldev_recv_timeout(cldev, (u8 *)&entry->rsp, sizeof(entry->rsp), + IPTS_MEI_RECV_MORE_MS); } while (ret == -EINTR); + if (ret == -ETIME) { + kfree(entry); + return false; + } + if (ret < 0) { dev_err(ipts->dev, "Error while reading response: %ld\n", ret); - return; + kfree(entry); + return false; } if (ret == 0) { dev_err(ipts->dev, "Received empty response\n"); - return; + kfree(entry); + return false; } - locked_list_add(&entry->list, &ipts->mei.messages, &ipts->mei.message_lock); + if (!ipts_mei_lock_timeout(&ipts->mei, IPTS_MEI_LOCK_TIMEOUT_MS)) { + dev_err_ratelimited(ipts->dev, "Message lock is busy, dropping a response\n"); + kfree(entry); + return true; + } + + list_add(&entry->list, &ipts->mei.messages); + WRITE_ONCE(ipts->mei.seq, ipts->mei.seq + 1); + ipts_mei_unlock(&ipts->mei); + wake_up_all(&ipts->mei.message_queue); + return true; +} + +static void ipts_mei_incoming(struct mei_cl_device *cldev) +{ + struct ipts_context *ipts = NULL; + + if (!cldev) { + pr_err("MEI device is NULL!"); + return; + } + + ipts = mei_cldev_get_drvdata(cldev); + if (!ipts) { + pr_err("IPTS driver context is NULL!"); + return; + } + + /* + * The bus calls this from a work item that it schedules when a response arrives. IPTS + * is a fixed-address client, so the ME can send the next response before that work has + * run, and scheduling it again then does nothing: one call, two responses ready. If + * only one was read, the other would wait with the bus until a later response arrives. + * When stopping, that is the QUIESCE_IO response, right behind the one for the pending + * READY_FOR_DATA, and the stop is never confirmed. So read until none is ready. The + * wait for each is bounded, so a call whose response an earlier call took returns too. + */ + while (ipts_mei_receive(ipts, cldev)) + ; } static int ipts_mei_search(struct ipts_mei *mei, enum ipts_command_code code, @@ -85,7 +158,8 @@ static int ipts_mei_search(struct ipts_mei *mei, enum ipts_command_code code, if (!rsp) return -EFAULT; - down_read(&mei->message_lock); + if (!ipts_mei_trylock(mei)) + return -EBUSY; /* * Iterate over the list of received messages, and check if there is one @@ -96,21 +170,23 @@ static int ipts_mei_search(struct ipts_mei *mei, enum ipts_command_code code, break; } - up_read(&mei->message_lock); - /* * If entry is not the list head, this means that the loop above has been stopped early, - * and that we found a matching element. We drop the message from the list and return it. + * and that we found a matching element. We drop the message from the list while still + * holding the lock, so that no other waiter can claim the same entry, and return it. */ if (!list_entry_is_head(entry, &mei->messages, list)) { - locked_list_del(&entry->list, &mei->message_lock); + list_del(&entry->list); + ipts_mei_unlock(mei); *rsp = entry->rsp; - devm_kfree(&mei->cldev->dev, entry); + kfree(entry); return 0; } + ipts_mei_unlock(mei); + return -EAGAIN; } @@ -118,36 +194,53 @@ int ipts_mei_recv(struct ipts_mei *mei, enum ipts_command_code code, struct ipts u64 timeout) { int ret = 0; + long left = 0; + unsigned long seq = 0; + unsigned long end = 0; if (!mei) return -EFAULT; /* - * A timeout of 0 means check and return immideately. + * A timeout of 0 means check and return immediately. */ - if (timeout == 0) - return ipts_mei_search(mei, code, rsp); + if (timeout == 0) { + ret = ipts_mei_search(mei, code, rsp); + return ret == -EBUSY ? -EAGAIN : ret; + } + + end = jiffies + msecs_to_jiffies(timeout); /* - * A timeout of less than 0 means to wait forever. + * Search with the task running, then sleep until a new message is queued or the time + * is up. seq is read before the search, so a message queued in between ends the sleep + * at once. While another task holds the lock, try again after a short sleep. */ - if (timeout < 0) { - wait_event(mei->message_queue, ipts_mei_search(mei, code, rsp) == 0); - return 0; - } + do { + seq = READ_ONCE(mei->seq); + /* Read the sequence before searching for a message. */ + smp_rmb(); - ret = wait_event_timeout(mei->message_queue, ipts_mei_search(mei, code, rsp) == 0, - msecs_to_jiffies(timeout)); + ret = ipts_mei_search(mei, code, rsp); + if (ret != -EAGAIN && ret != -EBUSY) + return ret; - if (ret > 0) - return 0; + left = (long)(end - jiffies); + if (left <= 0) + break; + + if (ret == -EBUSY) + usleep_range(IPTS_MEI_LOCK_POLL_US, 2 * IPTS_MEI_LOCK_POLL_US); + else + wait_event_timeout(mei->message_queue, READ_ONCE(mei->seq) != seq, left); + } while (left > 0); return -EAGAIN; } int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length) { - int ret = 0; + ssize_t ret = 0; if (!mei) return -EFAULT; @@ -158,9 +251,11 @@ int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length) if (!data) return -EFAULT; - do { - ret = mei_cldev_send(mei->cldev, (u8 *)data, length); - } while (ret == -EINTR); + /* + * Bounded: a send that is not acknowledged in time fails. An interrupted send is not + * retried, because the message is already queued and would go out twice. + */ + ret = mei_cldev_send_timeout(mei->cldev, (u8 *)data, length, IPTS_MEI_SEND_TIMEOUT_MS); if (ret < 0) return ret; @@ -168,6 +263,77 @@ int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length) return 0; } +void ipts_mei_free_messages(struct ipts_mei *mei) +{ + struct ipts_mei_message *entry = NULL; + struct ipts_mei_message *tmp = NULL; + + if (!mei) + return; + + /* + * Only called when the context is released, so every holder of the lock dropped its + * reference and the lock is free, unless its holder died with it: then the messages are + * leaked rather than freed under it. The raw lock is taken, so no reference is taken on + * the context being released. + */ + if (!down_write_trylock(&mei->message_lock)) + return; + + list_for_each_entry_safe(entry, tmp, &mei->messages, list) { + list_del(&entry->list); + kfree(entry); + } + + up_write(&mei->message_lock); +} + +size_t ipts_mei_flush(struct ipts_mei *mei) +{ + size_t count = 0; + struct ipts_mei_message *entry = NULL; + struct ipts_mei_message *tmp = NULL; + + if (!mei) + return 0; + + if (!ipts_mei_lock_timeout(mei, IPTS_MEI_LOCK_TIMEOUT_MS)) + return 0; + + list_for_each_entry_safe(entry, tmp, &mei->messages, list) { + list_del(&entry->list); + kfree(entry); + count++; + } + + ipts_mei_unlock(mei); + + return count; +} + +int ipts_mei_reconnect(struct ipts_mei *mei) +{ + int ret = 0; + + if (!mei) + return -EFAULT; + + if (!mei->cldev) + return -EFAULT; + + /* + * This also unregisters the receive callback, and fails only if the client was already + * gone. Try to connect anyway. + */ + mei_cldev_disable(mei->cldev); + + ret = mei_cldev_enable(mei->cldev); + if (ret) + return ret; + + return mei_cldev_register_rx_cb(mei->cldev, ipts_mei_incoming); +} + int ipts_mei_init(struct ipts_mei *mei, struct mei_cl_device *cldev) { if (!mei) @@ -177,6 +343,7 @@ int ipts_mei_init(struct ipts_mei *mei, struct mei_cl_device *cldev) return -EFAULT; mei->cldev = cldev; + mei->seq = 0; INIT_LIST_HEAD(&mei->messages); init_waitqueue_head(&mei->message_queue); diff --git a/drivers/hid/ipts/mei.h b/drivers/hid/ipts/mei.h index 973bade6b0fdd..9ebf15dc50a42 100644 --- a/drivers/hid/ipts/mei.h +++ b/drivers/hid/ipts/mei.h @@ -28,8 +28,27 @@ struct ipts_mei { wait_queue_head_t message_queue; struct rw_semaphore message_lock; + + /* + * Bumped under message_lock whenever a message is queued, so that waiters can sleep + * without taking the lock inside the wait condition. + */ + unsigned long seq; }; +/* + * Upper bounds for taking the message lock to queue a response, and for one send. While + * the lock is busy, it is tried again every IPTS_MEI_LOCK_POLL_US. + */ +#define IPTS_MEI_LOCK_TIMEOUT_MS 1000 +#define IPTS_MEI_LOCK_POLL_US 200 +#define IPTS_MEI_SEND_TIMEOUT_MS 2000 + +/* + * How long the receive callback waits for one more response before it returns. + */ +#define IPTS_MEI_RECV_MORE_MS 1 + /** * ipts_mei_recv() - Receive data from a MEI device. * @mei: The IPTS MEI device context. @@ -37,7 +56,7 @@ struct ipts_mei { * @rsp: The address that the received data will be copied to. * @timeout: How many milliseconds the function will wait at most. * - * A negative timeout means to wait forever. + * A timeout of 0 means to check once and return. * * Returns: 0 on success, <0 on error, -EAGAIN if no response has been received. */ @@ -54,6 +73,20 @@ int ipts_mei_recv(struct ipts_mei *mei, enum ipts_command_code code, struct ipts */ int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length); +/* + * The longest ipts_mei_reconnect() takes: the MEI core waits for the disconnect and for the + * connect up to its client connect timeout each, which is 30 seconds for slow firmware. + */ +#define IPTS_MEI_RECONNECT_TIMEOUT_MS (2 * 30000) + +/** + * ipts_mei_reconnect() - Disconnects from the ME client and connects again. + * @mei: The MEI device context. + * + * Return: 0 on success, <0 on error. + */ +int ipts_mei_reconnect(struct ipts_mei *mei); + /** * ipts_mei_init() - Initialize the MEI device context. * @mei: The MEI device context to initialize. @@ -63,4 +96,20 @@ int ipts_mei_send(struct ipts_mei *mei, void *data, size_t length); */ int ipts_mei_init(struct ipts_mei *mei, struct mei_cl_device *cldev); +/** + * ipts_mei_free_messages() - Free every message still queued. + * @mei: The MEI device context. + * + * Called from the context release function, once no user of the context is left. + */ +void ipts_mei_free_messages(struct ipts_mei *mei); + +/** + * ipts_mei_flush() - Drops all received messages that have not been consumed. + * @mei: The IPTS MEI device context. + * + * Returns: The number of dropped messages. + */ +size_t ipts_mei_flush(struct ipts_mei *mei); + #endif /* IPTS_MEI_H */ diff --git a/drivers/hid/ipts/receiver.c b/drivers/hid/ipts/receiver.c index 977724c728c3e..ef76737b8157a 100644 --- a/drivers/hid/ipts/receiver.c +++ b/drivers/hid/ipts/receiver.c @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -33,6 +34,21 @@ static u32 ipts_receiver_current_doorbell(struct ipts_context *ipts) return *doorbell; } +/* + * Only the last IPTS_BUFFERS buffers can hold new data, so never walk further back than that, + * whatever value the doorbell has. Returns the first buffer to look at. + */ +static u32 ipts_receiver_first_new(u32 doorbell, u32 lastdb) +{ + if ((s32)(doorbell - lastdb) < 0) + return doorbell; + + if (doorbell - lastdb > IPTS_BUFFERS) + return doorbell - IPTS_BUFFERS; + + return lastdb; +} + static void ipts_receiver_backoff(time64_t last, u32 n) { /* @@ -47,6 +63,62 @@ static void ipts_receiver_backoff(time64_t last, u32 n) msleep(200); } +/* + * End of a receiver loop, after QUIESCE_IO was sent: collect the last READY_FOR_DATA reply, + * then wait for the QUIESCE_IO confirmation, even if that reply was lost. Starting the + * device again before it has stopped can leave its firmware unresponsive until the next + * boot. + * + * Returns: 0 only if the device confirmed the stop. Otherwise the device may still write to + * its buffers, and the caller must not free them. + */ +static int ipts_receiver_finish(struct ipts_context *ipts) +{ + int ret = 0; + unsigned long end = 0; + + ret = ipts_control_wait_data(ipts, true); + if (ret && ret != -EAGAIN) + dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); + + end = jiffies + msecs_to_jiffies(IPTS_RECEIVER_STOP_CONFIRM_MS); + + do { + ret = ipts_control_wait_flush(ipts); + } while (ret == -EAGAIN && time_before(jiffies, end)); + + if (ret) { + dev_err(ipts->dev, "Device did not confirm the stop: %d\n", ret); + return ret == -EAGAIN ? -ETIMEDOUT : ret; + } + + return 0; +} + +/* + * In poll mode, the device confirms QUIESCE_IO only after every buffer it filled was given + * back. Give back the ones the loop did not get to, without passing their data on: HID input + * is already disabled. The time is bounded, and the first failed feedback ends it. + */ +static void ipts_receiver_return_buffers(struct ipts_context *ipts, u32 lastdb) +{ + int ret = 0; + u32 doorbell = ipts_receiver_current_doorbell(ipts); + unsigned long end = jiffies + msecs_to_jiffies(IPTS_RECEIVER_STOP_CONFIRM_MS); + + lastdb = ipts_receiver_first_new(doorbell, lastdb); + + while (lastdb != doorbell && time_before(jiffies, end)) { + ret = ipts_control_refill_buffer(ipts, lastdb % IPTS_BUFFERS); + if (ret) { + dev_err(ipts->dev, "Failed to send feedback: %d\n", ret); + return; + } + + lastdb++; + } +} + static int ipts_receiver_event_loop(struct ipts_thread *thread) { int ret = 0; @@ -68,7 +140,7 @@ static int ipts_receiver_event_loop(struct ipts_thread *thread) while (!ipts_thread_should_stop(thread)) { int i = 0; - for (i = 0; i < IPTS_BUFFERS; i++) { + for (i = 0; i < IPTS_BUFFERS && !ipts_thread_should_stop(thread); i++) { ret = ipts_control_wait_data(ipts, false); if (ret == -EAGAIN) break; @@ -105,27 +177,7 @@ static int ipts_receiver_event_loop(struct ipts_thread *thread) return ret; } - ret = ipts_control_wait_data(ipts, true); - if (ret) { - dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); - - if (ret != -EAGAIN) - return ret; - else - return 0; - } - - ret = ipts_control_wait_flush(ipts); - if (ret) { - dev_err(ipts->dev, "Failed to wait for flush: %d\n", ret); - - if (ret != -EAGAIN) - return ret; - else - return 0; - } - - return 0; + return ipts_receiver_finish(ipts); } static int ipts_receiver_poll_loop(struct ipts_thread *thread) @@ -149,23 +201,16 @@ static int ipts_receiver_poll_loop(struct ipts_thread *thread) dev_info(ipts->dev, "IPTS running in poll mode\n"); - while (true) { - if (ipts_thread_should_stop(thread)) { - ret = ipts_control_request_flush(ipts); - if (ret) { - dev_err(ipts->dev, "Failed to request flush: %d\n", ret); - return ret; - } - } - + while (!ipts_thread_should_stop(thread)) { doorbell = ipts_receiver_current_doorbell(ipts); + lastdb = ipts_receiver_first_new(doorbell, lastdb); /* * After filling up one of the data buffers, IPTS will increment * the doorbell. The value of the doorbell stands for the *next* * buffer that IPTS is going to fill. */ - while (lastdb != doorbell) { + while (lastdb != doorbell && !ipts_thread_should_stop(thread)) { buffer = lastdb % IPTS_BUFFERS; ret = ipts_hid_input_data(ipts, buffer); @@ -186,27 +231,15 @@ static int ipts_receiver_poll_loop(struct ipts_thread *thread) ipts_receiver_backoff(last, 5); } - ret = ipts_control_wait_data(ipts, true); + ret = ipts_control_request_flush(ipts); if (ret) { - dev_err(ipts->dev, "Failed to wait for data: %d\n", ret); - - if (ret != -EAGAIN) - return ret; - else - return 0; + dev_err(ipts->dev, "Failed to request flush: %d\n", ret); + return ret; } - ret = ipts_control_wait_flush(ipts); - if (ret) { - dev_err(ipts->dev, "Failed to wait for flush: %d\n", ret); - - if (ret != -EAGAIN) - return ret; - else - return 0; - } + ipts_receiver_return_buffers(ipts, lastdb); - return 0; + return ipts_receiver_finish(ipts); } int ipts_receiver_start(struct ipts_context *ipts) @@ -231,6 +264,11 @@ int ipts_receiver_start(struct ipts_context *ipts) return ret; } + /* + * The receiver thread uses the context until it stops: hold a reference for its whole run. + */ + ipts_context_get(ipts); + return 0; } @@ -241,7 +279,29 @@ int ipts_receiver_stop(struct ipts_context *ipts) if (!ipts) return -EFAULT; - ret = ipts_thread_stop(&ipts->receiver_loop); + /* + * A start that failed early never started the thread: there is no reference to drop, + * and the exit code of an earlier thread must not be reported again. + */ + if (!ipts->receiver_loop.thread) { + ipts->receiver_loop.exit_code = 0; + return 0; + } + + ret = ipts_thread_stop(&ipts->receiver_loop, IPTS_RECEIVER_STOP_TIMEOUT_MS); + if (ret == -ETIMEDOUT) { + /* + * Still running: the thread keeps its reference, and everything it uses. + */ + dev_err(ipts->dev, "Failed to stop receiver loop: %d\n", ret); + return ret; + } + + /* + * The thread is gone (it returned or died), so drop its reference. + */ + ipts_context_put(ipts); + if (ret) { dev_err(ipts->dev, "Failed to stop receiver loop: %d\n", ret); return ret; diff --git a/drivers/hid/ipts/receiver.h b/drivers/hid/ipts/receiver.h index 3de7da62d40c1..30b60aaa45e0c 100644 --- a/drivers/hid/ipts/receiver.h +++ b/drivers/hid/ipts/receiver.h @@ -8,7 +8,31 @@ #ifndef IPTS_RECEIVER_H #define IPTS_RECEIVER_H +#include "cmd.h" #include "context.h" +#include "mei.h" + +/* + * How long the end of a stop waits for the device to confirm QUIESCE_IO. + */ +#define IPTS_RECEIVER_STOP_CONFIRM_MS 3000 + +/* + * The longest one command (a send and its reply) can take. + */ +#define IPTS_RECEIVER_CMD_MS (IPTS_MEI_SEND_TIMEOUT_MS + IPTS_CMD_DEFAULT_TIMEOUT) + +/* + * How long a stop waits for the receiver thread to return: the sum of the bounds of what the + * thread can still do once it is asked to stop. It finishes the buffer it is handling (a + * command and a send), sends QUIESCE_IO, gives back buffers in poll mode (the confirmation + * time plus one command), collects the last READY_FOR_DATA reply, and waits for the + * confirmation (that time plus one reply). One second more covers the back-off sleep and + * scheduling. + */ +#define IPTS_RECEIVER_STOP_TIMEOUT_MS \ + (2 * IPTS_RECEIVER_CMD_MS + 2 * IPTS_MEI_SEND_TIMEOUT_MS + \ + 2 * IPTS_RECEIVER_STOP_CONFIRM_MS + 2 * IPTS_CMD_DEFAULT_TIMEOUT + 1000) int ipts_receiver_start(struct ipts_context *ipts); int ipts_receiver_stop(struct ipts_context *ipts); diff --git a/drivers/hid/ipts/thread.c b/drivers/hid/ipts/thread.c index 355e92bea26f8..81d13a8944d17 100644 --- a/drivers/hid/ipts/thread.c +++ b/drivers/hid/ipts/thread.c @@ -8,7 +8,11 @@ #include #include #include +#include #include +#include +#include +#include #include "thread.h" @@ -40,6 +44,8 @@ static int ipts_thread_runner(void *data) int ipts_thread_start(struct ipts_thread *thread, int (*threadfn)(struct ipts_thread *thread), void *data, const char *name) { + struct task_struct *task = NULL; + if (!thread) return -EFAULT; @@ -49,21 +55,40 @@ int ipts_thread_start(struct ipts_thread *thread, int (*threadfn)(struct ipts_th init_completion(&thread->done); thread->data = data; + thread->exit_code = 0; thread->should_stop = false; thread->threadfn = threadfn; - thread->thread = kthread_run(ipts_thread_runner, thread, name); - return PTR_ERR_OR_ZERO(thread->thread); + task = kthread_create(ipts_thread_runner, thread, "%s", name); + if (IS_ERR(task)) { + thread->thread = NULL; + thread->threadfn = NULL; + thread->data = NULL; + return PTR_ERR(task); + } + + /* + * Keep the task_struct until ipts_thread_stop() is done with it, even if the + * thread exits on its own (or dies) before that. + */ + get_task_struct(task); + thread->thread = task; + wake_up_process(task); + + return 0; } -int ipts_thread_stop(struct ipts_thread *thread) +int ipts_thread_stop(struct ipts_thread *thread, unsigned int timeout_ms) { int ret = 0; + unsigned long end = 0; + struct task_struct *task = NULL; if (!thread) return -EFAULT; - if (!thread->thread) + task = thread->thread; + if (!task) return 0; WRITE_ONCE(thread->should_stop, true); @@ -73,8 +98,29 @@ int ipts_thread_stop(struct ipts_thread *thread) */ wmb(); - wait_for_completion(&thread->done); - ret = kthread_stop(thread->thread); + end = jiffies + msecs_to_jiffies(timeout_ms); + + while (!wait_for_completion_timeout(&thread->done, + msecs_to_jiffies(IPTS_THREAD_STOP_POLL_MS))) { + /* + * A thread that died in an oops is unwinding through do_exit() and will + * never complete. It runs no driver code anymore, so it counts as stopped. + * kthread_stop() could wait for its exit forever, so it is not called. + */ + if ((task->flags & PF_EXITING) && !completion_done(&thread->done)) { + pr_err("ipts: thread %s died without finishing\n", task->comm); + ret = -EOWNERDEAD; + goto out; + } + + if (time_after(jiffies, end)) + return -ETIMEDOUT; + } + + thread->exit_code = kthread_stop(task); + +out: + put_task_struct(task); thread->thread = NULL; thread->data = NULL; diff --git a/drivers/hid/ipts/thread.h b/drivers/hid/ipts/thread.h index 1f966b8b32c45..1e4f8389db7d9 100644 --- a/drivers/hid/ipts/thread.h +++ b/drivers/hid/ipts/thread.h @@ -24,6 +24,11 @@ struct ipts_thread { bool should_stop; struct completion done; + /* + * Return value of the thread function, valid after ipts_thread_stop() returned 0. + */ + int exit_code; + void *data; int (*threadfn)(struct ipts_thread *thread); }; @@ -48,12 +53,24 @@ bool ipts_thread_should_stop(struct ipts_thread *thread); int ipts_thread_start(struct ipts_thread *thread, int (*threadfn)(struct ipts_thread *thread), void *data, const char name[]); +/* + * How often ipts_thread_stop() checks whether the thread died while it waits. + */ +#define IPTS_THREAD_STOP_POLL_MS 100 + /** * ipts_thread_stop() - Asks the thread to terminate and waits until it has finished. * @thread: The thread that should stop. + * @timeout_ms: How long to wait for the thread function to return. + * + * The wait is bounded. A thread that died (oops) without finishing runs no driver code + * anymore and is treated as stopped. A thread that is still running after the timeout is + * left alone, and nothing it uses may be freed. * - * Returns: The return value of the thread function. + * Returns: 0 if the thread function returned (its return value is in thread->exit_code), + * -EOWNERDEAD if the thread died without returning, -ETIMEDOUT if it is still running, + * <0 on other errors. */ -int ipts_thread_stop(struct ipts_thread *thread); +int ipts_thread_stop(struct ipts_thread *thread, unsigned int timeout_ms); #endif /* IPTS_THREAD_H */