summaryrefslogtreecommitdiffstats
path: root/private/nw/rdr/timer.c
blob: e5ca1204c54be51acd8fab2a1beeca11d1d3fa6c (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
/*++

Copyright (c) 1993  Microsoft Corporation

Module Name:

    timer.c

Abstract:

    This module contains code which implements the receive and send timeouts
    for each connection.

Author:

    Colin Watson (ColinW) 21-Feb-1993

Environment:

    Kernel mode

Revision History:

--*/

#include "procs.h"

//
//  The debug trace level
//

#define Dbg                             (DEBUG_TRACE_TIMER)

LARGE_INTEGER DueTime;
KDPC NwDpc;                               // DPC object for timeouts.
KTIMER Timer;                           // kernel timer for this request.
ULONG ScavengerTickCount;

BOOLEAN WorkerRunning = FALSE;
WORK_QUEUE_ITEM WorkItem;

#ifdef NWDBG
BOOLEAN DisableTimer = FALSE;
#endif

//
//  When we want to stop the timer, set TimerStop to TRUE. When the timer
//  is stopped TimerStopped will be set to the signalled state.
//

BOOLEAN TimerStop;
KEVENT TimerStopped;

VOID
TimerDPC(
    IN PKDPC Dpc,
    IN PVOID Context,
    IN PVOID SystemArgument1,
    IN PVOID SystemArgument2
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text( PAGE, StartTimer )
#pragma alloc_text( PAGE, StopTimer )

#endif


VOID
StartTimer(
    VOID
    )
/*++

Routine Description:

    This routine starts the timer ticking.

Arguments:

    None.

Return Value:

    None.

--*/
{
    PAGED_CODE();

    //
    //  We need 18.21 ticks per second
    //

    DueTime.QuadPart = (( 100000 * MILLISECONDS ) / 1821) * -1;

    //
    // This is the first connection with timeouts specified.
    // Set up the timer so that every 500 milliseconds we scan all the
    // connections for timed out receive and sends.
    //

    TimerStop = FALSE;

    KeInitializeEvent( &TimerStopped, SynchronizationEvent, FALSE );
    KeInitializeDpc( &NwDpc, TimerDPC, NULL );
    KeInitializeTimer( &Timer );

    (VOID)KeSetTimer(&Timer, DueTime, &NwDpc);

    DebugTrace(+0, Dbg, "StartTimer\n", 0);
}


VOID
StopTimer(
    VOID
    )
/*++

Routine Description:

    This routine stops the timer.  It blocks until the timer has stopped.

Arguments:

    None.

Return Value:

    None.

--*/
{
    PAGED_CODE();

    if (TimerStop == FALSE) {
        TimerStop = TRUE;

        DebugTrace(+0, Dbg, "StopTimer\n", 0);
        KeWaitForSingleObject (&TimerStopped, Executive, KernelMode, FALSE, NULL);
    }
}


VOID
TimerDPC(
    IN PKDPC Dpc,
    IN PVOID Context,
    IN PVOID SystemArgument1,
    IN PVOID SystemArgument2
    )
/*++

Routine Description:

    This routine is called to search for timed out send and receive
    requests.  This routine is called at DPC level.

Arguments:

    Dpc - Unused.
    Context - Unused.
    SystemArgument1 - Unused.
    SystemArgument2 - Unused.

Return Value:

    None.

--*/

{
    PLIST_ENTRY ScbQueueEntry;
    PLIST_ENTRY NextScbQueueEntry;
    PLIST_ENTRY IrpContextEntry;
    PLIST_ENTRY NextIrpContextEntry;
    SHORT RetryCount;
    PIRP_CONTEXT pIrpContext;
    LARGE_INTEGER CurrentTime = {0, 0};
    WCHAR AnonymousName[] = L"UNKNOWN";
    PWCHAR ServerLogName;

    if ( TimerStop ) {
        KeSetEvent( &TimerStopped, 0, FALSE );
        return;
    }

    //
    //  For each Server see if there is a timeout to process.
    //

#ifdef NWDBG
    if ( DisableTimer ) {
        //
        //  Reset the timer to run for another tick.
        //

        (VOID)KeSetTimer ( &Timer, DueTime, &NwDpc);

        return;
    }
#endif

    //DebugTrace(+1, Dbg, "TimerDpc....\n", 0);

    //
    //  Scan through the Scb's looking timed out requests.
    //

    KeAcquireSpinLockAtDpcLevel( &ScbSpinLock );

    ScbQueueEntry = ScbQueue.Flink;

    if (ScbQueueEntry != &ScbQueue) {
        PNONPAGED_SCB pNpScb = CONTAINING_RECORD(ScbQueueEntry,
                                                    NONPAGED_SCB,
                                                    ScbLinks);
        NwQuietReferenceScb( pNpScb );
    }

    for (;
         ScbQueueEntry != &ScbQueue ;
         ScbQueueEntry = NextScbQueueEntry ) {

        PNONPAGED_SCB pNpScb = CONTAINING_RECORD(ScbQueueEntry,
                                                    NONPAGED_SCB,
                                                    ScbLinks);

        //  Obtain a pointer to the next SCB in the SCB list before
        //  dereferencing the current one.
        //

        NextScbQueueEntry = pNpScb->ScbLinks.Flink;

        if (NextScbQueueEntry != &ScbQueue) {
            PNONPAGED_SCB pNextNpScb = CONTAINING_RECORD(NextScbQueueEntry,
                                                        NONPAGED_SCB,
                                                        ScbLinks);
            //
            //  Reference the next entry in the list to ensure the scavenger
            //  doesn't put it on another list or destroy it.
            //

            NwQuietReferenceScb( pNextNpScb );
        }

        KeReleaseSpinLockFromDpcLevel( &ScbSpinLock );

        //
        //  Acquire the Scb specific spin lock to protect access
        //  the the Scb fields.
        //

        KeAcquireSpinLockAtDpcLevel( &pNpScb->NpScbSpinLock );

        //
        //  Look at the first request on the queue only (since it is
        //  the only active request).
        //

        if ( ( !IsListEmpty( &pNpScb->Requests )) &&
             ( !pNpScb->Sending ) &&
             ( pNpScb->OkToReceive ) &&
             ( --pNpScb->TimeOut <= 0 ) ) {

             PIRP_CONTEXT pIrpContext;

            //
            //  This request has timed out.  Try to retransmit the request.
            //

            pIrpContext = CONTAINING_RECORD(
                              pNpScb->Requests.Flink,
                              IRP_CONTEXT,
                              NextRequest);

            pNpScb->TimeOut = pNpScb->MaxTimeOut;

            //
            //  Check the retry count while we own the spin lock.
            //

            RetryCount = --pNpScb->RetryCount;
            NwQuietDereferenceScb( pNpScb );

            //
            //  Set OkToReceive to FALSE, so that if we receive a response
            //  right now, our receive handler won't handle the response
            //  and cause IRP context to be freed.
            //

            pNpScb->OkToReceive = FALSE;
            KeReleaseSpinLockFromDpcLevel( &pNpScb->NpScbSpinLock );

            if ( pIrpContext->pOriginalIrp->Cancel ) {

                //
                //  This IRP has been cancelled.  Call the callback routine.
                //
                //  BUGBUG - This will cause a timeout error.
                //

                DebugTrace(+0, Dbg, "Timer cancel IRP %X\n", pIrpContext->pOriginalIrp );
                pIrpContext->pEx( pIrpContext, 0, NULL );

            } else if ( RetryCount >= 0) {

                //
                //  We're not out of retries.  Resend the request packet.
                //
                //  First adjust the send timeout up.  Adjust the timeout
                //  more slowly on a close by server.
                //

                if ( pNpScb->SendTimeout < pNpScb->MaxTimeOut ) {
                    if ( pNpScb->TickCount <= 4 ) {
                        pNpScb->SendTimeout++;
                    } else {
                        pNpScb->SendTimeout = pNpScb->SendTimeout * 3 / 2;
                        if ( pNpScb->SendTimeout > pNpScb->MaxTimeOut ) {
                            pNpScb->SendTimeout = pNpScb->MaxTimeOut;
                        }
                    }
                }

                pNpScb->TimeOut = pNpScb->SendTimeout;
                DebugTrace(+0, Dbg, "Adjusting send timeout: %x\n", pIrpContext );
                DebugTrace(+0, Dbg, "Adjusting send timeout to: %d\n", pNpScb->TimeOut );

                if ( pIrpContext->TimeoutRoutine != NULL ) {

                    DebugTrace(+0, Dbg, "Timeout Routine, retry %x\n", RetryCount+1);
                    DebugTrace(+0, Dbg, "Calling TimeoutRoutine, %x\n", pIrpContext->TimeoutRoutine);
                    pIrpContext->TimeoutRoutine( pIrpContext );

                } else {

                    DebugTrace(+0, Dbg, "Resending Packet, retry %x\n", RetryCount+1);
                    PreparePacket( pIrpContext, pIrpContext->pOriginalIrp, pIrpContext->TxMdl );

                    SetFlag( pIrpContext->Flags, IRP_FLAG_RETRY_SEND );
                    SendNow( pIrpContext );
                }

                Stats.FailedSessions++;

            } else {

                ASSERT( pIrpContext->pEx != NULL );

                //
                //  We are out of retries.
                //

                if ( BooleanFlagOn( pIrpContext->Flags, IRP_FLAG_REROUTE_ATTEMPTED ) ||
                     ( NwAbsoluteTotalWaitTime != 0  &&
                       pNpScb->TotalWaitTime >= NwAbsoluteTotalWaitTime ) ) {


                    ClearFlag( pIrpContext->Flags, IRP_FLAG_RETRY_SEND );

                    //
                    //  He have already attempted to reroute the request.
                    //  Give up.
                    //

                    DebugTrace(+0, Dbg, "Abandon Exchange\n", 0 );

                    if ( pIrpContext->pNpScb != &NwPermanentNpScb ) {

                        //
                        //  Reset to the attaching state.  If the server
                        //  is dead, the next attempt to open a handle will
                        //  fail with a better error than unexpected network
                        //  error.
                        //

                        pIrpContext->pNpScb->State = SCB_STATE_ATTACHING;

                        //
                        //  Determine the CurrentTime. We need to know if
                        //  TimeOutEventInterval minutes have passed before
                        //  we log the next time-out event.
                        //

                        KeQuerySystemTime( &CurrentTime );

                        if ( CanLogTimeOutEvent( pNpScb->NwNextEventTime,
                                                CurrentTime
                                                )) {

                            if ( pNpScb->ServerName.Buffer != NULL ) {
                                ServerLogName = pNpScb->ServerName.Buffer;
                            } else {
                                ServerLogName = &AnonymousName[0];
                            }

                            Error(
                                EVENT_NWRDR_TIMEOUT,
                                STATUS_UNEXPECTED_NETWORK_ERROR,
                                NULL,
                                0,
                                1,
                                ServerLogName );

                            //
                            //  Set the LastEventTime to the CurrentTime
                            //

                            UpdateNextEventTime(
                                    pNpScb->NwNextEventTime,
                                    CurrentTime,
                                    TimeOutEventInterval
                                    );
                        }

                    }

                    pIrpContext->ResponseParameters.Error = ERROR_UNEXP_NET_ERR;
                    pIrpContext->pEx( pIrpContext, 0, NULL );

                } else {

                    //
                    //  Attempt to reroute the request.
                    //

                    SetFlag( pIrpContext->Flags, IRP_FLAG_REROUTE_ATTEMPTED );

                    if ( BooleanFlagOn(
                            pIrpContext->Flags,
                            IRP_FLAG_BURST_PACKET ) ) {
                        pIrpContext->PostProcessRoutine = NewRouteBurstRetry;
                    } else {
                        pIrpContext->PostProcessRoutine = NewRouteRetry;
                    }

                    NwPostToFsp( pIrpContext, FALSE );
                }
            }

        } else {

            if ( ( !IsListEmpty( &pNpScb->Requests )) &&
                 ( !pNpScb->Sending ) &&
                 ( pNpScb->OkToReceive ) ) {

                DebugTrace( 0, Dbg, "TimeOut %d\n", pNpScb->TimeOut );
            }

            //
            //  Nothing to do for this SCB.  Dereference this SCB and
            //  release the spin lock.
            //

            KeReleaseSpinLockFromDpcLevel( &pNpScb->NpScbSpinLock );
            NwQuietDereferenceScb( pNpScb );
        }

        KeAcquireSpinLockAtDpcLevel( &ScbSpinLock );

    }

    KeReleaseSpinLockFromDpcLevel( &ScbSpinLock );

    //
    //  Now see if the scavenger routine needs to be run.
    //  Only ever queue one workitem.
    //

    KeAcquireSpinLockAtDpcLevel( &NwScavengerSpinLock );

    NwScavengerTickCount++;
    if (( !WorkerRunning ) &&
        ( NwScavengerTickCount > NwScavengerTickRunCount )) {

        ExInitializeWorkItem( &WorkItem, NwScavengerRoutine, &WorkItem );
        ExQueueWorkItem( &WorkItem, DelayedWorkQueue );
        NwScavengerTickCount = 0;
        WorkerRunning = TRUE;
    }

    KeReleaseSpinLockFromDpcLevel( &NwScavengerSpinLock );

    //
    //  Scan the list of pending locks, looking for locks to retry.
    //

    KeAcquireSpinLockAtDpcLevel( &NwPendingLockSpinLock );

    for (IrpContextEntry = NwPendingLockList.Flink ;
         IrpContextEntry != &NwPendingLockList ;
         IrpContextEntry = NextIrpContextEntry ) {

        NextIrpContextEntry = IrpContextEntry->Flink;
        pIrpContext = CONTAINING_RECORD( IrpContextEntry, IRP_CONTEXT, NextRequest );

        //
        //  BUGBUG surely we can't use the key like this to control the number
        //  of retries.
        //

        if ( --pIrpContext->Specific.Lock.Key <= 0 ) {

            //
            //  Remove the IRP Context from the queue and reattempt the lock.
            //  Set the SEQUENCE_NO_REQUIRED flag so that the packet gets
            //  renumbered.
            //

            RemoveEntryList( &pIrpContext->NextRequest );
            SetFlag( pIrpContext->Flags,  IRP_FLAG_SEQUENCE_NO_REQUIRED );
            PrepareAndSendPacket( pIrpContext );
        }

    }

    KeReleaseSpinLockFromDpcLevel( &NwPendingLockSpinLock );

    //
    //  Reset the timer to run for another tick.
    //

    (VOID)KeSetTimer ( &Timer, DueTime, &NwDpc);

    //DebugTrace(-1, Dbg, "TimerDpc\n", 0);
    return;

    UNREFERENCED_PARAMETER (Dpc);
    UNREFERENCED_PARAMETER (Context);
    UNREFERENCED_PARAMETER (SystemArgument1);
    UNREFERENCED_PARAMETER (SystemArgument2);

}