summaryrefslogblamecommitdiffstats
path: root/private/ntos/ex/uuid.c
blob: 2d84c304cb6443461336d269f8fef3f559c2d9a8 (plain) (tree)
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




























































































































































































































































































































































































































































































                                                                                        
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    uuid.c

Abstract:

    This module implements the core time and sequence number allocation
    for UUIDs.


Author:

    Mario Goertzel (MarioGo)  22-Nov-1994

Revision History:

--*/

#include "exp.h"


//
// Well known values
//

#define RPC_SEQUENCE_NUMBER_PATH L"\\Registry\\Machine\\Software\\Microsoft\\Rpc"
#define RPC_SEQUENCE_NUMBER_NAME L"UuidSequenceNumber"

//
//  Global variables
//

LARGE_INTEGER ExpUuidLastTimeAllocated;
ULONG         ExpUuidSequenceNumber;
BOOLEAN       ExpUuidSequenceNumberValid;
BOOLEAN       ExpUuidSequenceNumberNotSaved;
ERESOURCE     ExpUuidLock;
ERESOURCE     ExpSequenceLock;

//
// Helper functions to load and save the Uuid sequence number.
//

extern NTSTATUS ExpUuidLoadSequenceNumber(
    OUT PULONG
    );

extern NTSTATUS ExpUuidSaveSequenceNumber(
    IN ULONG
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, ExpUuidLoadSequenceNumber)
#pragma alloc_text(PAGE, ExpUuidSaveSequenceNumber)
#pragma alloc_text(INIT, ExpUuidInitialization)
#pragma alloc_text(PAGE, NtAllocateUuids)
#endif


NTSTATUS
ExpUuidLoadSequenceNumber(
    OUT PULONG Sequence
    )
/*++

Routine Description:

    This function loads the saved sequence number from the registry.  If
    no sequence number is found in the registry, it creates a 'random' one
    and saves that in the registry.

    This function is called only during system startup.

Arguments:

    Sequence - Pointer to storage for the sequence number.

Return Value:

    STATUS_SUCCESS when the sequence number is successfully read from the
        registry.

    STATUS_UNSUCCESSFUL when the sequence number is not correctly stored
        in the registry.

    Failure codes from ZwOpenKey() and ZwQueryValueKey() maybe returned.

--*/
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING KeyPath, KeyName;
    HANDLE Key;
    CHAR KeyValueBuffer[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(ULONG)];
    PKEY_VALUE_PARTIAL_INFORMATION KeyValueInformation;
    ULONG ResultLength;

    PAGED_CODE();

    KeyValueInformation = (PKEY_VALUE_PARTIAL_INFORMATION)KeyValueBuffer;

    RtlInitUnicodeString(&KeyPath, RPC_SEQUENCE_NUMBER_PATH);
    RtlInitUnicodeString(&KeyName, RPC_SEQUENCE_NUMBER_NAME);

    InitializeObjectAttributes( &ObjectAttributes,
                                &KeyPath,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );

    Status =
    ZwOpenKey( &Key,
               GENERIC_READ,
               &ObjectAttributes
             );

    if (NT_SUCCESS(Status)) {
        Status =
        ZwQueryValueKey( Key,
                         &KeyName,
                         KeyValuePartialInformation,
                         KeyValueInformation,
                         sizeof(KeyValueBuffer),
                         &ResultLength
                       );

        ZwClose( Key );
        }

    if (NT_SUCCESS(Status)) {
        if ( KeyValueInformation->Type == REG_DWORD &&
             KeyValueInformation->DataLength == sizeof(ULONG)
           ) {
            *Sequence = *(PULONG)KeyValueInformation->Data;
            }
        else {
            Status = STATUS_UNSUCCESSFUL;
            }
        }

    return(Status);
}


NTSTATUS
ExpUuidSaveSequenceNumber(
    IN ULONG Sequence
    )
