ipsec: Reference count the SAs

- this remove the need to iterate through all state when deleting an SA
- and ensures that if the SA is deleted by the client is remains for use
in any state until that state is also removed.

Type: feature

Change-Id: I438cb67588cb65c701e49a7a9518f88641925419
Signed-off-by: Neale Ranns <nranns@cisco.com>
diff --git a/src/vnet/ipsec/ipsec_spd_policy.c b/src/vnet/ipsec/ipsec_spd_policy.c
index 34b7dc2..6424210 100644
--- a/src/vnet/ipsec/ipsec_spd_policy.c
+++ b/src/vnet/ipsec/ipsec_spd_policy.c
@@ -142,14 +142,6 @@
   u32 spd_index;
   uword *p;
 
-  if (policy->policy == IPSEC_POLICY_ACTION_PROTECT)
-    {
-      p = hash_get (im->sa_index_by_sa_id, policy->sa_id);
-      if (!p)
-	return VNET_API_ERROR_SYSCALL_ERROR_1;
-      policy->sa_index = p[0];
-    }
-
   p = hash_get (im->spd_index_by_spd_id, policy->id);
 
   if (!p)
@@ -164,6 +156,17 @@
     {
       u32 policy_index;
 
+      if (policy->policy == IPSEC_POLICY_ACTION_PROTECT)
+	{
+	  index_t sa_index = ipsec_sa_find_and_lock (policy->sa_id);
+
+	  if (INDEX_INVALID == sa_index)
+	    return VNET_API_ERROR_SYSCALL_ERROR_1;
+	  policy->sa_index = sa_index;
+	}
+      else
+	policy->sa_index = INDEX_INVALID;
+
       pool_get (im->policies, vp);
       clib_memcpy (vp, policy, sizeof (*vp));
       policy_index = vp - im->policies;
@@ -188,6 +191,7 @@
 	if (ipsec_policy_is_equal (vp, policy))
 	  {
 	    vec_del1 (spd->policies[policy->type], ii);
+	    ipsec_sa_unlock (vp->sa_index);
 	    pool_put (im->policies, vp);
 	    break;
 	  }