summaryrefslogtreecommitdiffstats
path: root/private/os2/server/srvque.c
blob: abaeef2ddbc4aa73b9cd6ba0b0e113cd971e6ec3 (plain) (blame)
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
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    srvque.c

Abstract:

    Queues API

Author:

    Mark Lucovsky (markl) 10-Jul-1990

Revision History:

--*/

#define INCL_OS2V20_QUEUES
#define INCL_OS2V20_ERRORS
#define INCL_OS2V20_TASKING
#include "os2srv.h"

NTSTATUS
Os2InitializeQueues( VOID )
{
//    Os2Debug |= OS2_DEBUG_QUEUES;
    Os2QueueTable =
        Or2CreateQHandleTable( Os2Heap, sizeof( OS2_QUEUE ), 8 );

    if (Os2QueueTable == NULL) {
        return( STATUS_NO_MEMORY );
    } else {
        return( STATUS_SUCCESS );
    }
}


BOOLEAN
Os2DosCreateQueue( IN POS2_THREAD t, IN POS2_API_MSG m )
{
    POS2_DOSCREATEQUEUE_MSG a = &m->u.DosCreateQueue;
    POS2_LOCAL_OBJECT_DIRENT Dirent;
    STRING QueueName;
    OS2_QUEUE LQueue;
    POS2_QUEUE Queue;

    AcquireLocalObjectLock(Os2QueueTable);

    Dirent = Os2LookupLocalObjectByName(
                &a->QueueName,
                LocalObjectQueue
                );

    if (Dirent) {
        m->ReturnedErrorValue = ERROR_QUE_DUPLICATE;
    } else {

        m->ReturnedErrorValue = ERROR_QUE_NO_MEMORY;

        //
        // allocate and create the queue
        //

        a->QueueHandle = (HQUEUE) -1;

        if ( Or2CreateQHandle(
                Os2QueueTable,
                (PULONG)&a->QueueHandle,
                (PVOID)&LQueue
                ) ) {

            Queue = Or2MapQHandle(
                        Os2QueueTable,
                        (ULONG)a->QueueHandle,
                        TRUE
                        );

            if (Queue != NULL) {

                Queue->QueueType = a->QueueType;
                Queue->OpenCount = 1;
                Queue->EntryIdCounter = 1;
                Queue->CreatorPid = t->Process->ProcessId;
                QueueName = a->QueueName;
                QueueName.Buffer = RtlAllocateHeap( Os2Heap, 0, QueueName.Length);
                InitializeListHead(&Queue->Entries);
                InitializeListHead(&Queue->Waiters);
                InitializeListHead(&Queue->SemBlocks);

                if ( QueueName.Buffer ) {

                    RtlMoveMemory(QueueName.Buffer,a->QueueName.Buffer,QueueName.Length);

                    Dirent = Os2InsertLocalObjectName(
                                &QueueName,
                                LocalObjectQueue,
                                (ULONG)a->QueueHandle
                                );
                    if ( !Dirent ) {

                        RtlFreeHeap( Os2Heap, 0, QueueName.Buffer);

                        //
                        // Destroy will unlock the queue table
                        //

                        Or2DestroyQHandle(Os2QueueTable,(ULONG)a->QueueHandle);
                        return (TRUE);
                    } else {

                        Queue->Dirent = Dirent;
                        m->ReturnedErrorValue = NO_ERROR;
                    }
                }
#if DBG
                else {
                    KdPrint(( "Os2Srv: no memory for QueueName.Buffer\n" ));
                    ASSERT(FALSE);
                }
#endif

            }
#if DBG
            else {
                KdPrint(( "Os2Srv: Or2MapQHandle returned NULL\n" ));
                ASSERT(FALSE);
            }
#endif
        }
    }

    ReleaseLocalObjectLock(Os2QueueTable);

    return TRUE;
}

POS2_QUEUE
Os2OpenQueueByHandle(
    IN HQUEUE QueueHandle
    )

/*++

Routine Description:

    This function is used to open a queue once the queues index is
    known.

Arguments:

    QueueHandle - Supplies the handle to the queue being opened.

Return Value:

    NON-NULL - Returns the address of the opened queue.
    NULL - The queue could not be opened.

--*/

