Index: /pjproject/trunk/pjsip-apps/src/samples/stateful_proxy.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/samples/stateful_proxy.c	(revision 4419)
+++ /pjproject/trunk/pjsip-apps/src/samples/stateful_proxy.c	(revision 4420)
@@ -274,5 +274,5 @@
 	    pjsip_tx_data *cancel;
 
-	    pj_mutex_lock(uas_data->uac_tsx->mutex);
+	    pj_grp_lock_acquire(uas_data->uac_tsx->grp_lock);
 
 	    pjsip_endpt_create_cancel(global.endpt, uas_data->uac_tsx->last_tx,
@@ -280,9 +280,9 @@
 	    pjsip_endpt_send_request(global.endpt, cancel, -1, NULL, NULL);
 
-	    pj_mutex_unlock(uas_data->uac_tsx->mutex);
+	    pj_grp_lock_release(uas_data->uac_tsx->grp_lock);
 	}
 
 	/* Unlock UAS tsx because it is locked in find_tsx() */
-	pj_mutex_unlock(invite_uas->mutex);
+	pj_grp_lock_release(invite_uas->grp_lock);
     }
 
Index: /pjproject/trunk/pjsip/include/pjsip/sip_transaction.h
===================================================================
--- /pjproject/trunk/pjsip/include/pjsip/sip_transaction.h	(revision 4419)
+++ /pjproject/trunk/pjsip/include/pjsip/sip_transaction.h	(revision 4420)
@@ -86,5 +86,6 @@
     pjsip_module	       *tsx_user;	/**< Transaction user.	    */
     pjsip_endpoint	       *endpt;          /**< Endpoint instance.     */
-    pj_mutex_t		       *mutex;          /**< Mutex for this tsx.    */
+    pj_bool_t			terminating;	/**< terminate() was called */
+    pj_grp_lock_t	       *grp_lock;       /**< Transaction grp lock.  */
     pj_mutex_t		       *mutex_b;	/**< Second mutex to avoid
 						     deadlock. It is used to
@@ -214,4 +215,28 @@
 
 /**
+ * Variant of pjsip_tsx_create_uac() with additional parameter to specify
+ * the group lock to use. Group lock can be used to synchronize locking
+ * among several objects to prevent deadlock, and to synchronize the
+ * lifetime of objects sharing the same group lock.
+ *
+ * See pjsip_tsx_create_uac() for general info about this function.
+ *
+ * @param tsx_user  Module to be registered as transaction user of the new
+ *		    transaction, which will receive notification from the
+ *		    transaction via on_tsx_state() callback.
+ * @param tdata     The outgoing request message.
+ * @param grp_lock  Optional group lock to use by this transaction. If
+ * 		    the value is NULL, the transaction will create its
+ * 		    own group lock.
+ * @param p_tsx	    On return will contain the new transaction instance.
+ *
+ * @return          PJ_SUCCESS if successfull.
+ */
+PJ_DECL(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user,
+					   pjsip_tx_data *tdata,
+					   pj_grp_lock_t *grp_lock,
+					   pjsip_transaction **p_tsx);
+
+/**
  * Create, initialize, and register a new transaction as UAS from the
  * specified incoming request in \c rdata. After calling this function,
@@ -231,4 +256,27 @@
 					   pjsip_transaction **p_tsx );
 
+/**
+ * Variant of pjsip_tsx_create_uas() with additional parameter to specify
+ * the group lock to use. Group lock can be used to synchronize locking
+ * among several objects to prevent deadlock, and to synchronize the
+ * lifetime of objects sharing the same group lock.
+ *
+ * See pjsip_tsx_create_uas() for general info about this function.
+ *
+ * @param tsx_user  Module to be registered as transaction user of the new
+ *		    transaction, which will receive notification from the
+ *		    transaction via on_tsx_state() callback.
+ * @param rdata     The received incoming request.
+ * @param grp_lock  Optional group lock to use by this transaction. If
+ * 		    the value is NULL, the transaction will create its
+ * 		    own group lock.
+ * @param p_tsx	    On return will contain the new transaction instance.
+ *
+ * @return	    PJ_SUCCESS if successfull.
+ */
+PJ_DECL(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user,
+					   pjsip_rx_data *rdata,
+					   pj_grp_lock_t *grp_lock,
+					   pjsip_transaction **p_tsx );
 
 /**
Index: /pjproject/trunk/pjsip/src/pjsip-ua/sip_inv.c
===================================================================
--- /pjproject/trunk/pjsip/src/pjsip-ua/sip_inv.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/pjsip-ua/sip_inv.c	(revision 4420)
@@ -2911,5 +2911,5 @@
 
     if (invite_tsx)
-	pj_mutex_unlock(invite_tsx->mutex);
+	pj_grp_lock_release(invite_tsx->grp_lock);
 }
 
Index: /pjproject/trunk/pjsip/src/pjsip/sip_transaction.c
===================================================================
--- /pjproject/trunk/pjsip/src/pjsip/sip_transaction.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/pjsip/sip_transaction.c	(revision 4420)
@@ -28,4 +28,5 @@
 #include <pj/pool.h>
 #include <pj/os.h>
+#include <pj/rand.h>
 #include <pj/string.h>
 #include <pj/assert.h>
@@ -91,7 +92,4 @@
 };
 
-/* Thread Local Storage ID for transaction lock */
-static long pjsip_tsx_lock_tls_id;
-
 /* Transaction state names */
 static const char *state_str[] = 
