File: sproc.cpp

package info (click to toggle)
aolserver 3.4.2-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 22,692 kB
  • ctags: 33,612
  • sloc: ansic: 171,340; tcl: 10,218; sh: 3,821; cpp: 2,779; makefile: 2,041; yacc: 1,648; perl: 456; php: 13
file content (1510 lines) | stat: -rw-r--r-- 34,480 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
/*
 * The contents of this file are subject to the AOLserver 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
 * http://aolserver.com/.
 *
 * 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 AOLserver Code and related documentation
 * distributed by AOL.
 * 
 * The Initial Developer of the Original Code is America Online,
 * Inc. Portions created by AOL are Copyright (C) 1999 America Online,
 * Inc. All Rights Reserved.
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU General Public License (the "GPL"), in which case the
 * provisions of GPL are applicable instead of those above.  If you wish
 * to allow use of your version of this file only under the terms of the
 * GPL and not to allow others to use your version of this file under the
 * License, indicate your decision by deleting the provisions above and
 * replace them with the notice and other provisions required by the GPL.
 * If you do not delete the provisions above, a recipient may use your
 * version of this file under either the License or the GPL.
 */


/* 
 * sproc.c --
 *
 *	Interface routines for nsthreads using native SGI multiprocessing
 *	functions.  Basically an arena is created to hold locks,
 *  	threads are created using sproc(2) through a dedicated manager
 *  	process, conditions are signaled via a Unix signal, and a pointer
 *  	to the thread's context is stored in a portion of the PRDA, the
 *  	process data area.  This code is highly SGI specific although
 *  	the implementation and strategy is very similar to the Pthreads
 *  	interface on Linux (also known as LinuxThreads) where clone(2)
 *  	replaces the sproc(2) system call.  For background information see:
 *
 *  	sproc(2)   		Create new process
 *  	prctl(2)    		Process control
 *  	usinit(3P)  		Initialize shared arena
 *  	usnewlock(3P)  		Create new arena lock
 *	sigtimedwait(2)		Timed wait for signal
 *  	<sys/prcntl.h>		Process data area (PRDA) definition
 *
 */


#include "thread.h"
#include <sys/prctl.h>		/* prctl(), PRDA definition. */
#include <ulocks.h>		/* Arena locks. */
#include <mutex.h>		/* test_then_add. */
#include <sys/ioctl.h>
#include <sys/wait.h>

extern void	__exit(int);

/*
 * The following structure maintains the sproc-specific state of a
 * process thread including pointers for the run and condition
 * queues and a wakeup pointer for "rolling" condition broadcast.
 */

typedef struct Sproc {
    int     	   pid;     	/* Thread initialized pid. */
    struct Sproc  *nextRunPtr; 	/* Next starting, exiting, or running Sproc */
    struct Sproc  *nextWaitPtr;	/* Next Sproc in CondWait. */
    struct Sproc  *wakeupPtr;	/* Next Sproc to wakeup from CondWait. */
    struct Thread *thrPtr;  	/* Pointer to NsThread structure. */
    enum {  	    	    	/* State of sproc structure as follows: */
	SprocRunning,	    	/* Sproc is running freely. */
	SprocCondWait,	    	/* Sproc is in a condition wait. */
	SprocExited 	    	/* Sproc has exited and to be reaped. */
    } state;
} Sproc;

/*
 * The following structure defines a queue of threads in a condition wait.
 */

typedef struct {
    void   *lock;	/* Lock around Cond structure. */
    Sproc  *waitPtr;	/* First waiting Sproc or NULL. */
} Cond;

/*
 * The following structure defines the single critical section lock.
 */

struct {
    void    *lock;	/* Lock around structure. */
    int      owner;	/* Current owner. */
    int	     count;	/* Recursive lock depth. */
    usema_t *sema;	/* Semaphore to wakeup waiters. */
    int      nwait;	/* # of waiters. */
} master;

/*
 * The prdaPtrPtr pointer is declared static but is not actually shared by
 * all threads.  Instead, it's a pointer to a virtual address which always
 * points to the "per-process data area" (see <sys/prctl.h> for details). The
 * address of the current thread's Sproc process is stored at this location
 * at thread startup in SprocMain() and accessed via NsGetThread().
 * If you're interested in how per-thread context management would
 * be done on other platforms check out the LinuxThreads source
 * code.  For example, on Sparc Linux (and Solaris) a pointer to thread
 * context is stored in CPU register #6 and on Intel Linux it's
 * calculated based on the known spacing of thread context mmaped()'ed 
 * at high virtual memory addresses.
 */

