summaryrefslogtreecommitdiffstats
path: root/private/ntos/ex/ddkresrc.c
blob: 2c6af5b5f3dae3f23d98d1cd543853e67ff6f4d7 (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
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    Resource.c

Abstract:

    This module implements the executive functions to acquire and release
    a shared resource, that was unfortunately export to ntddk in release 1.

Author:

    Gary D. Kimura      [GaryKi]    25-Jun-1989

Environment:

    Kernel mode only.

Revision History:

--*/

#include "exp.h"
#pragma hdrstop

#include <nturtl.h>

//
//  The following variable, marcos, and procedure are only for debug purposes.
//

extern LARGE_INTEGER ExpTimeout;

//
//  thirty days worth
//

extern ULONG ExpResourceTimeoutCount;

//
//  Avoid the aliasing done in ex.h
//

#undef ExInitializeResource
#undef ExAcquireResourceExclusive
#undef ExReleaseResourceForThread
#undef ExDeleteResource

#if !DBG && NT_UP && defined(i386)
#define ExReleaseResourceForThread ExpReleaseResourceForThread
VOID
ExReleaseResourceForThread(
    IN PNTDDK_ERESOURCE Resource,
    IN ERESOURCE_THREAD OurThread
    );
#endif

#if DBG

VOID
ExpAssertResourceDdk (
    IN PNTDDK_ERESOURCE   Resource
    );

#define ASSERT_RESOURCE(_Resource)  ExpAssertResourceDdk(_Resource)
#else
#define ASSERT_RESOURCE(_Resource)
#endif

//
// bit value for ERESOURCE.Flag
//

#define ExclusiveWaiter             0x01    // ** Also in i386\resoura.asm **
#define SharedWaiter                0x02    // ** Also in i386\resoura.asm **
//      CounterShiftBit             0x04    - see below
#define DisablePriorityBoost        0x08
//      ResourceOwnedExclusive      0x80    - from ex.h

#if NT_UP
#define CounterShiftBit     0x00
#else
#define CounterShiftBit     0x04        // Must be 0x04!
#endif

#define IsExclusiveWaiting(a)   (((a)->Flag & ExclusiveWaiter) != 0)
#define IsOwnedExclusive(a)     (((a)->Flag & ResourceOwnedExclusive) != 0)
#define IsOwnedExclusive(a)     (((a)->Flag & ResourceOwnedExclusive) != 0)
#define IsBoostAllowed(a)       (((a)->Flag & DisablePriorityBoost) == 0)

//
//  The following static data and two macors are used to control entering and
//  exiting the resource critical section.
//

static KSPIN_LOCK ExpResourceSpinLock;

//++
//
//  Macros:
//      AcquireResourceLock - Obtains the Resource's spinlock
//      ReleaseResourceLock - Releases the Resource's spinlock
//
//      WaitForResourceExclusive(Resource, OldIrql)
//          Block on resource until WakeSharedWaiters
//
//      WakeExclusiveWaiters
//          Wakes threads on resource which are WaitForResourceShared
//
//--

#define AcquireResourceLock(_Resource,_Irql) {              \
    ExAcquireSpinLock( &_Resource->SpinLock, _Irql );       \
    ASSERT_RESOURCE( _Resource );                           \
}

#define ReleaseResourceLock(_Resource,_Irql) {              \
    ExReleaseSpinLock( &_Resource->SpinLock, _Irql );       \
}

#define INITIAL_TABLE_SIZE  4

#define WaitForResourceExclusive(_Resource, _OldIrql)   {               \
    _Resource->Flag |= ExclusiveWaiter;                                 \
    _Resource->NumberOfExclusiveWaiters += 1;                           \
    ReleaseResourceLock ( _Resource, _OldIrql );                        \
    ExpWaitForResourceDdk  ( _Resource, &_Resource->ExclusiveWaiters ); \
    AcquireResourceLock ( _Resource, &_OldIrql);                        \
    if (--_Resource->NumberOfExclusiveWaiters != 0) {                   \
        _Resource->Flag |= ExclusiveWaiter;                             \
    }                                                                   \
}

