]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc_r/uthread/uthread_file.c
Add RCS IDs to those files without them.
[FreeBSD/FreeBSD.git] / lib / libc_r / uthread / uthread_file.c
1 /*
2  * Copyright (c) 1995 John Birrell <jb@cimlogic.com.au>.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by John Birrell.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $Id: uthread_file.c,v 1.7 1999/06/20 08:28:20 jb Exp $
33  *
34  * POSIX stdio FILE locking functions. These assume that the locking
35  * is only required at FILE structure level, not at file descriptor
36  * level too.
37  *
38  */
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/queue.h>
43 #ifdef _THREAD_SAFE
44 #include <pthread.h>
45 #include "pthread_private.h"
46
47 /*
48  * Weak symbols for externally visible functions in this file:
49  */
50 #pragma weak    flockfile=_flockfile
51 #pragma weak    ftrylockfile=_ftrylockfile
52 #pragma weak    funlockfile=_funlockfile
53
54 /*
55  * The FILE lock structure. The FILE *fp is locked if the owner is
56  * not NULL. If not locked, the file lock structure can be
57  * reassigned to a different file by setting fp.
58  */
59 struct  file_lock {
60         LIST_ENTRY(file_lock)   entry;  /* Entry if file list.       */
61         TAILQ_HEAD(lock_head, pthread)
62                                 l_head; /* Head of queue for threads */
63                                         /* waiting on this lock.     */
64         FILE            *fp;            /* The target file.          */
65         pthread_t       owner;          /* Thread that owns lock.    */
66         int             count;          /* Lock count for owner.     */
67 };
68
69 /*
70  * The number of file lock lists into which the file pointer is
71  * hashed. Ideally, the FILE structure size would have been increased,
72  * but this causes incompatibility, so separate data structures are
73  * required.
74  */
75 #define NUM_HEADS       128
76
77 /*
78  * This macro casts a file pointer to a long integer and right
79  * shifts this by the number of bytes in a pointer. The shifted
80  * value is then remaindered using the maximum number of hash
81  * entries to produce and index into the array of static lock
82  * structures. If there is a collision, a linear search of the
83  * dynamic list of locks linked to each static lock is perfomed.
84  */
85 #define file_idx(_p)    ((((u_long) _p) >> sizeof(void *)) % NUM_HEADS)
86
87 /*
88  * Global array of file locks. The first lock for each hash bucket is
89  * allocated statically in the hope that there won't be too many
90  * collisions that require a malloc and an element added to the list.
91  */
92 struct static_file_lock {
93         LIST_HEAD(file_list_head, file_lock) head;
94         struct  file_lock       fl;
95 } flh[NUM_HEADS];
96
97 /* Set to non-zero when initialisation is complete: */
98 static  int     init_done       = 0;
99
100 /* Lock for accesses to the hash table: */
101 static  spinlock_t      hash_lock       = _SPINLOCK_INITIALIZER;
102
103 /*
104  * Find a lock structure for a FILE, return NULL if the file is
105  * not locked:
106  */
107 static
108 struct file_lock *
109 find_lock(int idx, FILE *fp)
110 {
111         struct file_lock *p;
112
113         /* Check if the file is locked using the static structure: */
114         if (flh[idx].fl.fp == fp && flh[idx].fl.owner != NULL)
115                 /* Return a pointer to the static lock: */
116                 p = &flh[idx].fl;
117         else {
118                 /* Point to the first dynamic lock: */
119                 p = flh[idx].head.lh_first;
120
121                 /*
122                  * Loop through the dynamic locks looking for the
123                  * target file:
124                  */
125                 while (p != NULL && (p->fp != fp || p->owner == NULL))
126                         /* Not this file, try the next: */
127                         p = p->entry.le_next;
128         }
129         return(p);
130 }
131
132 /*
133  * Lock a file, assuming that there is no lock structure currently
134  * assigned to it.
135  */
136 static
137 struct file_lock *
138 do_lock(int idx, FILE *fp)
139 {
140         struct file_lock *p;
141
142         /* Check if the static structure is not being used: */
143         if (flh[idx].fl.owner == NULL) {
144                 /* Return a pointer to the static lock: */
145                 p = &flh[idx].fl;
146         }
147         else {
148                 /* Point to the first dynamic lock: */
149                 p = flh[idx].head.lh_first;
150
151                 /*
152                  * Loop through the dynamic locks looking for a
153                  * lock structure that is not being used:
154                  */
155                 while (p != NULL && p->owner != NULL)
156                         /* This one is used, try the next: */
157                         p = p->entry.le_next;
158         }
159
160         /*
161          * If an existing lock structure has not been found,
162          * allocate memory for a new one:
163          */
164         if (p == NULL && (p = (struct file_lock *)
165             malloc(sizeof(struct file_lock))) != NULL) {
166                 /* Add the new element to the list: */
167                 LIST_INSERT_HEAD(&flh[idx].head, p, entry);
168         }
169
170         /* Check if there is a lock structure to acquire: */
171         if (p != NULL) {
172                 /* Acquire the lock for the running thread: */
173                 p->fp           = fp;
174                 p->owner        = _thread_run;
175                 p->count        = 1;
176                 TAILQ_INIT(&p->l_head);
177         }
178         return(p);
179 }
180
181 void
182 _flockfile_debug(FILE * fp, char *fname, int lineno)
183 {
184         int     idx = file_idx(fp);
185         struct  file_lock       *p;
186
187         /* Check if this is a real file: */
188         if (fp->_file >= 0) {
189                 /* Lock the hash table: */
190                 _SPINLOCK(&hash_lock);
191
192                 /* Check if the static array has not been initialised: */
193                 if (!init_done) {
194                         /* Initialise the global array: */
195                         memset(flh,0,sizeof(flh));
196
197                         /* Flag the initialisation as complete: */
198                         init_done = 1;
199                 }
200
201                 /* Get a pointer to any existing lock for the file: */
202                 if ((p = find_lock(idx, fp)) == NULL) {
203                         /*
204                          * The file is not locked, so this thread can
205                          * grab the lock:
206                          */
207                         p = do_lock(idx, fp);
208
209                         /* Unlock the hash table: */
210                         _SPINUNLOCK(&hash_lock);
211
212                 /*
213                  * The file is already locked, so check if the
214                  * running thread is the owner:
215                  */
216                 } else if (p->owner == _thread_run) {
217                         /*
218                          * The running thread is already the
219                          * owner, so increment the count of
220                          * the number of times it has locked
221                          * the file:
222                          */
223                         p->count++;
224
225                         /* Unlock the hash table: */
226                         _SPINUNLOCK(&hash_lock);
227                 } else {
228                         /*
229                          * The file is locked for another thread.
230                          * Append this thread to the queue of
231                          * threads waiting on the lock.
232                          */
233                         TAILQ_INSERT_TAIL(&p->l_head,_thread_run,qe);
234
235                         /* Unlock the hash table: */
236                         _SPINUNLOCK(&hash_lock);
237
238                         /* Wait on the FILE lock: */
239                         _thread_kern_sched_state(PS_FILE_WAIT, fname, lineno);
240                 }
241         }
242         return;
243 }
244
245 void
246 _flockfile(FILE * fp)
247 {
248         _flockfile_debug(fp, __FILE__, __LINE__);
249         return;
250 }
251
252 int
253 _ftrylockfile(FILE * fp)
254 {
255         int     ret = -1;
256         int     idx = file_idx(fp);
257         struct  file_lock       *p;
258
259         /* Check if this is a real file: */
260         if (fp->_file >= 0) {
261                 /* Lock the hash table: */
262                 _SPINLOCK(&hash_lock);
263
264                 /* Get a pointer to any existing lock for the file: */
265                 if ((p = find_lock(idx, fp)) == NULL) {
266                         /*
267                          * The file is not locked, so this thread can
268                          * grab the lock:
269                          */
270                         p = do_lock(idx, fp);
271
272                 /*
273                  * The file is already locked, so check if the
274                  * running thread is the owner:
275                  */
276                 } else if (p->owner == _thread_run) {
277                         /*
278                          * The running thread is already the
279                          * owner, so increment the count of
280                          * the number of times it has locked
281                          * the file:
282                          */
283                         p->count++;
284                 } else {
285                         /*
286                          * The file is locked for another thread,
287                          * so this try fails.
288                          */
289                         p = NULL;
290                 }
291
292                 /* Check if the lock was obtained: */
293                 if (p != NULL)
294                         /* Return success: */
295                         ret = 0;
296
297                 /* Unlock the hash table: */
298                 _SPINUNLOCK(&hash_lock);
299
300         }
301         return (ret);
302 }
303
304 void 
305 _funlockfile(FILE * fp)
306 {
307         int     status;
308         int     idx = file_idx(fp);
309         struct  file_lock       *p;
310
311         /* Check if this is a real file: */
312         if (fp->_file >= 0) {
313                 /*
314                  * Defer signals to protect the scheduling queues from
315                  * access by the signal handler:
316                  */
317                 _thread_kern_sig_defer();
318
319                 /* Lock the hash table: */
320                 _SPINLOCK(&hash_lock);
321
322                 /*
323                  * Get a pointer to the lock for the file and check that
324                  * the running thread is the one with the lock:
325                  */
326                 if ((p = find_lock(idx, fp)) != NULL &&
327                     p->owner == _thread_run) {
328                         /*
329                          * Check if this thread has locked the FILE
330                          * more than once:
331                          */
332                         if (p->count > 1)
333                                 /*
334                                  * Decrement the count of the number of
335                                  * times the running thread has locked this
336                                  * file:
337                                  */
338                                 p->count--;
339                         else {
340                                 /*
341                                  * The running thread will release the
342                                  * lock now:
343                                  */
344                                 p->count = 0;
345
346                                 /* Get the new owner of the lock: */
347                                 if ((p->owner = TAILQ_FIRST(&p->l_head)) != NULL) {
348                                         /* Pop the thread off the queue: */
349                                         TAILQ_REMOVE(&p->l_head,p->owner,qe);
350
351                                         /*
352                                          * This is the first lock for the new
353                                          * owner:
354                                          */
355                                         p->count = 1;
356
357                                         /* Allow the new owner to run: */
358                                         PTHREAD_NEW_STATE(p->owner,PS_RUNNING);
359                                 }
360                         }
361                 }
362
363                 /* Unlock the hash table: */
364                 _SPINUNLOCK(&hash_lock);
365
366                 /*
367                  * Undefer and handle pending signals, yielding if
368                  * necessary:
369                  */
370                 _thread_kern_sig_undefer();
371         }
372         return;
373 }
374
375 #endif