{

    POS2_QUEUE Queue;

    Queue = Or2MapQHandle(
                Os2QueueTable,
                (ULONG)QueueHandle,
                TRUE
                );

    ASSERT(Queue);

    Queue->OpenCount++;

    return Queue;
}

BOOLEAN
Os2DosOpenQueue( IN POS2_THREAD t, IN POS2_API_MSG m )
{
    POS2_DOSOPENQUEUE_MSG a = &m->u.DosOpenQueue;
    POS2_LOCAL_OBJECT_DIRENT Dirent;
    POS2_QUEUE Queue;

    UNREFERENCED_PARAMETER(t);
    AcquireLocalObjectLock(Os2QueueTable);

    Dirent = Os2LookupLocalObjectByName(
                &a->QueueName,
                LocalObjectQueue
                );

    if (!Dirent) {
        m->ReturnedErrorValue = ERROR_QUE_NAME_NOT_EXIST;
    } else {

        Queue = Os2OpenQueueByHandle((HQUEUE)Dirent->ObjectHandle);
        ASSERT(Queue);
        a->QueueHandle = (HQUEUE) Dirent->ObjectHandle;
        a->OwnerProcessId = Queue->CreatorPid;
    }

    ReleaseLocalObjectLock(Os2QueueTable);

    return TRUE;
}

APIRET
Os2CloseQueueByHandle(
    IN HQUEUE QueueHandle,
    IN ULONG CloseCount,
    IN PID OwnerPid,
    IN POS2_PROCESS Process
    )

/*++

Routine Description:

    This function is used to close a queue.  It is used by both
    DosCloseQueue and session rundown.

Arguments:

    QueueHandle - Supplies the handle to the queue being closed.

    CloseCount - Supplies the close count for the queue.

    Process - Supplies the address of the process doing the close

Return Value:

    None.

--*/


{

    APIRET rc;
    POS2_LOCAL_OBJECT_DIRENT Dirent;
    POS2_QUEUE Queue;

    Queue = (POS2_QUEUE)Or2MapQHandle( Os2QueueTable,
                                      (ULONG)QueueHandle,
                                      FALSE
                                    );
    if (!Queue) {
    rc = ERROR_QUE_INVALID_HANDLE;
    }
    else if ((OwnerPid != (PID)(-1)) && (OwnerPid != Queue->CreatorPid)) {
    rc = ERROR_QUE_INVALID_HANDLE;
    }
    else {
        rc = NO_ERROR;

        Queue->OpenCount -= CloseCount;
        if (Queue->OpenCount < 0) {
            ASSERT(Queue->OpenCount >= 0);
            Queue->OpenCount = 0;
        }

        //
        // Check to see if close is from owner of the queue.
        // If so, purge the queue
        //

        if ( Queue->CreatorPid == Process->ProcessId ) {

            //
            // Destroy the queue and then free remove the dirent from the
            // name table
            // When destroying the queue, you must hold the lock and then
            // nuke the dirent.
            //

            Dirent = Queue->Dirent;
            Os2DeleteLocalObject(Dirent);

            //
            // Now no-one can reference the queue since it's dirent is gone
            // and no-operations are going on on the queue since we hold the
            // lock. Release the queue lock and free the queue.
            //

            //
            // purge queue. free all asynch reads,
            //

            Os2PurgeQueueEntries(Queue);

            Os2NotifyWait(WaitQueue,(PVOID)Queue,(PVOID)ERROR_SYS_INTERNAL);
            Os2ProcessSemBlocks(Queue);

            Or2DestroyQHandle(Os2QueueTable, (ULONG)QueueHandle);
        }
        else {
            ReleaseHandleTableLock( Os2QueueTable );
        }
    }

    return rc;
}



BOOLEAN
Os2DosCloseQueue( IN POS2_THREAD t, IN POS2_API_MSG m )
{

    POS2_DOSCLOSEQUEUE_MSG a = &m->u.DosCloseQueue;
    APIRET rc;

    rc = Os2CloseQueueByHandle( a->QueueHandle,
                                a->CloseCount,
                                a->OwnerProcessId,
                                t->Process
                              );

    m->ReturnedErrorValue = rc;
    return TRUE;
}


