Bodo Moeller wrote,
> > Second you need to deal with MP cache coherency (Alpha, Itanium,
> > others?). Memory models can be so weak that reads and writes to the
> > same address can be reordered, and a write from a thread on one CPU
> > isn't guaranteed to be immediately visible to a subsequent read
> > from a thread on another.
>
> What do the C standards guarantee if we use 'volatile static'?

They don't say anything about semantics in multi-threaded/processor 
environments.

> > Putting those two together, I think we end up with something like,
> > [...] (nb. adapted from [1], so don't shoot me if I haven't got it
> > exactly right)
>
> Your proposed code can't work as intended (your 'tmp' flag is a local
> copy of 'init', so the second check is redundant).

Hmm ...

Well, looking at Doug Schmidts code (from the book) this is what he does 
too. OTOH, the version here,
  
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html#explicitMemoryBarriers

(which is more recent, so probably more reliable) uses volatile 
differently and has an extra read before the second check, which would 
give us something like this,
  
  SSL_METHOD *SSLv3_client_method(void)
  {
    static volatile int init=1;          /* previously not volatile */
    static SSL_METHOD SSLv3_client_data;

    int tmp = init;                      /* previously volatile */

  #if defined (ALPHA_MP)
    // CPU-specific memory barrier instruction
    asm("mb");
  #endif

    if (tmp)
    {
      CRYPTO_w_lock(CRYPTO_LOCK_SSL_METHOD);

      tmp = init;                        /* added */
      if (tmp)
      {
        memcpy((char *)&SSLv3_client_data,(char *)sslv3_base_method(),
               sizeof(SSL_METHOD));
        SSLv3_client_data.ssl_connect=ssl3_connect;
        SSLv3_client_data.get_ssl_method=ssl3_get_client_method;

  #if defined (ALPHA_MP)
        // CPU-specific memory barrier instruction
        asm("mb");
  #endif

        init=0;

      }

      CRYPTO_w_unlock(CRYPTO_LOCK_SSL_METHOD);
    }
    return(&SSLv3_client_data);
  }

TBH, this is subtle, counter-intuitive, and hard to understand. Which is 
why I'd recommend avoiding this kind of lazy initialization if at all 
possible.

Cheers,


Miles
______________________________________________________________________
OpenSSL Project                                 http://www.openssl.org
Development Mailing List                       [EMAIL PROTECTED]
Automated List Manager                           [EMAIL PROTECTED]

Reply via email to