/*++

Routine Description:

    This function save the uuid sequence number in the registry.  This
    value will be read by ExpUuidLoadSequenceNumber during the next boot.

Arguments:

    Sequence - The sequence number to save.

Return Value:

    STATUS_SUCCESS

    Failure codes from ZwOpenKey() and ZwSetValueKey() maybe returned.

--*/
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING KeyPath, KeyName;
    HANDLE Key;

    PAGED_CODE();

    RtlInitUnicodeString(&KeyPath, RPC_SEQUENCE_NUMBER_PATH);
    RtlInitUnicodeString(&KeyName, RPC_SEQUENCE_NUMBER_NAME);

    InitializeObjectAttributes( &ObjectAttributes,
                                &KeyPath,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );

    Status =
    ZwOpenKey( &Key,
               GENERIC_READ,
               &ObjectAttributes
             );

    if (NT_SUCCESS(Status)) {
        Status =
        ZwSetValueKey( Key,
                       &KeyName,
                       0,
                       REG_DWORD,
                       &Sequence,
                       sizeof(ULONG)
                     );

        ZwClose( Key );
        }

    return(Status);
}


BOOLEAN
ExpUuidInitialization (
    VOID
    )
/*++

Routine Description:

    This function initializes the UUID allocation.

Arguments:

    None.

Return Value:

    A value of TRUE is returned if the initialization is successfully
    completed.  Otherwise, a value of FALSE is returned.

--*/

{
    NTSTATUS Status;

    PAGED_CODE();

    ExInitializeResource(&ExpUuidLock);
    ExInitializeResource(&ExpSequenceLock);

    ExpUuidSequenceNumberValid = FALSE;

    // We can use the current time since we'll be changing the sequence number.

    KeQuerySystemTime(&ExpUuidLastTimeAllocated);

    return TRUE;
}


NTSTATUS
NtAllocateUuids (
    OUT PULARGE_INTEGER Time,
    OUT PULONG Range,
    OUT PULONG Sequence
    )

/*++

Routine Description:

    This function reserves a range of time for the caller(s) to use for 
    handing out Uuids.  As far a possible the same range of time and 
    sequence number will never be given out.  

    (It's possible to reboot 2^14-1 times and set the clock backwards and then 
    call this allocator and get a duplicate.  Since only the low 14bits of the 
    sequence number are used in a real uuid.) 

Arguments:

    Time - Supplies the address of a variable that will receive the
        start time (SYSTEMTIME format) of the range of time reserved.

    Range - Supplies the address of a variable that will receive the
        number of ticks (100ns) reserved after the value in Time.
        The range reserved is *Time to (*Time + *Range - 1).

    Sequence - Supplies the address of a variable that will receive
        the time sequence number.  This value is used with the associated
        range of time to prevent problems with clocks going backwards.

Return Value:

    STATUS_SUCCESS is returned if the service is successfully executed.

    STATUS_RETRY is returned if we're unable to reserve a range of
        UUIDs.  This may (?) occur if system clock hasn't advanced
        and the allocator is out of cached values.

    STATUS_ACCESS_VIOLATION is returned if the output parameter for the
        UUID cannot be written.

    STATUS_UNSUCCESSFUL is returned if some other service reports
        an error, most likly the registery.

--*/