BOOLEAN
Os2DosPurgeQueue( IN POS2_THREAD t, IN POS2_API_MSG m )
{
    POS2_DOSPURGEQUEUE_MSG a = &m->u.DosPurgeQueue;
    POS2_QUEUE Queue;
    APIRET rc;

    Queue = (POS2_QUEUE)Or2MapQHandle( Os2QueueTable,
                                      (ULONG)a->QueueHandle,
                                      FALSE
                                    );
    if (!Queue) {
        rc = ERROR_QUE_INVALID_HANDLE;
        }
    else {

        if ( Queue->CreatorPid != t->Process->ProcessId ) {
            rc = ERROR_QUE_PROC_NOT_OWNED;
            }
        else {
            rc = NO_ERROR;
            ReleaseHandleTableLock( Os2QueueTable );
            Os2PurgeQueueEntries(Queue);
            }
        }

    if ( rc != NO_ERROR ) {
        ReleaseHandleTableLock( Os2QueueTable );
        }

    m->ReturnedErrorValue = rc;
    return TRUE;
}

BOOLEAN
Os2DosQueryQueue( IN POS2_THREAD t, IN POS2_API_MSG m )
{

    POS2_DOSQUERYQUEUE_MSG a = &m->u.DosQueryQueue;
    POS2_QUEUE Queue;
    APIRET rc;
    PLIST_ENTRY NextEntry;
    ULONG ElementCount;

    UNREFERENCED_PARAMETER(t);
    Queue = (POS2_QUEUE)Or2MapQHandle( Os2QueueTable,
                                      (ULONG)a->QueueHandle,
                                      FALSE
                                    );
    if (!Queue) {
        rc = ERROR_QUE_INVALID_HANDLE;
        }
    else if (Queue->CreatorPid != a->OwnerProcessId) {
        rc = ERROR_QUE_INVALID_HANDLE;
    }
    else {

        //
        // Lock the queue and release the queue table.
        // Then simply walk the queue elements and count
        // them.
        //

        ReleaseHandleTableLock( Os2QueueTable );

        rc = NO_ERROR;
        ElementCount = 0;

        NextEntry = Queue->Entries.Flink;
        while ( NextEntry != &Queue->Entries ) {
            IF_OS2_DEBUG( QUEUES ) {
                POS2_QUEUE_ENTRY QueueEntry;
                QueueEntry = CONTAINING_RECORD(NextEntry,OS2_QUEUE_ENTRY,Links);
                DumpQueueEntry("Query",QueueEntry);
                }
            ElementCount++;
            NextEntry = NextEntry->Flink;
            }
        a->CountQueueElements = ElementCount;
        }

    m->ReturnedErrorValue = rc;
    return TRUE;
}