static Sproc  **prdaPtrPtr = (Sproc **) (&((PRDA)->usr2_prda));

static Sproc   *firstStartPtr;	/* List of sprocs to be started. */
static int      mgrPipe[2];	/* Trigger pipe to wakeup manager. */
static int      mgrPid = -1;	/* Manager pid, -1 until first thread. */
static int      initPid = -1;	/* Initial thread pid, -1 until first thread. */

/*
 * Static functions defined in this file.
 */

static void     MgrThread(void *arg);
static void     MgrTrigger(void);
static void	SprocMain(void *arg, size_t stacksize);
static void     CatchCLD(int signal);
static void	CatchHUP(void);
static void	CheckHUP(void);
static usptr_t *GetArena(void);
static int      StartSproc(Sproc *sPtr);
static int	GetWakeup(Sproc *sPtr);
static void	SendWakeup(int pid);
static Sproc   *InitSproc(void);
static int      shutdownPending;

#define GETSPROC()	(*prdaPtrPtr ? *prdaPtrPtr : InitSproc())


/*
 *----------------------------------------------------------------------
 *
 * NsThreadLibName --
 *
 *	Return the string name of the thread library.
 *
 * Results:
 *	Pointer to static string.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

char *
NsThreadLibName(void)
{
    return "sproc";
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_MasterLock --
 *
 *	Enter the single master critical section, initializing
 *	it the first time.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
Ns_MasterLock(void)
{
    static int initialized;
    int self = getpid();

    /*
     * Initialize the critical section on first use.  This is safe
     * because the first new thread can't be created without entering 
     * the master lock once.
     */

    if (!initialized) {
	master.lock = NsLockAlloc();
    	usinitlock(master.lock);
	master.sema = usnewsema(GetArena(), 0);
	if (master.sema == NULL) {
    	    NsThreadFatal("Ns_MasterLock", "usnewsema", errno);
	}
	master.count = 0;
	master.owner = -1;
	initialized = 1;
    }

    /*
     * Enter the critical section, waiting if necessary.
     */

    NsLockSet(master.lock);
    while (master.owner != self && master.count > 0) {
	++master.nwait;
    	NsLockUnset(master.lock);
	if (uspsema(master.sema) != 1) {
    	    NsThreadFatal("Ns_MasterUnlock", "usvsema", errno);
	}
    	NsLockSet(master.lock);
    }
    master.owner = self;
    ++master.count;
    NsLockUnset(master.lock);
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_MasterUnlock --
 *
 *	Leave the single master critical section.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
Ns_MasterUnlock(void)
{
    int self = getpid();

    /*
     * Leave the critical section, waking up one waiter if necessary.
     */

    NsLockSet(master.lock);
    if (master.owner == self && --master.count == 0) {
	master.owner = -1;
	if (master.nwait > 0) {
	    --master.nwait;
	    if (usvsema(master.sema) != 0) {
    	    	NsThreadFatal("Ns_MasterUnlock", "usvsema", errno);
	    }
	}
    }
    NsLockUnset(master.lock);
}


/*
 *----------------------------------------------------------------------
 *
 * NsLockAlloc --
 *
 *	Allocate and initialize a mutex lock in the arena.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void *
NsLockAlloc(void)
{
    ulock_t         lock;

    lock = usnewlock(GetArena());
    if (lock == NULL) {
    	NsThreadFatal("NsLockAlloc", "usnewlock", errno);
    }
    usinitlock(lock);
    return lock;
}


/*
 *----------------------------------------------------------------------
 *
 * NsLockFree --
 *
 *	Free a mutex lock in the arena.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
NsLockFree(void *lock)
{
    usfreelock((ulock_t) lock, GetArena());
}


/*
 *----------------------------------------------------------------------
 *
 * NsLockSet --
 *
 *	Set a mutex lock.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *  	None.
 *
 *----------------------------------------------------------------------
 */

