summaryrefslogtreecommitdiff
path: root/src/pal/src/shmemory/shmemory.cpp
blob: 35dadd6b3a0459476b505ba75e7398ee8cea2523 (plain)
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
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*++



Module Name:

    shmemory/shmemory.c

Abstract:

    Implementation of shared memory infrastructure for IPC

Issues :

 Interprocess synchronization


There doesn't seem to be ANY synchronization mechanism that will work
inter-process AND be pthread-safe. FreeBSD's pthread implementation has no
support for inter-process synchronization (PTHREAD_PROCESS_SHARED);
"traditionnal" inter-process syncronization functions, on the other hand, are
not pthread-aware, and thus will block entire processes instead of only the
calling thread.

From suggestions and information obtained on the freebsd-hackers mailing list,
I have come up with 2 possible strategies to ensure serialized access to our
shared memory region

Note that the estimates of relative efficiency are wild guesses; my assumptions
are that blocking entire processes is least efficient, busy wait somewhat
better, and anything that does neither is preferable. However, the overhead of
complex solutions is likely to have an important impact on performance

Option 1 : very simple; possibly less efficient. in 2 words : "busy wait"
Basically,

while(InterlockedCompareExchange(spinlock_in_shared_memory, 1, 0)
    sched_yield();

In other words, if a value is 0, set it to 1; otherwise, try again until we
succeed. use shed_yield to give the system a chance to schedule other threads
while we wait. (once a thread succeeds at this, it does its work, then sets
the value back to 0)
One inconvenient : threads will not unblock in the order they are blocked;
once a thread releases the mutex, whichever waiting thread is scheduled next
will be unblocked. This is what is called the "thundering herd" problem, and in
extreme cases, can lead to starvation
Update : we'll set the spinlock to our PID instead of 1, that way we can find
out if the lock is held by a dead process.

Option 2 : possibly more efficient, much more complex, borders on
"over-engineered". I'll explain it in stages, in the same way I deduced it.

Option 2.1 : probably less efficient, reasonably simple. stop at step 2)

1) The minimal, original idea was to use SysV semaphores for synchronization.
This didn't work, because semaphores block the entire process, which can easily
lead to deadlocks (thread 1 takes sem, thread 2 tries to take sem, blocks
process, thread 1 is blocked and never releases sem)

2) (this is option 2.1) Protect the use of the semaphores in critical sections.
Enter the critical section before taking the semaphore, leave the section after
releasing the semaphore. This ensures that 2 threads of the same process will
never try to acquire the semaphore at the same time, which avoids deadlocks.
However, the entire process still blocks if another process has the semaphore.
Here, unblocking order should match blocking order (assuming the semaphores work
properly); therefore, no risk of starvation.

3) This is where it gets complicated. To avoid blocking whole processes, we
can't use semaphores. One suggestion I got was to use multi-ended FIFOs, here's
how it would work.

-as in option 1, use InterlockedCompareExchange on a value in shared memory.
-if this was not succesful (someone else has locked the shared memory), then :
    -open a special FIFO for reading; try to read 1 byte. This will block until
     someone writes to it, and *should* only block the current thread. (note :
     more than one thread/process can open the same FIFO and block on read(),
     in this case, only one gets woken up when someone writes to it.
     *which* one is, again, not predictable; this may lead to starvation)
    -once we are unblocked, we have the lock.
-once we have the lock (either from Interlocked...() or from read()),
 we can do our work
-once the work is done, we open the FIFO for writing. this will fail if no one
 is listening.
-if no one is listening, release the lock by setting the shared memory value
 back to 0
-if someone is listening, write 1 byte to the FIFO to wake someone, then close
 the FIFO. the value in shared memory will remain nonzero until a thread tries
 to wake the next one and sees no one is listening.

problem with this option : it is possible for a thread to call Interlocked...()
BETWEEN the failed "open for write" attempt and the subsequent restoration of
the SHM value back to zero. In this case, that thread will go to sleep and will
not wake up until *another* thread asks for the lock, takes it and releases it.

so to fix that, we come to step

4) Instead of using InterlockedCompareExchange, use a SysV semaphore :
-when taking the lock :
    -take the semaphore
    -try to take the lock (check if value is zero, change it to 1 if it is)
    -if we fail : open FIFO for reading, release the semaphore, read() and block
    -if we succeed : release the semaphore
-when releasing the lock :
    -take the semaphore
    -open FIFO for write
    -if we succeed, release semaphore, then write value
    -if we fail, reset SHM value to 0, then release semaphore.

Yes, using a SysV semaphore will block the whole process, but for a very short
time (unlike option 2.1)
problem with this : again, we get deadlocks if 2 threads from a single process
try to take the semaphore. So like in option 2.1, we ave to wrap the semaphore
usage in a critical section. (complex enough yet?)

so the locking sequence becomes EnterCriticalSection - take semaphore - try to
    lock - open FIFO - release semaphore - LeaveCriticalSection - read
and the unlocking sequence becomes EnterCS - take sem - open FIFO - release
    sem - LeaveCS - write

Once again, the unblocking order probably won't match the blocking order.
This could be fixed by using multiple FIFOs : waiting thread open their own
personal FIFO, write the ID of their FIFO to another FIFO. The thread that wants
to release the lock reads ID from that FIFO, determines which FIFO to open for
writing and writes a byte to it. This way, whoever wrote its ID to the FIFO
first will be first to awake. How's that for complexity?

So to summarize, the options are
1 - busy wait
2.1 - semaphores + critical sections (whole process blocks)
2 - semaphores + critical sections + FIFOs (minimal process blocking)
2.2 - option 2 with multiple FIFOs (minimal process blocking, order preserved)

Considering the overhead involved in options 2 & 2.2, it is our guess that
option 1 may in fact be more efficient, and this is how we'll implement it for
the moment. Note that other platforms may not present the same difficulties
(i.e. other pthread implementations may support inter-process mutexes), and may
be able to use a simpler, more efficient approach.

B] Reliability.
It is important for the shared memory implementation to be as foolproof as
possible. Since more than one process will be able to modify the shared data,
it becomes possible for one unstable process to destabilize the others. The
simplest example is a process that dies while modifying shared memory : if
it doesn't release its lock, we're in trouble. (this case will be taken care
of by using PIDs in the spinlock; this we we can check if the locking process
is still alive).



--*/

#include "config.h"
#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "pal/shmemory.h"
#include "pal/critsect.h"
#include "pal/shmemory.h"
#include "pal/init.h"
#include "pal/process.h"
#include "pal/misc.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <sched.h>
#include <pthread.h>

#if HAVE_YIELD_SYSCALL
#include <sys/syscall.h>
#endif  /* HAVE_YIELD_SYSCALL */
        
SET_DEFAULT_DEBUG_CHANNEL(SHMEM);

/* Macro-definitions **********************************************************/

/* rounds 'val' up to be divisible by 'r'.  'r' must be a power of two. */
#ifndef roundup
#define roundup(val, r)  ( ((val)+(r)-1) & ~( (r)-1 ) )
#endif