BOOLEAN
Os2DosPeekQueue( IN POS2_THREAD t, IN POS2_API_MSG m )
{
    POS2_DOSPEEKQUEUE_MSG a = &m->u.DosPeekQueue;
    POS2_QUEUE Queue;
    APIRET rc;
    POS2_QUEUE_ENTRY QueueEntry, QueueEntry2;
    BOOL32 WaitFlag;
    BOOLEAN ret;
    ULONG ReadPosition;

    //
    // Check NoWait flag and map the queue handle
    //

    switch ((WaitFlag = a->NoWait)) {
        case DCWW_WAIT :
        case DCWW_NOWAIT :
            rc = ERROR_QUE_INVALID_HANDLE;
            Queue = (POS2_QUEUE)Or2MapQHandle( Os2QueueTable,
                                              (ULONG)a->QueueHandle,
                                              FALSE
                                            );
            break;
        default:
            Queue = NULL;
            rc = ERROR_QUE_INVALID_WAIT;
        }

    if (Queue) {

        //
        // Lock the queue agains modifications/deletions by
        // locking the queue and then dropping the queuetable/namespace
        // lock.
        //

        ReleaseHandleTableLock( Os2QueueTable );
        rc = NO_ERROR;

        //
        // If the queue is empty, then wait/register request
        // based on wait flag or event handle
        //

        if ( IsListEmpty(&Queue->Entries) ) {

            //
            // If the queue is empty and DCWW_WAIT was specified, then
            // setup a wait block and cause thread to wait. Otherwise,
            // return ERROR_QUE_EMPTY and possibly register an event to
            // set.
            //

            if (WaitFlag == DCWW_WAIT) {
                ret = Os2CreateWait( WaitQueue,
                                     Os2WaitQueueEntries,
                                     t,
                                     m,
                                     Queue,
                                     &Queue->Waiters
                                   );
                if ( ret ) {

                    //
                    // The wait is completely registered.
                    // Return false to signal that reply will be
                    // generated later.
                    //

                    return FALSE;

                    }
                else {

                    //
                    // If we fail to create a wait block and register the
                    // wait, then translate into no memory.
                    //

                    rc = ERROR_QUE_NO_MEMORY;
                    }
                }
            else {

                if ( a->SemIndex ) {

                    //
                    // If the queue is empty during a read/peek, and the
                    // caller is not waiting and has specified an event
                    // semaphore, then locate the semaphore and create a
                    // sem block. Otherwise, just return ERROR_QUE_EMPTY
                    //

                    POS2_SEMAPHORE Semaphore;
                    POS2_QUEUE_SEM_BLOCK SemBlock;

                    Semaphore = (POS2_SEMAPHORE)Or2MapHandle( Os2SharedSemaphoreTable,
                                                              a->SemIndex & 0x7fffffff,
                                                              FALSE
                                                            );
                    if (Semaphore == NULL) {
                        rc = ERROR_QUE_INVALID_HANDLE;
                        }
                    else {
                        SemBlock = RtlAllocateHeap( Os2Heap, 0, sizeof(*SemBlock) );
                        if ( !SemBlock ) {
                            rc = ERROR_QUE_NO_MEMORY;
                            }
                        else {
                            InsertTailList(&Queue->SemBlocks,&SemBlock->Links);
                            SemBlock->NtEvent = Semaphore->u.EventHandle;
                            rc = ERROR_QUE_EMPTY;
                            }
                        ReleaseHandleTableLock( Os2SharedSemaphoreTable );
                        }
                    }
                else {
                    rc = ERROR_QUE_EMPTY;
                    }
                }
            }
        else {

            //
            // If the queue has some entries, then either look for the
        // next entry, or use list head.  Remember, if the entry positon
        // is specified we peek the NEXT item.  Not the specified item as
        // in the case of a call to DosReadQueue.
            //

        //
        // Compute the next entry read position. If we are peeking
        // the last entry, then read position is 0. Otherwise it is
        // the entry id of the next entry.
        //

        QueueEntry = Os2LocateQueueEntry(Queue, a->ReadPosition);

        if (a->ReadPosition != 0)
         {
         if ( QueueEntry->Links.Flink == &Queue->Entries )
              {
              ReadPosition = 0;
              }
         else {
              QueueEntry2  = CONTAINING_RECORD(QueueEntry->Links.Flink,OS2_QUEUE_ENTRY,Links);
              ReadPosition = QueueEntry2->EntryId;
              }

         QueueEntry = Os2LocateQueueEntry(Queue, ReadPosition);
         }

            if ( !QueueEntry ) {
                rc = ERROR_QUE_ELEMENT_NOT_EXIST;
                }
            else {
                Os2PeekQueueEntry(Queue,QueueEntry,a);
                }
            }
        }
    m->ReturnedErrorValue = rc;
    return TRUE;
}