#define WakeExclusiveWaiters(_Resource)    {                            \
    _Resource->Flag &= ~ExclusiveWaiter;                                \
    KeSetEvent(&_Resource->ExclusiveWaiters, 0, FALSE);                 \
}

//
//  Local procedure prototypes
//

VOID
ExpWaitForResourceDdk (
    IN PNTDDK_ERESOURCE   Resource,
    IN PVOID        Object
    );

//
// The following list head points to a list of all currently
// initialized Executive Resources in the system.
//

extern LIST_ENTRY ExpSystemResourcesList;


#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT,ExpResourceInitialization)
#pragma alloc_text(PAGELK,ExQuerySystemLockInformation)
#endif

//
//
//
//


NTSTATUS
ExInitializeResource (
    IN PNTDDK_ERESOURCE Resource
    )

/*++

Routine Description:

    This routine initializes the input resource variable

Arguments:

    Resource - Supplies the resource variable being initialized

Return Value:

    Status of the operation.

--*/

{
    ULONG   i;

    ASSERTMSG("A resource cannot be in paged pool ", MmDeterminePoolType(Resource) != PagedPool);
    //
    //  Initialize the shared and exclusive waiting counters and semaphore.
    //  The counters indicate how many are waiting for access to the resource
    //  and the semaphores are used to wait on the resource.  Note that
    //  the semaphores can also indicate the number waiting for a resource
    //  however there is a race condition in the alogrithm on the acquire
    //  side if count if not updated before the critical section is exited.
    //  So we need to have an outside counter.
    //

    Resource->NumberOfSharedWaiters    = 0;
    Resource->NumberOfExclusiveWaiters = 0;

    KeInitializeSemaphore ( &Resource->SharedWaiters, 0, MAXLONG );
    KeInitializeEvent     ( &Resource->ExclusiveWaiters, SynchronizationEvent, FALSE );
    KeInitializeSpinLock  ( &Resource->SpinLock );

    Resource->OwnerThreads = Resource->InitialOwnerThreads;
    Resource->OwnerCounts  = Resource->InitialOwnerCounts;

    Resource->TableSize    = INITIAL_TABLE_SIZE;
    Resource->ActiveCount  = 0;
    Resource->TableRover   = 1;
    Resource->Flag         = 0;

    for(i=0; i < INITIAL_TABLE_SIZE; i++) {
        Resource->OwnerThreads[i] = 0;
        Resource->OwnerCounts[i] = 0;
    }

    Resource->ContentionCount = 0;
    InitializeListHead( &Resource->SystemResourcesList );

#if i386 && !FPO
    if (NtGlobalFlag & FLG_KERNEL_STACK_TRACE_DB) {
        Resource->CreatorBackTraceIndex = RtlLogStackBackTrace();
        }
    else {
        Resource->CreatorBackTraceIndex = 0;
        }
#endif // i386 && !FPO
    if (Resource >= (PNTDDK_ERESOURCE)MM_USER_PROBE_ADDRESS) {
        ExInterlockedInsertTailList (
                &ExpSystemResourcesList,
                &Resource->SystemResourcesList,
                &ExpResourceSpinLock );
    }

    return STATUS_SUCCESS;
}


BOOLEAN
ExAcquireResourceExclusive(
    IN PNTDDK_ERESOURCE Resource,
    IN BOOLEAN Wait
    )

/*++

Routine Description:

    The routine acquires the resource for exclusive access.  Upon return from
    the procedure the resource is acquired for exclusive access.

Arguments:

    Resource - Supplies the resource to acquire

    Wait - Indicates if the call is allowed to wait for the resource
        to become available for must return immediately

Return Value:

    BOOLEAN - TRUE if the resource is acquired and FALSE otherwise

--*/