#define SEGMENT_NAME_SUFFIX_LENGTH 10

/*
SHMPTR structure :
High byte is SHM segment number
Low bytes are offset in the segment
 */
#define SHMPTR_SEGMENT(shmptr) \
    (((shmptr)>>24)&0xFF)

#define SHMPTR_OFFSET(shmptr) \
    ((shmptr)&0x00FFFFFF)

#define MAKE_SHMPTR(segment,offset) \
    ((SHMPTR)((((segment)&0xFF)<<24)|((offset)&0x00FFFFFF)))

/*#define MAX_SEGMENTS 256*//*definition is now in shmemory.h*/

/* Use MAP_NOSYNC to improve performance if it's available */
#if defined(MAP_NOSYNC)
#define MAPFLAGS MAP_NOSYNC|MAP_SHARED
#else
#define MAPFLAGS MAP_SHARED
#endif


/* Type definitions ***********************************************************/

enum SHM_POOL_SIZES
{
    SPS_16 = 0,      /* 16 bytes */
    SPS_32,         /* 32 bytes */
    SPS_64,         /* 64 bytes */
    SPS_MAXPATHx2,  /* 520 bytes, for long Unicode paths */

    SPS_LAST
};
/* Block size associated to each SPS identifier */
static const int block_sizes[SPS_LAST] = {16,32,64,roundup((MAX_LONGPATH+1)*2, sizeof(INT64))};

/*
SHM_POOL_INFO
Description of a shared memory pool for a specific block size.

Note on pool structure :
first_free identifies the first available SHMPTR in the block. Free blocks are
arranged in a linked list, each free block indicating the location of the next
one. To walk the list, do something like this :
SHMPTR *shmptr_ptr=(SHMPTR *)SHMPTR_TO_PTR(pool->first_free)
while(shm_ptr)
{
    SHMPTR next = *shmptr_ptr;
    shmptr_ptr = (SHMPTR *)SHMPTR_TO_PTR(next)
}
 */
typedef struct
{
    int item_size;          /* size of 1 block, in bytes */
    int num_items;          /* total number of blocks in the pool */
    int free_items;         /* number of unused items in the pool */
    SHMPTR first_free;      /* location of first available block in the pool */
}SHM_POOL_INFO;

/*
SHM_SEGMENT_HEADER
Description of a single shared memory segment

Notes on segment names :
next_semgent contains the string generated by mkstemp() when a new segment is
generated. This allows processes to map segment files created by other
processes. To get the file name of a segment file, concatenate
"segment_name_prefix" and "next_segment".

Notes on pool segments :
Each segment is divided into one pool for each defined block size (SPS_*).
These pools are linked with pools in other segment to form one large pool for
each block size, so that SHMAlloc() doesn't have to search each segment to find
an available block.
the first_ and last_pool_blocks indicate the first and last block in a single
segment for each block size. This allows SHMFree() to determine the size of a
block by comparing its value with these boundaries. (note that within each
segment, each pool is composed of a single contiguous block of memory)
*/
typedef struct
{
    Volatile<SHMPTR> first_pool_blocks[SPS_LAST];
    Volatile<SHMPTR> last_pool_blocks[SPS_LAST];
} SHM_SEGMENT_HEADER;

/*
SHM_FIRST_HEADER
Global information about the shared memory system
In addition to the standard SHM_SEGGMENT_HEADER, the first segment contains some
information required to properly use the shared memory system.

The spinlock is used to ensure that only one process accesses shared memory at
the same time. A process can only take the spinlock if its contents is 0, and
it takes the spinlock by placing its PID in it. (this allows a process to catch
the special case where it tries to take a spinlock it already owns.

The first_* members will contain the location of the first element in the
various linked lists of shared information
 */

#ifdef TRACK_SHMLOCK_OWNERSHIP

#define SHMLOCK_OWNERSHIP_HISTORY_ARRAY_SIZE 5

#define CHECK_CANARIES(header) \
    _ASSERTE(HeadSignature == header->dwHeadCanaries[0]); \
    _ASSERTE(HeadSignature == header->dwHeadCanaries[1]); \
    _ASSERTE(TailSignature == header->dwTailCanaries[0]);   \
    _ASSERTE(TailSignature == header->dwTailCanaries[1])

typedef struct _pid_and_tid
{
    Volatile<pid_t> pid;
    Volatile<pthread_t> tid;
} pid_and_tid;

const DWORD HeadSignature  = 0x48454144;
const DWORD TailSignature  = 0x5441494C;

#endif // TRACK_SHMLOCK_OWNERSHIP

typedef struct
{
    SHM_SEGMENT_HEADER header;
#ifdef TRACK_SHMLOCK_OWNERSHIP
    Volatile<DWORD> dwHeadCanaries[2];
#endif // TRACK_SHMLOCK_OWNERSHIP
    Volatile<pid_t> spinlock;
#ifdef TRACK_SHMLOCK_OWNERSHIP
    Volatile<DWORD> dwTailCanaries[2];
    pid_and_tid pidtidCurrentOwner;
    pid_and_tid pidtidOwners[SHMLOCK_OWNERSHIP_HISTORY_ARRAY_SIZE];
    Volatile<ULONG> ulOwnersIdx;
#endif // TRACK_SHMLOCK_OWNERSHIP
    SHM_POOL_INFO pools[SPS_LAST]; /* information about each memory pool */
    Volatile<SHMPTR> shm_info[SIID_LAST]; /* basic blocks of shared information.*/
} SHM_FIRST_HEADER;


/* Static variables ***********************************************************/

/* Critical section to ensure that only one thread at a time accesses shared
memory. Rationale :
-Using a spinlock means that processes must busy-wait for the lock to be
 available. The critical section ensures taht only one thread will busy-wait,
 while the rest are put to sleep.
-Since the spinlock only contains a PID, it isn't possible to make a difference
 between threads of the same process. This could be resolved by using 2
 spinlocks, but this would introduce more busy-wait.
*/
static CRITICAL_SECTION shm_critsec;
                        
/* number of segments the current process knows about */
int shm_numsegments;

/* array containing the base address of each segment */
Volatile<LPVOID> shm_segment_bases[MAX_SEGMENTS];

/* number of locks the process currently holds (SHMLock calls without matching
SHMRelease). Because we take the critical section while inside a
SHMLock/SHMRelease pair, this is actually the number of locks held by a single
thread. */
static Volatile<LONG> lock_count;

/* thread ID of thread holding the SHM lock. used for debugging purposes : 
   SHMGet/SetInfo will verify that the calling thread holds the lock */
static Volatile<HANDLE> locking_thread;

/* Constants ******************************************************************/

/* size of a single segment : 256KB */
static const int segment_size = 0x40000;

/* Static function prototypes *************************************************/

static SHMPTR SHMInitPool(SHMPTR first, int block_size, int pool_size,
                          SHM_POOL_INFO *pool);
static SHMPTR SHMLinkPool(SHMPTR first, int block_size, int num_blocks);
static BOOL   SHMMapUnknownSegments(void);
static BOOL   SHMAddSegment(void);