BOOLEAN
Os2DosReadQueue( IN POS2_THREAD t, IN POS2_API_MSG m )
{
    POS2_DOSREADQUEUE_MSG a = &m->u.DosReadQueue;
    POS2_QUEUE Queue;
    APIRET rc;
    POS2_QUEUE_ENTRY QueueEntry;
    BOOL32 WaitFlag;
    BOOLEAN ret;

    //
    // Check NoWait flag and map the queue handle
    //

    switch ((WaitFlag = a->NoWait)) {
        case DCWW_WAIT :
        case DCWW_NOWAIT :
            rc = ERROR_QUE_INVALID_HANDLE;
            Queue = (POS2_QUEUE)Or2MapQHandle( Os2QueueTable,
                                              (ULONG)a->QueueHandle,
                                              FALSE
                                            );
            break;
        default:
            Queue = NULL;
            rc = ERROR_QUE_INVALID_WAIT;
        }

    if (Queue) {

        //
        // Lock the queue agains modifications/deletions by
        // locking the queue and then dropping the queuetable/namespace
        // lock.
        //

        ReleaseHandleTableLock( Os2QueueTable );
        rc = NO_ERROR;

        //
        // If the queue is empty, then wait/register request
        // based on wait flag or event handle
        //

        if ( IsListEmpty(&Queue->Entries) ) {

            //
            // If the queue is empty and DCWW_WAIT was specified, then
            // setup a wait block and cause thread to wait. Otherwise,
            // return ERROR_QUE_EMPTY and possibly register an event to
            // set.
            //

            if (WaitFlag == DCWW_WAIT) {
                ret = Os2CreateWait( WaitQueue,
                                     Os2WaitQueueEntries,
                                     t,
                                     m,
                                     Queue,
                                     &Queue->Waiters
                                   );
                if ( ret ) {

                    //
                    // The wait is completely registered.
                    // Return false to signal that reply will be
                    // generated later.
                    //

                    return FALSE;

                    }
                else {

                    //
                    // If we fail to create a wait block and register the
                    // wait, then translate into no memory.
                    //

                    rc = ERROR_QUE_NO_MEMORY;
                    }
                }
            else {

                if ( a->SemIndex ) {
                    //
                    // If the queue is empty during a read/peek, and the
                    // caller is not waiting and has specified an event
                    // semaphore, then locate the semaphore and create a
                    // sem block. Otherwise, just return ERROR_QUE_EMPTY
                    //

                    POS2_SEMAPHORE Semaphore;
                    POS2_QUEUE_SEM_BLOCK SemBlock;

                    Semaphore = (POS2_SEMAPHORE)Or2MapHandle( Os2SharedSemaphoreTable,
                                                              a->SemIndex & 0x7fffffff,
                                                              FALSE
                                                            );
                    if (Semaphore == NULL) {
                        rc = ERROR_QUE_INVALID_HANDLE;
                        }
                    else {
                        SemBlock = RtlAllocateHeap( Os2Heap, 0, sizeof(*SemBlock) );
                        if ( !SemBlock ) {
                            rc = ERROR_QUE_NO_MEMORY;
                            }
                        else {
                            InsertTailList(&Queue->SemBlocks,&SemBlock->Links);
                            SemBlock->NtEvent = Semaphore->u.EventHandle;
                            rc = ERROR_QUE_EMPTY;
                            }
                        ReleaseHandleTableLock( Os2SharedSemaphoreTable );
                        }
                    }
                else {
                    rc = ERROR_QUE_EMPTY;
                    }
                }
            }
        else {

            //
            // If the queue has some entries, then either look for the
            // specified entry, or use list head.
            //

            QueueEntry = Os2LocateQueueEntry(Queue, a->ReadPosition);

            if ( !QueueEntry ) {
                rc = ERROR_QUE_ELEMENT_NOT_EXIST;
                }
            else {
                Os2ReadQueueEntry(QueueEntry,a);
                }
            }
        }
    m->ReturnedErrorValue = rc;
    return TRUE;
}


APIRET
Os2WriteQueueByHandle(
    POS2_DOSWRITEQUEUE_MSG a,
    PID ProcessId
    )

/*++

Routine Description:

    This function writes the specified message to the
    specified queue. It is normally called by DosWriteQueue, but
    is also used to send a session termination message.

Arguments:

    a - Supplies a formatted write queue message

    ProcessId - Supplies the process id of the writer.

Return Value:

    Returns the OS/2 error value associated with the write.

--*/