@@ -123,12 +121,4 @@
     TSX_HAS_RESOLVED_SERVER	= 16,
 };
-
-/* Transaction lock. */
-typedef struct tsx_lock_data {
-    struct tsx_lock_data *prev;
-    pjsip_transaction    *tsx;
-    int			  is_alive;
-} tsx_lock_data;
-
 
 /* Timer timeout value constants */
@@ -149,7 +139,4 @@
 
 /* Prototypes. */
-static void	   lock_tsx(pjsip_transaction *tsx, struct tsx_lock_data *lck);
-static pj_status_t unlock_tsx( pjsip_transaction *tsx, 
-                               struct tsx_lock_data *lck);
 static pj_status_t tsx_on_state_null(		pjsip_transaction *tsx, 
 				                pjsip_event *event);
@@ -179,6 +166,8 @@
 				       const pjsip_transport_state_info *info);
 static pj_status_t tsx_create( pjsip_module *tsx_user,
+                               pj_grp_lock_t *grp_lock,
 			       pjsip_transaction **p_tsx);
-static pj_status_t tsx_destroy( pjsip_transaction *tsx );
+static void	   tsx_on_destroy(void *arg);
+static pj_status_t tsx_shutdown( pjsip_transaction *tsx );
 static void	   tsx_resched_retransmission( pjsip_transaction *tsx );
 static pj_status_t tsx_retransmit( pjsip_transaction *tsx, int resched);
