freebsd-dev/lib/libc_r/uthread/uthread_file.c

473 lines
12 KiB
C
Raw Normal View History

/*
* Copyright (c) 1995 John Birrell <jb@cimlogic.com.au>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by John Birrell.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
1999-08-28 00:22:10 +00:00
* $FreeBSD$
*
* POSIX stdio FILE locking functions. These assume that the locking
* is only required at FILE structure level, not at file descriptor
* level too.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/queue.h>
#ifdef _THREAD_SAFE
#include <pthread.h>
#include "pthread_private.h"
/*
* Weak symbols for externally visible functions in this file:
*/
#pragma weak flockfile=_flockfile
#pragma weak ftrylockfile=_ftrylockfile
#pragma weak funlockfile=_funlockfile
/*
* The FILE lock structure. The FILE *fp is locked if the owner is
* not NULL. If not locked, the file lock structure can be
* reassigned to a different file by setting fp.
*/
struct file_lock {
LIST_ENTRY(file_lock) entry; /* Entry if file list. */
TAILQ_HEAD(lock_head, pthread)
l_head; /* Head of queue for threads */
/* waiting on this lock. */
FILE *fp; /* The target file. */
pthread_t owner; /* Thread that owns lock. */
int count; /* Lock count for owner. */
};
/*
* The number of file lock lists into which the file pointer is
* hashed. Ideally, the FILE structure size would have been increased,
* but this causes incompatibility, so separate data structures are
* required.
*/
#define NUM_HEADS 128
/*
* This macro casts a file pointer to a long integer and right
* shifts this by the number of bytes in a pointer. The shifted
* value is then remaindered using the maximum number of hash
* entries to produce and index into the array of static lock
* structures. If there is a collision, a linear search of the
* dynamic list of locks linked to each static lock is perfomed.
*/
#define file_idx(_p) ((((u_long) _p) >> sizeof(void *)) % NUM_HEADS)
/*
* Global array of file locks. The first lock for each hash bucket is
* allocated statically in the hope that there won't be too many
* collisions that require a malloc and an element added to the list.
*/
struct static_file_lock {
LIST_HEAD(file_list_head, file_lock) head;
struct file_lock fl;
} flh[NUM_HEADS];
/* Set to non-zero when initialisation is complete: */
static int init_done = 0;
/* Lock for accesses to the hash table: */
static spinlock_t hash_lock = _SPINLOCK_INITIALIZER;
/*
* Find a lock structure for a FILE, return NULL if the file is
* not locked:
*/
static
struct file_lock *
find_lock(int idx, FILE *fp)
{
struct file_lock *p;
/* Check if the file is locked using the static structure: */
if (flh[idx].fl.fp == fp && flh[idx].fl.owner != NULL)
/* Return a pointer to the static lock: */
p = &flh[idx].fl;
else {
/* Point to the first dynamic lock: */
p = flh[idx].head.lh_first;
/*
* Loop through the dynamic locks looking for the
* target file:
*/
while (p != NULL && (p->fp != fp || p->owner == NULL))
/* Not this file, try the next: */
p = p->entry.le_next;
}
return(p);
}
/*
* Lock a file, assuming that there is no lock structure currently
* assigned to it.
*/
static
struct file_lock *
do_lock(int idx, FILE *fp)
{
struct file_lock *p;
/* Check if the static structure is not being used: */
if (flh[idx].fl.owner == NULL) {
/* Return a pointer to the static lock: */
p = &flh[idx].fl;
}
else {
/* Point to the first dynamic lock: */
p = flh[idx].head.lh_first;
/*
* Loop through the dynamic locks looking for a
* lock structure that is not being used:
*/
while (p != NULL && p->owner != NULL)
/* This one is used, try the next: */
p = p->entry.le_next;
}
/*
* If an existing lock structure has not been found,
* allocate memory for a new one:
*/
if (p == NULL && (p = (struct file_lock *)
malloc(sizeof(struct file_lock))) != NULL) {
/* Add the new element to the list: */
LIST_INSERT_HEAD(&flh[idx].head, p, entry);
}
/* Check if there is a lock structure to acquire: */
if (p != NULL) {
/* Acquire the lock for the running thread: */
p->fp = fp;
p->owner = _thread_run;
p->count = 1;
TAILQ_INIT(&p->l_head);
}
return(p);
}
void
_flockfile_debug(FILE * fp, char *fname, int lineno)
{
int idx = file_idx(fp);
struct file_lock *p;
/* Check if this is a real file: */
if (fp->_file >= 0) {
/* Lock the hash table: */
_SPINLOCK(&hash_lock);
/* Check if the static array has not been initialised: */
if (!init_done) {
/* Initialise the global array: */
memset(flh,0,sizeof(flh));
/* Flag the initialisation as complete: */
init_done = 1;
}
/* Get a pointer to any existing lock for the file: */
if ((p = find_lock(idx, fp)) == NULL) {
/*
* The file is not locked, so this thread can
* grab the lock:
*/
p = do_lock(idx, fp);
/* Unlock the hash table: */
_SPINUNLOCK(&hash_lock);
/*
* The file is already locked, so check if the
* running thread is the owner:
*/
} else if (p->owner == _thread_run) {
/*
* The running thread is already the
* owner, so increment the count of
* the number of times it has locked
* the file:
*/
p->count++;
/* Unlock the hash table: */
_SPINUNLOCK(&hash_lock);
} else {
/* Clear the interrupted flag: */
_thread_run->interrupted = 0;
/*
* Prevent being context switched out while
* adding this thread to the file lock queue.
*/
_thread_kern_sig_defer();
/*
* The file is locked for another thread.
* Append this thread to the queue of
* threads waiting on the lock.
*/
TAILQ_INSERT_TAIL(&p->l_head,_thread_run,qe);
_thread_run->flags |= PTHREAD_FLAGS_IN_FILEQ;
/* Unlock the hash table: */
_SPINUNLOCK(&hash_lock);
/* Wait on the FILE lock: */
_thread_kern_sched_state(PS_FILE_WAIT, fname, lineno);
if ((_thread_run->flags & PTHREAD_FLAGS_IN_FILEQ) != 0) {
TAILQ_REMOVE(&p->l_head,_thread_run,qe);
_thread_run->flags &= ~PTHREAD_FLAGS_IN_FILEQ;
}
_thread_kern_sig_undefer();
if (_thread_run->interrupted != 0 &&
_thread_run->continuation != NULL)
_thread_run->continuation((void *)_thread_run);
}
}
return;
}
void
_flockfile(FILE * fp)
{
_flockfile_debug(fp, __FILE__, __LINE__);
return;
}
int
_ftrylockfile(FILE * fp)
{
int ret = -1;
int idx = file_idx(fp);
struct file_lock *p;
/* Check if this is a real file: */
if (fp->_file >= 0) {
/* Lock the hash table: */
_SPINLOCK(&hash_lock);
/* Get a pointer to any existing lock for the file: */
if ((p = find_lock(idx, fp)) == NULL) {
/*
* The file is not locked, so this thread can
* grab the lock:
*/
p = do_lock(idx, fp);
/*
* The file is already locked, so check if the
* running thread is the owner:
*/
} else if (p->owner == _thread_run) {
/*
* The running thread is already the
* owner, so increment the count of
* the number of times it has locked
* the file:
*/
p->count++;
} else {
/*
* The file is locked for another thread,
* so this try fails.
*/
p = NULL;
}
/* Check if the lock was obtained: */
if (p != NULL)
/* Return success: */
ret = 0;
/* Unlock the hash table: */
_SPINUNLOCK(&hash_lock);
}
return (ret);
}
void
_funlockfile(FILE * fp)
{
int idx = file_idx(fp);
struct file_lock *p;
/* Check if this is a real file: */
if (fp->_file >= 0) {
In the words of the author: o The polling mechanism for I/O readiness was changed from select() to poll(). In additon, a wrapped version of poll() is now provided. o The wrapped select routine now converts each fd_set to a poll array so that the thread scheduler doesn't have to perform a bitwise search for selected fds each time file descriptors are polled for I/O readiness. o The thread scheduler was modified to use a new queue (_workq) for threads that need work. Threads waiting for I/O readiness and spinblocks are added to the work queue in addition to the waiting queue. This reduces the time spent forming/searching the array of file descriptors being polled. o The waiting queue (_waitingq) is now maintained in order of thread wakeup time. This allows the thread scheduler to find the nearest wakeup time by looking at the first thread in the queue instead of searching the entire queue. o Removed file descriptor locking for select/poll routines. An application should not rely on the threads library for providing this locking; if necessary, the application should use mutexes to protect selecting/polling of file descriptors. o Retrieve and use the kernel clock rate/resolution at startup instead of hardcoding the clock resolution to 10 msec (tested with kernel running at 1000 HZ). o All queues have been changed to use queue.h macros. These include the queues of all threads, dead threads, and threads waiting for file descriptor locks. o Added reinitialization of the GC mutex and condition variable after a fork. Also prevented reallocation of the ready queue after a fork. o Prevented the wrapped close routine from closing the thread kernel pipes. o Initialized file descriptor table for stdio entries at thread init. o Provided additional flags to indicate to what queues threads belong. o Moved TAILQ initialization for statically allocated mutex and condition variables to after the spinlock. o Added dispatching of signals to pthread_kill. Removing the dispatching of signals from thread activation broke sigsuspend when pthread_kill was used to send a signal to a thread. o Temporarily set the state of a thread to PS_SUSPENDED when it is first created and placed in the list of threads so that it will not be accidentally scheduled before becoming a member of one of the scheduling queues. o Change the signal handler to queue signals to the thread kernel pipe if the scheduling queues are protected. When scheduling queues are unprotected, signals are then dequeued and handled. o Ensured that all installed signal handlers block the scheduling signal and that the scheduling signal handler blocks all other signals. This ensures that the signal handler is only interruptible for and by non-scheduling signals. An atomic lock is used to decide which instance of the signal handler will handle pending signals. o Removed _lock_thread_list and _unlock_thread_list as they are no longer used to protect the thread list. o Added missing RCS IDs to modified files. o Added checks for appropriate queue membership and activity when adding, removing, and searching the scheduling queues. These checks add very little overhead and are enabled when compiled with _PTHREADS_INVARIANTS defined. Suggested and implemented by Tor Egge with some modification by me. o Close a race condition in uthread_close. (Tor Egge) o Protect the scheduling queues while modifying them in pthread_cond_signal and _thread_fd_unlock. (Tor Egge) o Ensure that when a thread gets a mutex, the mutex is on that threads list of owned mutexes. (Tor Egge) o Set the kernel-in-scheduler flag in _thread_kern_sched_state and _thread_kern_sched_state_unlock to prevent a scheduling signal from calling the scheduler again. (Tor Egge) o Don't use TAILQ_FOREACH macro while searching the waiting queue for threads in a sigwait state, because a change of state destroys the TAILQ link. It is actually safe to do so, though, because once a sigwaiting thread is found, the loop ends and the function returns. (Tor Egge) o When dispatching signals to threads, make the thread inherit the signal deferral flag of the currently running thread. (Tor Egge) Submitted by: Daniel Eischen <eischen@vigrid.com> and Tor Egge <Tor.Egge@fast.no>
1999-06-20 08:28:48 +00:00
/*
* Defer signals to protect the scheduling queues from
* access by the signal handler:
*/
_thread_kern_sig_defer();
/* Lock the hash table: */
_SPINLOCK(&hash_lock);
/*
* Get a pointer to the lock for the file and check that
* the running thread is the one with the lock:
*/
if ((p = find_lock(idx, fp)) != NULL &&
p->owner == _thread_run) {
/*
* Check if this thread has locked the FILE
* more than once:
*/
if (p->count > 1)
/*
* Decrement the count of the number of
* times the running thread has locked this
* file:
*/
p->count--;
else {
/*
* The running thread will release the
* lock now:
*/
p->count = 0;
/* Get the new owner of the lock: */
while ((p->owner = TAILQ_FIRST(&p->l_head)) != NULL) {
/* Pop the thread off the queue: */
TAILQ_REMOVE(&p->l_head,p->owner,qe);
p->owner->flags &= ~PTHREAD_FLAGS_IN_FILEQ;
if (p->owner->interrupted == 0) {
/*
* This is the first lock for
* the new owner:
*/
p->count = 1;
/* Allow the new owner to run: */
PTHREAD_NEW_STATE(p->owner,PS_RUNNING);
/* End the loop when we find a
* thread that hasn't been
* cancelled or interrupted;
*/
break;
}
}
}
}
/* Unlock the hash table: */
_SPINUNLOCK(&hash_lock);
In the words of the author: o The polling mechanism for I/O readiness was changed from select() to poll(). In additon, a wrapped version of poll() is now provided. o The wrapped select routine now converts each fd_set to a poll array so that the thread scheduler doesn't have to perform a bitwise search for selected fds each time file descriptors are polled for I/O readiness. o The thread scheduler was modified to use a new queue (_workq) for threads that need work. Threads waiting for I/O readiness and spinblocks are added to the work queue in addition to the waiting queue. This reduces the time spent forming/searching the array of file descriptors being polled. o The waiting queue (_waitingq) is now maintained in order of thread wakeup time. This allows the thread scheduler to find the nearest wakeup time by looking at the first thread in the queue instead of searching the entire queue. o Removed file descriptor locking for select/poll routines. An application should not rely on the threads library for providing this locking; if necessary, the application should use mutexes to protect selecting/polling of file descriptors. o Retrieve and use the kernel clock rate/resolution at startup instead of hardcoding the clock resolution to 10 msec (tested with kernel running at 1000 HZ). o All queues have been changed to use queue.h macros. These include the queues of all threads, dead threads, and threads waiting for file descriptor locks. o Added reinitialization of the GC mutex and condition variable after a fork. Also prevented reallocation of the ready queue after a fork. o Prevented the wrapped close routine from closing the thread kernel pipes. o Initialized file descriptor table for stdio entries at thread init. o Provided additional flags to indicate to what queues threads belong. o Moved TAILQ initialization for statically allocated mutex and condition variables to after the spinlock. o Added dispatching of signals to pthread_kill. Removing the dispatching of signals from thread activation broke sigsuspend when pthread_kill was used to send a signal to a thread. o Temporarily set the state of a thread to PS_SUSPENDED when it is first created and placed in the list of threads so that it will not be accidentally scheduled before becoming a member of one of the scheduling queues. o Change the signal handler to queue signals to the thread kernel pipe if the scheduling queues are protected. When scheduling queues are unprotected, signals are then dequeued and handled. o Ensured that all installed signal handlers block the scheduling signal and that the scheduling signal handler blocks all other signals. This ensures that the signal handler is only interruptible for and by non-scheduling signals. An atomic lock is used to decide which instance of the signal handler will handle pending signals. o Removed _lock_thread_list and _unlock_thread_list as they are no longer used to protect the thread list. o Added missing RCS IDs to modified files. o Added checks for appropriate queue membership and activity when adding, removing, and searching the scheduling queues. These checks add very little overhead and are enabled when compiled with _PTHREADS_INVARIANTS defined. Suggested and implemented by Tor Egge with some modification by me. o Close a race condition in uthread_close. (Tor Egge) o Protect the scheduling queues while modifying them in pthread_cond_signal and _thread_fd_unlock. (Tor Egge) o Ensure that when a thread gets a mutex, the mutex is on that threads list of owned mutexes. (Tor Egge) o Set the kernel-in-scheduler flag in _thread_kern_sched_state and _thread_kern_sched_state_unlock to prevent a scheduling signal from calling the scheduler again. (Tor Egge) o Don't use TAILQ_FOREACH macro while searching the waiting queue for threads in a sigwait state, because a change of state destroys the TAILQ link. It is actually safe to do so, though, because once a sigwaiting thread is found, the loop ends and the function returns. (Tor Egge) o When dispatching signals to threads, make the thread inherit the signal deferral flag of the currently running thread. (Tor Egge) Submitted by: Daniel Eischen <eischen@vigrid.com> and Tor Egge <Tor.Egge@fast.no>
1999-06-20 08:28:48 +00:00
/*
* Undefer and handle pending signals, yielding if
* necessary:
*/
_thread_kern_sig_undefer();
}
return;
}
void
_funlock_owned(pthread_t pthread)
{
int idx;
struct file_lock *p, *next_p;
/*
* Defer signals to protect the scheduling queues from
* access by the signal handler:
*/
_thread_kern_sig_defer();
/* Lock the hash table: */
_SPINLOCK(&hash_lock);
for (idx = 0; idx < NUM_HEADS; idx++) {
/* Check the static file lock first: */
p = &flh[idx].fl;
next_p = LIST_FIRST(&flh[idx].head);
while (p != NULL) {
if (p->owner == pthread) {
/*
* The running thread will release the
* lock now:
*/
p->count = 0;
/* Get the new owner of the lock: */
while ((p->owner = TAILQ_FIRST(&p->l_head)) != NULL) {
/* Pop the thread off the queue: */
TAILQ_REMOVE(&p->l_head,p->owner,qe);
p->owner->flags &= ~PTHREAD_FLAGS_IN_FILEQ;
if (p->owner->interrupted == 0) {
/*
* This is the first lock for
* the new owner:
*/
p->count = 1;
/* Allow the new owner to run: */
PTHREAD_NEW_STATE(p->owner,PS_RUNNING);
/* End the loop when we find a
* thread that hasn't been
* cancelled or interrupted;
*/
break;
}
}
}
p = next_p;
if (next_p != NULL)
next_p = LIST_NEXT(next_p, entry);
}
}
/* Unlock the hash table: */
_SPINUNLOCK(&hash_lock);
/*
* Undefer and handle pending signals, yielding if
* necessary:
*/
_thread_kern_sig_undefer();
}
#endif