#define init_waste()
#define log_waste(x,y)
#define save_waste()

/* Public function implementations ********************************************/

/*++
SHMInitialize

Hook this process into the PAL shared memory system; initialize the shared
memory if no other process has done it.

--*/
BOOL SHMInitialize(void)
{
    InternalInitializeCriticalSection(&shm_critsec);

    init_waste();
    
        int size;
        SHM_FIRST_HEADER *header;
        SHMPTR pool_start;
        SHMPTR pool_end;
        enum SHM_POOL_SIZES sps;

        TRACE("Now initializing global shared memory system\n");
        
        // Not really shared in CoreCLR; we don't try to talk to other CoreCLRs.
        shm_segment_bases[0] = mmap(NULL, segment_size,PROT_READ|PROT_WRITE,
                                    MAP_ANON|MAP_PRIVATE, -1, 0);
        if(shm_segment_bases[0] == MAP_FAILED)
        {
            ERROR("mmap() failed; error is %d (%s)\n", errno, strerror(errno));
            return FALSE;
        }
        TRACE("Mapped first SHM segment at %p\n",shm_segment_bases[0].Load());

        /* Initialize first segment's header */
        header = (SHM_FIRST_HEADER *)shm_segment_bases[0].Load();

        InterlockedExchange((LONG *)&header->spinlock, 0);
        
#ifdef TRACK_SHMLOCK_OWNERSHIP
        header->dwHeadCanaries[0] = HeadSignature;
        header->dwHeadCanaries[1] = HeadSignature;
        header->dwTailCanaries[0] = TailSignature;
        header->dwTailCanaries[1] = TailSignature;        

        // Check spinlock size
        _ASSERTE(sizeof(DWORD) == sizeof(header->spinlock));
        // Check spinlock alignment
        _ASSERTE(0 == ((DWORD_PTR)&header->spinlock % (DWORD_PTR)sizeof(void *)));        
#endif // TRACK_SHMLOCK_OWNERSHIP

#ifdef TRACK_SHMLOCK_OWNERSHIP
        header->pidtidCurrentOwner.pid = 0;
        header->pidtidCurrentOwner.tid = 0;
        memset((void *)header->pidtidOwners, 0, sizeof(header->pidtidOwners));
        header->ulOwnersIdx = 0;
#endif // TRACK_SHMLOCK_OWNERSHIP

        /* SHM information array starts with NULLs */
        memset((void *)header->shm_info, 0, SIID_LAST*sizeof(SHMPTR));

        /* Initialize memory pools */

        /* first pool starts right after header */
        pool_start = roundup(sizeof(SHM_FIRST_HEADER), sizeof(INT64));

        /* Same size for each pool, ensuring alignment is correct */
        size = ((segment_size-pool_start)/SPS_LAST) & ~(sizeof(INT64)-1);

        for (sps = static_cast<SHM_POOL_SIZES>(0); sps < SPS_LAST;
             sps = static_cast<SHM_POOL_SIZES>(sps + 1))
        {
            pool_end = SHMInitPool(pool_start, block_sizes[sps], size,
                                   (SHM_POOL_INFO *)&header->pools[sps]);

            if(pool_end ==0)
            {
                ERROR("SHMInitPool failed.\n");
                munmap(shm_segment_bases[0],segment_size);
                return FALSE;
            }
            /* save first and last element of each pool for this segment */
            header->header.first_pool_blocks[sps] = pool_start;
            header->header.last_pool_blocks[sps] = pool_end;

            /* next pool starts immediately after this one */
            pool_start +=size;
        }

        TRACE("Global shared memory initialization complete.\n");

    shm_numsegments = 1;
    lock_count = 0;
    locking_thread = 0;

    /* hook into all SHM segments */
    if(!SHMMapUnknownSegments())
    {
        ERROR("Error while mapping segments!\n");
        SHMCleanup();
        return FALSE;
    }
    return TRUE;
}

/*++
SHMCleanup

Release all shared memory resources held; remove ourselves from the list of
registered processes, and remove all shared memory files if no process remains

Note that this function does not use thread suspension wrapper for unlink and free
because all thread objects are deleted before this function is called
in PALCommonCleanup.

--*/
void SHMCleanup(void)
{
    SHM_FIRST_HEADER *header;
    pid_t my_pid;

    TRACE("Starting shared memory cleanup\n");

    SHMLock();
    SHMRelease();

    /* We should not be holding the spinlock at this point. If we are, release
       the spinlock. by setting it to 0 */
    my_pid = gPID;
    header = (SHM_FIRST_HEADER *)shm_segment_bases[0].Load();

    _ASSERT_MSG(header->spinlock != my_pid,
            "SHMCleanup called while the current process still owns the lock "
            "[owner thread=%u, current thread: %u]\n", 
            locking_thread.Load(), THREADSilentGetCurrentThreadId());

    /* Now for the interprocess stuff. */
    DeleteCriticalSection(&shm_critsec);


    /* Unmap memory segments */
    while(shm_numsegments)
    {
        shm_numsegments--;
        if ( -1 == munmap( shm_segment_bases[ shm_numsegments ], 
                           segment_size ) )
        {
            ASSERT( "munmap() failed; errno is %d (%s).\n",
                  errno, strerror( errno ) );
        }
    }

    save_waste();
    TRACE("SHMCleanup complete!\n");
}