@@ -271,8 +260,7 @@
 {
 #define SEPARATOR   '$'
-    char *key, *p, *end;
+    char *key, *p;
     int len;
     pj_size_t len_required;
-    pjsip_uri *req_uri;
     pj_str_t *host;
 
@@ -284,5 +272,4 @@
 
     host = &rdata->msg_info.via->sent_by.host;
-    req_uri = (pjsip_uri*)rdata->msg_info.msg->line.req.uri;
 
     /* Calculate length required. */
@@ -294,5 +281,4 @@
 		   16;			    /* Separator+Allowance. */
     key = p = (char*) pj_pool_alloc(pool, len_required);
-    end = p + len_required;
 
     /* Add role. */
@@ -452,11 +438,4 @@
     timeout_timer_val = td_timer_val;
 
-    /* Initialize TLS ID for transaction lock. */
-    status = pj_thread_local_alloc(&pjsip_tsx_lock_tls_id);
-    if (status != PJ_SUCCESS)
-	return status;
-
-    pj_thread_local_set(pjsip_tsx_lock_tls_id, NULL);
-
     /*
      * Initialize transaction layer structure.
@@ -483,5 +462,5 @@
     }
 
-    /* Create mutex. */
+    /* Create group lock. */
     status = pj_mutex_create_recursive(pool, "tsxlayer", &mod_tsx_layer.mutex);
     if (status != PJ_SUCCESS) {
@@ -666,6 +645,8 @@
      */
     PJ_TODO(FIX_RACE_CONDITION_HERE);
+    PJ_RACE_ME(5);
+
     if (tsx && lock)
-	pj_mutex_lock(tsx->mutex);
+	pj_grp_lock_acquire(tsx->grp_lock);
 
     return tsx;
@@ -712,5 +693,5 @@
 	    pjsip_tsx_terminate(tsx, PJSIP_SC_SERVICE_UNAVAILABLE);
 	    mod_tsx_layer_unregister_tsx(tsx);
-	    tsx_destroy(tsx);
+	    tsx_shutdown(tsx);
 	}
 	it = next;
@@ -735,7 +716,4 @@
     /* Release pool. */
     pjsip_endpt_release_pool(mod_tsx_layer.endpt, mod_tsx_layer.pool);
-
-    /* Free TLS */
-    pj_thread_local_free(pjsip_tsx_lock_tls_id);
 
     /* Mark as unregistered. */
@@ -814,4 +792,5 @@
      */
     PJ_TODO(FIX_RACE_CONDITION_HERE);
+    PJ_RACE_ME(5);
 
     /* Pass the message to the transaction. */
@@ -863,4 +842,5 @@
      */
     PJ_TODO(FIX_RACE_CONDITION_HERE);
+    PJ_RACE_ME(5);
 
     /* Pass the message to the transaction. */
@@ -929,41 +909,4 @@
  *****************************************************************************
  **/
-/*
- * Lock transaction and set the value of Thread Local Storage.
- */
-static void lock_tsx(pjsip_transaction *tsx, struct tsx_lock_data *lck)
-{
-    struct tsx_lock_data *prev_data;
-
-    pj_mutex_lock(tsx->mutex);
-    prev_data = (struct tsx_lock_data *) 
-                    pj_thread_local_get(pjsip_tsx_lock_tls_id);
-    lck->prev = prev_data;
-    lck->tsx = tsx;
-    lck->is_alive = 1;
-    pj_thread_local_set(pjsip_tsx_lock_tls_id, lck);
-}
-
-
-/*
- * Unlock transaction.
- * This will selectively unlock the mutex ONLY IF the transaction has not been 
- * destroyed. The function knows whether the transaction has been destroyed
- * because when transaction is destroyed the is_alive flag for the transaction
- * will be set to zero.
- */
-static pj_status_t unlock_tsx( pjsip_transaction *tsx, 
-                               struct tsx_lock_data *lck)
-{
-    pj_assert( (void*)pj_thread_local_get(pjsip_tsx_lock_tls_id) == lck);
-    pj_assert( lck->tsx == tsx );
-    pj_thread_local_set(pjsip_tsx_lock_tls_id, lck->prev);
-    if (lck->is_alive)
-	pj_mutex_unlock(tsx->mutex);
-
-    return lck->is_alive ? PJ_SUCCESS : PJSIP_ETSXDESTROYED;
-}
-
-
 /* Lock transaction for accessing the timeout timer only. */
 static void lock_timer(pjsip_transaction *tsx)
@@ -982,4 +925,5 @@
  */
 static pj_status_t tsx_create( pjsip_module *tsx_user,
+                               pj_grp_lock_t *grp_lock,
 			       pjsip_transaction **p_tsx)
 {
@@ -1010,14 +954,20 @@
     tsx->timeout_timer.cb = &tsx_timer_callback;
     
-    status = pj_mutex_create_recursive(pool, tsx->obj_name, &tsx->mutex);
-    if (status != PJ_SUCCESS) {
-	pjsip_endpt_release_pool(mod_tsx_layer.endpt, pool);
-	return status;
-    }
+    if (grp_lock) {
+	tsx->grp_lock = grp_lock;
+    } else {
+	status = pj_grp_lock_create(pool, NULL, &tsx->grp_lock);
+	if (status != PJ_SUCCESS) {
+	    pjsip_endpt_release_pool(mod_tsx_layer.endpt, pool);
+	    return status;
+	}
+    }
+
+    pj_grp_lock_add_ref(tsx->grp_lock);
+    pj_grp_lock_add_handler(tsx->grp_lock, tsx->pool, tsx, &tsx_on_destroy);
 
     status = pj_mutex_create_simple(pool, tsx->obj_name, &tsx->mutex_b);
     if (status != PJ_SUCCESS) {
-	pj_mutex_destroy(tsx->mutex);
-	pjsip_endpt_release_pool(mod_tsx_layer.endpt, pool);
+	tsx_shutdown(tsx);
 	return status;
     }
@@ -1027,15 +977,26 @@
 }
 
-
-/* Destroy transaction. */
-static pj_status_t tsx_destroy( pjsip_transaction *tsx )
-{
-    struct tsx_lock_data *lck;
-
+/* Really destroy transaction, when grp_lock reference is zero */
+static void tsx_on_destroy( void *arg )
+{
+    pjsip_transaction *tsx = (pjsip_transaction*)arg;
+
+    PJ_LOG(5,(tsx->obj_name, "Transaction destroyed!"));
+
+    pj_mutex_destroy(tsx->mutex_b);
+    pjsip_endpt_release_pool(tsx->endpt, tsx->pool);
+}
+
+/* Shutdown transaction. */
+static pj_status_t tsx_shutdown( pjsip_transaction *tsx )
+{
     /* Release the transport */
     tsx_update_transport(tsx, NULL);
 
-    /* Decrement reference counter in transport selector */
-    pjsip_tpselector_dec_ref(&tsx->tp_sel);
+    /* Decrement reference counter in transport selector, only if
+     * we haven't been called before */
+    if (!tsx->terminating) {
+	pjsip_tpselector_dec_ref(&tsx->tp_sel);
+    }
 
     /* Free last transmitted message. */
@@ -1057,4 +1018,5 @@
     /* Clear some pending flags. */
     tsx->transport_flag &= ~(TSX_HAS_PENDING_RESCHED | TSX_HAS_PENDING_SEND);
+
 
     /* Refuse to destroy transaction if it has pending resolving. */
@@ -1064,22 +1026,12 @@
 	PJ_LOG(4,(tsx->obj_name, "Will destroy later because transport is "
 				 "in progress"));
-	return PJ_EBUSY;
-    }
-
-    /* Clear TLS, so that mutex will not be unlocked */
-    lck = (struct tsx_lock_data*) pj_thread_local_get(pjsip_tsx_lock_tls_id);
-    while (lck) {
-	if (lck->tsx == tsx) {
-	    lck->is_alive = 0;
-	}
-	lck = lck->prev;
-    }
-
-    pj_mutex_destroy(tsx->mutex_b);
-    pj_mutex_destroy(tsx->mutex);
-
-    PJ_LOG(5,(tsx->obj_name, "Transaction destroyed!"));
-
-    pjsip_endpt_release_pool(tsx->endpt, tsx->pool);
+    }
+
+    if (!tsx->terminating) {
+	tsx->terminating = PJ_TRUE;
+	pj_grp_lock_dec_ref(tsx->grp_lock);
+    }
+
+    /* No acccess to tsx after this, it may have been destroyed */
 
     return PJ_SUCCESS;
@@ -1094,5 +1046,4 @@
     pjsip_event event;
     pjsip_transaction *tsx = (pjsip_transaction*) entry->user_data;
-    struct tsx_lock_data lck;
 
     PJ_UNUSED_ARG(theap);
@@ -1108,7 +1059,7 @@
 
     /* Dispatch event to transaction. */
-    lock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
     (*tsx->state_handler)(tsx, &event);
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 
     pj_log_pop_indent();
@@ -1209,5 +1160,5 @@
 
 	/* Destroy transaction. */
-	tsx_destroy(tsx);
+	tsx_shutdown(tsx);
     }
 
