1 // SPDX-License-Identifier: CDDL-1.0 2 /* 3 * CDDL HEADER START 4 * 5 * The contents of this file are subject to the terms of the 6 * Common Development and Distribution License (the "License"). 7 * You may not use this file except in compliance with the License. 8 * 9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 10 * or https://opensource.org/licenses/CDDL-1.0. 11 * See the License for the specific language governing permissions 12 * and limitations under the License. 13 * 14 * When distributing Covered Code, include this CDDL HEADER in each 15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 16 * If applicable, add the following below this CDDL HEADER, with the 17 * fields enclosed by brackets "[]" replaced with your own identifying 18 * information: Portions Copyright [yyyy] [name of copyright owner] 19 * 20 * CDDL HEADER END 21 */ 22 /* 23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. 24 * Copyright (c) 2012, 2018 by Delphix. All rights reserved. 25 * Copyright (c) 2016 Actifio, Inc. All rights reserved. 26 * Copyright (c) 2025, Klara, Inc. 27 */ 28 29 #include <assert.h> 30 #include <pthread.h> 31 #include <errno.h> 32 #include <atomic.h> 33 #include <sys/rwlock.h> 34 35 /* 36 * ========================================================================= 37 * rwlocks 38 * ========================================================================= 39 */ 40 41 void 42 rw_init(krwlock_t *rwlp, char *name, int type, void *arg) 43 { 44 (void) name, (void) type, (void) arg; 45 VERIFY0(pthread_rwlock_init(&rwlp->rw_lock, NULL)); 46 rwlp->rw_readers = 0; 47 rwlp->rw_owner = 0; 48 } 49 50 void 51 rw_destroy(krwlock_t *rwlp) 52 { 53 VERIFY0(pthread_rwlock_destroy(&rwlp->rw_lock)); 54 } 55 56 void 57 rw_enter(krwlock_t *rwlp, krw_t rw) 58 { 59 if (rw == RW_READER) { 60 VERIFY0(pthread_rwlock_rdlock(&rwlp->rw_lock)); 61 atomic_inc_uint(&rwlp->rw_readers); 62 } else { 63 VERIFY0(pthread_rwlock_wrlock(&rwlp->rw_lock)); 64 rwlp->rw_owner = pthread_self(); 65 } 66 } 67 68 void 69 rw_exit(krwlock_t *rwlp) 70 { 71 if (RW_READ_HELD(rwlp)) 72 atomic_dec_uint(&rwlp->rw_readers); 73 else 74 rwlp->rw_owner = 0; 75 76 VERIFY0(pthread_rwlock_unlock(&rwlp->rw_lock)); 77 } 78 79 int 80 rw_tryenter(krwlock_t *rwlp, krw_t rw) 81 { 82 int error; 83 84 if (rw == RW_READER) 85 error = pthread_rwlock_tryrdlock(&rwlp->rw_lock); 86 else 87 error = pthread_rwlock_trywrlock(&rwlp->rw_lock); 88 89 if (error == 0) { 90 if (rw == RW_READER) 91 atomic_inc_uint(&rwlp->rw_readers); 92 else 93 rwlp->rw_owner = pthread_self(); 94 95 return (1); 96 } 97 98 VERIFY3S(error, ==, EBUSY); 99 100 return (0); 101 } 102 103 int 104 rw_tryupgrade(krwlock_t *rwlp) 105 { 106 (void) rwlp; 107 return (0); 108 } 109