{
    KIRQL OldIrql;
    ERESOURCE_THREAD  OurThread;

    ASSERTMSG("Routine cannot be called at DPC ", !KeIsExecutingDpc() );

    ASSERT((Resource->Flag & ResourceNeverExclusive) == 0);

    OurThread = (ULONG)ExGetCurrentResourceThread();

    //
    //  Get exclusive access to this resource structure
    //

    AcquireResourceLock( Resource, &OldIrql );

    //
    //  Loop until the resource is ours or exit if we cannot wait.
    //

    while (TRUE) {
        if (Resource->ActiveCount == 0) {

            //
            // Resource is un-ownded, obtain it exclusive
            //

            Resource->InitialOwnerThreads[0] = OurThread;
            Resource->OwnerThreads[0] = OurThread;
            Resource->OwnerCounts[0]  = 1;
            Resource->ActiveCount     = 1;
            Resource->Flag           |= ResourceOwnedExclusive;
            ReleaseResourceLock ( Resource, OldIrql );
            return TRUE;
        }

        if (IsOwnedExclusive(Resource) &&
            Resource->OwnerThreads[0] == OurThread) {

            //
            // Our thread is already the exclusive resource owner
            //

            Resource->OwnerCounts[0] += 1;
            ReleaseResourceLock( Resource, OldIrql );
            return TRUE;
        }

        //
        //  Check if we are allowed to wait or must return immedately, and
        //  indicate that we didn't acquire the resource
        //

        if (!Wait) {
            ReleaseResourceLock( Resource, OldIrql );
            return FALSE;
        }

        //
        //  Otherwise we need to wait to acquire the resource.
        //

        WaitForResourceExclusive ( Resource, OldIrql );
    }
}


VOID
ExReleaseResourceForThread(
    IN PNTDDK_ERESOURCE Resource,
    IN ERESOURCE_THREAD OurThread
    )

/*++

Routine Description:

    This routine release the input resource the indcated thread.  The
    resource can have been acquired for either shared or exclusive access.

Arguments:

    Resource - Supplies the resource to release

    Thread - Supplies the thread that originally acquired the resource

Return Value:

    None.

--*/

{
    KIRQL OldIrql;

    ASSERT( OurThread != 0 );

    //
    //  Get exclusive access to this resource structure
    //

    AcquireResourceLock( Resource, &OldIrql );

    ASSERT( Resource->OwnerThreads[0] == OurThread );

    //
    // OwnerThread[0] is optimized for resources which get
    // single users.  We check it first, plus we clear the
    // threadid if the counts goes to zero
    //

    if (--Resource->OwnerCounts[0] != 0) {
        ReleaseResourceLock( Resource, OldIrql );
        return;
    }

    Resource->OwnerThreads[0] = 0;
    Resource->InitialOwnerThreads[0] = 0;

    //
    // Thread's count went to zero, lower the resource's active count.
    //

    Resource->ActiveCount -= 1;

    ASSERT( Resource->ActiveCount == 0 );

    //
    // Resource's activecount went to zero - clear possible exclusive
    // owner bit, and wake any waiters
    //

    if (IsExclusiveWaiting(Resource)) {

        WakeExclusiveWaiters ( Resource );
    }

    //
    //  No longer owned exclusive
    //

    Resource->Flag &= ~ResourceOwnedExclusive;

    ReleaseResourceLock( Resource, OldIrql );
    return;
}

NTSTATUS
ExDeleteResource (
    IN PNTDDK_ERESOURCE Resource
    )

/*++

Routine Description:

    This routine deletes (i.e., uninitializes) the input resource variable


Arguments:

    Resource - Supplies the resource variable being deleted

Return Value:

    None

--*/

{
    ASSERTMSG("Routine cannot be called at DPC ", !KeIsExecutingDpc() );

    ASSERT_RESOURCE( Resource );
    ASSERT( !IsExclusiveWaiting(Resource) );


    if (Resource >= (PNTDDK_ERESOURCE)MM_USER_PROBE_ADDRESS) {
        KIRQL OldIrql;

        ExAcquireSpinLock( &ExpResourceSpinLock, &OldIrql );
        RemoveEntryList( &Resource->SystemResourcesList );
        ExReleaseSpinLock( &ExpResourceSpinLock, OldIrql );

    }

    return STATUS_SUCCESS;
}