@@ -1221,4 +1172,12 @@
 PJ_DEF(pj_status_t) pjsip_tsx_create_uac( pjsip_module *tsx_user,
 					  pjsip_tx_data *tdata,
+					  pjsip_transaction **p_tsx)
+{
+    return pjsip_tsx_create_uac2(tsx_user, tdata, NULL, p_tsx);
+}
+
+PJ_DEF(pj_status_t) pjsip_tsx_create_uac2(pjsip_module *tsx_user,
+					  pjsip_tx_data *tdata,
+					  pj_grp_lock_t *grp_lock,
 					  pjsip_transaction **p_tsx)
 {
@@ -1228,5 +1187,4 @@
     pjsip_via_hdr *via;
     pjsip_host_info dst_info;
-    struct tsx_lock_data lck;
     pj_status_t status;
 
@@ -1252,5 +1210,5 @@
 
     /* Create transaction instance. */
-    status = tsx_create( tsx_user, &tsx);
+    status = tsx_create( tsx_user, grp_lock, &tsx);
     if (status != PJ_SUCCESS)
 	return status;
@@ -1258,5 +1216,5 @@
 
     /* Lock transaction. */
-    lock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
 
     /* Role is UAC. */
@@ -1324,6 +1282,6 @@
     status = pjsip_get_request_dest(tdata, &dst_info);
     if (status != PJ_SUCCESS) {
-	unlock_tsx(tsx, &lck);
-	tsx_destroy(tsx);
+	pj_grp_lock_release(tsx->grp_lock);
+	tsx_shutdown(tsx);
 	return status;
     }
@@ -1336,6 +1294,6 @@
 	pj_assert(!"Bug in branch_param generator (i.e. not unique)");
 	*/
-	unlock_tsx(tsx, &lck);
-	tsx_destroy(tsx);
+	pj_grp_lock_release(tsx->grp_lock);
+	tsx_shutdown(tsx);
 	return status;
     }
@@ -1343,5 +1301,5 @@
 
     /* Unlock transaction and return. */
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 
     pj_log_push_indent();
@@ -1360,4 +1318,12 @@
 PJ_DEF(pj_status_t) pjsip_tsx_create_uas( pjsip_module *tsx_user,
 					  pjsip_rx_data *rdata,
+					  pjsip_transaction **p_tsx)
+{
+    return pjsip_tsx_create_uas2(tsx_user, rdata, NULL, p_tsx);
+}
+
+PJ_DEF(pj_status_t) pjsip_tsx_create_uas2(pjsip_module *tsx_user,
+					  pjsip_rx_data *rdata,
+					  pj_grp_lock_t *grp_lock,
 					  pjsip_transaction **p_tsx)
 {
@@ -1367,5 +1333,4 @@
     pjsip_cseq_hdr *cseq;
     pj_status_t status;
-    struct tsx_lock_data lck;
 
     /* Validate arguments. */
@@ -1405,5 +1370,5 @@
      * Create transaction instance. 
      */
-    status = tsx_create( tsx_user, &tsx);
+    status = tsx_create( tsx_user, grp_lock, &tsx);
     if (status != PJ_SUCCESS)
 	return status;
@@ -1411,5 +1376,5 @@
 
     /* Lock transaction. */
-    lock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
 
     /* Role is UAS */
@@ -1428,6 +1393,6 @@
                                   PJSIP_ROLE_UAS, &tsx->method, rdata);
     if (status != PJ_SUCCESS) {
-	unlock_tsx(tsx, &lck);
-        tsx_destroy(tsx);
+	pj_grp_lock_release(tsx->grp_lock);
+	tsx_shutdown(tsx);
         return status;
     }
@@ -1455,6 +1420,6 @@
     status = pjsip_get_response_addr( tsx->pool, rdata, &tsx->res_addr );
     if (status != PJ_SUCCESS) {
-	unlock_tsx(tsx, &lck);
-	tsx_destroy(tsx);
+	pj_grp_lock_release(tsx->grp_lock);
+	tsx_shutdown(tsx);
 	return status;
     }
@@ -1477,6 +1442,6 @@
     status = mod_tsx_layer_register_tsx(tsx);
     if (status != PJ_SUCCESS) {
-	unlock_tsx(tsx, &lck);
-	tsx_destroy(tsx);
+	pj_grp_lock_release(tsx->grp_lock);
+	tsx_shutdown(tsx);
 	return status;
     }
@@ -1486,5 +1451,5 @@
 
     /* Unlock transaction and return. */
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 
     pj_log_push_indent();