/*++
SHMalloc

Allocate a block of memory of the specified size

Parameters :
    size_t size : size of block required

Return value :
    A SHMPTR identifying the new block, or 0 on failure. Use SHMPTR_TO_PTR to
    convert a SHMPTR into a useable pointer (but remember to lock the shared
    memory first!)

Notes :
    SHMalloc will fail if the requested size is larger than a certain maximum.
    At the moment, the maximum is 520 bytes (MAX_LONGPATH*2).
--*/
SHMPTR SHMalloc(size_t size)
{
    enum SHM_POOL_SIZES sps;
    SHMPTR first_free;
    SHMPTR next_free;
    SHM_FIRST_HEADER *header;
    SHMPTR *shmptr_ptr;

    TRACE("SHMalloc() called; requested size is %u\n", size);

    if(0 == size)
    {
        WARN("Got a request for a 0-byte block! returning 0\n");
        return 0;
    }

    /* Find the first block size >= requested size */
    for (sps = static_cast<SHM_POOL_SIZES>(0); sps < SPS_LAST;
         sps = static_cast<SHM_POOL_SIZES>(sps + 1))
    {
        if (size <= static_cast<size_t>(block_sizes[sps]))
        {
            break;
        }
    }

    /* If no block size is found, requested size was too large. */
    if( SPS_LAST == sps )
    {
        ASSERT("Got request for shared memory block of %u bytes; maximum block "
              "size is %d.\n", size, block_sizes[SPS_LAST-1]);
        return 0;
    }

    TRACE("Best block size is %d (%d bytes wasted)\n",
          block_sizes[sps], block_sizes[sps]-size );

    log_waste(sps, block_sizes[sps]-size);

    SHMLock();
    header = (SHM_FIRST_HEADER *)shm_segment_bases[0].Load();

    /* If there are no free items of the specified size left, it's time to
       allocate a new shared memory segment.*/
    if(header->pools[sps].free_items == 0)
    {
        TRACE("No blocks of %d bytes left; allocating new segment.\n",
              block_sizes[sps]);
        if(!SHMAddSegment())
        {
            ERROR("Unable to allocate new shared memory segment!\n");
            SHMRelease();
            return 0;
        }
    }

    /* Remove the first free block from the pool */
    first_free = header->pools[sps].first_free;
    shmptr_ptr = static_cast<SHMPTR*>(SHMPTR_TO_PTR(first_free));

    if( 0 == first_free )
    {
        ASSERT("First free block in %d-byte pool (%08x) was invalid!\n",
              block_sizes[sps], first_free);
        SHMRelease();
        return 0;
    }

    /* the block "first_free" is the head of a linked list of free blocks;
       take the next link in the list and set it as new head of list. */
    next_free = *shmptr_ptr;
    header->pools[sps].first_free = next_free;
    header->pools[sps].free_items--;

    /* make sure we're still in a sane state */
    if(( 0 == header->pools[sps].free_items && 0 != next_free) ||
       ( 0 != header->pools[sps].free_items && 0 == next_free))
    {
        ASSERT("free block count is %d, but next free block is %#x\n", 
               header->pools[sps].free_items, next_free);
        /* assume all remaining blocks in the pool are corrupt */
        header->pools[sps].first_free = 0;
        header->pools[sps].free_items = 0;
    }
    else if (0 != next_free && 0 == SHMPTR_TO_PTR(next_free) )
    {
        ASSERT("Next free block (%#x) in %d-byte pool is invalid!\n",
               next_free, block_sizes[sps]);
        /* assume all remaining blocks in the pool are corrupt */
        header->pools[sps].first_free = 0;
        header->pools[sps].free_items = 0;
    }

    SHMRelease();

    TRACE("Allocation successful; %d blocks of %d bytes left. Returning %08x\n",
          header->pools[sps].free_items, block_sizes[sps], first_free);
    return first_free;
}

/*++
SHMfree

Release a block of shared memory and put it back in the shared memory pool

Parameters :
    SHMPTR shmptr : identifier of block to release

(no return value)
--*/
void SHMfree(SHMPTR shmptr)
{
    int segment;
    int offset;
    SHM_SEGMENT_HEADER *header;
    SHM_FIRST_HEADER *first_header;
    enum SHM_POOL_SIZES sps;
    SHMPTR *shmptr_ptr;

    if(0 == shmptr)
    {
        WARN("can't SHMfree() a NULL SHMPTR!\n");
        return;
    }
    SHMLock();

    TRACE("Releasing SHMPTR 0x%08x\n", shmptr);

    shmptr_ptr = static_cast<SHMPTR*>(SHMPTR_TO_PTR(shmptr));

    if(!shmptr_ptr)
    {
        ASSERT("Tried to free an invalid shared memory pointer 0x%08x\n", shmptr);
        SHMRelease();
        return;
    }

    /* note : SHMPTR_TO_PTR has already validated the segment/offset pair */
    segment = SHMPTR_SEGMENT(shmptr);
    header = (SHM_SEGMENT_HEADER *)shm_segment_bases[segment].Load();

    /* Find out the size of this block. Each segment tells where are its first
       and last blocks for each block size, so we simply need to check in which
       interval the block fits */
    for (sps = static_cast<SHM_POOL_SIZES>(0); sps < SPS_LAST;
         sps = static_cast<SHM_POOL_SIZES>(sps + 1))
    {
        if(header->first_pool_blocks[sps]<=shmptr &&
           header->last_pool_blocks[sps]>=shmptr)
        {
            break;
        }
    }

    /* If we didn't find an interval, then the block doesn't really belong in
       this segment (shouldn't happen, the offset check in SHMPTR_TO_PTR should
       have caught this.)  */
    if(sps == SPS_LAST)
    {
        ASSERT("Shared memory pointer 0x%08x is out of bounds!\n", shmptr);
        SHMRelease();
        return;
    }

    TRACE("SHMPTR 0x%08x is a %d-byte block located in segment %d\n",
          shmptr, block_sizes[sps], segment);

    /* Determine the offset of this block (in bytes) relative to the first
       block of the same size in this segment */
    offset = shmptr - header->first_pool_blocks[sps];

    /* Make sure that the offset is a multiple of the block size; otherwise,
       this isn't a real SHMPTR */
    if( 0 != ( offset % block_sizes[sps] ) )
    {
        ASSERT("Shared memory pointer 0x%08x is misaligned!\n", shmptr);
        SHMRelease();
        return;
    }

    /* Put the SHMPTR back in its pool. */
    first_header = (SHM_FIRST_HEADER *)shm_segment_bases[0].Load();

    /* first_free is the head of a linked list of free SHMPTRs. All we need to
       do is make shmptr point to first_free, and set shmptr as the new head
       of the list. */
    *shmptr_ptr = first_header->pools[sps].first_free;
    first_header->pools[sps].first_free = shmptr;
    first_header->pools[sps].free_items++;

    TRACE("SHMPTR 0x%08x released; there are now %d blocks of %d bytes "
          "available\n", shmptr, first_header->pools[sps].free_items,
          block_sizes[sps]);
    SHMRelease();
}