VOID
ExpWaitForResourceDdk (
    IN PNTDDK_ERESOURCE   Resource,
    IN PVOID        Object
    )
/*++

Routine Description:

    The routine waits on the Resource's object to be set.  If the
    wait is too long the current owners of the resoruce are boosted
    in priority.

Arguments:

    Resource - Supplies the resource

    Object - Event or Semaphore to wait on

Return Value:

    None

--*/
{
    KIRQL       OldIrql;
    NTSTATUS    Status;
    ULONG       i;


    Resource->ContentionCount += 1;

    i = 0;
    for (; ;) {
        Status = KeWaitForSingleObject (
                        Object,
                        Executive,
                        KernelMode,
                        FALSE,
                        &ExpTimeout );

        if (Status != STATUS_TIMEOUT) {
            break;
        }

        if (i++ >= ExpResourceTimeoutCount) {
            i = 0;

            DbgPrint("Resource @ %lx\n", Resource);
            DbgPrint(" ActiveCount = %04lx  Flags = %s%s%s\n",
                Resource->ActiveCount,
                IsOwnedExclusive(Resource)   ? "IsOwnedExclusive " : "",
                "",
                IsExclusiveWaiting(Resource) ? "ExclusiveWaiter "  : ""
            );

            DbgPrint(" NumberOfExclusiveWaiters = %04lx\n", Resource->NumberOfExclusiveWaiters);

            DbgPrint("  Thread = %08lx, Count = %02x\n",
                Resource->OwnerThreads[0],
                Resource->OwnerCounts[0] );

            DbgBreakPoint();
            DbgPrint("EX - Rewaiting\n");
        }

        //
        //  Give owning thread(s) a priority boost
        //

        AcquireResourceLock( Resource, &OldIrql );

        if (IsBoostAllowed(Resource) && IsOwnedExclusive(Resource)) {

            //
            //  Only one thread, boost it
            //

            KeBoostPriorityThread((PKTHREAD) Resource->OwnerThreads[0],
                                  ERESOURCE_INCREMENT );
        }

        ReleaseResourceLock( Resource, OldIrql );

        //
        //  Loop and wait some more
        //
    }

    //
    //  Wait was statisfied
    //

    ASSERT(NT_SUCCESS(Status));
    return ;
}

#if DBG
VOID
ExpAssertResourceDdk (
    IN PNTDDK_ERESOURCE   Resource
)
{
    USHORT  Sum;

    //
    //  Assert internal structures headers are correct
    //

    ASSERT(Resource->SharedWaiters.Header.Type == SemaphoreObject);
    ASSERT(Resource->SharedWaiters.Header.Size == sizeof(KSEMAPHORE));
    ASSERT(Resource->ExclusiveWaiters.Header.Type == SynchronizationEvent);
    ASSERT(Resource->ExclusiveWaiters.Header.Size == sizeof(KEVENT));

    //
    //  Count number of currently owned threads
    //

    Sum = Resource->OwnerCounts[0];

    //
    //  Verify sum is consistent with what's in the resource
    //

    ASSERT(Resource->ActiveCount == Sum);

    if (Sum == 0) {
        ASSERT(!IsOwnedExclusive(Resource));
        ASSERT(Resource->OwnerThreads[0] == 0);
        ASSERT(Resource->InitialOwnerThreads[0] == 0);
    }

    if (Sum > 1) {
        ASSERT(!IsOwnedExclusive(Resource));
    }

    //
    //  Verify resource flags appear correct
    //

    if (IsOwnedExclusive(Resource)) {
        ASSERT (Sum == 1);
        ASSERT (Resource->OwnerCounts[0] != 0);
        ASSERT (Resource->OwnerThreads[0] == Resource->InitialOwnerThreads[0]);
    }
}
#endif  // dbg