{

    POS2_QUEUE Queue;
    APIRET rc;
    POS2_QUEUE_ENTRY QueueEntry;
    POS2_QUEUE_ENTRY NextQueueEntry;
    PLIST_ENTRY Pred;
    PLIST_ENTRY NextEntry;

    Queue = (POS2_QUEUE)Or2MapQHandle( Os2QueueTable,
                                      (ULONG)a->QueueHandle,
                                      FALSE
                                    );
    if (!Queue) {
        rc = ERROR_QUE_INVALID_HANDLE;
    }
        //
        // If not called by the server (ProcessId == 0), check against
        // the creator of the queue
        //
    else if (ProcessId != 0 && Queue->CreatorPid != a->OwnerProcessId) {
        ReleaseHandleTableLock( Os2QueueTable );
        rc = ERROR_QUE_INVALID_HANDLE;
    }
    else {

        //
        // Now allocate space for a queue entry. Then lock the
        // queue and release queue table lock. Then insert entry
        // in queue and release queue lock.
        //

        QueueEntry = RtlAllocateHeap( Os2Heap, 0, sizeof(*QueueEntry) );

        if ( !QueueEntry ) {
            ReleaseHandleTableLock( Os2QueueTable );
            rc = ERROR_QUE_NO_MEMORY;
            }
        else {

            ReleaseHandleTableLock( Os2QueueTable );
            rc = NO_ERROR;

            QueueEntry->RequestData.SenderProcessId = ProcessId;
            QueueEntry->RequestData.SenderData = a->SenderData;
            QueueEntry->ElementAddress = (PVOID) a->Data;
            QueueEntry->ElementLength = a->DataLength;

        if (a->ElementPriority>15) a->ElementPriority = 15;

            QueueEntry->Priority = (Queue->QueueType == QUE_PRIORITY ? a->ElementPriority : 0);
            QueueEntry->EntryId = Queue->EntryIdCounter++;

            if ( Queue->EntryIdCounter == 0 ) {
                Queue->EntryIdCounter++;
                }

            //
            // Insert Entry in queue
            //

            switch ( Queue->QueueType ) {
                case QUE_FIFO     :
                    Pred = Queue->Entries.Blink;
                    break;

                case QUE_LIFO     :
                    Pred = &Queue->Entries;
                    break;

                case QUE_PRIORITY :
                    Pred = &Queue->Entries;
                    while (Pred->Flink != &Queue->Entries) {
                        NextEntry = Pred->Flink;
                        NextQueueEntry = CONTAINING_RECORD(NextEntry, OS2_QUEUE_ENTRY, Links);
                        if (QueueEntry->Priority > NextQueueEntry->Priority) {
                            break;
                        }
                        Pred = NextEntry;
                    }
                    break;
                }

            IF_OS2_DEBUG( QUEUES ) DumpQueueEntry("Write",QueueEntry);

            InsertHeadList(Pred,&QueueEntry->Links);
            Os2ProcessSemBlocks(Queue);
            Os2QueueWaitCheck(Queue);

            }
        }

    return rc;
}


BOOLEAN
Os2DosWriteQueue( IN POS2_THREAD t, IN POS2_API_MSG m )
{

    POS2_DOSWRITEQUEUE_MSG a = &m->u.DosWriteQueue;

    m->ReturnedErrorValue = Os2WriteQueueByHandle(a,t->Process->ProcessId);

    return TRUE;
}

VOID
Os2PurgeQueueEntries(
    IN POS2_QUEUE Queue
    )

/*++

Routine Description:

    This function is called during DosCloseQueue and DosPurgeQueue
    to empty the queue.

    This function must be called with the queue locked !

Arguments:

    Queue - Supplies the address of the queue to purge.

Return Value:

    None.

--*/

{
    PLIST_ENTRY NextEntry;
    POS2_QUEUE_ENTRY QueueEntry;

    while ( !IsListEmpty(&Queue->Entries) ) {
        NextEntry = RemoveHeadList(&Queue->Entries);
        QueueEntry = CONTAINING_RECORD(NextEntry,OS2_QUEUE_ENTRY,Links);
        RtlFreeHeap( Os2Heap, 0, QueueEntry);
        }
}

POS2_QUEUE_ENTRY
Os2LocateQueueEntry(
    IN POS2_QUEUE Queue,
    IN ULONG ReadPosition
    )

/*++

Routine Description:

    This function is called during DosReadQueue and DosPeekQueue
    to determine if the specified queue contains an entry whose
    entry id matches ReadPosition. Note that a read position of
    0 matches the entry at the head of the queue.

    This function must be called with the queue locked !

Arguments:

    Queue - Supplies the address of the queue to search.

    ReadPosition - Supplies the key of the queue entry to
        locate.

Return Value:

    NON-NULL - Returns the address of the queue entry that matches
        ReadPosition.

    NULL - The queue does not contain the specified entry.

--*/

