title: Is it safe to spin lock list_for_each_entry_safe or list_for_each_entry?
body: <p>I want to add things to my list, and if something already exists in the list I want to remove it before re-adding it. This is just an exercise that I'm trying out for myself (I know, there is no practical purpose to doing something like this)</p>
  <pre><code>spin_lock(&amp;mylock);
  bool added = false
  list_for_each_entry_safe(cur, nxt, &amp;mylist.entries, entries)
  {
      //Check to see if cur == the item I want to add, if it is add it and set my bool to true
  }
  
  //Check to see if my bool is true. If it's false, add the item to the list
  
  spin_unlock(&amp;mylock);
  
  </code></pre>
  <p>Is this unsafe? The problem is I cannot figure out how to put the spin locks anywhere else without the creating a race condition. For example if I did this</p>
  <pre><code>list_for_each_entry_safe(cur, nxt, &amp;mylist.entries, entries)
  {
  spin_lock(&amp;mylock);
  
      //Check to see if cur == the item I want to add, if it is add it and set my bool to true
  
  spin_unlock(&amp;mylock);
  }
  
  //race condition here
  
  spin_lock(&amp;mylock);
  
  //Check to see if my bool is true. If it's false, add the item to the list 
  
  spin_unlock(&amp;mylock);
  
  </code></pre>
  <p>There could be a race condition where I commented &quot;race condition here&quot;, because some other thread could add the item, and then I wouldn't know and the current thread would add the item again, so there would be a duplicate item in the list.</p>
  <p>The issue is I don't know if it's ok or not to have an entire list_for_each_entry inside the critical section of a spin lock?</p>