1 /*
   2  * Copyright (c) 2017, 2019, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #ifndef SHARE_GC_SHENANDOAH_SHENANDOAHLOCK_HPP
  25 #define SHARE_GC_SHENANDOAH_SHENANDOAHLOCK_HPP
  26 
  27 #include "gc/shenandoah/shenandoahPadding.hpp"
  28 #include "memory/allocation.hpp"
  29 #include "runtime/thread.hpp"
  30 
  31 class ShenandoahLock  {
  32 private:
  33   enum LockState { unlocked = 0, locked = 1 };
  34 
  35   shenandoah_padding(0);
  36   volatile int _state;
  37   shenandoah_padding(1);
  38   volatile Thread* _owner;
  39   shenandoah_padding(2);
  40 
  41 public:
  42   ShenandoahLock() : _state(unlocked), _owner(NULL) {};
  43 
  44   void lock() {
  45 #ifdef ASSERT
  46     assert(_owner != Thread::current(), "reentrant locking attempt, would deadlock");
  47 #endif
  48     Thread::SpinAcquire(&_state, "Shenandoah Heap Lock");
  49 #ifdef ASSERT
  50     assert(_state == locked, "must be locked");
  51     assert(_owner == NULL, "must not be owned");
  52     _owner = Thread::current();
  53 #endif
  54   }
  55 
  56   void unlock() {
  57 #ifdef ASSERT
  58     assert (_owner == Thread::current(), "sanity");
  59     _owner = NULL;
  60 #endif
  61     Thread::SpinRelease(&_state);
  62   }
  63 
  64   bool owned_by_self() {
  65 #ifdef ASSERT
  66     return _state == locked && _owner == Thread::current();
  67 #else
  68     ShouldNotReachHere();
  69     return false;
  70 #endif
  71   }
  72 };
  73 
  74 class ShenandoahLocker : public StackObj {
  75 private:
  76   ShenandoahLock* const _lock;
  77 public:
  78   ShenandoahLocker(ShenandoahLock* lock) : _lock(lock) {
  79     if (_lock != NULL) {
  80       _lock->lock();
  81     }
  82   }
  83 
  84   ~ShenandoahLocker() {
  85     if (_lock != NULL) {
  86       _lock->unlock();
  87     }
  88   }
  89 };
  90 
  91 #endif // SHARE_VM_GC_SHENANDOAH_SHENANDOAHLOCK_HPP