Skip to contentSkip to conversation

misc: fastrpc: fixes for v7.4

PATCH New [email protected] 1 participant 7 messages Nov 27

Subsystems (3)
lore
Share & tools
lore

[email protected]

author maintainer
#0 lore raw

cover misc: fastrpc: fixes for v7.4

From: Srinivas Kandagatla <[email protected]>

Hi Greg,

Here are few fastrpc fixes for v7.4, Could you please queue these for v7.4.

Patches include
- Fix NULL rpdev dereference and init ordering race in rpmsg probe
- Drop dead context drain and fix DSP-response reference leak on channel removal
- Fix context leak and hang on signal-interrupted invoke
- Avoid duplicate DMA mappings in fastrpc_create_maps()

Thanks,
Srini

Anandu Krishnan E (3):
misc: fastrpc: remove dead context drain in fastrpc_user_free()
misc: fastrpc: drop the DSP-response reference on channel removal
misc: fastrpc: fix context leak and hang on signal-interrupted invoke

Jianping Li (1):
misc: fastrpc: avoid duplicate DMA mappings in fastrpc_create_maps()

Vinayak Katoch (2):
misc: fastrpc: fix NULL rpdev dereference when session alloc fails
misc: fastrpc: fix init ordering race in rpmsg probe

 drivers/misc/fastrpc.c | 335 +++++++++++++++++++++++++++++------------
 1 file changed, 242 insertions(+), 93 deletions(-)
Signature · 1 line
2.53.0
author maintainer
#1 lore raw

PATCH 1/6 misc: fastrpc: fix NULL rpdev dereference when session alloc fails

From: Vinayak Katoch <[email protected]>

When a fastrpc client process dies abnormally without closing its file descriptor, fastrpc_device_release() is never called and the compute-cb session slot is never freed. The abnormal client death on the DSP side triggers a glink channel teardown which propagates up through the rpmsg bus and calls fastrpc_rpmsg_remove().

fastrpc_rpmsg_remove() nulls cctx->rpdev before calling misc_deregister(). If a concurrent open() enters fastrpc_device_open() in this window and fastrpc_session_alloc() returns NULL (sessions exhausted by the leaked slot), the error path dereferences cctx->rpdev->dev causing a NULL pointer dereference:

  Unable to handle kernel NULL pointer dereference at virtual address 0000000000000000
  pc : fastrpc_device_open+0x1b8/0x258 [fastrpc]
  Call trace:
   fastrpc_device_open+0x1b8/0x258 [fastrpc] (P)
   misc_open+0xd8/0x1a0

Fix by moving misc_deregister() before rpdev = NULL. misc_open() and misc_deregister() both take misc_mtx, so misc_deregister() will either block until fastrpc_device_open() completes or prevent new opens from entering it entirely.

Fixes 7c11df42d0c7 ("misc: fastrpc: Fix device_open when no session is available")
Fixes 46248400d81e ("misc: fastrpc: reject new invocations during device removal")
---
 drivers/misc/fastrpc.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/misc/fastrpc.c +6 -6
index af18ff1992ee..4f1c6ff8054c 100644
@@ -2675,6 +2675,12 @@ static void fastrpc_rpmsg_remove(struct rpmsg_device *rpdev)
 	struct fastrpc_user *user;
 	unsigned long flags;
 
+	if (cctx->fdevice)
+		misc_deregister(&cctx->fdevice->miscdev);
+
+	if (cctx->secure_fdevice)
+		misc_deregister(&cctx->secure_fdevice->miscdev);
+
 	/* No invocations past this point */
 	spin_lock_irqsave(&cctx->lock, flags);
 	cctx->rpdev = NULL;
@@ -2682,12 +2688,6 @@ static void fastrpc_rpmsg_remove(struct rpmsg_device *rpdev)
 		fastrpc_notify_users(user);
 	spin_unlock_irqrestore(&cctx->lock, flags);
 
-	if (cctx->fdevice)
-		misc_deregister(&cctx->fdevice->miscdev);
-
-	if (cctx->secure_fdevice)
-		misc_deregister(&cctx->secure_fdevice->miscdev);
-
 	list_for_each_entry_safe(buf, b, &cctx->invoke_interrupted_mmaps, node)
 		list_del(&buf->node);
 
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

PATCH 2/6 misc: fastrpc: fix init ordering race in rpmsg probe

In reply to [email protected]

From: Vinayak Katoch <[email protected]>

fastrpc_device_register() calls misc_register() which makes the device node visible to userspace. However, kref_init(), spin_lock_init(), INIT_LIST_HEAD(), dev_set_drvdata() and of_platform_populate() were all called after the switch/misc_register block, leaving a window where userspace can open the device and call fastrpc_device_open() on a partially initialised channel context.

On a concurrent open(), fastrpc_channel_ctx_get() calls kref_get() on a kzalloc-zeroed, never kref_init()'d refcount of 0, triggering:

refcount_t: addition on 0; use-after-free.

  Call trace:
   refcount_warn_saturate+0x120/0x148 (P)
   fastrpc_device_open+0x204/0x258 [fastrpc]
   misc_open+0xd8/0x1a0