/*++
SHMLock

Restrict shared memory access to the current thread of the current process

(no parameters)

Return value :
    New lock count

Notes :
see comments at the declaration of shm_critsec for rationale of critical
section usage
--*/
int SHMLock(void)
{
    /* Hold the critical section until the lock is released */
    PALCEnterCriticalSection(&shm_critsec);

    _ASSERTE((0 == lock_count && 0 == locking_thread) ||
             (0 < lock_count && (HANDLE)pthread_self() == locking_thread));
             
    if(lock_count == 0)
    {
        SHM_FIRST_HEADER *header;
        pid_t my_pid, tmp_pid;
        int spincount = 1;
#ifdef TRACK_SHMLOCK_OWNERSHIP
        ULONG ulIdx;
#endif // TRACK_SHMLOCK_OWNERSHIP

        TRACE("First-level SHM lock : taking spinlock\n");

        header = (SHM_FIRST_HEADER *)shm_segment_bases[0].Load();

        // Store the id of the current thread as the (only) one that is 
        // trying to grab the spinlock from the current process
        locking_thread = (HANDLE)pthread_self();

        my_pid = gPID;
        
        while(TRUE)
        {
#ifdef TRACK_SHMLOCK_OWNERSHIP
            _ASSERTE(0 != my_pid);
            _ASSERTE(getpid() == my_pid);
            _ASSERTE(my_pid != header->spinlock);
            CHECK_CANARIES(header);
#endif // TRACK_SHMLOCK_OWNERSHIP

            //
            // Try to grab the spinlock
            //
            tmp_pid = InterlockedCompareExchange((LONG *) &header->spinlock, my_pid,0);

#ifdef TRACK_SHMLOCK_OWNERSHIP
            CHECK_CANARIES(header);
#endif // TRACK_SHMLOCK_OWNERSHIP

            if (0 == tmp_pid)
            {
                // Spinlock acquired: break out of the loop
                break;
            }

            /* Check if lock holder is alive. If it isn't, we can reset the
               spinlock and try to take it again. If it is, we have to wait.
               We use "spincount" to do this check only every 8th time through
               the loop, for performance reasons.*/
            if( (0 == (spincount&0x7)) &&
                (-1 == kill(tmp_pid,0)) &&
                (errno == ESRCH))
            {
                TRACE("SHM spinlock owner (%08x) is dead; releasing its lock\n",
                      tmp_pid);

                InterlockedCompareExchange((LONG *) &header->spinlock, 0, tmp_pid);
            }
            else
            {
                /* another process is holding the lock... we want to yield and 
                   give the holder a chance to release the lock
                   The function sched_yield() only yields to a thread in the 
                   current process; this doesn't help us much, anddoens't help 
                   at all if there's only 1 thread. There doesn't seem to be 
                   any clean way to force a yield to another process, but the 
                   FreeBSD syscall "yield" does the job. We alternate between 
                   both methods to give other threads of this process a chance 
                   to run while we wait.
                 */
#if HAVE_YIELD_SYSCALL
                if(spincount&1)
                {
#endif  /* HAVE_YIELD_SYSCALL */
                    sched_yield();
#if HAVE_YIELD_SYSCALL
                }
                else
                {
                    /* use the syscall first, since we know we'l need to yield 
                       to another process eventually - the lock can't be held 
                       by the current process, thanks to the critical section */
                    syscall(SYS_yield, 0);
                }
#endif  /* HAVE_YIELD_SYSCALL */
            }

            // Increment spincount
            spincount++;
        }

        _ASSERT_MSG(my_pid == header->spinlock,
            "\n(my_pid = %u) != (header->spinlock = %u)\n"
            "tmp_pid         = %u\n"
            "spincount       = %d\n"
            "locking_thread  = %u\n", 
            (DWORD)my_pid, (DWORD)header->spinlock, 
            (DWORD)tmp_pid,
            (int)spincount,
            (HANDLE)locking_thread);

#ifdef TRACK_SHMLOCK_OWNERSHIP
        _ASSERTE(0 == header->pidtidCurrentOwner.pid);
        _ASSERTE(0 == header->pidtidCurrentOwner.tid);

        header->pidtidCurrentOwner.pid = my_pid;
        header->pidtidCurrentOwner.tid = locking_thread;

        ulIdx = header->ulOwnersIdx % (sizeof(header->pidtidOwners) / sizeof(header->pidtidOwners[0])); 
        
        header->pidtidOwners[ulIdx].pid = my_pid;
        header->pidtidOwners[ulIdx].tid = locking_thread;

        header->ulOwnersIdx += 1;
#endif // TRACK_SHMLOCK_OWNERSHIP
        
    }

    lock_count++;
    TRACE("SHM lock level is now %d\n", lock_count.Load());
    return lock_count;
}

/*++
SHMRelease

Release a lock on shared memory taken with SHMLock.

(no parameters)

Return value :
    New lock count

--*/
int SHMRelease(void)
{
    /* prevent a thread from releasing another thread's lock */
    PALCEnterCriticalSection(&shm_critsec);

    if(lock_count==0)
    {
        ASSERT("SHMRelease called without matching SHMLock!\n");
        PALCLeaveCriticalSection(&shm_critsec);
        return 0;
    }

    lock_count--;

    _ASSERTE(lock_count >= 0);

    /* If lock count is 0, this call matches the first Lock call; it's time to
       set the spinlock back to 0. */
    if(lock_count == 0)
    {
        SHM_FIRST_HEADER *header;
        pid_t my_pid, tmp_pid;

        TRACE("Releasing first-level SHM lock : resetting spinlock\n");

        my_pid = gPID;
        
        header = (SHM_FIRST_HEADER *)shm_segment_bases[0].Load();

#ifdef TRACK_SHMLOCK_OWNERSHIP
        CHECK_CANARIES(header);
        _ASSERTE(0 != my_pid);
        _ASSERTE(getpid() == my_pid);        
        _ASSERTE(my_pid == header->spinlock);
        _ASSERTE(header->pidtidCurrentOwner.pid == my_pid);
        _ASSERTE(pthread_self() == header->pidtidCurrentOwner.tid);
        _ASSERTE((pthread_t)locking_thread == header->pidtidCurrentOwner.tid);

        header->pidtidCurrentOwner.pid = 0;
        header->pidtidCurrentOwner.tid = 0;
#endif // TRACK_SHMLOCK_OWNERSHIP


        /* Make sure we don't touch the spinlock if we don't own it. We're
           supposed to own it if we get here, but just in case... */
        tmp_pid = InterlockedCompareExchange((LONG *) &header->spinlock, 0, my_pid);

        if (tmp_pid != my_pid)
        {
            ASSERT("Process 0x%08x tried to release spinlock owned by process "
                   "0x%08x! \n", my_pid, tmp_pid);
            PALCLeaveCriticalSection(&shm_critsec);
            return 0;
        }

        /* indicate no thread (in this process) holds the SHM lock */
        locking_thread = 0;

#ifdef TRACK_SHMLOCK_OWNERSHIP
        CHECK_CANARIES(header);
#endif // TRACK_SHMLOCK_OWNERSHIP
    }

    TRACE("SHM lock level is now %d\n", lock_count.Load());

    /* This matches the EnterCriticalSection from SHMRelease */
    PALCLeaveCriticalSection(&shm_critsec);

    /* This matches the EnterCriticalSection from SHMLock */
    PALCLeaveCriticalSection(&shm_critsec);

    return lock_count;
}