@@ -1505,11 +1470,9 @@
 					    const pjsip_tpselector *sel)
 {
-    struct tsx_lock_data lck;
-
     /* Must be UAC transaction */
     PJ_ASSERT_RETURN(tsx && sel, PJ_EINVAL);
 
     /* Start locking the transaction. */
-    lock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
 
     /* Decrement reference counter of previous transport selector */
@@ -1523,5 +1486,5 @@
 
     /* Unlock transaction. */
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 
     return PJ_SUCCESS;
@@ -1548,6 +1511,4 @@
 PJ_DEF(pj_status_t) pjsip_tsx_terminate( pjsip_transaction *tsx, int code )
 {
-    struct tsx_lock_data lck;
-
     PJ_ASSERT_RETURN(tsx != NULL, PJ_EINVAL);
 
@@ -1561,8 +1522,8 @@
     pj_log_push_indent();
 
-    lock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
     tsx_set_status_code(tsx, code, NULL);
     tsx_set_state( tsx, PJSIP_TSX_STATE_TERMINATED, PJSIP_EVENT_USER, NULL);
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 
     pj_log_pop_indent();
@@ -1579,6 +1540,4 @@
 PJ_DEF(pj_status_t) pjsip_tsx_stop_retransmit(pjsip_transaction *tsx)
 {
-    struct tsx_lock_data lck;
-
     PJ_ASSERT_RETURN(tsx != NULL, PJ_EINVAL);
     PJ_ASSERT_RETURN(tsx->role == PJSIP_ROLE_UAC &&
@@ -1590,5 +1549,5 @@
     pj_log_push_indent();
 
-    lock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
     /* Cancel retransmission timer. */
     if (tsx->retransmit_timer.id != 0) {
@@ -1596,5 +1555,5 @@
 	tsx->retransmit_timer.id = 0;
     }
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 
     pj_log_pop_indent();
@@ -1618,6 +1577,6 @@
 		     PJ_EINVALIDOP);
 
-    /* Note: must not call lock_tsx() as that would introduce deadlock.
-     * See #1121.
+    /* Note: must not call pj_grp_lock_acquire(tsx->grp_lock) as
+     * that would introduce deadlock. See #1121.
      */
     lock_timer(tsx);
@@ -1660,5 +1619,4 @@
 {
     pjsip_event event;
-    struct tsx_lock_data lck;
     pj_status_t status;
 
@@ -1676,5 +1634,5 @@
 
     /* Dispatch to transaction. */
-    lock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
 
     /* Set transport selector to tdata */
@@ -1684,5 +1642,5 @@
     status = (*tsx->state_handler)(tsx, &event);
 
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 
     /* Only decrement reference counter when it returns success.
@@ -1707,6 +1665,4 @@
 {
     pjsip_event event;
-    struct tsx_lock_data lck;
-    pj_status_t status;
 
     PJ_LOG(5,(tsx->obj_name, "Incoming %s in state %s", 
@@ -1721,7 +1677,7 @@
 
     /* Dispatch to transaction. */
-    lock_tsx(tsx, &lck);
-    status = (*tsx->state_handler)(tsx, &event);
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
+    (*tsx->state_handler)(tsx, &event);
+    pj_grp_lock_release(tsx->grp_lock);
 
     pj_log_pop_indent();
@@ -1735,5 +1691,4 @@
     pjsip_transaction *tsx = (pjsip_transaction*) send_state->token;
     pjsip_tx_data *tdata = send_state->tdata;
-    struct tsx_lock_data lck;
 
     /* Check if transaction has cancelled itself from this transmit
@@ -1749,9 +1704,9 @@
     }
 
+    pj_grp_lock_acquire(tsx->grp_lock);
+
     /* Reset */
     tdata->mod_data[mod_tsx_layer.mod.id] = NULL;
     tsx->pending_tx = NULL;
-
-    lock_tsx(tsx, &lck);
 
     if (sent > 0) {
@@ -1783,5 +1738,5 @@
 	    tsx_set_state( tsx, PJSIP_TSX_STATE_DESTROYED, 
 			   PJSIP_EVENT_UNKNOWN, NULL );
-	    unlock_tsx(tsx, &lck);
+	    pj_grp_lock_release(tsx->grp_lock);
 	    return;
 	}
@@ -1825,5 +1780,5 @@
 	    err =pj_strerror(-sent, errmsg, sizeof(errmsg));
 
-	    PJ_LOG(2,(tsx->obj_name, 
+	    PJ_LOG(2,(tsx->obj_name,
 		      "Failed to send %s! err=%d (%s)",
 		      pjsip_tx_data_get_info(send_state->tdata), -sent,
@@ -1863,11 +1818,8 @@
 
 	} else {
-	    char errmsg[PJ_ERR_MSG_SIZE];
-
-	    PJ_LOG(2,(tsx->obj_name, 
-		      "Temporary failure in sending %s, "
-		      "will try next server. Err=%d (%s)",
-		      pjsip_tx_data_get_info(send_state->tdata), -sent,
-		      pj_strerror(-sent, errmsg, sizeof(errmsg)).ptr));
+	    PJ_PERROR(2,(tsx->obj_name, -sent,
+		         "Temporary failure in sending %s, "
+		         "will try next server",
+		         pjsip_tx_data_get_info(send_state->tdata)));
 
 	    /* Reset retransmission count */
@@ -1894,5 +1846,5 @@
     }
 
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 }
 
@@ -1904,5 +1856,4 @@
     if (sent < 0) {
 	pjsip_transaction *tsx = (pjsip_transaction*) token;
-	struct tsx_lock_data lck;
 	char errmsg[PJ_ERR_MSG_SIZE];
 	pj_str_t err;
@@ -1913,7 +1864,7 @@
 
 	PJ_LOG(2,(tsx->obj_name, "Transport failed to send %s! Err=%d (%s)",
-		  pjsip_tx_data_get_info(tdata), -sent, errmsg));
-
-	lock_tsx(tsx, &lck);
+		pjsip_tx_data_get_info(tdata), -sent, errmsg));
+
+	pj_grp_lock_acquire(tsx->grp_lock);
 
 	/* Release transport. */
@@ -1925,5 +1876,5 @@
 		       PJSIP_EVENT_TRANSPORT_ERROR, tdata );
 
-	unlock_tsx(tsx, &lck);
+	pj_grp_lock_release(tsx->grp_lock);
    }
 }
@@ -1941,5 +1892,4 @@
     if (state == PJSIP_TP_STATE_DISCONNECTED) {
 	pjsip_transaction *tsx;
-	struct tsx_lock_data lck;
 
 	pj_assert(tp && info && info->user_data);
@@ -1947,5 +1897,5 @@
 	tsx = (pjsip_transaction*)info->user_data;
 
-	lock_tsx(tsx, &lck);
+	pj_grp_lock_acquire(tsx->grp_lock);
 
 	/* Terminate transaction when transport disconnected */
@@ -1960,5 +1910,5 @@
 	}
 
-	unlock_tsx(tsx, &lck);
+	pj_grp_lock_release(tsx->grp_lock);
     }
 }
