From d3904a21c4b8c21c510ec645db87488ca1d54387 Mon Sep 17 00:00:00 2001
From: Tilghman Lesher <tilghman@meg.abyt.es>
Date: Fri, 28 Sep 2007 05:37:16 +0000
Subject: [PATCH] Merged revisions 84049 via svnmerge from
 https://origsvn.digium.com/svn/asterisk/branches/1.4

........
r84049 | tilghman | 2007-09-28 00:30:22 -0500 (Fri, 28 Sep 2007) | 3 lines

Avoid a deadlock with ALL of the locks in the masquerade function, not just the
pairs of channels.  (Closes issue #10406)

........


git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@84050 65c4cc65-6c06-0410-ace0-fbb531ad65f3
---
 main/channel.c | 22 +++++++++++++++++-----
 1 file changed, 17 insertions(+), 5 deletions(-)

diff --git a/main/channel.c b/main/channel.c
index d8a137ec00..e11afe9d47 100644
--- a/main/channel.c
+++ b/main/channel.c
@@ -3333,7 +3333,11 @@ int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *pe
 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
 {
 	int res = -1;
-	struct ast_channel *final_orig = original, *final_clone = clone;
+	struct ast_channel *final_orig, *final_clone;
+
+retrymasq:
+	final_orig = original;
+	final_clone = clone;
 
 	ast_channel_lock(original);
 	while (ast_channel_trylock(clone)) {
@@ -3351,11 +3355,19 @@ int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clo
 		final_clone = clone->_bridge;
 
 	if ((final_orig != original) || (final_clone != clone)) {
-		ast_channel_lock(final_orig);
-		while (ast_channel_trylock(final_clone)) {
+		/* Lots and lots of deadlock avoidance.  The main one we're competing with
+		 * is ast_write(), which locks channels recursively, when working with a
+		 * proxy channel. */
+		if (ast_channel_trylock(final_orig)) {
+			ast_channel_unlock(clone);
+			ast_channel_unlock(original);
+			goto retrymasq;
+		}
+		if (ast_channel_trylock(final_clone)) {
 			ast_channel_unlock(final_orig);
-			usleep(1);
-			ast_channel_lock(final_orig);
+			ast_channel_unlock(clone);
+			ast_channel_unlock(original);
+			goto retrymasq;
 		}
 		ast_channel_unlock(clone);
 		ast_channel_unlock(original);
-- 
GitLab