Additionally, of_platform_populate() not having run means sesscount is still 0, so fastrpc_session_alloc() returns NULL and fastrpc_device_open() hits the error path which calls fastrpc_channel_ctx_put() on the already-bogus refcount. This triggers the free callback, kfree()-ing the channel context. A subsequent IRQ-path fastrpc_rpmsg_callback() then dereferences the freed spinlock:

  Unable to handle kernel paging request at virtual address ffffcd5841510ca0
  Internal error: Oops: 0000000096000047 [#1] SMP
  Call trace:
   queued_spin_lock_slowpath+0x414/0x5e0 (P)
   _raw_spin_lock_irqsave+0x74/0x90
   fastrpc_rpmsg_callback+0x4c/0xf0 [fastrpc]
   qcom_glink_native_rx+0x6c4/0xf10
   qcom_glink_smem_intr+0x1c/0x38 [qcom_glink_smem]
  Kernel panic - not syncing: Oops: Fatal exception in interrupt

Fix by moving all channel context initialisation (kref_init, spin_lock_init, INIT_LIST_HEAD, idr_init, dev_set_drvdata) and of_platform_populate() before fastrpc_device_register(), ensuring the struct is fully ready before the device node is visible to userspace.

Add err_depopulate label in the error path since of_platform_populate() now runs before misc_register(); a fastrpc_device_register() failure must call of_platform_depopulate() to clean up the compute-cb children.

On CDSP/GDSP the secure node is registered before the non-secure one, so an application may already have opened the first node and hold a channel context reference when the second registration fails. Freeing the context with kfree() there would leave that user with a dangling pointer. Handle it like fastrpc_rpmsg_remove(): after the nodes are deregistered, clear rpdev, wake pending invocations with -EPIPE and drop only the probe reference with fastrpc_channel_ctx_put(), so the last holder frees the context. Move fastrpc_notify_users() above probe so it can be used there.

Fixes 965602eabb57 ("misc: fastrpc: separate fastrpc device from channel context")
---
 drivers/misc/fastrpc.c | 82 +++++++++++++++++++++++++-----------------
 1 file changed, 50 insertions(+), 32 deletions(-)
drivers/misc/fastrpc.c +50 -32
index 4f1c6ff8054c..70b5642f5fbc 100644
@@ -2542,6 +2542,18 @@ static int fastrpc_init_reserved_mem(struct fastrpc_channel_ctx *cctx,
 				  cctx->vmperms, cctx->vmcount);
 }
 
+static void fastrpc_notify_users(struct fastrpc_user *user)
+{
+	struct fastrpc_invoke_ctx *ctx;
+
+	spin_lock(&user->lock);
+	list_for_each_entry(ctx, &user->pending, node) {
+		ctx->retval = -EPIPE;
+		complete(&ctx->work);
+	}
+	spin_unlock(&user->lock);
+}
+
 static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 {
 	struct device *rdev = &rpdev->dev;
@@ -2551,6 +2563,8 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 	bool secure_dsp;
 	unsigned int vmids[FASTRPC_MAX_VMIDS];
 	const struct fastrpc_soc_data *soc_data;
+	struct fastrpc_user *user;
+	unsigned long flags;
 
 	soc_data = device_get_match_data(rdev);
 
@@ -2599,6 +2613,23 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 	data->poll_mode_supported = soc_data->poll_mode_supported ||
 		of_machine_get_match(fastrpc_poll_supported_machines);
 
+	kref_init(&data->refcount);
+	atomic_set(&data->ctx_seq, 0);
+
+	rdev->dma_mask = &data->dma_mask;
+	dma_set_mask_and_coherent(rdev, DMA_BIT_MASK(32));
+	INIT_LIST_HEAD(&data->users);
+	INIT_LIST_HEAD(&data->invoke_interrupted_mmaps);
+	spin_lock_init(&data->lock);
+	idr_init(&data->ctx_idr);
+	data->domain_id = domain_id;
+	data->rpdev = rpdev;
+	dev_set_drvdata(&rpdev->dev, data);
+
+	err = of_platform_populate(rdev->of_node, NULL, NULL, rdev);
+	if (err)
+		goto err_free_data;
+
 	switch (domain_id) {
 	case ADSP_DOMAIN_ID:
 	case MDSP_DOMAIN_ID:
@@ -2607,7 +2638,7 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 		data->unsigned_support = false;
 		err = fastrpc_device_register(rdev, data, secure_dsp, domain);
 		if (err)
-			goto err_free_data;
+			goto err_depopulate;
 		break;
 	case CDSP_DOMAIN_ID:
 	case GDSP_DOMAIN_ID:
@@ -2615,7 +2646,7 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 		/* Create both device nodes so that we can allow both Signed and Unsigned PD */
 		err = fastrpc_device_register(rdev, data, true, domain);
 		if (err)
-			goto err_free_data;
+			goto err_depopulate;
 
 		err = fastrpc_device_register(rdev, data, false, domain);
 		if (err)
@@ -2623,26 +2654,9 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 		break;
 	default:
 		err = -EINVAL;
-		goto err_free_data;
+		goto err_depopulate;
 	}
 
-	kref_init(&data->refcount);
-	atomic_set(&data->ctx_seq, 0);
-
-	rdev->dma_mask = &data->dma_mask;
-	dma_set_mask_and_coherent(rdev, DMA_BIT_MASK(32));
-	INIT_LIST_HEAD(&data->users);
-	INIT_LIST_HEAD(&data->invoke_interrupted_mmaps);
-	spin_lock_init(&data->lock);
-	idr_init(&data->ctx_idr);
-	data->domain_id = domain_id;
-	data->rpdev = rpdev;
-	dev_set_drvdata(&rpdev->dev, data);
-
-	err = of_platform_populate(rdev->of_node, NULL, NULL, rdev);
-	if (err)
-		goto err_deregister_fdev;
-
 	return 0;
 
 err_deregister_fdev:
@@ -2651,23 +2665,27 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 	if (data->secure_fdevice)
 		misc_deregister(&data->secure_fdevice->miscdev);
 
+err_depopulate:
+	/*
+	 * A registered device node may already have been opened, so a user
+	 * can hold a cctx reference. Drop only our reference instead of
+	 * freeing the context directly.
+	 */
+	spin_lock_irqsave(&data->lock, flags);
+	data->rpdev = NULL;
+	list_for_each_entry(user, &data->users, user)
+		fastrpc_notify_users(user);
+	spin_unlock_irqrestore(&data->lock, flags);
+
+	of_platform_depopulate(rdev);
+	fastrpc_channel_ctx_put(data);
+	return err;
+
 err_free_data:
 	kfree(data);
 	return err;
 }
 