@@ -1992,10 +1942,7 @@
 
 	if (status != PJ_SUCCESS) {
-	    char errmsg[PJ_ERR_MSG_SIZE];
-
-	    PJ_LOG(2,(tsx->obj_name, 
-		      "Error sending %s: Err=%d (%s)",
-		      pjsip_tx_data_get_info(tdata), status, 
-		      pj_strerror(status, errmsg, sizeof(errmsg)).ptr));
+	    PJ_PERROR(2,(tsx->obj_name, status,
+		         "Error sending %s",
+		         pjsip_tx_data_get_info(tdata)));
 
 	    /* On error, release transport to force using full transport
@@ -2110,13 +2057,12 @@
 						  pjsip_tx_data *tdata)
 {
-    struct tsx_lock_data lck;
     pj_status_t status;
 
-    lock_tsx(tsx, &lck);
+    pj_grp_lock_acquire(tsx->grp_lock);
     if (tdata == NULL) {
 	tdata = tsx->last_tx;
     }
     status = tsx_send_msg(tsx, tdata);
-    unlock_tsx(tsx, &lck);
+    pj_grp_lock_release(tsx->grp_lock);
 
     /* Only decrement reference counter when it returns success.
Index: /pjproject/trunk/pjsip/src/pjsip/sip_ua_layer.c
===================================================================
--- /pjproject/trunk/pjsip/src/pjsip/sip_ua_layer.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/pjsip/sip_ua_layer.c	(revision 4420)
@@ -546,5 +546,5 @@
 	if (tsx) {
 	    dlg = (pjsip_dialog*) tsx->mod_data[mod_ua.mod.id];
-	    pj_mutex_unlock(tsx->mutex);
+	    pj_grp_lock_release(tsx->grp_lock);
 
 	    /* Dlg may be NULL on some extreme condition
Index: /pjproject/trunk/pjsip/src/test/regc_test.c
===================================================================
--- /pjproject/trunk/pjsip/src/test/regc_test.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/test/regc_test.c	(revision 4420)
@@ -348,5 +348,8 @@
 	return -210;
     }
-    if (client_result.code != client_cfg->code) {
+    if (client_result.code != client_cfg->code &&
+	client_cfg->code != 502 && client_cfg->code != 503 &&
+	client_result.code != 502 && client_result.code != 503)
+    {
 	PJ_LOG(3,(THIS_FILE, "    error: expecting code=%d, got code=%d",
 		  client_cfg->code, client_result.code));
Index: /pjproject/trunk/pjsip/src/test/test.c
===================================================================
--- /pjproject/trunk/pjsip/src/test/test.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/test/test.c	(revision 4420)
@@ -48,7 +48,8 @@
 
 pjsip_endpoint *endpt;
+pj_caching_pool caching_pool;
 int log_level = 3;
 int param_log_decor = PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_TIME | 
-		      PJ_LOG_HAS_MICRO_SEC;
+		      PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT;
 
 static pj_oshandle_t fd_report;
@@ -224,5 +225,4 @@
 {
     pj_status_t rc;
-    pj_caching_pool caching_pool;
     const char *filename;
     unsigned tsx_test_cnt=0;
@@ -370,4 +370,10 @@
 #endif
 
+    /*
+     * Better be last because it recreates the endpt
+     */
+#if INCLUDE_TSX_DESTROY_TEST
+    DO_TEST(tsx_destroy_test());
+#endif
 
 on_return:
Index: /pjproject/trunk/pjsip/src/test/test.h
===================================================================
--- /pjproject/trunk/pjsip/src/test/test.h	(revision 4419)
+++ /pjproject/trunk/pjsip/src/test/test.h	(revision 4420)
@@ -24,4 +24,5 @@
 
 extern pjsip_endpoint *endpt;
+extern pj_caching_pool caching_pool;
 
 #define TEST_UDP_PORT	    15060
@@ -65,4 +66,5 @@
 #define INCLUDE_RESOLVE_TEST	INCLUDE_TRANSPORT_GROUP
 #define INCLUDE_TSX_TEST	INCLUDE_TSX_GROUP
+#define INCLUDE_TSX_DESTROY_TEST INCLUDE_TSX_GROUP
 #define INCLUDE_INV_OA_TEST	INCLUDE_INV_GROUP
 #define INCLUDE_REGC_TEST	INCLUDE_REGC_GROUP
@@ -76,4 +78,5 @@
 int txdata_test(void);
 int tsx_bench(void);
+int tsx_destroy_test(void);
 int transport_udp_test(void);
 int transport_loop_test(void);
Index: /pjproject/trunk/pjsip/src/test/tsx_basic_test.c
===================================================================
--- /pjproject/trunk/pjsip/src/test/tsx_basic_test.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/test/tsx_basic_test.c	(revision 4420)
@@ -126,5 +126,5 @@
 	    return -40;
 	}
