diff --git a/sys/kern/uipc_socket.c b/sys/kern/uipc_socket.c --- a/sys/kern/uipc_socket.c +++ b/sys/kern/uipc_socket.c @@ -565,6 +565,7 @@ so->so_snd.sb_mtx = &so->so_snd_mtx; so->so_rcv.sb_mtx = &so->so_rcv_mtx; } + refcount_init(&so->so_count, 1); /* * Auto-sizing of socket buffers is managed by the protocols and * the appropriate flags must be set in the pru_attach function. @@ -573,10 +574,10 @@ error = prp->pr_attach(so, proto, td); CURVNET_RESTORE(); if (error) { + refcount_init(&so->so_count, 0); sodealloc(so); return (error); } - soref(so); *aso = so; return (0); } diff --git a/sys/sys/socketvar.h b/sys/sys/socketvar.h --- a/sys/sys/socketvar.h +++ b/sys/sys/socketvar.h @@ -343,7 +343,11 @@ * Note that you must still explicitly close the socket, but the last ref * count will free the structure. */ -#define soref(so) refcount_acquire(&(so)->so_count) +#define soref(so) do { \ + u_int __old __diagused; \ + __old = refcount_acquire(&(so)->so_count); \ + KASSERT(__old > 0, ("%s: refcount is 0", __func__)); \ +} while (0) #define sorele(so) do { \ SOCK_UNLOCK_ASSERT(so); \ if (!refcount_release_if_not_last(&(so)->so_count)) { \