void
NsLockSet(void *lock)
{
    if (ussetlock((ulock_t) lock) == -1) {
	NsThreadFatal("NsLockSet", "ussetlock", errno);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * NsLockTry --
 *
 *	Try once to set a mutex lock.
 *
 * Results:
 *	1 if locked, 0 otherwise.
 *
 * Side effects:
 *  	None.
 *
 *----------------------------------------------------------------------
 */

int
NsLockTry(void *lock)
{
    int locked;

    locked = uscsetlock((ulock_t) lock, 1);
    if (locked == -1) {
    	NsThreadFatal("NsLockTry", "uscsetlock", errno);
    }
    return locked;
}


/*
 *----------------------------------------------------------------------
 *
 * NsLockUnset --
 *
 *	Unlock a mutex in the arena.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *  	Some other thread may resume.
 *
 *----------------------------------------------------------------------
 */

void
NsLockUnset(void *lock)
{
    if (usunsetlock((ulock_t) lock) != 0) {
	NsThreadFatal("NsLockUnset", "usunsetlock", errno);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_CondInit --
 *
 *	Initialize a condition variable.  Note that this function is rarely
 *	called directly as static NULL condition variables are now self 
 *	initialized when first accessed.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
Ns_CondInit(Ns_Cond *condPtr)
{
    Cond          *cPtr;

    cPtr = NsAlloc(sizeof(Cond));
    cPtr->lock = NsLockAlloc();
    *condPtr = (Ns_Cond) cPtr;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_CondDestroy --
 *
 *	Destroy a previously initialized condition variable.  Note this
 *	function is almost never called as condition variables
 *	normally exist until the process exits.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
Ns_CondDestroy(Ns_Cond *condPtr)
{
    Cond *cPtr = (Cond *) *condPtr;

    if (cPtr != NULL) {
    	NsLockFree(cPtr->lock);
	cPtr->waitPtr = NULL;
    	NsFree(cPtr);
    	*condPtr = NULL;
    }
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_CondSignal --
 *
 *	Signal a condition variable, releasing a single thread if one
 *	is waiting.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A single waiting thread may be resumed.
 *
 *----------------------------------------------------------------------
 */

void
Ns_CondSignal(Ns_Cond *condPtr)
{
    Sproc   	 *sPtr;
    Cond         *cPtr = GETCOND(condPtr);
    int		  wakeup;

    NsLockSet(cPtr->lock);
    sPtr = cPtr->waitPtr;
    if (sPtr != NULL) {
	cPtr->waitPtr = sPtr->nextWaitPtr;
	wakeup = GetWakeup(sPtr);
    }
    NsLockUnset(cPtr->lock);
    if (sPtr != NULL) {
	SendWakeup(wakeup);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_CondBroadcast --
 *
 *	Broadcast a condition by resuming the first waiting thread.
 *	The first thread will then signal the next thread in when
 *	exiting Ns_CondTimedWait which is signal the next and so
 *	on resulting an a rolling wakeup which avoids lock contention
 *	from all thread waking up at once.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	One or more waiting threads may be resumed.
 *
 *----------------------------------------------------------------------
 */

void
Ns_CondBroadcast(Ns_Cond *condPtr)
{
    Sproc   	  *sPtr;
    Cond          *cPtr = GETCOND(condPtr);
    int            wakeup;

    /*
     * Mark each thread to wakeup the next thread on the queue.
     */

    NsLockSet(cPtr->lock);
    sPtr = cPtr->waitPtr;
    while (sPtr != NULL) {
	sPtr->wakeupPtr = sPtr->nextWaitPtr;
	sPtr = sPtr->nextWaitPtr;
    }
    sPtr = cPtr->waitPtr;
    if (sPtr != NULL) {
	cPtr->waitPtr = NULL;
	wakeup = GetWakeup(sPtr);
    }
    NsLockUnset(cPtr->lock);
    if (sPtr != NULL) {
	SendWakeup(wakeup);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_CondWait --
 *
 *	Wait indefinitely for a condition to be signaled.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
Ns_CondWait(Ns_Cond *condPtr, Ns_Mutex *lockPtr)
{
    (void) Ns_CondTimedWait(condPtr, lockPtr, NULL);
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_CondTimedWait --
 *
 *	Wait for a condition to be signaled up to a given absolute time
 *	out.  This code is very tricky to avoid the race condition between
 *	locking and unlocking the coordinating mutex and catching a
 *	a wakeup signal.  Be sure you understand how condition variables
 *	work before screwing around with this code.
 *
 * Results:
 *	NS_OK on signal being received within the timeout period, otherwise
 *	NS_TIMEOUT.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
Ns_CondTimedWait(Ns_Cond *condPtr, Ns_Mutex *mutexPtr, Ns_Time *timePtr)
{
    int status, wakeup;
    struct timespec ts;
    Cond           *cPtr;
    sigset_t        set;
    Sproc	   *sPtr, *wakeupPtr, **waitPtrPtr;
    Ns_Time 	    now, wait;

    /*
     * Block SIGHUP which is used as the sigtimedwait() signal.
     */
 
    sigemptyset(&set);
    sigaddset(&set, SIGHUP);
    sigprocmask(SIG_BLOCK, &set, NULL);

    /*
     * Lock the condition and queue this thread for wakeup.
     */

    sPtr = GETSPROC();
    cPtr = GETCOND(condPtr);
    NsLockSet(cPtr->lock);
    waitPtrPtr = &cPtr->waitPtr;
    while (*waitPtrPtr != NULL) {
	waitPtrPtr = &(*waitPtrPtr)->nextWaitPtr;
    }
    *waitPtrPtr = sPtr;
    sPtr->nextWaitPtr = NULL;

    /*
     * Unlock the associated mutex and wait for a wakeup signal
     * or timeout.  Note that because the state of the sproc is check
     * and the relative timeout is recalculated on each interation of
     * the loop it's safe to receive the wakeup signal multiple times,
     * perhaps from a previously missed wakeup.
     */

    Ns_MutexUnlock(mutexPtr);

    sPtr->state = SprocCondWait;
    status = NS_OK;
    while (status == NS_OK && sPtr->state == SprocCondWait) {
        NsLockUnset(cPtr->lock);
        if (timePtr != NULL) {
	    Ns_GetTime(&now);
	    Ns_DiffTime(timePtr, &now, &wait);
	    if (wait.sec < 0 || (wait.sec == 0 && wait.usec <= 0)) {
		status = NS_TIMEOUT;
	    } else {
	    	ts.tv_sec = wait.sec;
	    	ts.tv_nsec = wait.usec * 1000;
	    }
        }
	if (status == NS_OK &&
		sigtimedwait(&set, NULL, timePtr ? &ts : NULL) == -1) {
            if (errno == EAGAIN) {
	    	status = NS_TIMEOUT;
	    } else if (errno != EINTR) {
		NsThreadFatal("Ns_CondTimedWait", "sigtimedwait", errno);
	    }
	}

	/*
	 * Check for parent death now as SIGHUP, the death signal is blocked.
	 */

	CheckHUP();
    	NsLockSet(cPtr->lock);
    }

    /*
     * On what appears to be a timeout, first check the thread state again
     * in case the signal arrived just before the lock could be re-aquired.
     * If so, reset the status to NS_OK.  Otherwise, remove this thread from
     * the condition queue and leave the status NS_TIMEOUT.
     */

    if (status == NS_TIMEOUT) {
	if (sPtr->state == SprocRunning) {
	    status = NS_OK;
	} else {
	    waitPtrPtr = &cPtr->waitPtr;
	    while (*waitPtrPtr != sPtr) {
		waitPtrPtr = &(*waitPtrPtr)->nextWaitPtr;
	    }
	    *waitPtrPtr = sPtr->nextWaitPtr;
	    sPtr->nextWaitPtr = NULL;
	    sPtr->state = SprocRunning;
	}
    }

    /*
     * Check for the next sproc to wakeup in the case of
     * a rolling broadcast (see Ns_CondBroadcast).
     */

    wakeupPtr = sPtr->wakeupPtr;
    if (wakeupPtr != NULL) {
	sPtr->wakeupPtr = NULL;
	wakeup = GetWakeup(wakeupPtr);
    }

    /*
     * Unlock the condition and lock the associated mutex.
     */
    
    NsLockUnset(cPtr->lock);

    /*
     * Signal the next process, if any, now that the lock is
     * released. 
     */

    if (wakeupPtr != NULL) {
	SendWakeup(wakeup);
    }

    Ns_MutexLock(mutexPtr);

    /*
     * Unblock SIGHUP which will deliver any pending death signal.
     */

    sigprocmask(SIG_UNBLOCK, &set, NULL);

    return status;
}


/*
 *----------------------------------------------------------------------
 *
 * GetWakeup, SendWakeup --
 *
 *	Get/send a signal to wakeup a sproc from condition wait. The
 *	wakup is in two parts so the kill() can be sent after the lock
 *	is released.
 *
 * Results:
 *	GetWakeup:  Pid to pass to SendWakup.
 *
 * Side effects:
 *	GetWakeup:  Sets Sproc to running.
 *
 *----------------------------------------------------------------------
 */

static int
GetWakeup(Sproc *sPtr)
{
    sPtr->state = SprocRunning;
    return sPtr->pid;
}

static void
SendWakeup(int pid)
{
    if (kill(pid, SIGHUP) != 0) {
    	NsThreadError("SendWakeup: kill(%d, SIGHUP) failed: %s", 
	    pid, strerror(errno));
    }
}


/*
 *----------------------------------------------------------------------
 *
 * NsThreadCreate --
 *
 *	Sproc specific thread create function called by Ns_ThreadCreate.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	New process is queued for start by manager thread which itself
 *	is created when first needed.
 *
 *----------------------------------------------------------------------
 */

void
NsThreadCreate(Thread *thrPtr)
{
    Sproc	*sPtr;
    int		 trigger = 0;

    /*
     * Create the manager sproc if necessary.
     */

    if (mgrPid < 0) {
    	static Sproc mgrSproc;
	
	initPid = getpid();
	if (pipe(mgrPipe) != 0) {
            NsThreadFatal("NsThreadCreate", "pipe", errno);
	}
        fcntl(mgrPipe[0], F_SETFD, 1);
        fcntl(mgrPipe[1], F_SETFD, 1);
	ns_signal(SIGCLD, CatchCLD);	/* NB: Trap exit of manager. */
	mgrSproc.thrPtr = NsNewThread();
	mgrSproc.thrPtr->proc = MgrThread;
	mgrSproc.thrPtr->stackSize = 8192;
	mgrSproc.state = SprocRunning;
	mgrPid = StartSproc(&mgrSproc);
    }
    
    /*
     * Allocate a new sproc and queue for start, triggering 
     * wakeup if necessary.
     */
     
    sPtr = NsAlloc(sizeof(Sproc));
    sPtr->thrPtr = thrPtr;
    sPtr->state = SprocRunning;

    Ns_MasterLock();
    if (firstStartPtr == NULL) {
	trigger = 1;
    }
    sPtr->nextRunPtr = firstStartPtr;
    firstStartPtr = sPtr;
    Ns_MasterUnlock();
    if (trigger) {
	MgrTrigger();
    }
}


/*
 *----------------------------------------------------------------------
 *
 * NsThreadExit --
 *
 *	Terminate a sproc processes, which will be reaped later by the
 *  	manager thread.  Note that __exit(2) is called instead of exit(3)
 *  	(which would kill all remaining threads - see below) or
 *	_exit(2) (which would bypass various profiling hooks).
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Manager process will later reap the process status.
 *
 *----------------------------------------------------------------------
 */

void
NsThreadExit(void)
{
    Sproc *sPtr = GETSPROC();

    if (sPtr->thrPtr != NULL) {
    	NsCleanupThread(sPtr->thrPtr);
    }
    Ns_MasterLock();
    sPtr->state = SprocExited;
    sPtr->thrPtr = NULL;
    Ns_MasterUnlock();
    __exit(0);
}


/*
 *----------------------------------------------------------------------
 *
 * NsSetThread --
 *
 *	Sproc specific routine for setting a thread's data structure.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
NsSetThread(Thread *thrPtr)
{
    Sproc *sPtr = GETSPROC();

    sPtr->thrPtr = thrPtr;
    thrPtr->tid = sPtr->pid;
}


/*
 *----------------------------------------------------------------------
 *
 * NsGetThread --
 *
 *	Sproc specific routine for getting a thread's structure. 
 *
 * Results:
 *	Pointer to this thread's structure.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

Thread      *
NsGetThread(void)
{
    Sproc *sPtr = GETSPROC();
    Thread *thrPtr;

    thrPtr = sPtr->thrPtr;
    if (thrPtr == NULL) {
	/* NB: Unlike pthread/win32, only possible for init thread. */
	thrPtr = NsNewThread();
	NsSetThread(thrPtr);
    }
    return thrPtr;
}


/*
 *----------------------------------------------------------------------
 *
 * InitSproc --
 *
 *	Get the Sproc structure for the initial process.
 *	The sPtr is NULL for the initial thread because it never has
 *	a chance to be set in SprocMain as with subsequent threads.
 *	In this case, just return a static structure here, initializing 
 *	the pid and state elements the first time.  Note that it's unsafe
 *	to simply set the prdaPtrPtr for the initial thread because if
 *	this is done before the arena is created it appears to become
 *	a shared variable instead of a per-thread variable.
 *
 * Results:
 *	Pointer to static Sproc.
 *
 * Side effects:
 *	Sproc is initialized on first use.
 *
 *----------------------------------------------------------------------
 */

static Sproc *
InitSproc(void)
{
    static Sproc initSproc;

    if (initSproc.pid == 0) {
	initSproc.pid = getpid();
	initSproc.state = SprocRunning;
    }
    return &initSproc;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_ThreadYield --
 *
 *	Sproc specific thread yield.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Process may yield cpu to another process. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_ThreadYield(void)
{
    sginap(0);
}


/*
 *----------------------------------------------------------------------
 *
 * ns_sigmask --
 *
 *	Set the thread signal mask.
 *
 * Results:
 *	0 on success, otherwise an error code.
 *
 * Side effects:
 *	Previously blocked signals will be returned in oset if not null.
 *
 *----------------------------------------------------------------------
 */

int
ns_sigmask(int how, sigset_t * set, sigset_t * oset)
{
    if (sigprocmask(how, set, oset) != 0) {
	return errno;
    }
    return 0;
}


/*
 *----------------------------------------------------------------------
 *
 * SprocMain --
 *
 *	Startup routine for sproc process threads.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
SprocMain(void *arg, size_t stacksize)
{
    Sproc *sPtr = arg;

    *prdaPtrPtr = sPtr;
    sPtr->pid = getpid();
    CatchHUP();
    NsThreadMain(sPtr->thrPtr);
}


/*
 *----------------------------------------------------------------------
 *
 * GetArena --
 *
 *	Return the SGI arena, creating it if necessary.  The arena
 *	is shared memory where locks are maintained.
 *
 * Results:
 *	Pointer to arena.
 *
 * Side effects:
 *	Arena is created the first time this routine is called.  Note
 *	this is safe because a mutex protects creating any new thread
 *	and the initialization of the mutex will ensure the arena is
 *	created before any additional thread could present a race
 *	condition.
 *
 *----------------------------------------------------------------------
 */

static int
GetOpt(char *env, int def, int min, int max)
{
    char *val;
    int n;

    val = getenv(env);
    if (val != NULL) {
	n = atoi(val);
	if (n >= min && n <= max) {
	    return n;
	}
	NsThreadError("ignored invalid %s: %s", env, val);
    }
    return def;
}

static usptr_t *
GetArena(void)
{
    static usptr_t *arenaPtr = NULL;

    if (arenaPtr == NULL) {
	int opt;

	opt = GetOpt("NS_THREAD_CONF_LOCKTYPE", US_NODEBUG,
		     US_NODEBUG, US_DEBUGPLUS);
	if (usconfig(CONF_LOCKTYPE, opt) < 0) {
            NsThreadFatal("GetArena", "usconfig(CONF_LOCKTYPE)", errno);
	}
	opt = GetOpt("NS_THREAD_CONF_INITUSERS", 100, 2, 10000);
	if (usconfig(CONF_INITUSERS, opt) < 0) {
            NsThreadFatal("GetArena", "usconfig(CONF_INITUSERS)", errno);
	}
	opt = GetOpt("NS_THREAD_CONF_INITSIZE", 256*1024, 64*1024, INT_MAX);
	if (usconfig(CONF_INITSIZE, opt) < 0) {
            NsThreadFatal("GetArena", "usconfig(CONF_INITSIZE)", errno);
	}
	arenaPtr = usinit("/dev/zero");
	if (arenaPtr == NULL) {
            NsThreadFatal("GetArena", "usinit", errno);
	}
    }

    return arenaPtr;
}


/*
 *----------------------------------------------------------------------
 *
 *  CatchCLD --
 *
 *	SIGCLD signal handler for the initial process which watches
 *	for death of the manager thread.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Initial process will exit immediately if manager exits.
 *
 *----------------------------------------------------------------------
 */

static void
CatchCLD(int signal)
{
    if (waitpid(mgrPid, NULL, WNOHANG) == mgrPid) {
    	_exit(0);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * CatchHUP --
 *
 *	Install the SIGHUP signal handler.  SIGHUP is used to notify a
 *	child sproc process when the manager thread exits or to notify
 *	the manager thread if the initial process thread exits.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Signal handler is set for this thread.
 *
 *----------------------------------------------------------------------
 */

static void
CatchHUP(void)
{
    struct sigaction sa;
    sigset_t set;

    /*
     * Install the CheckHUP signal handler for SIGHUP.
     */

    sa.sa_flags = SA_RESTART;
    sigemptyset(&sa.sa_mask);
    sa.sa_handler = CheckHUP;
    sigaction(SIGHUP, &sa, NULL);

    /*
     * Have the OS send this process a SIGHUP when the parent process
     * dies.  This is a SGI-specific system call which allows all threads,
     * to catch a death of the initial or manager threads.  Note that
     * the normal order of shutdown is to kill and wait for all threads
     * directly through exit() (see below).
     */

    prctl(PR_TERMCHILD);

    /*
     * Unblock SIGHUP now that the handler is installed.
     */

    sigemptyset(&set);
    sigaddset(&set, SIGHUP);
    sigprocmask(SIG_UNBLOCK, &set, NULL);

    /*
     * Reset SIGCLD from the handler used by the thread manager.
     */

    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    sa.sa_handler = SIG_DFL;
    sigaction(SIGCLD, &sa, NULL);

    /*
     * Call CheckHUP now in case we just missed a SIGHUP.
     */

    CheckHUP();
}


/*
 *----------------------------------------------------------------------
 *
 * CheckHUP --
 *
 *	SIGHUP signal handler which checks for death of the manager or
 *	initial process.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Process will exit if it appears the thread manager process has
 *	died.  Note that a thread existing is this way will not dump
 *	it's profiling data.  To ensure profiling, threads must call
 *	NsThreadExit.
 *
 *----------------------------------------------------------------------
 */

static void
CheckHUP(void)
{
    if (getppid() == 1 && getpid() != initPid) {
	_exit(0);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * StartSproc --
 *
 *	Start a new sproc process, called by the manager thread and
 *  	the initial thread when creating the manager.
 *
 * Results:
 *	New process id.
 *
 * Side effects:
 *	Process will be created with all attributes shared.
 *
 *----------------------------------------------------------------------
 */

static int
StartSproc(Sproc *sPtr)
{
    int pid;

    pid = sprocsp(SprocMain, PR_SALL, (void *) sPtr,
    	    	    	     NULL, sPtr->thrPtr->stackSize);
    if (pid < 0) {
	NsThreadFatal("StartSproc", "sprocsp", errno);
    }
    return pid;
}


/*
 *----------------------------------------------------------------------
 *
 * MgrThread --
 *
 *	Startup routine for the manager process.  This process is
 *	sproc'ed the first time NsThreadCreate is called and is
 *	responsible for sproc'ing and reaping all future process
 *	threads.  This manager thread is used instead of having
 *	processes sproc additional processes directly to ensure
 *	a single process is the parent of all other processes which
 *	enables the death of any thread to be noticed immediately.
 *  	The trigger pipe is used as a simple semaphore to wakeup
 *  	the manager either when new sprocs are to be created,
 *  	or dead sprocs are to be reaped. A pipe is used instead
 *  	of a condition because a write() is a safe operation
 *  	to perform in the SIGCHLD signal handler.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Processes will be endlessly sproc'ed and reaped.
 *
 *----------------------------------------------------------------------
 */

static void
MgrThread(void *arg)
{
    int             status, pid, new;
    char    	    c;
    Sproc	   *sPtr, *nextPtr, **sPtrPtr;
    Sproc          *runPtr, *startPtr;
    struct sigaction sa;
    sigset_t        set;

    Ns_ThreadSetName("-sproc-");

    /*
     * Watch for parent death like other threads.
     */

    CatchHUP();

    /*
     * Wake up the manager on thread exit.
     */

    sa.sa_flags = SA_RESTART;
    sigemptyset(&sa.sa_mask);
    sa.sa_handler = MgrTrigger;
    sigaction(SIGCLD, &sa, NULL);

    /*
     * Endlessly wait for wakeup messages on the trigger pipe.
     */

    runPtr = NULL;
    while (read(mgrPipe[0], &c, 1)) {
    	Ns_MasterLock();
	if (shutdownPending) {
	    Ns_MasterUnlock();
	    break;
	}
	startPtr = firstStartPtr;
	firstStartPtr = NULL;
	Ns_MasterUnlock();

        /*
         * Check for exited threads to be reaped. If the thread died
         * from a signal or because user code called _exit(), simply
         * kill the thread manager which will cause all other threads
         * to receive a SIGHUP and die when the CatchHUP signal handler
	 * is invoked.  On error, call NsThreadError and _exit()
	 * instead of NsThreadAbort to avoid over-writing a core file
	 * written by a crashed thread.
         */

        while ((pid = waitpid(0, &status, WNOHANG)) > 0) {
            if (WIFSIGNALED(status)) {
		NsThreadError("sproc %d killed by signal %d", pid,
			WTERMSIG(status));
		_exit(1);
            }
	    if (WEXITSTATUS(status) != 0) {
		NsThreadError("sproc %d exited with non-zero status %d",
		    pid, WEXITSTATUS(status));
		_exit(1);
	    }
    	    sPtrPtr = &runPtr;
	    while ((*sPtrPtr)->pid != pid) {
	    	sPtrPtr = &(*sPtrPtr)->nextRunPtr;
	    }
    	    sPtr = *sPtrPtr;
	    *sPtrPtr = sPtr->nextRunPtr;
	    Ns_MasterLock();
	    if (sPtr->state != SprocExited) {
		NsThreadError("sproc %d called _exit() directly", pid);
		_exit(1);
	    }
	    Ns_MasterUnlock();
	    NsFree(sPtr);
        }

        /*
         * Start any new threads.
         */

	while ((sPtr = startPtr) != NULL) {
	    startPtr = sPtr->nextRunPtr;
	    sPtr->nextRunPtr = runPtr;
	    runPtr = sPtr;
	    StartSproc(sPtr);
	}
    }
}


/*
 *----------------------------------------------------------------------
 *
 * MgrTrigger --
 *
 *	Wakeup the manager thread.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Manager thread will wakeup if it's in a blocking read.
 *
 *----------------------------------------------------------------------
 */

static void
MgrTrigger(void)
{
    if (write(mgrPipe[1], "", 1) != 1) {
        NsThreadAbort("trigger write() faild: %s", strerror(errno));
    }
}


/*
 *----------------------------------------------------------------------
 *
 * exit --
 *
 *	Replacement for standard exit(3) routine to kill and wait
 *  	for all threads to die before calling the real libc
 *	__exit(3) routine.  It's important to wait for all
 *	threads to leave the share group to ensure exit(3) cleanup
 *	is performed (i.e., run atexit(3) procs, close streams, etc.).
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	All other threads are almost instantly killed.
 *
 *----------------------------------------------------------------------
 */

void
exit(int status)
{
    int maxticks, nshare, pid, nmax;
    Sproc *sPtr;

    if (mgrPid > 0) {

	/*
	 * Ignore the manager death signal and then signal
	 * shutdown pending.
	 */

	pid = getpid();
	if (pid == initPid) {
	    ns_signal(SIGCLD, SIG_IGN);
	} else {
	    ns_signal(SIGHUP, SIG_IGN);
	}
	Ns_MasterLock();
	shutdownPending = 1;
	Ns_MasterUnlock();
	MgrTrigger();

	/*
	 * Spin wait up to two seconds for all other threads to leave
	 * the share group.
	 */

	if (pid == initPid) {
	    nmax = 1;
	} else {
	    nmax = 2;
	}
	maxticks = CLK_TCK * 2;
	while ((nshare = prctl(PR_GETNSHARE)) > nmax && --maxticks >= 0) {
	    sginap(2);
	}
	if (nshare > nmax) {
	    NsThreadError("warning: exit timeout: %d sprocs remain in share group",
		nshare);
	}
    }
    __exit(status);
}


/*
 *----------------------------------------------------------------------
 *
 * fork --
 *
 *	Fork wrapper to forget about the thread manager and update
 *	the pid's in the child.
 *
 * Results:
 *	See fork(2).
 *
 * Side effects:
 *	Child will not have access to parent's thread manager.
 *
 *----------------------------------------------------------------------
 */

pid_t
fork(void)
{
    extern pid_t _fork(void);
    pid_t pid;
    Sproc *sPtr;

    pid = _fork();
    if (pid == 0) {

	/*
	 * Close off the thread manager pipe if opened.
	 */

	if (mgrPid != -1) {
    	    mgrPid = -1;
    	    close(mgrPipe[0]);
    	    close(mgrPipe[1]);
	}

	/*
	 * Update the new process pid.
	 */

    	sPtr = GETSPROC();
	sPtr->pid = getpid();
	if (sPtr->thrPtr != NULL) {
	    sPtr->thrPtr->tid = sPtr->pid;
	}
    }
    return pid;
}