-	pj_mutex_unlock(tsx->mutex);
+	pj_grp_lock_release(tsx->grp_lock);
     }
 
@@ -156,2 +156,188 @@
     return 0;
 }
+
+/**************************************************************************/
+
+struct tsx_test_state
+{
+    int pool_cnt;
+};
+
+static void save_tsx_test_state(struct tsx_test_state *st)
+{
+    st->pool_cnt = caching_pool.used_count;
+}
+
+static pj_status_t check_tsx_test_state(struct tsx_test_state *st)
+{
+    if (caching_pool.used_count > st->pool_cnt)
+	return -1;
+
+    return 0;
+}
+
+static void destroy_endpt()
+{
+    pjsip_endpt_destroy(endpt);
+    endpt = NULL;
+}
+
+static pj_status_t init_endpt()
+{
+    pj_str_t ns = { "10.187.27.172", 13};	/* just a random, unreachable IP */
+    pj_dns_resolver *resolver;
+    pj_status_t rc;
+
+    rc = pjsip_endpt_create(&caching_pool.factory, "endpt", &endpt);
+    if (rc != PJ_SUCCESS) {
+	app_perror("pjsip_endpt_create", rc);
+	return rc;
+    }
+
+    /* Start transaction layer module. */
+    rc = pjsip_tsx_layer_init_module(endpt);
+    if (rc != PJ_SUCCESS) {
+	app_perror("tsx_layer_init", rc);
+	return rc;
+    }
+
+    rc = pjsip_udp_transport_start(endpt, NULL, NULL, 1,  NULL);
+    if (rc != PJ_SUCCESS) {
+	app_perror("udp init", rc);
+	return rc;
+    }
+
+    rc = pjsip_tcp_transport_start(endpt, NULL, 1, NULL);
+    if (rc != PJ_SUCCESS) {
+	app_perror("tcp init", rc);
+	return rc;
+    }
+
+    rc = pjsip_endpt_create_resolver(endpt, &resolver);
+    if (rc != PJ_SUCCESS) {
+	app_perror("create resolver", rc);
+	return rc;
+    }
+
+    pj_dns_resolver_set_ns(resolver, 1, &ns, NULL);
+
+    rc = pjsip_endpt_set_resolver(endpt, resolver);
+    if (rc != PJ_SUCCESS) {
+	app_perror("set resolver", rc);
+	return rc;
+    }
+
+    return PJ_SUCCESS;
+}
+
+static int tsx_create_and_send_req(void *arg)
+{
+    pj_str_t dst_uri = pj_str((char*)arg);
+    pj_str_t from_uri = pj_str((char*)"<sip:user@host>");
+    pjsip_tx_data *tdata;
+    pj_status_t status;
+
+    status = pjsip_endpt_create_request(endpt, &pjsip_options_method,
+                                        &dst_uri, &from_uri, &dst_uri,
+                                        NULL, NULL, -1, NULL,
+                                        &tdata);
+    if (status != PJ_SUCCESS)
+	return status;
+
+    status = pjsip_endpt_send_request(endpt, tdata, -1, NULL, NULL);
+    if (status != PJ_SUCCESS)
+	return status;
+
+    return PJ_SUCCESS;
+}
+
+int tsx_destroy_test()
+{
+    struct tsx_test_state state;
+    struct test_desc
+    {
+	const char *title;
+	int (*func)(void*);
+	void *arg;
+	int sleep_before_unload;
+	int sleep_after_unload;
+    } test_entries[] =
+    {
+	{
+	    "normal unable to resolve",
+	    &tsx_create_and_send_req,
+	    "sip:user@somehost",
+	    10000,
+	    1
+	},
+	{
+	    "resolve and destroy, wait",
+	    &tsx_create_and_send_req,
+	    "sip:user@somehost",
+	    1,
+	    10000
+	},
+	{
+	    "tcp connect and destroy",
+	    &tsx_create_and_send_req,
+	    "sip:user@10.125.36.63:58517;transport=tcp",
+	    60000,
+	    1000
+	},
+	{
+	    "tcp connect and destroy",
+	    &tsx_create_and_send_req,
+	    "sip:user@10.125.36.63:58517;transport=tcp",
+	    1,
+	    60000
+	},
+
+    };
+    int rc;
+    unsigned i;
+    const int INDENT = 2;
+
+    pj_log_add_indent(INDENT);
+    destroy_endpt();
+
+    for (i=0; i<PJ_ARRAY_SIZE(test_entries); ++i) {
+	struct test_desc *td = &test_entries[i];
+
+	PJ_LOG(3,(THIS_FILE, "%s", td->title));
+
+	pj_log_add_indent(INDENT);
+	save_tsx_test_state(&state);
+
+	rc = init_endpt();
+	if (rc != PJ_SUCCESS) {
+	    pj_log_add_indent(-INDENT*2);
+	    return -10;
+	}
+
+	rc = td->func(td->arg);
+	if (rc != PJ_SUCCESS) {
+	    pj_log_add_indent(-INDENT*2);
+	    return -20;
+	}
+
+	flush_events(td->sleep_before_unload);
+	pjsip_tsx_layer_destroy();
+	flush_events(td->sleep_after_unload);
+	destroy_endpt();
+
+	rc = check_tsx_test_state(&state);
+	if (rc != PJ_SUCCESS) {
+	    init_endpt();
+	    pj_log_add_indent(-INDENT*2);
+	    return -30;
+	}
+
+	pj_log_add_indent(-INDENT);
+    }
+
+    init_endpt();
+
+    pj_log_add_indent(-INDENT);
+    return 0;
+}
+
Index: /pjproject/trunk/pjsip/src/test/tsx_bench.c
===================================================================
--- /pjproject/trunk/pjsip/src/test/tsx_bench.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/test/tsx_bench.c	(revision 4420)
@@ -80,6 +80,11 @@
     for (i=0; i<working_set; ++i) {
 	if (tsx[i]) {
+	    pj_timer_heap_t *th;
+
 	    pjsip_tsx_terminate(tsx[i], 601);
 	    tsx[i] = NULL;
+
+	    th = pjsip_endpt_get_timer_heap(endpt);
+	    pj_timer_heap_poll(th, NULL);
 	}
     }