/*++
SHMPtrToPtr

Convert a SHMPTR value to a valid pointer within the address space of the
current process

Parameters :
    SHMPTR shmptr : SHMPTR value to convert into a pointer

Return value :
    Address corresponding to the given SHMPTR, valid for the current process

Notes :
(see notes for SHMPTR_SEGMENT macro for details on SHMPTR structure)

It is possible for the segment index to be greater than the known total number
of segments (shm_numsegments); this means that the SHMPTR points to a memory
block in a shared memory segment this process doesn't know about. In this case,
we must obtain an address for that new segment and add it to our array
(see SHMMapUnknownSegments for details)

In the simplest case (no need to map new segments), there is no need to hold
the lock, since we don't access any information that can change
--*/
LPVOID SHMPtrToPtr(SHMPTR shmptr)
{
    void *retval;
    int segment;
    int offset;

    TRACE("Converting SHMPTR 0x%08x to a valid pointer...\n", shmptr);
    if(!shmptr)
    {
        WARN("Got SHMPTR \"0\"; returning NULL pointer\n");
        return NULL;
    }

    segment = SHMPTR_SEGMENT(shmptr);

    /* If segment isn't known, it may have been added by another process. We
       need to map all new segments into our address space. */
    if(segment>= shm_numsegments)
    {
        TRACE("SHMPTR is in segment %d, we know only %d. We must now map all "
              "unknowns.\n", segment, shm_numsegments);
        SHMMapUnknownSegments();

        /* if segment is still unknown, then it doesn't exist */
        if(segment>=shm_numsegments)
        {
            ASSERT("Segment %d still unknown; returning NULL\n", segment);
            return NULL;
        }
        TRACE("Segment %d found; continuing\n", segment);
    }

    /* Make sure the offset doesn't point outside the segment */
    offset = SHMPTR_OFFSET(shmptr);
    if(offset>=segment_size)
    {
        ASSERT("Offset %d is larger than segment size (%d)! returning NULL\n",
              offset, segment_size);
        return NULL;

    }

    /* Make sure the offset doesn't point in the segment's header */
    if(segment == 0)
    {
        if (static_cast<size_t>(offset) < roundup(sizeof(SHM_FIRST_HEADER), sizeof(INT64)))
        {
            ASSERT("Offset %d is in segment header! returning NULL\n", offset);
            return NULL;
        }
    }
    else
    {
        if (static_cast<size_t>(offset) < sizeof(SHM_SEGMENT_HEADER))
        {
            ASSERT("Offset %d is in segment header! returning NULL\n", offset);
            return NULL;
        }
    }

    retval = shm_segment_bases[segment];
    retval = static_cast<BYTE*>(retval) + offset;

    TRACE("SHMPTR %#x is at offset %d in segment %d; maps to address %p\n",
          shmptr, offset, segment, retval);
    return retval;
}


/*++
Function :
    SHMGetInfo

    Retrieve some information from shared memory

Parameters :
    SHM_INFO_ID element : identifier of element to retrieve

Return value :
    Value of specified element

Notes :
    The SHM lock should be held while manipulating shared memory
--*/
SHMPTR SHMGetInfo(SHM_INFO_ID element)
{
    SHM_FIRST_HEADER *header = NULL;
    SHMPTR retval = 0;

    if(element < 0 || element >= SIID_LAST)
    {
        ASSERT("Invalid SHM info element %d\n", element);
        return 0;
    }

    /* verify that this thread holds the SHM lock. No race condition: if the 
       current thread is here, it can't be in SHMLock or SHMUnlock */
    if( (HANDLE)pthread_self() != locking_thread )
    {
        ASSERT("SHMGetInfo called while thread does not hold the SHM lock!\n");
    }

    header = (SHM_FIRST_HEADER *)shm_segment_bases[0].Load();

    retval = header->shm_info[element];

    TRACE("SHM info element %d is %08x\n", element, retval );
    return retval;
}


/*++
Function :
    SHMSetInfo

    Place some information into shared memory

Parameters :
    SHM_INFO_ID element : identifier of element to save
    SHMPTR value : new value of element

Return value :
    TRUE if successfull, FALSE otherwise.

Notes :
    The SHM lock should be held while manipulating shared memory
--*/
BOOL SHMSetInfo(SHM_INFO_ID element, SHMPTR value)
{
    SHM_FIRST_HEADER *header;

    if(element < 0 || element >= SIID_LAST)
    {
        ASSERT("Invalid SHM info element %d\n", element);
        return FALSE;
    }
    
    /* verify that this thread holds the SHM lock. No race condition: if the 
       current thread is here, it can't be in SHMLock or SHMUnlock */
    if( (HANDLE)pthread_self() != locking_thread )
    {
        ASSERT("SHMGetInfo called while thread does not hold the SHM lock!\n");
    }

    header = (SHM_FIRST_HEADER*)shm_segment_bases[0].Load();

    TRACE("Setting SHM info element %d to %08x; used to be %08x\n",
          element, value, header->shm_info[element].Load() );

    header->shm_info[element] = value;

    return TRUE;
}


/* Static function implementations ********************************************/

/*++
SHMInitPool

Perform one-time initialization for a shared memory pool.

Parameters :
    SHMPTR first : SHMPTR of first memory block in the pool
    int block_size : size (in bytes) of a memory block in this pool
    int pool_size : total size (in bytes) of this pool
    SHM_POOL_INFO *pool : pointer to initialize with information about the pool

Return value :
    SHMPTR of last memory block in the pool

Notes :
This function is used to initialize the memory pools of the first SHM segment.
In addition to creating a linked list of SHMPTRs, it initializes the given
SHM_POOL_INFO based on the given information.
--*/
static SHMPTR SHMInitPool(SHMPTR first, int block_size, int pool_size,
                          SHM_POOL_INFO *pool)
{
    int num_blocks;
    SHMPTR last;

    TRACE("Initializing SHM pool for %d-byte blocks\n", block_size);

    /* Number of memory blocks of size "block_size" that can fit in "pool_size"
       bytes (rounded down) */
    num_blocks = pool_size/block_size;

    /* Create the initial linked list of free blocks */
    last = SHMLinkPool(first, block_size, num_blocks);
    if( 0 == last )
    {
        ERROR("Failed to create linked list of free blocks!\n");
        return 0;
    }

    /* Initialize SHM_POOL_INFO */
    pool->first_free = first;
    pool->free_items = num_blocks;
    pool->item_size = block_size;
    pool->num_items = num_blocks;

    TRACE("New SHM pool extends from SHMPTR 0x%08x to 0x%08x\n", first, last);
    return last;
}

/*++
SHMLinkPool

Joins contiguous blocks of memory into a linked list..

Parameters :
    SHMPTR first : First SHMPTR in the memory pool; first link in the list
    int block_size : size (in bytes) of the memory blocks
    int num_blocks : number of contiguous blocks to link

Return value :
    SHMPTR of last memory block in the pool

Notes :
The linked list is created by saving the value of the next SHMPTR in the list
in the memory location corresponding to the previous SHMPTR :
*(SHMPTR *)SHMPTR_TO_PTR(previous) = previous + block_size
--*/
static SHMPTR SHMLinkPool(SHMPTR first, int block_size, int num_blocks)
{
    LPBYTE item_ptr;
    SHMPTR *shmptr_ptr;
    SHMPTR next_shmptr;
    int i;

    TRACE("Linking %d blocks of %d bytes, starting at 0x%08x\n",
          num_blocks, block_size, first);

    item_ptr = static_cast<LPBYTE>(
        static_cast<LPBYTE>(shm_segment_bases[SHMPTR_SEGMENT(first)].Load()) +
            (SHMPTR_OFFSET(first)));
    next_shmptr = first/*+block_size*/;

    /* Link blocks together */
    for(i=0; i<num_blocks; i++)
    {
        next_shmptr += block_size;

        /* item_ptr is char * (so we can increment with +=blocksize), we cast
           it to a SHMPTR * and set its content to the next SHMPTR in the list*/
        shmptr_ptr = (SHMPTR *)item_ptr;
        *shmptr_ptr = next_shmptr;

        item_ptr+=block_size;
    }
    /* Last SHMPTR in the list must point to NULL */
    item_ptr-=block_size;
    shmptr_ptr = (SHMPTR *)item_ptr;
    *shmptr_ptr = 0;

    /* Return SHMPTR of last element in the list */
    next_shmptr -= block_size;

    TRACE("New linked pool goes from 0x%08x to 0x%08x\n", first, next_shmptr);
    return next_shmptr;
}

