jslock.c revision 6b15695578f07a3f72c4c9475c1a261a3021472a
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifdef JS_THREADSAFE
/*
* JS locking stubs.
*/
#include "jsstddef.h"
#include <stdlib.h>
#include "jspubtd.h"
#include "prthread.h"
#include "jsutil.h" /* Added by JSIFY */
#include "jstypes.h"
#include "jsbit.h"
#include "jscntxt.h"
#include "jsdtoa.h"
#include "jsgc.h"
#include "jslock.h"
#include "jsscope.h"
#include "jsstr.h"
#define ReadWord(W) (W)
#ifndef NSPR_LOCK
#include <memory.h>
static PRLock **global_locks;
static uint32 global_locks_log2 = 0;
static uint32 global_locks_mask = 0;
static void
js_LockGlobal(void *id)
{
PR_Lock(global_locks[i]);
}
static void
js_UnlockGlobal(void *id)
{
PR_Unlock(global_locks[i]);
}
/* Exclude Alpha NT. */
static JS_INLINE int
{
__asm {
}
}
/* Note: This fails on 386 cpus, cmpxchgl is a >= 486 instruction */
static JS_INLINE int
{
unsigned int res;
"lock\n"
"cmpxchgl %2, (%1)\n"
"sete %%al\n"
"andl $1, %%eax\n"
: "=a" (res)
: "cc", "memory");
return (int)res;
}
static JS_INLINE int
{
#if defined(__GNUC__)
unsigned int res;
asm volatile ("\
stbar\n\
cas [%1],%2,%3\n\
cmp %2,%3\n\
be,a 1f\n\
mov 1,%0\n\
mov 0,%0\n\
1:"
: "=r" (res)
return (int)res;
#else /* !__GNUC__ */
#endif
}
#include <sys/atomic_op.h>
static JS_INLINE int
{
}
#else
#error "Define NSPR_LOCK if your platform lacks a compare-and-swap instruction."
#endif /* arch-tests */
#endif /* !NSPR_LOCK */
{
return CurrentThreadId();
}
void
{
#ifdef NSPR_LOCK
#else
#endif
}
void
{
#ifdef NSPR_LOCK
#else
#endif
}
static void js_Dequeue(JSThinLock *);
#ifdef DEBUG_SCOPE_COUNT
#include <stdio.h>
#include "jsdhash.h"
static JSDHashTable logtbl;
typedef struct logentry {
char op;
const char *file;
int line;
} logentry;
static void
{
if (!logfp) {
if (!logfp)
return;
}
if (!logtbl.entryStore &&
sizeof(logentry), 100)) {
return;
}
if (!entry)
return;
}
void
{
if (!logtbl.entryStore)
return;
}
#else
#endif /* DEBUG_SCOPE_COUNT */
/*
* Return true if scope's ownercx, or the ownercx of a single-threaded scope
* for which ownercx is waiting to become multi-threaded and shared, is cx.
* That condition implies deadlock in ClaimScope if cx's thread were to wait
* to share scope.
*
* (i) rt->gcLock held
*/
static JSBool
{
do {
return JS_TRUE;
}
return JS_FALSE;
}
/*
* Make scope multi-threaded, i.e. share its ownership among contexts in rt
* using a "thin" or (if necessary due to contention) "fat" lock. Called only
* from ClaimScope, immediately below, when we detect deadlock were we to wait
* for scope's lock, because its ownercx is waiting on a scope owned by the
* calling cx.
*
* (i) rt->gcLock held
*/
static void
{
}
}
/*
* Nesting locks on another thread that's using scope->ownercx: give
* the held lock a reentrancy count of 1 and set its lock.owner field
* directly (no compare-and-swap needed while scope->ownercx is still
* non-null). See below in ClaimScope, before the ShareScope call,
* for more on why this is necessary.
*
* If NSPR_LOCK is defined, we cannot deadlock holding rt->gcLock and
* acquiring scope->lock.fat here, against another thread holding that
* fat lock and trying to grab rt->gcLock. This is because no other
* thread can attempt to acquire scope->lock.fat until scope->ownercx
* is null *and* our thread has released rt->gcLock, which interlocks
* scope->ownercx's transition to null against tests of that member
* in ClaimScope.
*/
#ifdef NSPR_LOCK
#endif
} else {
}
}
/*
* js_FinishSharingScope is the tail part of ShareScope, split out to become a
* subroutine of JS_EndRequest too. The bulk of the work here involves making
* mutable strings in the scope's object's slots be immutable. We have to do
* this because such strings will soon be available to multiple threads, so
* their buffers can't be realloc'd any longer in js_ConcatStrings, and their
* members can't be modified by js_ConcatStrings, js_MinimizeDependentStrings,
* or js_UndependString.
*
* The last bit of work done by js_FinishSharingScope nulls scope->ownercx and
* updates rt->sharedScopes.
*/
if (*flagp_ & GCF_MUTABLE) { \
if (JSSTRING_IS_DEPENDENT(str_) && \
*vp = JSVAL_VOID; \
} else { \
*flagp_ &= ~GCF_MUTABLE; \
} \
} \
void
{
v = *vp;
if (JSVAL_IS_STRING(v))
}
}
/*
* Given a scope with apparently non-null ownercx different from cx, try to
* set ownercx to cx, claiming exclusive (single-threaded) ownership of scope.
* If we claim ownership, return true. Otherwise, we wait for ownercx to be
* set to null (indicating that scope is multi-threaded); or if waiting would
* deadlock, we set ownercx to null ourselves via ShareScope. In any case,
* once ownercx is null we return false.
*/
static JSBool
{
JS_LOCK_GC(rt);
/* Reload in case ownercx went away while we blocked on the lock. */
/*
* Avoid selflock if ownercx is dead, or is not running a request, or
* has the same thread as cx. Set scope->ownercx to cx so that the
* matching JS_UNLOCK_SCOPE or JS_UNLOCK_OBJ macro call will take the
* fast path around the corresponding js_UnlockScope or js_UnlockObj
* function call.
*
* If scope->u.link is non-null, scope has already been inserted on
* the rt->scopeSharingTodo list, because another thread's context
* already wanted to lock scope while ownercx was running a request.
* We can't claim any scope whose u.link is non-null at this point,
* even if ownercx->requestDepth is 0 (see below where we suspend our
* request before waiting on rt->scopeSharingDone).
*/
!ownercx->requestDepth ||
return JS_TRUE;
}
/*
* Avoid deadlock if scope's owner context is waiting on a scope that
* we own, by revoking scope's ownership. This approach to deadlock
* avoidance works because the engine never nests scope locks, except
* for the notable case of js_SetProtoOrParent (see jsobj.c).
*
* If cx could hold locks on ownercx->scopeToShare, or if ownercx
* could hold locks on scope, we would need to keep reentrancy counts
* for all such "flyweight" (ownercx != NULL) locks, so that control
* would unwind properly once these locks became "thin" or "fat".
* Apart from the js_SetProtoOrParent exception, the engine promotes
* a scope from exclusive to shared access only when locking, never
* when holding or unlocking.
*
* If ownercx's thread is calling js_SetProtoOrParent, trying to lock
* the inner scope (the scope of the object being set as the prototype
* of the outer object), ShareScope will find the outer object's scope
* at rt->setSlotScope. If it's the same as scope, we give it a lock
* held by ownercx's thread with reentrancy count of 1, then we return
* here and break. After that we unwind to js_[GS]etSlotThreadSafe or
* js_LockScope (our caller), where we wait on the newly-fattened lock
* until ownercx's thread unwinds from js_SetProtoOrParent.
*
* cx is on the active GC's thread, because in that case, no requests
* will run until the GC completes. Any scope wanted by the GC (from
* a finalizer) that can't be claimed must be slated for sharing.
*/
(ownercx->scopeToShare &&
break;
}
/*
* Thanks to the non-zero NO_SCOPE_SHARING_TODO link terminator, we
* can decide whether scope is on rt->scopeSharingTodo with a single
* non-null test, and avoid double-insertion bugs.
*/
}
/*
* Inline JS_SuspendRequest before we wait on rt->scopeSharingDone,
* saving and clearing cx->requestDepth so we don't deadlock if the
* GC needs to run on ownercx.
*
* Unlike JS_SuspendRequest and JS_EndRequest, we must take care not
* to decrement rt->requestCount if cx is active on the GC's thread,
* because the GC has already reduced rt->requestCount to exclude all
* such such contexts.
*/
if (saveDepth) {
cx->requestDepth = 0;
rt->requestCount--;
if (rt->requestCount == 0)
}
}
/*
* We know that some other thread's context owns scope, which is now
* linked onto rt->scopeSharingTodo, awaiting the end of that other
* thread's request. So it is safe to wait on rt->scopeSharingDone.
*/
/*
* Inline JS_ResumeRequest after waiting on rt->scopeSharingDone,
* restoring cx->requestDepth. Same note as above for the inlined,
* specialized JS_SuspendRequest code: beware rt->gcThread.
*/
if (saveDepth) {
rt->requestCount++;
}
}
/*
* Don't clear cx->scopeToShare until after we're through waiting on
* all condition variables protected by rt->gcLock -- that includes
* rt->scopeSharingDone *and* rt->gcDone (hidden in JS_AWAIT_GC_DONE,
* in the inlined JS_ResumeRequest code immediately above).
*
* Otherwise, the GC could easily deadlock with another thread that
* owns a scope wanted by a finalizer. By keeping cx->scopeToShare
* set till here, we ensure that such deadlocks are detected, which
* results in the finalized object's scope being shared (it must, of
* course, have other, live objects sharing it).
*/
}
return JS_FALSE;
}
/* Exported to js.c, which calls it via OBJ_GET_* and JSVAL_IS_* macros. */
{
jsval v;
#ifndef NSPR_LOCK
JSThinLock *tl;
#endif
/*
* We handle non-native objects via JSObjectOps.getRequiredSlot, treating
* all slots starting from 0 as required slots. A property definition or
* some prior arrangement must have allocated slot.
*
* Note once again (see jspubtd.h, before JSGetRequiredSlotOp's typedef)
* the crucial distinction between a |required slot number| that's passed
* to the get/setRequiredSlot JSObjectOps, and a |reserved slot index|
* passed to the JS_Get/SetReservedSlot APIs.
*/
if (!OBJ_IS_NATIVE(obj))
/*
* Native object locking is inlined here to optimize the single-threaded
* and contention-free multi-threaded cases.
*/
/*
* Avoid locking if called from the GC (see GC_AWARE_GET_SLOT in jsobj.h).
* Also avoid locking an object owning a sealed scope. If neither of those
* special cases applies, try to claim scope's flyweight lock from whatever
* context may have had it in an earlier request.
*/
if (CX_THREAD_IS_RUNNING_GC(cx) ||
}
#ifndef NSPR_LOCK
/*
* Got the lock with one compare-and-swap. Even so, someone else may
* have mutated obj so it now has its own scope and lock, which would
* require either a restart from the top of this routine, or a thin
* lock release followed by fat lock acquisition.
*/
/* Assert that scope locks never revert to flyweight. */
}
return v;
}
js_Dequeue(tl);
}
}
#endif
/*
* Test whether cx took ownership of obj's scope during js_LockObj.
*
* This does not mean that a given scope reverted to flyweight from "thin"
* or "fat" -- it does mean that obj's map pointer changed due to another
* thread setting a property, requiring obj to cease sharing a prototype
* object's scope (whose lock was not flyweight, else we wouldn't be here
* in the first place!).
*/
return v;
}
void
{
#ifndef NSPR_LOCK
JSThinLock *tl;
#endif
/* Any string stored in a thread-safe object must be immutable. */
if (JSVAL_IS_STRING(v))
/*
* We handle non-native objects via JSObjectOps.setRequiredSlot, as above
* for the Get case.
*/
if (!OBJ_IS_NATIVE(obj)) {
return;
}
/*
* Native object locking is inlined here to optimize the single-threaded
* and contention-free multi-threaded cases.
*/
/*
* Avoid locking if called from the GC (see GC_AWARE_GET_SLOT in jsobj.h).
* Also avoid locking an object owning a sealed scope. If neither of those
* special cases applies, try to claim scope's flyweight lock from whatever
* context may have had it in an earlier request.
*/
if (CX_THREAD_IS_RUNNING_GC(cx) ||
return;
}
#ifndef NSPR_LOCK
/* Assert that scope locks never revert to flyweight. */
}
return;
}
js_Dequeue(tl);
}
return;
}
#endif
/*
* Same drill as above, in js_GetSlotThreadSafe. Note that we cannot
* assume obj has its own mutable scope (where scope->object == obj) yet,
* because OBJ_SET_SLOT is called for the "universal", common slots such
* as JSSLOT_PROTO and JSSLOT_PARENT, without a prior js_GetMutableScope.
* See also the JSPROP_SHARED attribute and its usage.
*/
}
#ifndef NSPR_LOCK
static JSFatLock *
{
return fl;
}
static void
{
}
static JSFatLock *
ListOfFatlocks(int listc)
{
JSFatLock *m;
int i;
m0 = m = NewFatlock();
for (i=1; i<listc; i++) {
m->next = NewFatlock();
m = m->next;
}
return m0;
}
static void
{
for (; m; m=m0) {
DestroyFatlock(m);
}
}
static uint32 fl_list_table_len = 0;
static uint32 fl_list_chunk_len = 0;
static JSFatLock *
GetFatlock(void *id)
{
JSFatLock *m;
#ifdef DEBUG
if (fl_list_table[i].taken)
printf("Ran out of fat locks!\n");
#endif
}
m = fl_list_table[i].free;
m->susp = 0;
if (fl_list_table[i].taken)
fl_list_table[i].taken = m;
return m;
}
static void
{
uint32 i;
if (m == NULL)
return;
/* Unlink m from fl_list_table[i].taken. */
if (m->next)
/* Insert m in fl_list_table[i].free. */
i = GLOBAL_LOCK_INDEX(id);
fl_list_table[i].free = m;
}
#endif /* !NSPR_LOCK */
{
#ifndef NSPR_LOCK
uint32 i;
if (global_locks)
return JS_TRUE;
#ifdef DEBUG
#endif
if (!global_locks)
return JS_FALSE;
for (i = 0; i < global_lock_count; i++) {
global_locks[i] = PR_NewLock();
if (!global_locks[i]) {
global_lock_count = i;
return JS_FALSE;
}
}
if (!fl_list_table) {
return JS_FALSE;
}
for (i = 0; i < global_lock_count; i++)
#endif /* !NSPR_LOCK */
return JS_TRUE;
}
void
{
#ifndef NSPR_LOCK
uint32 i;
if (global_locks) {
for (i = 0; i < global_lock_count; i++)
global_locks = NULL;
global_lock_count = 1;
global_locks_log2 = 0;
global_locks_mask = 0;
}
if (fl_list_table) {
for (i = 0; i < fl_list_table_len; i++) {
}
fl_list_table_len = 0;
}
#endif /* !NSPR_LOCK */
}
void
{
}
#ifndef NSPR_LOCK
/*
* Fast locking and unlocking is implemented by delaying the allocation of a
* system lock (fat lock) until contention. As long as a locking thread A
* runs uncontended, the lock is represented solely by storing A's identity in
* the object being locked.
*
* If another thread B tries to lock the object currently locked by A, B is
* enqueued into a fat lock structure (which might have to be allocated and
* pointed to by the object), and suspended using NSPR conditional variables
* (wait). A wait bit (Bacon bit) is set in the lock word of the object,
* signalling to A that when releasing the lock, B must be dequeued and
* notified.
*
* The basic operation of the locking primitives (js_Lock, js_Unlock,
* js_Enqueue, and js_Dequeue) is compare-and-swap. Hence, when locking into
* the word pointed at by p, compare-and-swap(p, 0, A) success implies that p
* is unlocked. Similarly, when unlocking p, if compare-and-swap(p, A, 0)
* succeeds this implies that p is uncontended (no one is waiting because the
* wait bit is not set).
*
* When dequeueing, the lock is released, and one of the threads suspended on
* the lock is notified. If other threads still are waiting, the wait bit is
* kept (in js_Enqueue), and if not, the fat lock is deallocated.
*
* The functions js_Enqueue, js_Dequeue, js_SuspendThread, and js_ResumeThread
* are serialized using a global lock. For scalability, a hashtable of global
* locks is used, which is indexed modulo the thin lock pointer.
*/
/*
* Invariants:
* (i) global lock is held
* (ii) fl->susp >= 0
*/
static int
{
else
}
}
/*
* (i) global lock is held
* (ii) fl->susp > 0
*/
static void
{
}
static void
{
jsword o, n;
for (;;) {
n = Thin_SetWait(o);
if (js_SuspendThread(tl))
else
}
return;
}
}
}
static void
{
jsword o;
JS_ASSERT(Thin_GetWait(o) != 0);
JS_ASSERT(0);
}
JS_INLINE void
{
return;
#ifdef DEBUG
else
JS_ASSERT(0);
#endif
}
JS_INLINE void
{
return;
js_Dequeue(tl);
#ifdef DEBUG
else
JS_ASSERT(0);
#endif
}
#endif /* !NSPR_LOCK */
void
{
#ifdef DEBUG
#endif
}
void
{
#ifdef DEBUG
rt->rtLockOwner = 0;
#endif
}
void
{
if (CX_THREAD_IS_RUNNING_GC(cx))
return;
return;
} else {
}
}
void
{
/* We hope compilers use me instead of reloading cx->thread in the macro. */
if (CX_THREAD_IS_RUNNING_GC(cx))
return;
return;
}
JS_ASSERT(0); /* unbalanced unlock */
return;
}
}
}
/*
* NB: oldscope may be null if our caller is js_GetMutableScope and it just
* dropped the last reference to oldscope.
*/
void
{
JSThinLock *tl;
/*
* If the last reference to oldscope went away, newscope needs no lock
* state update.
*/
if (!oldscope)
return;
/*
* Special case in js_LockScope and js_UnlockScope for the GC calling
* code that locks, unlocks, or mutates. Nothing to do in these cases,
* because scope and newscope were "locked" by the GC thread, so neither
* was actually locked.
*/
if (CX_THREAD_IS_RUNNING_GC(cx))
return;
/*
* Special case in js_LockObj and js_UnlockScope for locking the sealed
* scope of an object that owns that scope (the prototype or mutated obj
* for which OBJ_SCOPE(obj)->object == obj), and unlocking it.
*/
return;
}
/*
* If oldscope is single-threaded, there's nothing to do.
*/
return;
}
/*
* We transfer oldscope->u.count only if newscope is not single-threaded.
* JS_UNLOCK_OBJ macro calls, which will decrement newscope->u.count only
* if they find newscope->ownercx != cx.
*/
}
/*
* Reset oldscope's lock state so that it is completely unlocked.
*/
}
void
{
for (;;) {
!cx->lockedSealedScope) {
return;
}
/* If obj still has this scope, we're done. */
return;
/* Lost a race with a mutator; retry with obj's new scope. */
}
}
void
{
}
#ifdef DEBUG
{
}
{
}
{
/* Special case: the GC locking any object's scope, see js_LockScope. */
if (CX_THREAD_IS_RUNNING_GC(cx))
return JS_TRUE;
/* Special case: locked object owning a sealed scope, see js_LockObj. */
return JS_TRUE;
/*
* General case: the scope is either exclusively owned (by cx), or it has
* a thin or fat lock to cope with shared (concurrent) ownership.
*/
return JS_TRUE;
}
}
#endif /* DEBUG */
#endif /* JS_THREADSAFE */