@@ -178,6 +183,12 @@
     for (i=0; i<working_set; ++i) {
 	if (tsx[i]) {
+	    pj_timer_heap_t *th;
+
 	    pjsip_tsx_terminate(tsx[i], 601);
 	    tsx[i] = NULL;
+
+	    th = pjsip_endpt_get_timer_heap(endpt);
+	    pj_timer_heap_poll(th, NULL);
+
 	}
     }
@@ -209,4 +220,6 @@
 	PJ_LOG(3,(THIS_FILE, "    test %d of %d..",
 		  i+1, REPEAT));
+	PJ_LOG(3,(THIS_FILE, "    number of current tsx: %d",
+		  pjsip_tsx_layer_get_tsx_count()));
 	status = uac_tsx_bench(WORKING_SET, &usec[i]);
 	if (status != PJ_SUCCESS)
@@ -247,4 +260,6 @@
 	PJ_LOG(3,(THIS_FILE, "    test %d of %d..",
 		  i+1, REPEAT));
+	PJ_LOG(3,(THIS_FILE, "    number of current tsx: %d",
+		  pjsip_tsx_layer_get_tsx_count()));
 	status = uas_tsx_bench(WORKING_SET, &usec[i]);
 	if (status != PJ_SUCCESS)
Index: /pjproject/trunk/pjsip/src/test/tsx_uac_test.c
===================================================================
--- /pjproject/trunk/pjsip/src/test/tsx_uac_test.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/test/tsx_uac_test.c	(revision 4420)
@@ -221,8 +221,11 @@
 
 	    /* Test the status code. */
-	    if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR) {
-		PJ_LOG(3,(THIS_FILE, 
-			  "    error: status code is %d instead of %d",
-			  tsx->status_code, PJSIP_SC_TSX_TRANSPORT_ERROR));
+	    if (tsx->status_code != PJSIP_SC_TSX_TRANSPORT_ERROR &&
+		tsx->status_code != PJSIP_SC_BAD_GATEWAY)
+	    {
+		PJ_LOG(3,(THIS_FILE, 
+			  "    error: status code is %d instead of %d or %d",
+			  tsx->status_code, PJSIP_SC_TSX_TRANSPORT_ERROR,
+			  PJSIP_SC_BAD_GATEWAY));
 		test_complete = -720;
 	    }
@@ -689,5 +692,5 @@
 	    if (tsx) {
 		pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED);
-		pj_mutex_unlock(tsx->mutex);
+		pj_grp_lock_release(tsx->grp_lock);
 	    } else {
 		PJ_LOG(3,(THIS_FILE, "    error: uac transaction not found!"));
@@ -1028,5 +1031,5 @@
 	if (tsx) {
 	    pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED);
-	    pj_mutex_unlock(tsx->mutex);
+	    pj_grp_lock_release(tsx->grp_lock);
 	    flush_events(1000);
 	}
Index: /pjproject/trunk/pjsip/src/test/tsx_uas_test.c
===================================================================
--- /pjproject/trunk/pjsip/src/test/tsx_uas_test.c	(revision 4419)
+++ /pjproject/trunk/pjsip/src/test/tsx_uas_test.c	(revision 4420)
@@ -226,10 +226,10 @@
 	// Some tests do expect failure!
 	//PJ_LOG(3,(THIS_FILE,"    error: timer unable to send response"));
-	pj_mutex_unlock(tsx->mutex);
+	pj_grp_lock_release(tsx->grp_lock);
 	pjsip_tx_data_dec_ref(r->tdata);
 	return;
     }
 
-    pj_mutex_unlock(tsx->mutex);
+    pj_grp_lock_release(tsx->grp_lock);
 }
 
@@ -314,5 +314,5 @@
 
     pjsip_tsx_terminate(tsx, status_code);
-    pj_mutex_unlock(tsx->mutex);
+    pj_grp_lock_release(tsx->grp_lock);
 }
 
@@ -1260,5 +1260,5 @@
 	if (tsx) {
 	    pjsip_tsx_terminate(tsx, PJSIP_SC_REQUEST_TERMINATED);
-	    pj_mutex_unlock(tsx->mutex);
+	    pj_grp_lock_release(tsx->grp_lock);
 	    flush_events(1000);
 	}