/*++
SHMMapUnknownSegments

Map into this process all SHM segments not yet mapped

(no parameters)

Return value :
    TRUE on success, FALSE in case of error
--*/
static BOOL SHMMapUnknownSegments(void)
{
    return TRUE;
}

/*++
SHMAddSegment

Create a new SHM segment, map it into this process, initialize it, then link it
to the other SHM segments

(no parameters)

Return value :
    TRUE on success, FALSE in case of error

Notes :
    This function assumes the SHM lock is held.
--*/
static BOOL SHMAddSegment(void)
{
    LPVOID segment_base;
    SHM_SEGMENT_HEADER *header;
    SHM_FIRST_HEADER *first_header;
    SHMPTR first_shmptr;
    SHMPTR *shmptr_ptr;
    int sps;
    int used_size;
    int new_size;
    int current_pool_size;
    int used_pool_size;
    int new_pool_size;
    int num_new_items;

    /* Map all segments this process doesn't yet know about, so we link the new
       segment at the right place */
    if(!SHMMapUnknownSegments())
    {
        ERROR("SHMMapUnknownSegments failed!\n");
        return FALSE;
    }

    /* Avoid overflowing */
    if(shm_numsegments == MAX_SEGMENTS)
    {
        ERROR("Can't map more segments : maximum number (%d) reached!\n",
              MAX_SEGMENTS);
        return FALSE;
    }

    TRACE("Creating SHM segment #%d\n", shm_numsegments);

    segment_base = mmap(NULL, segment_size, PROT_READ|PROT_WRITE,
                        MAP_ANON|MAP_PRIVATE,-1, 0);

    if(segment_base == MAP_FAILED)
    {
        ERROR("mmap() failed! error is %d (%s)\n", errno, strerror(errno));
        return FALSE;
    }

    shm_segment_bases[shm_numsegments] = segment_base;

    /* Save name (well, suffix) of new segment in the header of the old last
       segment, so that other processes know where it is. */
    header = (SHM_SEGMENT_HEADER *)shm_segment_bases[shm_numsegments-1].Load();

    /* Indicate that the new segment is the last one */
    header = (SHM_SEGMENT_HEADER *)segment_base;

    /* We're now ready to update our memory pools */

    first_header = (SHM_FIRST_HEADER *)shm_segment_bases[0].Load();

    /* Calculate total amount of used memory (in bytes) */
    used_size = 0;
    for(sps = 0; sps<SPS_LAST;sps++)
    {
        /* Add total size of this pool */
        used_size += first_header->pools[sps].num_items*block_sizes[sps];

        /* Remove unused size of this pool */
        used_size -= first_header->pools[sps].free_items*block_sizes[sps];
    }

    /* Determine how to divide the new segment between the pools for the
       different block sizes, then update the pool inforamtion accordingly
       Allocation strategy :
       1) Calculate the proportion of used memory used by each pool
       2) Allocate this proportion of the new segment to each pool
     */

    /* Add the new segment to the total amount of SHM memory */
    new_size = segment_size-roundup(sizeof(SHM_SEGMENT_HEADER), sizeof(INT64));

    /* Calculate value of first SHMPTR in the new segment : segment is
       shm_numsegments (not yet incremented); offset is the first byte after
       the segment header */
    first_shmptr = MAKE_SHMPTR(shm_numsegments,roundup(sizeof(SHM_SEGMENT_HEADER), sizeof(INT64)));

    TRACE("Updating SHM pool information; Total memory used is %d bytes; "
          "we are adding %d bytes\n", used_size, new_size);

    /* We want to allocate at least 1 block of each size (to avoid adding
       special cases everywhere). We remove the required space for these blocks
       from the size used in the calculations, then add 1 to each block count */
    for(sps=0;sps<SPS_LAST;sps++)
        new_size -= block_sizes[sps];

    /* Loop through all block sizes */
    for(sps=0; sps<SPS_LAST; sps++)
    {
        TRACE("Now processing block size \"%d\"...\n", block_sizes[sps]);
        /* amount of memory currently reserved for this block size */
        current_pool_size = first_header->pools[sps].num_items*block_sizes[sps];

        /* how much of that is actually used? */
        used_pool_size = current_pool_size -
                         first_header->pools[sps].free_items*block_sizes[sps];

        DBGOUT("%d bytes of %d bytes used (%d%%)\n", used_pool_size,
               current_pool_size, (used_pool_size*100)/current_pool_size);

        /* amount of memory we want to add to the pool for this block size :
           amount used by this pool/total amount used * new segment's size */
        new_pool_size = (((LONGLONG)used_pool_size)*new_size)/used_size;

        DBGOUT("Allocating %d bytes of %d to %d-byte pool\n",
               new_pool_size, new_size, block_sizes[sps]);

        /* determine the number of blocks that can fit in the chosen amount */
        num_new_items = new_pool_size/block_sizes[sps];

        /* make sure we allocate at least 1 block of each size */
        num_new_items +=1;

        DBGOUT("Adding %d new blocks\n", num_new_items);

        /* Save the first and last block of the current block size in the new
           segment; join all blocks in between in a linked list */
        header->first_pool_blocks[sps] = first_shmptr;
        header->last_pool_blocks[sps] = SHMLinkPool(first_shmptr,
                                                    block_sizes[sps],
                                                    num_new_items);

        /* Link the last block in the new linked list to the first block of the
           old global linked list. We don't use SHMPTR_TO_PTR because the pool
           data isn't updated yet */
        shmptr_ptr = reinterpret_cast<SHMPTR*>(
            static_cast<LPBYTE>(shm_segment_bases[SHMPTR_SEGMENT(header->last_pool_blocks[sps])].Load()) +
                     SHMPTR_OFFSET(header->last_pool_blocks[sps]));

        *shmptr_ptr = first_header->pools[sps].first_free;

        /* Save the first block of the new linked list as the new beginning of
           the global linked list; the global list now contains all new blocks
           AND all blocks that were already free */
        first_header->pools[sps].first_free = header->first_pool_blocks[sps];

        /* Update block counts to include new blocks */
        first_header->pools[sps].free_items+=num_new_items;
        first_header->pools[sps].num_items+=num_new_items;

        DBGOUT("There are now %d %d-byte blocks, %d are free\n",
               first_header->pools[sps].num_items, block_sizes[sps],
               first_header->pools[sps].free_items);

        /* Update first_shmptr to first byte after the new pool */
        first_shmptr+=num_new_items*block_sizes[sps];
    }
    shm_numsegments++;

    return TRUE;
}

