1 /*
 2  * Copyright (c) 2019, Red Hat, Inc. All rights reserved.
 3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 4  *
 5  * This code is free software; you can redistribute it and/or modify it
 6  * under the terms of the GNU General Public License version 2 only, as
 7  * published by the Free Software Foundation.
 8  *
 9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 
27 #include "runtime/os.hpp"
28 
29 #include "gc/shenandoah/shenandoahLock.hpp"
30 #include "runtime/atomic.hpp"
31 #include "runtime/javaThread.hpp"
32 #include "runtime/os.inline.hpp"
33 
34 ShenandoahSimpleLock::ShenandoahSimpleLock() {
35   assert(os::mutex_init_done(), "Too early!");
36 }
37 
38 void ShenandoahSimpleLock::lock() {
39   _lock.lock();
40 }
41 
42 void ShenandoahSimpleLock::unlock() {
43   _lock.unlock();
44 }
45 
46 ShenandoahReentrantLock::ShenandoahReentrantLock() :
47   ShenandoahSimpleLock(), _owner(nullptr), _count(0) {
48   assert(os::mutex_init_done(), "Too early!");
49 }
50 
51 ShenandoahReentrantLock::~ShenandoahReentrantLock() {
52   assert(_count == 0, "Unbalance");
53 }
54 
55 void ShenandoahReentrantLock::lock() {
56   Thread* const thread = Thread::current();
57   Thread* const owner = Atomic::load(&_owner);
58 
59   if (owner != thread) {
60     ShenandoahSimpleLock::lock();
61     Atomic::store(&_owner, thread);
62   }
63 
64   _count++;
65 }
66 
67 void ShenandoahReentrantLock::unlock() {
68   assert(owned_by_self(), "Invalid owner");
69   assert(_count > 0, "Invalid count");
70 
71   _count--;
72 
73   if (_count == 0) {
74     Atomic::store(&_owner, (Thread*)nullptr);
75     ShenandoahSimpleLock::unlock();
76   }
77 }
78 
79 bool ShenandoahReentrantLock::owned_by_self() const {
80   Thread* const thread = Thread::current();
81   Thread* const owner = Atomic::load(&_owner);
82   return owner == thread;
83 }