{

    KPROCESSOR_MODE PreviousMode;
    NTSTATUS Status;
    LARGE_INTEGER CurrentTime;
    LARGE_INTEGER AvailableTime;
    LARGE_INTEGER OutputTime;
    ULONG OutputRange;
    ULONG OutputSequence;

    PAGED_CODE();

    //
    // Establish an exception handler and attempt to write the output
    // arguments. If the write attempt fails, then return
    // the exception code as the service status. Otherwise return success
    // as the service status.
    //

    try {

        //
        // Get previous processor mode and probe arguments if necessary.
        //

        PreviousMode = KeGetPreviousMode();
        if (PreviousMode != KernelMode) {
            ProbeForWrite((PVOID)Time, sizeof(LARGE_INTEGER), sizeof(ULONG));
            ProbeForWrite((PVOID)Range, sizeof(ULONG), sizeof(ULONG));
            ProbeForWrite((PVOID)Sequence, sizeof(ULONG), sizeof(ULONG));
            }
        }
    except (ExSystemExceptionFilter())
        {
        return GetExceptionCode();
        }

    ExAcquireResourceExclusive(&ExpUuidLock, TRUE);

    //
    // Make sure we have a valid sequence number.  If not, make one up.
    //

    if (ExpUuidSequenceNumberValid == FALSE) {
        Status = ExpUuidLoadSequenceNumber(&ExpUuidSequenceNumber);

        if (!NT_SUCCESS(Status)) {
            // Unable read the sequence number, this means we should make one up.

            LARGE_INTEGER PerfCounter;
            LARGE_INTEGER PerfFrequency;

            // This should only happen when NtAllocateUuids() is called
            // for the first time on a given machine. (machine, not boot)

            KdPrint(("Uuid: Generating first sequence number.\n"));

            PerfCounter = KeQueryPerformanceCounter(&PerfFrequency);

            ExpUuidSequenceNumber ^= (ULONG)&Status ^ PerfCounter.LowPart ^
                PerfCounter.HighPart ^ (ULONG)Sequence;
            }
        else {
            // We increment the sequence number on every boot.
            ExpUuidSequenceNumber++;
            }

        ExpUuidSequenceNumberValid = TRUE;
        ExpUuidSequenceNumberNotSaved = TRUE;
        }

    //
    // Get the current time, usually we will have plenty of avaliable
    // to give the caller.  But we may need to deal with time going
    // backwards and really fast machines.
    //

    KeQuerySystemTime(&CurrentTime);

    AvailableTime.QuadPart = CurrentTime.QuadPart - ExpUuidLastTimeAllocated.QuadPart;

    if (AvailableTime.QuadPart < 0) {
            
        // Time has been set time backwards. This means that we must make sure
        // that somebody increments the sequence number and saves the new
        // sequence number in the registry.

        ExpUuidSequenceNumberNotSaved = TRUE;
        ExpUuidSequenceNumber++;

        // The sequence number has been changed, so it's now okay to set time
        // backwards.  Since time is going backwards anyway, it's okay to set
        // it back an extra millisecond or two.

        ExpUuidLastTimeAllocated.QuadPart = CurrentTime.QuadPart - 20000;
        AvailableTime.QuadPart = 20000;
        }

    if (AvailableTime.QuadPart == 0) {
        // System time hasn't moved.  The caller should yield the CPU and retry.
        ExReleaseResource(&ExpUuidLock);
        return(STATUS_RETRY);
        }

    //
    // Common case, time has moved forward.
    //

    if (AvailableTime.QuadPart > 10*1000*1000) {
        // We never want to give out really old (> 1 second) Uuids.
        AvailableTime.QuadPart = 10*1000*1000;
        }

    if (AvailableTime.QuadPart > 10000) {
        // We've got over a millisecond to give out.  We'll save some time for
        // another caller so that we can avoid returning STATUS_RETRY very offen.
        OutputRange = 10000;
        AvailableTime.QuadPart -= 10000;
        }
    else {
        // Not much time avaiable, give it all away.
        OutputRange = (ULONG)AvailableTime.QuadPart;
        AvailableTime.QuadPart = 0;
        }

    OutputTime.QuadPart = CurrentTime.QuadPart - (OutputRange + AvailableTime.QuadPart);

    ExpUuidLastTimeAllocated.QuadPart = OutputTime.QuadPart + OutputRange;

    // Last time allocated is just after the range we hand back to the caller
    // this may be almost a second behind the true system time.

    OutputSequence = ExpUuidSequenceNumber;

    ExReleaseResource(&ExpUuidLock);

    // Saving the sequence number will usually complete without any problems.
    // So we let any other threads go at this point. If the save fails,
    // we'll retry on some future call.

    if (ExpUuidSequenceNumberNotSaved == TRUE) {
        if (ExAcquireResourceExclusive(&ExpSequenceLock, FALSE) == TRUE) {
            if (ExpUuidSequenceNumberNotSaved == TRUE) {

                ExpUuidSequenceNumberNotSaved = FALSE;

                // Print this message just to make sure we aren't hitting the
                // registry too much under normal usage.

                KdPrint(("Uuid: Saving new sequence number.\n"));

                Status = ExpUuidSaveSequenceNumber(ExpUuidSequenceNumber);

                if (!NT_SUCCESS(Status)) {
                    ExpUuidSequenceNumberNotSaved = TRUE;
                    }
                }
            }
        ExReleaseResource(&ExpSequenceLock);
        }

    //
    // Attempt to store the result of this call into the output parameters.
    // This is done within an exception handler in case output parameters
    // are now invalid.
    //

    try {
        Time->QuadPart = OutputTime.QuadPart;
        *Range = OutputRange;
        *Sequence = OutputSequence;
    }
    except (ExSystemExceptionFilter()) {
        return GetExceptionCode();
        }

    return(STATUS_SUCCESS);
}