-static void fastrpc_notify_users(struct fastrpc_user *user)
-{
-	struct fastrpc_invoke_ctx *ctx;
-
-	spin_lock(&user->lock);
-	list_for_each_entry(ctx, &user->pending, node) {
-		ctx->retval = -EPIPE;
-		complete(&ctx->work);
-	}
-	spin_unlock(&user->lock);
-}
-
 static void fastrpc_rpmsg_remove(struct rpmsg_device *rpdev)
 {
 	struct fastrpc_channel_ctx *cctx = dev_get_drvdata(&rpdev->dev);
Signature · 1 line
2.53.0
author maintainer
#3 lore raw

PATCH 3/6 misc: fastrpc: remove dead context drain in fastrpc_user_free()

In reply to [email protected]

From: Anandu Krishnan E <[email protected]>

fastrpc_context_alloc() takes a reference on fl via fastrpc_user_get() for the lifetime of every context, and fastrpc_context_free() always unlinks the context from fl->pending before releasing that reference with fastrpc_user_put(). This means fl->refcount cannot reach zero - and fastrpc_user_free() cannot run - while any context is still linked on fl->pending: whichever context's release happens to be the one that drops the last reference has, by construction, already removed itself from the list a few lines earlier in the very same call.

The list_for_each_entry_safe() loop over fl->pending in fastrpc_user_free() can therefore never find anything to iterate. It has been unreachable since fl's own lifetime was switched from file-close-synchronous teardown to kref-counted teardown; it was never updated to reflect that the list it walks is now guaranteed empty by the time this callback can run. Remove it.

Fixes e85eb5feca8e2 ("misc: fastrpc: fix use-after-free of fastrpc_user in workqueue context")
---
 drivers/misc/fastrpc.c | 6 ------
 1 file changed, 6 deletions(-)
drivers/misc/fastrpc.c +0 -6
index 70b5642f5fbc..60c9d1d0834b 100644
@@ -559,17 +559,11 @@ static void fastrpc_context_put(struct fastrpc_invoke_ctx *ctx);
 static void fastrpc_user_free(struct kref *ref)
 {
 	struct fastrpc_user *fl = container_of(ref, struct fastrpc_user, refcount);
-	struct fastrpc_invoke_ctx *ctx, *n;
 	struct fastrpc_map *map, *m;
 	struct fastrpc_buf *buf, *b;
 
 	fastrpc_buf_free(fl->init_mem);
 
-	list_for_each_entry_safe(ctx, n, &fl->pending, node) {
-		list_del(&ctx->node);
-		fastrpc_context_put(ctx);
-	}
-
 	list_for_each_entry_safe(map, m, &fl->maps, node)
 		fastrpc_map_put(map);
 
Signature · 1 line
2.53.0
author maintainer
#4 lore raw

PATCH 4/6 misc: fastrpc: drop the DSP-response reference on channel removal

In reply to [email protected]

From: Anandu Krishnan E <[email protected]>

fastrpc_invoke_send() takes a second reference on the invoke context before calling rpmsg_send(), to be dropped later by whichever side consumes the eventual DSP response: fastrpc_rpmsg_callback() for a real reply, via schedule_work(&ctx->put_work).

fastrpc_notify_users(), called from fastrpc_rpmsg_remove() when the rpmsg channel goes away (e.g. on subsystem restart), only completes each pending context with -EPIPE so its waiter can return - it never schedules the matching put. Since the channel is gone, no response will ever arrive to trigger it through the normal callback path either. Every context that was genuinely in flight (successfully sent, not yet answered) at the time of an SSR therefore leaks that second reference, and with it the context, its DMA maps, and the reference it holds on fl and cctx.

Schedule the same put_work that a real response would have triggered, exactly as fastrpc_rpmsg_callback() does. rpmsg guarantees .callback and .remove are mutually exclusive for a given device, so there is no concurrent real response that could race with this.

Fixes c68cfb718c8f ("misc: fastrpc: Add support for context Invoke method")
---
 drivers/misc/fastrpc.c | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/misc/fastrpc.c +7 -0
index 60c9d1d0834b..7820c384cde6 100644
@@ -2544,6 +2544,13 @@ static void fastrpc_notify_users(struct fastrpc_user *user)
 	list_for_each_entry(ctx, &user->pending, node) {
 		ctx->retval = -EPIPE;
 		complete(&ctx->work);
+		/*
+		 * fastrpc_invoke_send() took a second reference for the
+		 * DSP response that will now never arrive since the
+		 * channel is gone; schedule the matching put the same
+		 * way a real response would via fastrpc_rpmsg_callback().
+		 */
+		schedule_work(&ctx->put_work);
 	}
 	spin_unlock(&user->lock);
 }
Signature · 1 line
2.53.0
author maintainer
#5 lore raw

PATCH 5/6 misc: fastrpc: fix context leak and hang on signal-interrupted invoke

In reply to [email protected]

From: Anandu Krishnan E <[email protected]>

fastrpc invokes work by sending an RPC message to the DSP and blocking in wait_for_completion_interruptible() until the DSP responds. If a signal arrives during this wait, the syscall returns -ERESTARTSYS and the invoke context, which holds the in-flight DMA buffers and completion state, is left stranded in fl->pending.

On the next syscall attempt (either auto-restarted by the kernel via SA_RESTART or manually retried by user-space after EINTR), a fresh context is allocated and the RPC message is re-sent to the DSP. This has two consequences:

- The original context leaks in fl->pending until the file is closed.
- The DSP receives a duplicate invocation. If the DSP was mid-way through processing the first request and had issued a reverse RPC call back to the host, the retry sends a new forward request instead of the expected reverse-RPC response. The DSP thread waiting for that response is never woken, causing a hang.

Fix this by saving the interrupted context to a new fl->interrupted list on -ERESTARTSYS, instead of freeing it or leaving it on fl->pending. The context keeps the same reference it already held; only list membership changes, so the refcount stays symmetric no matter how many times a context is interrupted and retried. When the same thread retries with a matching handle and sc, the context is pulled back onto fl->pending and the call jumps straight to the wait, skipping context allocation and message re-send. A mismatched handle/sc falls through to a normal fresh allocation, so a thread that issues a different call after an interrupted one is never wedged.

A context on fl->interrupted can be matched and reclaimed by fastrpc_context_restore_interrupted() on a retry while a concurrent kref_put() from an unrelated drain (SSR, fd close, or a delayed DSP response) has already dropped its refcount to zero and is waiting on fl->lock to unlink it in fastrpc_context_free(). Without a check, the retry can win that lock race, hand back a context already committed to being freed, and use it after the other side frees it. kref_get_unless_zero() closes the window: it fails if the refcount is already zero, so the retry falls through to a fresh allocation instead of resurrecting a dying context.

Distinguish an interruption of the send itself (rpmsg_send() returning -ERESTARTSYS before the message ever reaches the DSP) from an interruption of the wait that follows a successful send: only the latter is safe to park and resume without resending, since nothing is actually in flight in the former case. Rather than track this with an extra flag, give the two failure sites their own cleanup instead of funnelling both into the same bail: label.

ctx->args is now owned by the context (copied at alloc time) and freed exactly once by fastrpc_context_free(), rather than aliasing the caller's array, which could otherwise be freed or reused by the time a parked context is eventually drained.

A context parked on fl->interrupted is reachable from a resumed retry, process exit and SSR all at once. fastrpc_context_free() now removes it from whichever list it is on before releasing its resources, using list_del_init() (plain list_del() poisons the node, which would otherwise break this same check if the context is freed via a race with one of the other drains). Because the DSP response worker (fastrpc_rpmsg_callback()) and the exit/SSR/fd-close paths can all end up scheduling the same ctx->put_work for a parked context, a put_work_scheduled flag checked and set under fl->lock ensures only one of them actually queues it.

fastrpc_device_release() now also drains fl->interrupted, completing any parked context with -EPIPE and dropping the invoker's reference, so a context stuck there at fd close cannot leak it. It cannot drop the worker reference unconditionally, though: the DSP may still be using that context's buffers if it hasn't answered yet, and freeing them under it would be unsafe. fastrpc_release_current_dsp_process(), already called at the top of fastrpc_device_release(), tells the DSP to tear down the whole process; if that succeeds, the DSP is known to be done with everything for this process, so the worker reference is dropped too. If it doesn't succeed, the context is left exactly where a real response or a future SSR would still find it: still linked on fl->interrupted, and fl is left on cctx->users (the unlink moves from fastrpc_device_release() into fastrpc_user_free(), which only runs once fl truly has no references left) so fastrpc_notify_users() can still walk down to it later.

The same unreachable-orphan problem exists for a timed-out kernel invoke (-ETIMEDOUT, only possible when kernel=true): the bail: path used to unconditionally unlink the context from fl->pending before dropping its reference, even though the DSP may still answer later. Leave it linked on fl->pending in that case instead, so fastrpc_notify_users() can still find and release it if the channel is torn down before that answer arrives.

Remove the obsolete invoke_interrupted_mmaps mechanism from fastrpc_channel_ctx; context resources are now kept alive through the context refcount rather than by migrating mmaps to a channel-level list.

---
 drivers/misc/fastrpc.c | 188 ++++++++++++++++++++++++++++++++---------
 1 file changed, 146 insertions(+), 42 deletions(-)
drivers/misc/fastrpc.c +146 -42
index 7820c384cde6..c8b701395821 100644
@@ -261,6 +261,7 @@ struct fastrpc_invoke_ctx {
 	int pid;
 	int client_id;
 	u32 sc;
+	u32 handle;
 	u64 *fdlist;
 	u32 *crc;
 	/* Poll memory that DSP updates */
@@ -271,6 +272,8 @@ struct fastrpc_invoke_ctx {
 	bool is_work_done;
 	/* process updates poll memory instead of glink response */
 	bool is_polled;
+	/* set once put_work has been scheduled for this ctx, guarded by fl->lock */
+	bool put_work_scheduled;
 	struct kref refcount;
 	struct list_head node; /* list of ctxs */
 	struct completion work;
@@ -320,7 +323,6 @@ struct fastrpc_channel_ctx {
 	u32 dsp_attributes[FASTRPC_MAX_DSP_ATTRIBUTES];
 	struct fastrpc_device *secure_fdevice;
 	struct fastrpc_device *fdevice;
-	struct list_head invoke_interrupted_mmaps;
 	bool secure;
 	bool unsigned_support;
 	bool poll_mode_supported;
@@ -340,6 +342,7 @@ struct fastrpc_user {
 	struct list_head user;
 	struct list_head maps;
 	struct list_head pending;
+	struct list_head interrupted;
 	struct list_head mmaps;
 
 	struct fastrpc_channel_ctx *cctx;
@@ -559,8 +562,15 @@ static void fastrpc_context_put(struct fastrpc_invoke_ctx *ctx);
 static void fastrpc_user_free(struct kref *ref)
 {
 	struct fastrpc_user *fl = container_of(ref, struct fastrpc_user, refcount);
+	struct fastrpc_channel_ctx *cctx = fl->cctx;
 	struct fastrpc_map *map, *m;
 	struct fastrpc_buf *buf, *b;
+	unsigned long flags;
+
+	/* fl stays on cctx->users until this point, so an SSR before fd close can still find it. */
+	spin_lock_irqsave(&cctx->lock, flags);
+	list_del(&fl->user);
+	spin_unlock_irqrestore(&cctx->lock, flags);
 
 	fastrpc_buf_free(fl->init_mem);
 
@@ -572,7 +582,7 @@ static void fastrpc_user_free(struct kref *ref)
 		fastrpc_buf_free(buf);
 	}
 
-	fastrpc_channel_ctx_put(fl->cctx);
+	fastrpc_channel_ctx_put(cctx);
 	mutex_destroy(&fl->mutex);
 	kfree(fl);
 }
@@ -599,6 +609,12 @@ static void fastrpc_context_free(struct kref *ref)
 	cctx = ctx->cctx;
 	fl = ctx->fl;
 
+	/* list_del_init(), not list_del(): a concurrent drain may still check list_empty(). */
+	spin_lock(&fl->lock);
+	if (!list_empty(&ctx->node))
+		list_del_init(&ctx->node);
+	spin_unlock(&fl->lock);
+
 	for (i = 0; i < ctx->nbufs; i++)
 		fastrpc_map_put(ctx->maps[i]);
 
@@ -610,6 +626,7 @@ static void fastrpc_context_free(struct kref *ref)
 
 	kfree(ctx->maps);
 	kfree(ctx->olaps);
+	kfree(ctx->args);
 	kfree(ctx);
 
 	/* Release the reference taken in fastrpc_context_alloc() */
@@ -635,6 +652,54 @@ static void fastrpc_context_put_wq(struct work_struct *work)
 	fastrpc_context_put(ctx);
 }
 
+/* Schedules put_work at most once per ctx; racing callers may both try. */
+static void fastrpc_context_schedule_put_work(struct fastrpc_invoke_ctx *ctx)
+{
+	bool do_schedule;
+
+	spin_lock(&ctx->fl->lock);
+	do_schedule = !ctx->put_work_scheduled;
+	ctx->put_work_scheduled = true;
+	spin_unlock(&ctx->fl->lock);
+
+	if (do_schedule)
+		schedule_work(&ctx->put_work);
+}
+
+/* References held by ctx are left intact; only list membership changes. */
+static void fastrpc_context_save_interrupted(struct fastrpc_invoke_ctx *ctx)
+{
+	spin_lock(&ctx->fl->lock);
+	list_move_tail(&ctx->node, &ctx->fl->interrupted);
+	spin_unlock(&ctx->fl->lock);
+}
+
+/* Matches on handle+sc, not sc alone, to avoid resuming an unrelated call. */
+static struct fastrpc_invoke_ctx *fastrpc_context_restore_interrupted(struct fastrpc_user *fl,
+								      u32 handle, u32 sc)
+{
+	struct fastrpc_invoke_ctx *ctx = NULL, *ictx;
+
+	spin_lock(&fl->lock);
+	list_for_each_entry(ictx, &fl->interrupted, node) {
+		if (ictx->pid == current->pid && ictx->handle == handle &&
+		    ictx->sc == sc) {
+			/* May already be mid-teardown; don't resurrect it. */
+			if (kref_get_unless_zero(&ictx->refcount)) {
+				ctx = ictx;
+				list_move_tail(&ctx->node, &fl->pending);
+			}
+			break;
+		}
+	}
+	spin_unlock(&fl->lock);
+
+	if (ctx)
+		fastrpc_context_put(ctx);
+
+	return ctx;
+}
+
 #define CMP(aa, bb) ((aa) == (bb) ? 0 : (aa) < (bb) ? -1 : 1)
 static int olaps_cmp(const void *a, const void *b)
 {
@@ -685,7 +750,7 @@ static void fastrpc_get_buff_overlaps(struct fastrpc_invoke_ctx *ctx)
 }
 
 static struct fastrpc_invoke_ctx *fastrpc_context_alloc(
-			struct fastrpc_user *user, u32 kernel, u32 sc,
+			struct fastrpc_user *user, u32 kernel, u32 handle, u32 sc,
 			struct fastrpc_invoke_args *args)
 {
 	struct fastrpc_channel_ctx *cctx = user->cctx;
@@ -715,7 +780,15 @@ static struct fastrpc_invoke_ctx *fastrpc_context_alloc(
 			kfree(ctx);
 			return ERR_PTR(-ENOMEM);
 		}
-		ctx->args = args;
+		/* Own copy: ctx may outlive the caller's args if parked on fl->interrupted. */
+		ctx->args = kzalloc_objs(*ctx->args, ctx->nscalars);
+		if (!ctx->args) {
+			kfree(ctx->olaps);
+			kfree(ctx->maps);
+			kfree(ctx);
+			return ERR_PTR(-ENOMEM);
+		}
+		memcpy(ctx->args, args, ctx->nscalars * sizeof(*args));
 		fastrpc_get_buff_overlaps(ctx);
 	}
 
@@ -725,6 +798,7 @@ static struct fastrpc_invoke_ctx *fastrpc_context_alloc(
 	fastrpc_user_get(user);
 
 	ctx->sc = sc;
+	ctx->handle = handle;
 	ctx->retval = -1;
 	ctx->pid = current->pid;
 	ctx->client_id = user->client_id;
@@ -759,6 +833,7 @@ static struct fastrpc_invoke_ctx *fastrpc_context_alloc(
 	fastrpc_channel_ctx_put(cctx);
 	kfree(ctx->maps);
 	kfree(ctx->olaps);
+	kfree(ctx->args);
 	kfree(ctx);
 
 	return ERR_PTR(ret);
@@ -1349,8 +1424,6 @@ static int fastrpc_internal_invoke(struct fastrpc_user *fl,  u32 kernel,
 				   struct fastrpc_invoke_args *args)
 {
 	struct fastrpc_invoke_ctx *ctx = NULL;
-	struct fastrpc_buf *buf, *b;
-
 	int err = 0;
 
 	if (!fl->sctx)
@@ -1364,7 +1437,13 @@ static int fastrpc_internal_invoke(struct fastrpc_user *fl,  u32 kernel,
 		return -EPERM;
 	}
 
-	ctx = fastrpc_context_alloc(fl, kernel, sc, args);
+	/* Resume an interrupted invoke instead of resending to the DSP. */
+	if (!kernel)
+		ctx = fastrpc_context_restore_interrupted(fl, handle, sc);
+	if (ctx)
+		goto wait;
+
+	ctx = fastrpc_context_alloc(fl, kernel, handle, sc, args);
 	if (IS_ERR(ctx))
 		return PTR_ERR(ctx);
 
@@ -1376,8 +1455,15 @@ static int fastrpc_internal_invoke(struct fastrpc_user *fl,  u32 kernel,
 	dma_wmb();
 	/* Send invoke buffer to remote dsp */
 	err = fastrpc_invoke_send(fl->sctx, ctx, kernel, handle);
-	if (err)
-		goto bail;
+	if (err) {
+		/* Never sent, so not safe to park and resume like bail: does. */
+		spin_lock(&fl->lock);
+		list_del_init(&ctx->node);
+		spin_unlock(&fl->lock);
+		fastrpc_context_put(ctx);
+		dev_dbg(fl->sctx->dev, "Error: Invoke Failed %d\n", err);
+		return err;
+	}
 
 	/*
 	 * Set message context as polled if the call is for a user PD
@@ -1386,7 +1472,16 @@ static int fastrpc_internal_invoke(struct fastrpc_user *fl,  u32 kernel,
 	if (handle > FASTRPC_MAX_STATIC_HANDLE && fl->pd == USER_PD && fl->poll_mode)
 		ctx->is_polled = true;
 
+wait:
 	err = fastrpc_wait_for_completion(ctx, kernel);
+	if (err == -ETIMEDOUT)
+		dev_warn(fl->sctx->dev,
+			 "fastrpc_invoke: TIMEOUT ctxid=0x%llx handle=0x%x nscalars=%d\n",
+			 ctx->ctxid, handle, ctx->nscalars);
+	else if (err == -ERESTARTSYS)
+		dev_dbg(fl->sctx->dev,
+			"fastrpc_invoke: INTERRUPTED ctxid=0x%llx handle=0x%x nscalars=%d\n",
+			ctx->ctxid, handle, ctx->nscalars);
 	if (err)
 		goto bail;
 
@@ -1403,21 +1498,16 @@ static int fastrpc_internal_invoke(struct fastrpc_user *fl,  u32 kernel,
 		goto bail;
 
 bail:
-	if (err != -ERESTARTSYS && err != -ETIMEDOUT) {
-		/* We are done with this compute context */
-		spin_lock(&fl->lock);
-		list_del(&ctx->node);
-		spin_unlock(&fl->lock);
-		fastrpc_context_put(ctx);
-	}
-
 	if (err == -ERESTARTSYS) {
+		fastrpc_context_save_interrupted(ctx);
+	} else if (err == -ETIMEDOUT) {
+		/* Leave linked: a late DSP answer or notify_users() still needs to reach it. */
+		fastrpc_context_put(ctx);
+	} else {
 		spin_lock(&fl->lock);
-		list_for_each_entry_safe(buf, b, &fl->mmaps, node) {
-			list_del(&buf->node);
-			list_add_tail(&buf->node, &fl->cctx->invoke_interrupted_mmaps);
-		}
+		list_del_init(&ctx->node);
 		spin_unlock(&fl->lock);
+		fastrpc_context_put(ctx);
 	}
 
 	if (err)
@@ -1719,13 +1809,28 @@ static int fastrpc_device_release(struct inode *inode, struct file *file)
 {
 	struct fastrpc_user *fl = (struct fastrpc_user *)file->private_data;
 	struct fastrpc_channel_ctx *cctx = fl->cctx;
-	unsigned long flags;
+	struct fastrpc_invoke_ctx *ctx, *n;
+	int release_err;
 
-	fastrpc_release_current_dsp_process(fl);
+	release_err = fastrpc_release_current_dsp_process(fl);
 
-	spin_lock_irqsave(&cctx->lock, flags);
-	list_del(&fl->user);
-	spin_unlock_irqrestore(&cctx->lock, flags);
+	/*
+	 * Drop the invoker ref unconditionally: no retry can arrive once the
+	 * fd is closed. Drop the worker ref only if the DSP confirmed it is
+	 * done with the process; otherwise leave ctx linked so a real answer
+	 * or a later SSR can still release it.
+	 */
+	spin_lock(&fl->lock);
+	list_for_each_entry_safe(ctx, n, &fl->interrupted, node) {
+		ctx->retval = -EPIPE;
+		complete(&ctx->work);
+		spin_unlock(&fl->lock);
+		if (!release_err)
+			fastrpc_context_schedule_put_work(ctx);
+		fastrpc_context_put(ctx);
+		spin_lock(&fl->lock);
+	}
+	spin_unlock(&fl->lock);
 
 	fastrpc_session_free(cctx, fl->sctx);
 	file->private_data = NULL;
@@ -1756,6 +1861,7 @@ static int fastrpc_device_open(struct inode *inode, struct file *filp)
 	spin_lock_init(&fl->lock);
 	mutex_init(&fl->mutex);
 	INIT_LIST_HEAD(&fl->pending);
+	INIT_LIST_HEAD(&fl->interrupted);
 	INIT_LIST_HEAD(&fl->maps);
 	INIT_LIST_HEAD(&fl->mmaps);
 	INIT_LIST_HEAD(&fl->user);
@@ -2544,13 +2650,16 @@ static void fastrpc_notify_users(struct fastrpc_user *user)
 	list_for_each_entry(ctx, &user->pending, node) {
 		ctx->retval = -EPIPE;
 		complete(&ctx->work);
-		/*
-		 * fastrpc_invoke_send() took a second reference for the
-		 * DSP response that will now never arrive since the
-		 * channel is gone; schedule the matching put the same
-		 * way a real response would via fastrpc_rpmsg_callback().
-		 */
-		schedule_work(&ctx->put_work);
+		fastrpc_context_schedule_put_work(ctx);
+	}
+	/*
+	 * Invoker ref for a parked context is released by fastrpc_user_free()
+	 * or fastrpc_device_release(); this only drops the worker ref.
+	 */
+	list_for_each_entry(ctx, &user->interrupted, node) {
+		ctx->retval = -EPIPE;
+		complete(&ctx->work);
+		fastrpc_context_schedule_put_work(ctx);
 	}
 	spin_unlock(&user->lock);
 }
@@ -2620,7 +2729,6 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 	rdev->dma_mask = &data->dma_mask;
 	dma_set_mask_and_coherent(rdev, DMA_BIT_MASK(32));
 	INIT_LIST_HEAD(&data->users);
-	INIT_LIST_HEAD(&data->invoke_interrupted_mmaps);
 	spin_lock_init(&data->lock);
 	idr_init(&data->ctx_idr);
 	data->domain_id = domain_id;
@@ -2690,7 +2798,6 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 static void fastrpc_rpmsg_remove(struct rpmsg_device *rpdev)
 {
 	struct fastrpc_channel_ctx *cctx = dev_get_drvdata(&rpdev->dev);
-	struct fastrpc_buf *buf, *b;
 	struct fastrpc_user *user;
 	unsigned long flags;
 
@@ -2707,9 +2814,6 @@ static void fastrpc_rpmsg_remove(struct rpmsg_device *rpdev)
 		fastrpc_notify_users(user);
 	spin_unlock_irqrestore(&cctx->lock, flags);
 
-	list_for_each_entry_safe(buf, b, &cctx->invoke_interrupted_mmaps, node)
-		list_del(&buf->node);
-
 	if (cctx->remote_heap_size && cctx->vmcount) {
 		u64 src_perms = 0;
 		int err, i;
@@ -2791,11 +2895,11 @@ static int fastrpc_rpmsg_callback(struct rpmsg_device *rpdev, void *data,
 	complete(&ctx->work);
 
 	/*
-	 * The DMA buffer associated with the context cannot be freed in
-	 * interrupt context so schedule it through a worker thread to
-	 * avoid a kernel BUG.
+	 * Can't free the DMA buffer in interrupt context; defer to a
+	 * worker. Guarded: notify_users()/device_release() may also be
+	 * racing to schedule this for the same ctx.
 	 */
-	schedule_work(&ctx->put_work);
+	fastrpc_context_schedule_put_work(ctx);
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#6 lore raw

PATCH 6/6 misc: fastrpc: avoid duplicate DMA mappings in fastrpc_create_maps()

In reply to [email protected]

From: Jianping Li <[email protected]>

DMA handles passed as invoke arguments (scalars beyond nbufs) may refer to the same dma_buf fd as an input/output buffer argument. Taking an extra reference for such DMA handle maps leads to duplicate mappings and an unbalanced reference count, since DMA handle maps are released separately when the DSP returns the fd through the fdlist.

Fix this by not taking an extra reference for DMA handle arguments (take_ref = false) and tagging them with FASTRPC_MAP_DMA_HANDLE. As these maps are borrowed references, fastrpc_get_args() re-validates the map via fastrpc_map_lookup() before dereferencing it, so it is not used after being freed. fastrpc_put_args() only releases maps flagged as FASTRPC_MAP_DMA_HANDLE and clears the flag to guarantee the map is freed exactly once.

Fixes 10df039834f84 ("misc: fastrpc: Skip reference for DMA handles")
---
 drivers/misc/fastrpc.c | 56 +++++++++++++++++++++++++++++++-----------
 1 file changed, 41 insertions(+), 15 deletions(-)
drivers/misc/fastrpc.c +41 -15
index c8b701395821..767db10a595b 100644
@@ -52,6 +52,9 @@
 #define FASTRPC_CTXID_SEQ_SHIFT	16
 #define FASTRPC_CTXID_SEQ_MASK	GENMASK_ULL(63, 16)
 
+/* Map the DMA handle in the invoke call for backward compatibility */
+#define FASTRPC_MAP_DMA_HANDLE  0x20000
+
 /*
  * Newer DSP firmware implements a PD (Protection Domain) notification
  * framework that sends PD state notifications upon request. The PD exit
@@ -251,6 +254,7 @@ struct fastrpc_map {
 	u64 len;
 	u64 raddr;
 	u32 attr;
+	u32 flags;
 	struct kref refcount;
 };
 
@@ -950,7 +954,7 @@ static dma_addr_t fastrpc_compute_dma_addr(struct fastrpc_user *fl, dma_addr_t s
 }
 
 static int fastrpc_map_attach(struct fastrpc_user *fl, int fd,
-			      u64 len, u32 attr, struct fastrpc_map **ppmap)
+			      u64 len, u32 attr, struct fastrpc_map **ppmap, int mflags)
 {
 	struct fastrpc_session_ctx *sess = fl->sctx;
 	struct fastrpc_map *map = NULL;
@@ -967,6 +971,7 @@ static int fastrpc_map_attach(struct fastrpc_user *fl, int fd,
 
 	map->fl = fl;
 	map->fd = fd;
+	map->flags = mflags;
 	map->buf = dma_buf_get(fd);
 	if (IS_ERR(map->buf)) {
 		err = PTR_ERR(map->buf);
@@ -1041,13 +1046,13 @@ static int fastrpc_map_attach(struct fastrpc_user *fl, int fd,
 	return err;
 }
 
-static int fastrpc_map_create(struct fastrpc_user *fl, int fd,
-			      u64 len, u32 attr, struct fastrpc_map **ppmap)
+static int fastrpc_map_create(struct fastrpc_user *fl, int fd, u64 len, u32 attr,
+			      struct fastrpc_map **ppmap, bool take_ref, int mflags)
 {
-	if (!fastrpc_map_lookup(fl, fd, ppmap, true))
+	if (!fastrpc_map_lookup(fl, fd, ppmap, take_ref))
 		return 0;
 
-	return fastrpc_map_attach(fl, fd, len, attr, ppmap);
+	return fastrpc_map_attach(fl, fd, len, attr, ppmap, mflags);
 }
 
 /*
@@ -1118,23 +1123,25 @@ static int fastrpc_create_maps(struct fastrpc_invoke_ctx *ctx)
 	int i, err;
 
 	for (i = 0; i < ctx->nscalars; ++i) {
+		bool take_ref = i < ctx->nbufs;
+		int mflags = 0;
 
 		if (ctx->args[i].fd == 0 || ctx->args[i].fd == -1 ||
 		    ctx->args[i].length == 0)
 			continue;
 
-		if (i < ctx->nbufs)
-			err = fastrpc_map_create(ctx->fl, ctx->args[i].fd,
-				 ctx->args[i].length, ctx->args[i].attr, &ctx->maps[i]);
-		else
-			err = fastrpc_map_attach(ctx->fl, ctx->args[i].fd,
-				 ctx->args[i].length, ctx->args[i].attr, &ctx->maps[i]);
+		/* Set the DMA handle mapping flag for DMA handles */
+		if (i >= ctx->nbufs)
+			mflags = FASTRPC_MAP_DMA_HANDLE;
+
+		err = fastrpc_map_create(ctx->fl, ctx->args[i].fd, ctx->args[i].length,
+					 ctx->args[i].attr, &ctx->maps[i], take_ref, mflags);
 		if (err) {
 			dev_err(dev, "Error Creating map %d\n", err);
 			return -EINVAL;
 		}
-
 	}
+
 	return 0;
 }
 
@@ -1266,6 +1273,16 @@ static int fastrpc_get_args(u32 kernel, struct fastrpc_invoke_ctx *ctx)
 		list[i].num = ctx->args[i].length ? 1 : 0;
 		list[i].pgidx = i;
 		if (ctx->maps[i]) {
+			/* It is possible that map is created with
+			 * mflags FASTRPC_MAP_DMA_HANDLE and take_ref
+			 * is false. Check if map still exists or is
+			 * being freed as take_ref is false
+			 */
+			if (fastrpc_map_lookup(ctx->fl, ctx->args[i].fd,
+					       &ctx->maps[i], false)) {
+				ctx->maps[i] = NULL;
+				return -EINVAL;
+			}
 			pages[i].addr = ctx->maps[i]->dma_addr;
 			pages[i].size = ctx->maps[i]->size;
 		}
@@ -1315,8 +1332,17 @@ static int fastrpc_put_args(struct fastrpc_invoke_ctx *ctx,
 	for (i = 0; i < FASTRPC_MAX_FDLIST; i++) {
 		if (!fdlist[i])
 			break;
-		if (!fastrpc_map_lookup(fl, (int)fdlist[i], &mmap, false))
+		/*
+		 * DMA handle maps are released when the DSP returns the corresponding fd in
+		 * fdlist. The DSP is expected to return a specific fd only once in fdlist,
+		 * so no two fastrpc_put_args() paths should clear the DMA_HANDLE flag for
+		 * the same map concurrently.
+		 */
+		if (!fastrpc_map_lookup(fl, (int)fdlist[i], &mmap, false) &&
+		    mmap->flags == FASTRPC_MAP_DMA_HANDLE) {
+			mmap->flags = 0;
 			fastrpc_map_put(mmap);
+		}
 	}
 
 	return ret;
@@ -1692,7 +1718,7 @@ static int fastrpc_init_create_process(struct fastrpc_user *fl,
 	fl->pd = USER_PD;
 
 	if (init.filelen && init.filefd) {
-		err = fastrpc_map_create(fl, init.filefd, init.filelen, 0, &map);
+		err = fastrpc_map_create(fl, init.filefd, init.filelen, 0, &map, true, 0);
 		if (err)
 			goto err;
 	}
@@ -2314,7 +2340,7 @@ static int fastrpc_req_mem_map(struct fastrpc_user *fl, char __user *argp)
 		return -EFAULT;
 
 	/* create SMMU mapping */
-	err = fastrpc_map_create(fl, req.fd, req.length, 0, &map);
+	err = fastrpc_map_create(fl, req.fd, req.length, 0, &map, true, 0);
 	if (err) {
 		dev_err(dev, "failed to map buffer, fd = %d\n", req.fd);
 		return err;
Signature · 1 line
2.53.0