{
    PLIST_ENTRY NextEntry;
    POS2_QUEUE_ENTRY QueueEntry;

    if ( IsListEmpty(&Queue->Entries) ) {
        return NULL;
        }

    if ( ReadPosition == 0 ) {
        QueueEntry = CONTAINING_RECORD(Queue->Entries.Flink,OS2_QUEUE_ENTRY,Links);
        IF_OS2_DEBUG( QUEUES ) DumpQueueEntry("LocateReturn",QueueEntry);
        return QueueEntry;
        }

    NextEntry = Queue->Entries.Flink;

    while ( NextEntry != &Queue->Entries ) {
        QueueEntry = CONTAINING_RECORD(NextEntry,OS2_QUEUE_ENTRY,Links);
        if ( QueueEntry->EntryId == ReadPosition ) {
            return QueueEntry;
            }
        NextEntry = NextEntry->Flink;
        }
    return NULL;
}

VOID
Os2ProcessSemBlocks(
    IN POS2_QUEUE Queue
    )

/*++

Routine Description:

    This function processes the semaphore blocks for the specified
    queue. This function is called whenever an entry is placed in the
    queue. Its function is to signal all waiting semaphores and
    to deallocate the semaphore block.

Arguments:

    Queue - Supplies the queue whose semaphore blocks need processing.

Return Value:

    None.

--*/

{

    PLIST_ENTRY NextEntry;
    POS2_QUEUE_SEM_BLOCK SemBlock;

    while ( !IsListEmpty(&Queue->SemBlocks) ) {
        NextEntry = RemoveHeadList(&Queue->SemBlocks);
        SemBlock = CONTAINING_RECORD(NextEntry,OS2_QUEUE_SEM_BLOCK,Links);
        NtSetEvent(SemBlock->NtEvent,NULL);
        RtlFreeHeap( Os2Heap, 0, SemBlock);
        }

}


BOOLEAN
Os2WaitQueueEntries(
    IN OS2_WAIT_REASON WaitReason,
    IN POS2_THREAD WaitingThread,
    IN POS2_API_MSG WaitReplyMessage,
    IN PVOID WaitParameter,
    IN PVOID SatisfyParameter1,
    IN PVOID SatisfyParameter2
    )

/*++

Routine Description:

    This function is called by the Os2NotifyWait function whenever
    a queue waiter is awakened. This is typically due to a queue write
    where there are waiters present and a write occurs. Os2 Exception
    logic may also cause this routine to be entered.

Arguments:

    WaitReason - Supplies the reason this wait is being satisfied.

    WaitingThread - Supplies the address of the thread waiting being
        unwaited.

    WaitReplyMessage - Supplies the API message that originally caused
        the thread to wait.

    WaitParameter - Supplies the address of the queue that the waiter is
        waiting on.

    SatisfyParameter1 - Supplies the address of the queue that has an
        entry to satisfy the wait. The queue is locked by the wait
        notifier.

    SatisfyParameter2 - If not null, then supplies the error code
        for the wait. Used when a queue is being closed.

Return Value:

    TRUE - A reply should be generated

    FALSE - A reply should not be generated

--*/

{

    POS2_DOSREADQUEUE_MSG read = &WaitReplyMessage->u.DosReadQueue;
    POS2_DOSPEEKQUEUE_MSG peek = &WaitReplyMessage->u.DosPeekQueue;
    POS2_QUEUE Queue;
    APIRET rc;
    POS2_QUEUE_ENTRY QueueEntry;
    ULONG ReadPosition;
    BOOLEAN Peek;

    UNREFERENCED_PARAMETER(WaitingThread);
    if (WaitReason == WaitInterrupt) {
        return TRUE;
    }
    else {
        ASSERT(WaitReason == WaitQueue);
    }

    if ( WaitParameter != SatisfyParameter1 ) {
        return FALSE;
    }

    //
    // If we are being waked due to queue closure, then return
    // with error.
    //

    if ( SatisfyParameter2 ) {
        rc = (APIRET)SatisfyParameter2;
        }
    else {

        Queue = (POS2_QUEUE)SatisfyParameter1;

        if ( WaitReplyMessage->ApiNumber == Os2PeekQueue ) {
            Peek = TRUE;
            ReadPosition = peek->ReadPosition;
            }
        else {
            Peek = FALSE;
            ReadPosition = read->ReadPosition;
            }

        QueueEntry = Os2LocateQueueEntry(Queue, ReadPosition);

        if ( !QueueEntry ) {
            if ( ReadPosition ) {
                rc = ERROR_QUE_ELEMENT_NOT_EXIST;
                }
            else {
                return FALSE;
                }
            }
        else {

            rc = NO_ERROR;
            if ( Peek ) {
                Os2PeekQueueEntry(Queue,QueueEntry,peek);
                }
            else {
                Os2ReadQueueEntry(QueueEntry,read);
                }
            IF_OS2_DEBUG( QUEUES ) DumpQueueEntry("WaitReturn",QueueEntry);
            }
        }

    WaitReplyMessage->ReturnedErrorValue = rc;

    return TRUE;
}

