Path: blob/main/sys/contrib/openzfs/lib/libspl/rwlock.c
96339 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* Common Development and Distribution License (the "License").6* You may not use this file except in compliance with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or https://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/21/*22* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.23* Copyright (c) 2012, 2018 by Delphix. All rights reserved.24* Copyright (c) 2016 Actifio, Inc. All rights reserved.25* Copyright (c) 2025, Klara, Inc.26*/2728#include <assert.h>29#include <pthread.h>30#include <errno.h>31#include <atomic.h>32#include <sys/rwlock.h>3334/*35* =========================================================================36* rwlocks37* =========================================================================38*/3940void41rw_init(krwlock_t *rwlp, char *name, int type, void *arg)42{43(void) name, (void) type, (void) arg;44VERIFY0(pthread_rwlock_init(&rwlp->rw_lock, NULL));45rwlp->rw_readers = 0;46rwlp->rw_owner = 0;47}4849void50rw_destroy(krwlock_t *rwlp)51{52VERIFY0(pthread_rwlock_destroy(&rwlp->rw_lock));53}5455void56rw_enter(krwlock_t *rwlp, krw_t rw)57{58if (rw == RW_READER) {59VERIFY0(pthread_rwlock_rdlock(&rwlp->rw_lock));60atomic_inc_uint(&rwlp->rw_readers);61} else {62VERIFY0(pthread_rwlock_wrlock(&rwlp->rw_lock));63rwlp->rw_owner = pthread_self();64}65}6667void68rw_exit(krwlock_t *rwlp)69{70if (RW_READ_HELD(rwlp))71atomic_dec_uint(&rwlp->rw_readers);72else73rwlp->rw_owner = 0;7475VERIFY0(pthread_rwlock_unlock(&rwlp->rw_lock));76}7778int79rw_tryenter(krwlock_t *rwlp, krw_t rw)80{81int error;8283if (rw == RW_READER)84error = pthread_rwlock_tryrdlock(&rwlp->rw_lock);85else86error = pthread_rwlock_trywrlock(&rwlp->rw_lock);8788if (error == 0) {89if (rw == RW_READER)90atomic_inc_uint(&rwlp->rw_readers);91else92rwlp->rw_owner = pthread_self();9394return (1);95}9697VERIFY3S(error, ==, EBUSY);9899return (0);100}101102int103rw_tryupgrade(krwlock_t *rwlp)104{105(void) rwlp;106return (0);107}108109110