/*++
SHMStrDup

Duplicates the string in shared memory.

Returns the new address as SHMPTR on success.
Returns (SHMPTR)NULL on failure.
--*/
SHMPTR SHMStrDup( LPCSTR string )
{
    UINT length = 0;
    SHMPTR retVal = 0;

    if ( string )
    {
        length = strlen( string );

        retVal = SHMalloc( ++length );

        if ( retVal != 0 ) 
        {
            LPVOID ptr = SHMPTR_TO_PTR( retVal );
            _ASSERT_MSG(ptr != NULL, "SHMPTR_TO_PTR returned NULL.\n");
            if (ptr != NULL)
            {
                memcpy( ptr, string, length );
            }
            else
            {
                // This code should never be reached. If a valid pointer
                // is passed to SHMPTR_TO_PTR and NULL is returned, then
                // there's a problem in either the macro, or the underlying
                // call to SHMPtrToPtr. In case the impossible happens,
                // though, free the memory and return NULL rather than
                // returning uninitialized memory.
                SHMfree( retVal );
                retVal = NULL;
            }
        }
    }
    return retVal;
}

/*++
SHMWStrDup

Duplicates the wide string in shared memory.

Returns the new address as SHMPTR on success.
Returns (SHMPTR)NULL on failure.
--*/
SHMPTR SHMWStrDup( LPCWSTR string )
{
    UINT length = 0;
    SHMPTR retVal = 0;

    if ( string )
    {
        length = ( PAL_wcslen( string ) + 1 ) * sizeof( WCHAR );
        
        retVal = SHMalloc( length );

        if ( retVal != 0 ) 
        {
            LPVOID ptr = SHMPTR_TO_PTR(retVal);
            _ASSERT_MSG(ptr != NULL, "SHMPTR_TO_PTR returned NULL.\n");
            if (ptr != NULL)
            {
                memcpy( ptr, string, length );
            }
            else
            {
                // This code should never be reached. If a valid pointer
                // is passed to SHMPTR_TO_PTR and NULL is returned, then
                // there's a problem in either the macro, or the underlying
                // call to SHMPtrToPtr. In case the impossible happens,
                // though, free the memory and return NULL rather than
                // returning uninitialized memory.
                SHMfree( retVal );
                retVal = NULL;
            }
        }
    }
    return retVal;
}



/*++
SHMFindNamedObjectByName

Searches for an object whose name matches the name and ID passed in.

Returns a SHMPTR to its location in shared memory. If no object
matches the name, the function returns NULL and sets pbNameExists to FALSE.
If an object matches the name but is of a different type, the function
returns NULL and sets pbNameExists to TRUE.

--*/
SHMPTR SHMFindNamedObjectByName( LPCWSTR lpName, SHM_NAMED_OBJECTS_ID oid,
                                 BOOL *pbNameExists )
{
    PSHM_NAMED_OBJECTS pNamedObject = NULL;
    SHMPTR shmNamedObject = 0;
    LPWSTR object_name = NULL;

    if(oid==SHM_NAMED_LAST)
    {
        ASSERT("Invalid named object type.\n");
        return 0;
    }
    
    if (pbNameExists == NULL)
    {
        ASSERT("pbNameExists must be non-NULL.\n");
    }

    SHMLock();
    
    *pbNameExists = FALSE;
    shmNamedObject = SHMGetInfo( SIID_NAMED_OBJECTS );
    
    TRACE( "Entering SHMFindNamedObjectByName looking for %S .\n", 
           lpName?lpName:W16_NULLSTRING );

    while ( shmNamedObject )
    {
        pNamedObject = (PSHM_NAMED_OBJECTS)SHMPTR_TO_PTR( shmNamedObject );
        if(NULL == pNamedObject)
        {
            ASSERT("Got invalid SHMPTR value; list of named objects is "
                   "corrupted.\n");
            break;
        }
        
        if ( pNamedObject->ShmObjectName )
        {
            object_name = (LPWSTR)SHMPTR_TO_PTR( pNamedObject->ShmObjectName );
        }

        if ( object_name && 
             PAL_wcscmp( lpName, object_name ) == 0 )
        {
            if(oid == pNamedObject->ObjectType)
            {
                TRACE( "Returning the kernel object %p.\n", pNamedObject );
            }
            else
            {
                shmNamedObject = 0;
                *pbNameExists = TRUE;
            }
            goto Exit;
        }
        shmNamedObject = pNamedObject->ShmNext;
    }

    shmNamedObject = 0;
    TRACE( "No matching kernel object was found.\n" );

Exit:
    SHMRelease();
    return shmNamedObject;

}

/*++ 
SHMRemoveNamedObject

Removes the specified named object from the list

No return.

note : the caller is reponsible for releasing all associated memory
--*/
void SHMRemoveNamedObject( SHMPTR shmNamedObject )
{
    PSHM_NAMED_OBJECTS pshmLast = 0;
    PSHM_NAMED_OBJECTS pshmCurrent = 0;

    TRACE( "Entered SHMDeleteNamedObject shmNamedObject = %d\n", shmNamedObject );
    SHMLock();

    pshmCurrent = 
        (PSHM_NAMED_OBJECTS)SHMPTR_TO_PTR( SHMGetInfo( SIID_NAMED_OBJECTS ) );
    pshmLast = pshmCurrent;

    while ( pshmCurrent )
    {
        if ( pshmCurrent->ShmSelf == shmNamedObject )
        {
            TRACE( "Patching the list.\n" );
            
            /* Patch the list, and delete the object. */
            if ( pshmLast->ShmSelf == pshmCurrent->ShmSelf )
            {
                /* Either the first element or no elements left. */
                SHMSetInfo( SIID_NAMED_OBJECTS, pshmCurrent->ShmNext );
            }
            else if ( (PSHM_NAMED_OBJECTS)SHMPTR_TO_PTR( pshmCurrent->ShmNext ) )
            {
                pshmLast->ShmNext = pshmCurrent->ShmNext;
            }
            else
            {
                /* Only one left. */
                pshmLast->ShmNext = 0;
            }
            
            break;
        }
        else
        {
            pshmLast = pshmCurrent;
            pshmCurrent = (PSHM_NAMED_OBJECTS)SHMPTR_TO_PTR( pshmCurrent->ShmNext );
        }
    }

    SHMRelease();
    return;
}

/*++ SHMAddNamedObject

Adds the specified named object to the list.

No return.
--*/
void SHMAddNamedObject( SHMPTR shmNewNamedObject )
{
    PSHM_NAMED_OBJECTS pshmNew = 0;
   
    pshmNew = (PSHM_NAMED_OBJECTS)SHMPTR_TO_PTR( shmNewNamedObject );
   
    if ( pshmNew == NULL )
    {
        ASSERT( "pshmNew should not be NULL\n" );
    }
 
    SHMLock();
    
    pshmNew->ShmNext = SHMGetInfo( SIID_NAMED_OBJECTS );
    
    if ( !SHMSetInfo( SIID_NAMED_OBJECTS, shmNewNamedObject ) )
    {
        ASSERT( "Unable to add the mapping object to shared memory.\n" );
    }

    SHMRelease();
    return;
}