Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 12 May 2019 06:32:46 +0000 (UTC)
From:      Mateusz Guzik <mjg@FreeBSD.org>
To:        src-committers@freebsd.org, svn-src-all@freebsd.org, svn-src-head@freebsd.org
Subject:   svn commit: r347500 - head/sys/libkern
Message-ID:  <201905120632.x4C6Wkmr093871@repo.freebsd.org>

next in thread | raw e-mail | index | archive | help
Author: mjg
Date: Sun May 12 06:32:46 2019
New Revision: 347500
URL: https://svnweb.freebsd.org/changeset/base/347500

Log:
  random(4): depessimize arc4random
  
  - __predict_false reseeding on entry as it is almost never true.
  - don't blindly atomic_cmpset as on x86 it ends up dirtying the cacheline.
  it almost ever succeeds per above
  - fetch the timestamp prior to getting the cpu number
  
  Reviewed by:	cem
  Approved by:	secteam (delphij)
  Sponsored by:	The FreeBSD Foundation
  Differential Revision:	https://reviews.freebsd.org/D20242

Modified:
  head/sys/libkern/arc4random.c

Modified: head/sys/libkern/arc4random.c
==============================================================================
--- head/sys/libkern/arc4random.c	Sat May 11 22:58:25 2019	(r347499)
+++ head/sys/libkern/arc4random.c	Sun May 12 06:32:46 2019	(r347500)
@@ -173,18 +173,20 @@ arc4rand(void *ptr, u_int len, int reseed)
 	u_int length;
 	u_int8_t *p;
 
-	if (reseed || atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_HAVE, ARC4_ENTR_SEED))
+	if (__predict_false(reseed ||
+	    (arc4rand_iniseed_state == ARC4_ENTR_HAVE &&
+	    atomic_cmpset_int(&arc4rand_iniseed_state, ARC4_ENTR_HAVE, ARC4_ENTR_SEED))))
 		CHACHA20_FOREACH(chacha20)
 			chacha20_randomstir(chacha20);
 
-	chacha20 = &chacha20inst[curcpu];
 	getmicrouptime(&tv);
+	chacha20 = &chacha20inst[curcpu];
 	/* We may get unlucky and be migrated off this CPU, but that is expected to be infrequent */
 	if ((chacha20->numbytes > CHACHA20_RESEED_BYTES) || (tv.tv_sec > chacha20->t_reseed))
 		chacha20_randomstir(chacha20);
 
-	mtx_lock(&chacha20->mtx);
 	p = ptr;
+	mtx_lock(&chacha20->mtx);
 	while (len) {
 		length = MIN(CHACHA20_BUFFER_SIZE, len);
 		chacha_encrypt_bytes(&chacha20->ctx, chacha20->m_buffer, p, length);



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?201905120632.x4C6Wkmr093871>