VOID
Os2QueueWaitCheck(
    POS2_QUEUE Queue
    )

/*++

Routine Description:

    This function is called to check to see if there are queue waiters
    whose waits might be satisfied if entries exist on the queue.

Arguments:

    Queue - Supplies the address of the queue to check.

Return Value:

    None.

--*/

{

    POS2_WAIT_BLOCK WaitBlock;

    //
    // If there are no entries on the list, then there is nothing to
    // do.
    //

    if ( IsListEmpty(&Queue->Entries) ) {
        return;
        }

    //
    // If there are entries in the queue, but no waiters, then return
    // since there is no-one to wake.
    //

    if ( IsListEmpty(&Queue->Waiters) ) {

        //
        // actually, we need to deal w/ semaphores...
        //
        return;
        }

    //
    // There are waiters, so pop the first waiter
    //

    WaitBlock = CONTAINING_RECORD(Queue->Waiters.Flink,OS2_WAIT_BLOCK,UserLink);

    Os2NotifyWait(WaitQueue,(PVOID)Queue,NULL);
}

VOID
Os2ReadQueueEntry(
    IN POS2_QUEUE_ENTRY QueueEntry,
    OUT POS2_DOSREADQUEUE_MSG ReadMsg
    )

/*++

Routine Description:

    This function reads the specified queue entry from its queue

Arguments:

    QueueEntry - Supplies the address of the queue entry to read from the
        queue.

    ReadMsg - Supplies the read queue api message to fill in.

Return Value:

    None.

--*/

{
    //
    // Remove the queue entry, capture all the data,
    // and free the entry;
    //

    RemoveEntryList(&QueueEntry->Links);

    ReadMsg->RequestInfo = QueueEntry->RequestData;
    ReadMsg->DataLength = QueueEntry->ElementLength;
    ReadMsg->Data = QueueEntry->ElementAddress;
    ReadMsg->ElementPriority = (BYTE)QueueEntry->Priority;
    RtlFreeHeap( Os2Heap, 0, QueueEntry);
}

VOID
Os2PeekQueueEntry(
    IN POS2_QUEUE Queue,
    IN POS2_QUEUE_ENTRY QueueEntry,
    OUT POS2_DOSPEEKQUEUE_MSG PeekMsg
    )

/*++

Routine Description:

    This function peeks the specified queue entry from its queue. It
    also computes the next queue entry.

Arguments:

    Queue - Supplies the queue to peek from.

    QueueEntry - Supplies the address of the queue entry to read from the
        queue.

    PeekMsg - Supplies the read queue api message to fill in.

Return Value:

    None.

--*/

{

    PeekMsg->RequestInfo = QueueEntry->RequestData;
    PeekMsg->DataLength = QueueEntry->ElementLength;
    PeekMsg->Data = QueueEntry->ElementAddress;
    PeekMsg->ElementPriority = (BYTE)QueueEntry->Priority;

    PeekMsg->ReadPosition=QueueEntry->EntryId;

}

VOID
DumpQueueEntry(
    IN PSZ Str,
    IN POS2_QUEUE_ENTRY QueueEntry
    )
{
#if DBG
    KdPrint(("\n*** %s QUEUE ENTRY st 0x%lx***\n",Str,QueueEntry));
    KdPrint(("RequestData.SenderProcessId   0x%lx\n",QueueEntry->RequestData.SenderProcessId));
    KdPrint(("RequestData.SenderData        0x%lx\n",QueueEntry->RequestData.SenderData     ));
    KdPrint(("EntryId;                      0x%lx\n",QueueEntry->EntryId                    ));
    KdPrint(("ElementAddress                0x%lx\n",QueueEntry->ElementAddress             ));
    KdPrint(("ElementLength                 0x%lx\n",QueueEntry->ElementLength              ));
    KdPrint(("Priority                      0x%lx\n",QueueEntry->Priority                   ));
    KdPrint(("*******************\n"));
#endif
}