Revert "bio: remove reference count."

Android uses BIO reference counting.

This reverts commit 9bde6aeb76b1d2a45d76637553c3fb3f31e4ecbd.

Change-Id: Ibf4a7f42477549d10829a424ea3b52f09098666c
Reviewed-on: https://boringssl-review.googlesource.com/4472
Reviewed-by: David Benjamin <davidben@chromium.org>
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/bio/bio.c b/crypto/bio/bio.c
index ad6c259..2fcad6c 100644
--- a/crypto/bio/bio.c
+++ b/crypto/bio/bio.c
@@ -75,6 +75,7 @@
 
   bio->method = method;
   bio->shutdown = 1;
+  bio->references = 1;
 
   if (method->create != NULL && !method->create(bio)) {
     return 0;
@@ -102,6 +103,11 @@
   BIO *next_bio;
 
   for (; bio != NULL; bio = next_bio) {
+    int refs = CRYPTO_add(&bio->references, -1, CRYPTO_LOCK_BIO);
+    if (refs > 0) {
+      return 0;
+    }
+
     if (bio->callback != NULL) {
       int i = (int)bio->callback(bio, BIO_CB_FREE, NULL, 0, 0, 1);
       if (i <= 0) {
diff --git a/include/openssl/bio.h b/include/openssl/bio.h
index f0e2519..84996e9 100644
--- a/include/openssl/bio.h
+++ b/include/openssl/bio.h
@@ -781,6 +781,7 @@
   /* num is a BIO-specific value. For example, in fd BIOs it's used to store a
    * file descriptor. */
   int num;
+  int references;
   void *ptr;
   /* next_bio points to the next |BIO| in a chain. This |BIO| owns a reference
    * to |next_bio|. */