summaryrefslogtreecommitdiffstats
path: root/private/ntos/mm/forksup.c
blob: 1fb726c7c106130cd308d655151f61c45a48dfc5 (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
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
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

   forksup.c

Abstract:

    This module contains the routines which support the POSIX fork operation.

Author:

    Lou Perazzoli (loup) 22-Jul-1989

Revision History:

--*/

#include "mi.h"

VOID
MiUpPfnReferenceCount (
    IN ULONG Page,
    IN USHORT Count
    );

VOID
MiDownPfnReferenceCount (
    IN ULONG Page
    );

VOID
MiUpControlAreaRefs (
    IN PCONTROL_AREA ControlArea
    );

ULONG
MiDoneWithThisPageGetAnother (
    IN PULONG PageFrameIndex,
    IN PMMPTE PointerPde,
    IN PEPROCESS CurrentProcess
    );

VOID
MiUpForkPageShareCount(
    IN PMMPFN PfnForkPtePage
    );

VOID
MiUpCloneProtoRefCount (
    IN PMMCLONE_BLOCK CloneProto,
    IN PEPROCESS CurrentProcess
    );

ULONG
MiHandleForkTransitionPte (
    IN PMMPTE PointerPte,
    IN PMMPTE PointerNewPte,
    IN PMMCLONE_BLOCK ForkProtoPte
    );

VOID
MiDownShareCountFlushEntireTb (
    IN ULONG PageFrameIndex
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE,MiCloneProcessAddressSpace)
#endif



NTSTATUS
MiCloneProcessAddressSpace (
    IN PEPROCESS ProcessToClone,
    IN PEPROCESS ProcessToInitialize,
    IN ULONG PdePhysicalPage,
    IN ULONG HyperPhysicalPage
    )

/*++

Routine Description:

    This routine stands on its head to produce a copy of the specified
    process's address space in the process to initialize.  This
    is done by examining each virtual address descriptor's inherit
    attributes.  If the pages described by the VAD should be inherited,
    each PTE is examined and copied into the new address space.

    For private pages, fork prototype PTEs are constructed and the pages
    become shared, copy-on-write, between the two processes.


Arguments:

    ProcessToClone - Supplies the process whose address space should be
                     cloned.

    ProcessToInitialize - Supplies the process whose address space is to
                          be created.

    PdePhysicalPage - Supplies the physical page number of the page directory
                      of the process to initialize.

    HyperPhysicalPage - Supplies the physical page number of the page table
                        page which maps hyperspace for the process to
                        initialize.

Return Value:

    None.

Environment:

    Kernel mode, APC's disabled.

--*/

{
    PEPROCESS CurrentProcess;
    PMMWSL HyperBase;
    PMMPTE PdeBase;
    PMMCLONE_HEADER CloneHeader;
    PMMCLONE_BLOCK CloneProtos;
    PMMCLONE_DESCRIPTOR CloneDescriptor;
    PMMVAD NewVad;
    PMMVAD Vad;
    PMMVAD NextVad;
    PMMVAD *VadList;
    PMMVAD FirstNewVad;
    PMMCLONE_DESCRIPTOR *CloneList;
    PMMCLONE_DESCRIPTOR FirstNewClone;
    PMMCLONE_DESCRIPTOR Clone;
    PMMCLONE_DESCRIPTOR NextClone;
    PMMCLONE_DESCRIPTOR NewClone;
    ULONG Attached = FALSE;
    ULONG CloneFailed;
    ULONG VadInsertFailed;
    ULONG WorkingSetIndex;
    PVOID VirtualAddress;
    NTSTATUS status;
    PMMPFN Pfn1;
    PMMPFN Pfn2;
    PMMPFN PfnPdPage;
    MMPTE TempPte;
    MMPTE PteContents;
    PMDL Mdl0;
    PMDL Mdl1;
    PMDL Mdl2;
    ULONG MdlHack0[(sizeof(MDL)/4) + 1];
    ULONG MdlHack1[(sizeof(MDL)/4) + 1];
    ULONG MdlHack2[(sizeof(MDL)/4) + 1];
    PULONG MdlPage;
    PMMPTE PointerPte;
    PMMPTE PointerPde;
    PMMPTE LastPte;
    PMMPTE PointerNewPte;
    PMMPTE PointerNewPde;
    ULONG PageFrameIndex = 0xFFFFFFFF;
    PMMCLONE_BLOCK ForkProtoPte;
    PMMCLONE_BLOCK CloneProto;
    PMMCLONE_BLOCK LockedForkPte;
    PMMPTE ContainingPte;
    ULONG NumberOfForkPtes = 0;
    ULONG NumberOfPrivatePages;
    ULONG PageTablePage;
    ULONG TotalPagedPoolCharge;
    ULONG TotalNonPagedPoolCharge;
    PMMPFN PfnForkPtePage;
    PUSHORT UsedPageTableEntries;
    ULONG ReleasedWorkingSetMutex;
    ULONG FirstTime;

#if DBG
    if (MmDebug & MM_DBG_FORK) {
        DbgPrint("beginning clone operation process to clone = %lx\n",
            ProcessToClone);
    }
#endif //DBG

    PAGED_CODE();

    if (ProcessToClone != PsGetCurrentProcess()) {
        Attached = TRUE;
        KeAttachProcess (&ProcessToClone->Pcb);
    }

    CurrentProcess = ProcessToClone;

    //
    // Get the working set mutex and the address creation mutex
    // of the process to clone.  This prevents page faults while we
    // are examining the address map and prevents virtual address space
    // from being created or deleted.
    //

    LOCK_ADDRESS_SPACE (CurrentProcess);

    //
    // Make sure the address space was not deleted, if so, return an error.
    //

    if (CurrentProcess->AddressSpaceDeleted != 0) {
        status = STATUS_PROCESS_IS_TERMINATING;
        goto ErrorReturn1;
    }

    //
    // Attempt to acquire the needed pool before starting the
    // clone operation, this allows an easier failure path in
    // the case of insufficient system resources.
    //

    NumberOfPrivatePages = CurrentProcess->NumberOfPrivatePages;

    CloneProtos = ExAllocatePoolWithTag (PagedPool, sizeof(MMCLONE_BLOCK) *
                                                NumberOfPrivatePages,
                                                '  mM');
    if (CloneProtos == NULL) {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto ErrorReturn1;
    }

    CloneHeader = ExAllocatePoolWithTag (NonPagedPool,
                                         sizeof(MMCLONE_HEADER),
                                         '  mM');
    if (CloneHeader == NULL) {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto ErrorReturn2;
    }

    CloneDescriptor = ExAllocatePoolWithTag (NonPagedPool,
                                             sizeof(MMCLONE_DESCRIPTOR),
                                             '  mM');
    if (CloneDescriptor == NULL) {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto ErrorReturn3;
    }

    Vad = MiGetFirstVad (CurrentProcess);
    VadList = &FirstNewVad;

    while (Vad != (PMMVAD)NULL) {

        //
        // If the VAD does not go to the child, ignore it.
        //

        if ((Vad->u.VadFlags.PrivateMemory == 1) ||
            (Vad->u.VadFlags.Inherit == MM_VIEW_SHARE)) {

            NewVad = ExAllocatePoolWithTag (NonPagedPool, sizeof(MMVAD), ' daV');

            if (NewVad == NULL) {

                //
                // Unable to allocate pool for all the VADs.  Deallocate
                // all VADs and other pool obtained so far.
                //

                *VadList = (PMMVAD)NULL;
                NewVad = FirstNewVad;
                while (NewVad != NULL) {
                    Vad = NewVad->Parent;
                    ExFreePool (NewVad);
                    NewVad = Vad;
                }
                status = STATUS_INSUFFICIENT_RESOURCES;
                goto ErrorReturn4;
            }
            *VadList = NewVad;
            VadList = &NewVad->Parent;
        }
        Vad = MiGetNextVad (Vad);
    }

    //
    // Terminate list of VADs for new process.
    //

    *VadList = (PMMVAD)NULL;


    //
    // Charge the current process the quota for the paged and nonpage
    // global structures.  This consists of the array of clone blocks
    // in paged pool and the clone header in non-paged pool.
    //

    try {
        PageTablePage = 1;
        PsChargePoolQuota (CurrentProcess, PagedPool, sizeof(MMCLONE_BLOCK) *
                                                NumberOfPrivatePages);
        PageTablePage = 0;
        PsChargePoolQuota (CurrentProcess, NonPagedPool, sizeof(MMCLONE_HEADER));

    } except (EXCEPTION_EXECUTE_HANDLER) {

        if (PageTablePage == 0) {
            PsReturnPoolQuota (CurrentProcess, PagedPool, sizeof(MMCLONE_BLOCK) *
                                NumberOfPrivatePages);
        }

        //
        // Unable to allocate pool for all the VADs.  Deallocate
        // all VADs and other pool obtained so far.
        //

        NewVad = FirstNewVad;
        while (NewVad != NULL) {
            Vad = NewVad->Parent;
            ExFreePool (NewVad);
            NewVad = Vad;
        }
        status = GetExceptionCode();
        goto ErrorReturn4;
    }

    LOCK_WS (CurrentProcess);

    ASSERT (CurrentProcess->ForkInProgress == NULL);

    //
    // Indicate to the pager that the current process is being
    // forked.  This blocks other threads in that process from
    // modifying clone blocks counts and contents.
    //

    CurrentProcess->ForkInProgress = PsGetCurrentThread();

    //
    // Map the PDE and the hyperspace page into the system address space
    // This is accomplished by building an MDL to describe the
    // Page directory and the hyperspace page.
    //

    Mdl0 = (PMDL)&MdlHack0[0];
    MdlPage = (PULONG)(Mdl0 + 1);

    MmInitializeMdl(Mdl0, (PVOID)PDE_BASE, PAGE_SIZE);
    Mdl0->MdlFlags |= MDL_PAGES_LOCKED;
    *MdlPage = PdePhysicalPage;

    //
    // Increment the reference count for the pages which are being "locked"
    // in MDLs.  This prevents the page from being reused while it is
    // being double mapped.
    //

    MiUpPfnReferenceCount (PdePhysicalPage,1);
    MiUpPfnReferenceCount (HyperPhysicalPage,2);

    PdeBase = (PMMPTE)MmMapLockedPages (Mdl0, KernelMode);

    Mdl1 = (PMDL)&MdlHack1[0];

    MdlPage = (PULONG)(Mdl1 + 1);
    MmInitializeMdl(Mdl1, (PVOID)MmWorkingSetList, PAGE_SIZE);
    Mdl1->MdlFlags |= MDL_PAGES_LOCKED;
    *MdlPage = HyperPhysicalPage;

    HyperBase = (PMMWSL)MmMapLockedPages (Mdl1, KernelMode);

    PfnPdPage = MI_PFN_ELEMENT (PdePhysicalPage);

    //
    // Initialize MDL2 to lock and map the hyperspace page so it
    // can be unlocked in the loop and the end of the loop without
    // any testing to see if has a valid value the first time through.
    //

    Mdl2 = (PMDL)&MdlHack2[0];
    MdlPage = (PULONG)(Mdl2 + 1);
    MmInitializeMdl(Mdl2, (PVOID)MmWorkingSetList, PAGE_SIZE);
    Mdl2->MdlFlags |= MDL_PAGES_LOCKED;
    *MdlPage = HyperPhysicalPage;

    PointerNewPte = (PMMPTE)MmMapLockedPages (Mdl2, KernelMode);

    //
    // Build new clone prototype PTE block and descriptor, note that
    // each prototype PTE has a reference count following it.
    //

    ForkProtoPte = CloneProtos;

    LockedForkPte = ForkProtoPte;
    MiLockPagedAddress (LockedForkPte, FALSE);

    CloneHeader->NumberOfPtes = NumberOfPrivatePages;
    CloneHeader->NumberOfProcessReferences = 1;
    CloneHeader->ClonePtes = CloneProtos;



    CloneDescriptor->StartingVa = (PVOID)CloneProtos;
    CloneDescriptor->EndingVa = (PVOID)((ULONG)CloneProtos +
                            NumberOfPrivatePages *
                              sizeof(MMCLONE_BLOCK));
    CloneDescriptor->NumberOfReferences = 0;
    CloneDescriptor->NumberOfPtes = NumberOfPrivatePages;
    CloneDescriptor->CloneHeader = CloneHeader;
    CloneDescriptor->PagedPoolQuotaCharge = sizeof(MMCLONE_BLOCK) *
                                NumberOfPrivatePages;

    //
    // Insert the clone descriptor for this fork operation into the
    // process which was cloned.
    //

    MiInsertClone (CloneDescriptor);

    //
    // Examine each virtual address descriptor and create the
    // proper structures for the new process.
    //

    Vad = MiGetFirstVad (CurrentProcess);
    NewVad = FirstNewVad;

    while (Vad != (PMMVAD)NULL) {

        //
        // Examine the VAD to determine its type and inheritence
        // attribute.
        //

        if ((Vad->u.VadFlags.PrivateMemory == 1) ||
            (Vad->u.VadFlags.Inherit == MM_VIEW_SHARE)) {

            //
            // The virtual address descriptor should be shared in the
            // forked process.
            //

            //
            // Make a copy of the VAD for the new process, the new vads
            // are preallocated and linked together through the parent
            // field.
            //

            NextVad = NewVad->Parent;


            if (Vad->u.VadFlags.PrivateMemory == 1) {
                *(PMMVAD_SHORT)NewVad = *(PMMVAD_SHORT)Vad;
                NewVad->u.VadFlags.NoChange = 0;
            } else {
                *NewVad = *Vad;
            }

            if (NewVad->u.VadFlags.NoChange) {
                if ((NewVad->u2.VadFlags2.OneSecured) ||
                    (NewVad->u2.VadFlags2.MultipleSecured)) {

                    //
                    // Eliminate these as the memory was secured
                    // only in this process, not in the new one.
                    //

                    NewVad->u2.VadFlags2.OneSecured = 0;
                    NewVad->u2.VadFlags2.MultipleSecured = 0;
                    NewVad->u2.VadFlags2.StoredInVad = 0;
                    NewVad->u3.List.Flink = NULL;
                    NewVad->u3.List.Blink = NULL;
                }
                if (NewVad->u2.VadFlags2.SecNoChange == 0) {
                    NewVad->u.VadFlags.NoChange = 0;
                }
            }
            NewVad->Parent = NextVad;

            //
            // If the VAD refers to a section, up the view count for that
            // section.  This requires the PFN mutex to be held.
            //

            if ((Vad->u.VadFlags.PrivateMemory == 0) &&
                (Vad->ControlArea != (PCONTROL_AREA)NULL)) {

                //
                // Increment the count of the number of views for the
                // section object.  This requires the PFN mutex to be held.
                //

                MiUpControlAreaRefs (Vad->ControlArea);
            }

            //
            // Examine each PTE and create the appropriate PTE for the
            // new process.
            //

            PointerPde = MiGetPdeAddress (Vad->StartingVa);
            PointerPte = (volatile PMMPTE) MiGetPteAddress (Vad->StartingVa);
            LastPte = MiGetPteAddress (Vad->EndingVa);
            FirstTime = TRUE;

            while ((PMMPTE)PointerPte <= LastPte) {

                //
                // For each PTE contained in the VAD check the page table
                // page, and if non-zero, make the appropriate modifications
                // to copy the PTE to the new process.
                //

                if ((FirstTime) || (((ULONG)PointerPte & (PAGE_SIZE - 1)) == 0)) {

                    PointerPde = MiGetPteAddress (PointerPte);

                    while (!MiDoesPdeExistAndMakeValid (PointerPde,
                                                        CurrentProcess,
                                                        FALSE)) {

                        //
                        // This page directory is empty, go to the next one.
                        //

                        PointerPde += 1;
                        PointerPte = MiGetVirtualAddressMappedByPte (PointerPde);

                        if ((PMMPTE)PointerPte > LastPte) {

                            //
                            // All done with this VAD, exit loop.
                            //

                            goto AllDone;
                        }
                    }

                    FirstTime = FALSE;

                    //
                    // Calculate the address of the pde in the new process's
                    // page table page.
                    //

                    PointerNewPde = &PdeBase[MiGetPteOffset(PointerPte)];

                    if (PointerNewPde->u.Long == 0) {

                        //
                        // No physical page has been allocated yet, get a page
                        // and map it in as a transition page.  This will
                        // become a page table page for the new process.
                        //


                        ReleasedWorkingSetMutex =
                                MiDoneWithThisPageGetAnother (&PageFrameIndex,
                                                              PointerPde,
                                                              CurrentProcess);
                        if (ReleasedWorkingSetMutex) {
                            MiDoesPdeExistAndMakeValid (PointerPde,
                                                        CurrentProcess,
                                                        FALSE);
                        }

                        //
                        // Hand initialize this PFN as normal initialization
                        // would do it for the process whose context we are
                        // attached to.
                        //

                        Pfn1 = MI_PFN_ELEMENT (PageFrameIndex);
                        Pfn1->OriginalPte = DemandZeroPde;
                        Pfn1->u2.ShareCount = 1;
                        Pfn1->u3.e2.ReferenceCount = 1;
                        Pfn1->PteAddress = PointerPde;
                        Pfn1->u3.e1.Modified = 1;
                        Pfn1->u3.e1.PageLocation = ActiveAndValid;
                        Pfn1->PteFrame = PdePhysicalPage;

                        //
                        // Increment the share count for the page containing
                        // this PTE as the PTE is in transition.
                        //

                        PfnPdPage->u2.ShareCount += 1;

                        //
                        // Put the PDE into the transition state as it is not
                        // really mapped and decrement share count does not
                        // put private pages into transition, only prototypes.
                        //

                        *PointerNewPde = TransitionPde;

                        //
                        // Make the PTE owned by user mode.
                        //

#ifndef _ALPHA_
                        MI_SET_OWNER_IN_PTE (PointerNewPde, UserMode);
#endif //_ALPHA_
                        PointerNewPde->u.Trans.PageFrameNumber = PageFrameIndex;

                        //
                        // Map the new page table page into the system portion
                        // of the address space.  Note that hyperspace
                        // cannot be used as other operations (allocating
                        // nonpaged pool at DPC level) could cause the
                        // hyperspace page being used to be reused.
                        //

                        MmUnmapLockedPages (Mdl2->MappedSystemVa, Mdl2);

                        MiDownPfnReferenceCount (*MdlPage);

                        Mdl2->StartVa = MiGetVirtualAddressMappedByPte(PointerPde);

                        *MdlPage = PageFrameIndex;

                        MiUpPfnReferenceCount (PageFrameIndex, 1);

                        PointerNewPte = (PMMPTE)MmMapLockedPages (Mdl2,
                                                                  KernelMode);

                        UsedPageTableEntries = &HyperBase->UsedPageTableEntries
                                                    [MiGetPteOffset( PointerPte )];

                    }

                    //
                    // Calculate the address of the new pte to build.
                    // Note that FirstTime could be true, yet the page
                    // table page already built.
                    //

                    PointerNewPte = (PMMPTE)((ULONG)PAGE_ALIGN(PointerNewPte) |
                                            BYTE_OFFSET (PointerPte));
                }

                //
                // Make the forkprototype Pte location resident.
                //

                if (PAGE_ALIGN (ForkProtoPte) != PAGE_ALIGN (LockedForkPte)) {
                    MiUnlockPagedAddress (LockedForkPte, FALSE);
                    LockedForkPte = ForkProtoPte;
                    MiLockPagedAddress (LockedForkPte, FALSE);
                }

                MiMakeSystemAddressValid (PointerPte,
                                            CurrentProcess);

                PteContents = *PointerPte;

                //
                // Check each PTE.
                //

                if (PteContents.u.Long == 0) {
                    NOTHING;

                } else if (PteContents.u.Hard.Valid == 1) {

                    //
                    // Valid.
                    //

                    Pfn2 = MI_PFN_ELEMENT (PteContents.u.Hard.PageFrameNumber);
                    VirtualAddress = MiGetVirtualAddressMappedByPte (PointerPte);
                    WorkingSetIndex = MiLocateWsle (VirtualAddress,
                                                    MmWorkingSetList,
                                                    Pfn2->u1.WsIndex);

                    ASSERT (WorkingSetIndex != WSLE_NULL_INDEX);

                    if (Pfn2->u3.e1.PrototypePte == 1) {

                        //
                        // This PTE is already in prototype PTE format.
                        //

                        //
                        // This is a prototype PTE.  The PFN database does
                        // not contain the contents of this PTE it contains
                        // the contents of the prototype PTE.  This PTE must
                        // be reconstructed to contain a pointer to the
                        // prototype PTE.
                        //
                        // The working set list entry contains information about
                        // how to reconstruct the PTE.
                        //

                        if (MmWsle[WorkingSetIndex].u1.e1.SameProtectAsProto
                                                                        == 0) {

                            //
                            // The protection for the prototype PTE is in the
                            // WSLE.
                            //

                            TempPte.u.Long = 0;
                            TempPte.u.Soft.Protection =
                                      MmWsle[WorkingSetIndex].u1.e1.Protection;
                            TempPte.u.Soft.PageFileHigh = 0xFFFFF;

                        } else {

                            //
                            // The protection is in the prototype PTE.
                            //

                            TempPte.u.Long = MiProtoAddressForPte (
                                                            Pfn2->PteAddress);
 //                            TempPte.u.Proto.ForkType =
 //                                        MmWsle[WorkingSetIndex].u1.e1.ForkType;
                        }

                        TempPte.u.Proto.Prototype = 1;
                        *PointerNewPte = TempPte;

                        //
                        // A PTE is now non-zero, increment the used page
                        // table entries counter.
                        //

                        *UsedPageTableEntries += 1;

                        //
                        // Check to see if this is a fork prototype PTE,
                        // and if it is increment the reference count
                        // which is in the longword following the PTE.
                        //

                        if (MiLocateCloneAddress ((PVOID)Pfn2->PteAddress) !=
                                    (PMMCLONE_DESCRIPTOR)NULL) {

                            //
                            // The reference count field, or the prototype PTE
                            // for that matter may not be in the working set.
                            //

                            CloneProto = (PMMCLONE_BLOCK)Pfn2->PteAddress;

                            MiUpCloneProtoRefCount (CloneProto,
                                                    CurrentProcess);

                            if (PAGE_ALIGN (ForkProtoPte) !=
                                                    PAGE_ALIGN (LockedForkPte)) {
                                MiUnlockPagedAddress (LockedForkPte, FALSE);
                                LockedForkPte = ForkProtoPte;
                                MiLockPagedAddress (LockedForkPte, FALSE);
                            }

                            MiMakeSystemAddressValid (PointerPte,
                                                        CurrentProcess);
                        }

                    } else {

                        //
                        // This is a private page, create a fork prototype PTE
                        // which becomes the "prototype" PTE for this page.
                        // The protection is the same as that in the prototype'
                        // PTE so the WSLE does not need to be updated.
                        //

                        MI_MAKE_VALID_PTE_WRITE_COPY (PointerPte);

                        ForkProtoPte->ProtoPte = *PointerPte;
                        ForkProtoPte->CloneRefCount = 2;

                        //
                        // Transform the PFN element to reference this new fork
                        // prototype PTE.
                        //

                        Pfn2->PteAddress = &ForkProtoPte->ProtoPte;
                        Pfn2->u3.e1.PrototypePte = 1;

                        ContainingPte = MiGetPteAddress(&ForkProtoPte->ProtoPte);
                        Pfn2->PteFrame = ContainingPte->u.Hard.PageFrameNumber;


                        //
                        // Increment the share count for the page containing the
                        // fork prototype PTEs as we have just placed a valid
                        // PTE into the page.
                        //

                        PfnForkPtePage = MI_PFN_ELEMENT (
                                            ContainingPte->u.Hard.PageFrameNumber );

                        MiUpForkPageShareCount (PfnForkPtePage);

                        //
                        // Change the protection in the PFN database to COPY
                        // on write, if writable.
                        //

                        MI_MAKE_PROTECT_WRITE_COPY (Pfn2->OriginalPte);

                        //
                        // Put the protection into the WSLE and mark the WSLE
                        // to indicate that the protection field for the PTE
                        // is the same as the prototype PTE.
                        //

                        MmWsle[WorkingSetIndex].u1.e1.Protection =
                                            Pfn2->OriginalPte.u.Soft.Protection;

                        MmWsle[WorkingSetIndex].u1.e1.SameProtectAsProto = 1;

                        TempPte.u.Long = MiProtoAddressForPte (Pfn2->PteAddress);
                        TempPte.u.Proto.Prototype = 1;
                        *PointerNewPte = TempPte;

                        //
                        // A PTE is now non-zero, increment the used page
                        // table entries counter.
                        //

                        *UsedPageTableEntries += 1;

                        //
                        // One less private page (it's now shared).
                        //

                        CurrentProcess->NumberOfPrivatePages -= 1;

                        ForkProtoPte += 1;
                        NumberOfForkPtes += 1;

                    }

                } else if (PteContents.u.Soft.Prototype == 1) {

                    //
                    // Prototype PTE, check to see if this is a fork
                    // prototype PTE already.  Note that if COW is set,
                    // the PTE can just be copied (fork compatible format).
                    //

                    *PointerNewPte = PteContents;

                    //
                    // A PTE is now non-zero, increment the used page
                    // table entries counter.
                    //

                    *UsedPageTableEntries += 1;

                    //
                    // Check to see if this is a fork prototype PTE,
                    // and if it is increment the reference count
                    // which is in the longword following the PTE.
                    //

                    CloneProto = (PMMCLONE_BLOCK)(MiPteToProto(PointerPte));

                    if (MiLocateCloneAddress ((PVOID)CloneProto) !=
                                (PMMCLONE_DESCRIPTOR)NULL) {

                        //
                        // The reference count field, or the prototype PTE
                        // for that matter may not be in the working set.
                        //

                        MiUpCloneProtoRefCount (CloneProto,
                                                CurrentProcess);

                        if (PAGE_ALIGN (ForkProtoPte) !=
                                                PAGE_ALIGN (LockedForkPte)) {
                            MiUnlockPagedAddress (LockedForkPte, FALSE);
                            LockedForkPte = ForkProtoPte;
                            MiLockPagedAddress (LockedForkPte, FALSE);
                        }

                        MiMakeSystemAddressValid (PointerPte,
                                                    CurrentProcess);
                    }

                } else if (PteContents.u.Soft.Transition == 1) {

                    //
                    // Transition.
                    //

                    if (MiHandleForkTransitionPte (PointerPte,
                                                   PointerNewPte,
                                                   ForkProtoPte)) {
                        //
                        // PTE is no longer transition, try again.
                        //

                        continue;
                    }

                    //
                    // A PTE is now non-zero, increment the used page
                    // table entries counter.
                    //

                    *UsedPageTableEntries += 1;

                    //
                    // One less private page (it's now shared).
                    //

                    CurrentProcess->NumberOfPrivatePages -= 1;

                    ForkProtoPte += 1;
                    NumberOfForkPtes += 1;

                } else {

                    //
                    // Page file format (may be demand zero).
                    //

                    if (IS_PTE_NOT_DEMAND_ZERO (PteContents)) {

                        if (PteContents.u.Soft.Protection == MM_DECOMMIT) {

                            //
                            // This is a decommitted PTE, just move it
                            // over to the new process.  Don't increment
                            // the count of private pages.
                            //

                            *PointerNewPte = PteContents;
                        } else {

                            //
                            // The PTE is not demand zero, move the PTE to
                            // a fork prototype PTE and make this PTE and
                            // the new processes PTE refer to the fork
                            // prototype PTE.
                            //

                            ForkProtoPte->ProtoPte = PteContents;

                            //
                            // Make the protection write-copy if writable.
                            //

                            MI_MAKE_PROTECT_WRITE_COPY (ForkProtoPte->ProtoPte);

                            ForkProtoPte->CloneRefCount = 2;

                            TempPte.u.Long =
                                 MiProtoAddressForPte (&ForkProtoPte->ProtoPte);

                            TempPte.u.Proto.Prototype = 1;

                            *PointerPte = TempPte;
                            *PointerNewPte = TempPte;

                            //
                            // One less private page (it's now shared).
                            //

                            CurrentProcess->NumberOfPrivatePages -= 1;

                            ForkProtoPte += 1;
                            NumberOfForkPtes += 1;
                        }
                    } else {

                        //
                        // The page is demand zero, make the new process's
                        // page demand zero.
                        //

                        *PointerNewPte = PteContents;
                    }

                    //
                    // A PTE is now non-zero, increment the used page
                    // table entries counter.
                    //

                    *UsedPageTableEntries += 1;
                }

                PointerPte += 1;
                PointerNewPte += 1;

            }  // end while for PTEs
AllDone:
            NewVad = NewVad->Parent;
        }
        Vad = MiGetNextVad (Vad);

    } // end while for VADs

    //
    // Unlock paged pool page.
    //

    MiUnlockPagedAddress (LockedForkPte, FALSE);

    //
    // Unmap the PD Page and hyper space page.
    //

    MmUnmapLockedPages (PdeBase, Mdl0);
    MmUnmapLockedPages (HyperBase, Mdl1);
    MmUnmapLockedPages (Mdl2->MappedSystemVa, Mdl2);

    MiDownPfnReferenceCount (*(PULONG)((Mdl0 + 1)));
    MiDownPfnReferenceCount (*(PULONG)((Mdl1 + 1)));
    MiDownPfnReferenceCount (*(PULONG)((Mdl2 + 1)));

    //
    // Make the count of private pages match between the two processes.
    //

    ASSERT ((LONG)CurrentProcess->NumberOfPrivatePages >= 0);

    ProcessToInitialize->NumberOfPrivatePages =
                                          CurrentProcess->NumberOfPrivatePages;

    ASSERT (NumberOfForkPtes <= CloneDescriptor->NumberOfPtes);

    if (NumberOfForkPtes != 0) {

        //
        // The number of fork PTEs is non-zero, set the values
        // into the structres.
        //

        CloneHeader->NumberOfPtes = NumberOfForkPtes;
        CloneDescriptor->NumberOfReferences = NumberOfForkPtes;
        CloneDescriptor->NumberOfPtes = NumberOfForkPtes;

    } else {

        //
        // There were no fork ptes created.  Remove the clone descriptor
        // from this process and clean up the related structures.
        // Note - must be holding the working set mutex and not holding
        // the PFN lock.
        //

        MiRemoveClone (CloneDescriptor);

        UNLOCK_WS (CurrentProcess);

        ExFreePool (CloneDescriptor->CloneHeader->ClonePtes);

        ExFreePool (CloneDescriptor->CloneHeader);

        //
        // Return the pool for the global structures referenced by the
        // clone descriptor.
        //

        PsReturnPoolQuota (CurrentProcess,
                           PagedPool,
                           CloneDescriptor->PagedPoolQuotaCharge);

        PsReturnPoolQuota (CurrentProcess, NonPagedPool, sizeof(MMCLONE_HEADER));

        ExFreePool (CloneDescriptor);

        LOCK_WS (CurrentProcess);
    }

    MiDownShareCountFlushEntireTb (PageFrameIndex);

    PageFrameIndex = 0xFFFFFFFF;

    //
    // Copy the clone descriptors from this process to the new process.
    //

    Clone = MiGetFirstClone ();
    CloneList = &FirstNewClone;
    CloneFailed = FALSE;

    while (Clone != (PMMCLONE_DESCRIPTOR)NULL) {

        //
        // Increment the count of processes referencing this clone block.
        //

        Clone->CloneHeader->NumberOfProcessReferences += 1;

        NewClone = ExAllocatePoolWithTag (NonPagedPool,
                                          sizeof( MMCLONE_DESCRIPTOR),
                                          '  mM');

        if (NewClone == NULL) {

            //
            // There are insuffienct resources to continue this operation,
            // however, to properly clean up at this point, all the
            // clone headers must be allocated, so when the cloned process
            // is deleted, the clone headers will be found.  Get MustSucceed
            // pool, but force the operation to fail so the pool will be
            // soon released.
            //

            CloneFailed = TRUE;
            status = STATUS_INSUFFICIENT_RESOURCES;
            NewClone = ExAllocatePoolWithTag (NonPagedPoolMustSucceed,
                                              sizeof( MMCLONE_DESCRIPTOR),
                                              '  mM');
        }

        *NewClone = *Clone;

        *CloneList = NewClone;
        CloneList = &NewClone->Parent;
        Clone = MiGetNextClone (Clone);
    }

    *CloneList = (PMMCLONE_DESCRIPTOR)NULL;

    //
    // Release the working set mutex and the address creation mutex from
    // the current process as all the neccessary information is now
    // captured.
    //

    UNLOCK_WS (CurrentProcess);

    CurrentProcess->ForkInProgress = NULL;

    UNLOCK_ADDRESS_SPACE (CurrentProcess);

    //
    // As we have updated many PTEs to clear dirty bits, flush the
    // tb cache.  Note that this was not done every time we changed
    // a valid PTE so other threads could be modifying the address
    // space without causing copy on writes. (Too bad).
    //


    //
    // attach to the process to initialize and insert the vad and clone
    // descriptors into the tree.
    //

    if (Attached) {
        KeDetachProcess ();
        Attached = FALSE;
    }

    if (PsGetCurrentProcess() != ProcessToInitialize) {
        Attached = TRUE;
        KeAttachProcess (&ProcessToInitialize->Pcb);
    }

    CurrentProcess = ProcessToInitialize;

    //
    // We are now in the context of the new process, build the
    // VAD list and the clone list.
    //

    Vad = FirstNewVad;
    VadInsertFailed = FALSE;

    LOCK_WS (CurrentProcess);

    while (Vad != (PMMVAD)NULL) {

        NextVad = Vad->Parent;

        try {


            if (VadInsertFailed) {
                Vad->u.VadFlags.CommitCharge = MM_MAX_COMMIT;
            }

            MiInsertVad (Vad);

        } except (EXCEPTION_EXECUTE_HANDLER) {

            //
            // Charging quota for the VAD failed, set the
            // remaining quota fields in this VAD and all
            // subsequent VADs to zero so the VADs can be
            // inserted and later deleted.
            //

            VadInsertFailed = TRUE;
            status = GetExceptionCode();

            //
            // Do the loop again for this VAD.
            //

            continue;
        }

        //
        // Update the current virtual size.
        //

        CurrentProcess->VirtualSize += 1 + (ULONG)Vad->EndingVa -
                                                        (ULONG)Vad->StartingVa;

        Vad = NextVad;
    }

    UNLOCK_WS (CurrentProcess);
    //MmUnlockCode (MiCloneProcessAddressSpace, 5000);

    //
    // Update the peak virtual size.
    //

    CurrentProcess->PeakVirtualSize = CurrentProcess->VirtualSize;

    Clone = FirstNewClone;
    TotalPagedPoolCharge = 0;
    TotalNonPagedPoolCharge = 0;

    while (Clone != (PMMCLONE_DESCRIPTOR)NULL) {

        NextClone = Clone->Parent;
        MiInsertClone (Clone);

        //
        // Calculate the page pool and non-paged pool to charge for these
        // operations.
        //

        TotalPagedPoolCharge += Clone->PagedPoolQuotaCharge;
        TotalNonPagedPoolCharge += sizeof(MMCLONE_HEADER);

        Clone = NextClone;
    }

    if (CloneFailed || VadInsertFailed) {

        if (Attached) {
            KeDetachProcess ();
        }
        KdPrint(("MMFORK: vad insert failed\n"));

        return status;
    }

    try {

        PageTablePage = 1;
        PsChargePoolQuota (CurrentProcess, PagedPool, TotalPagedPoolCharge);
        PageTablePage = 0;
        PsChargePoolQuota (CurrentProcess, NonPagedPool, TotalNonPagedPoolCharge);

    } except (EXCEPTION_EXECUTE_HANDLER) {

        if (PageTablePage == 0) {
            PsReturnPoolQuota (CurrentProcess, PagedPool, TotalPagedPoolCharge);
        }
        KdPrint(("MMFORK: pool quota failed\n"));

        if (Attached) {
            KeDetachProcess ();
        }
        return GetExceptionCode();
    }

    CurrentProcess->ForkWasSuccessful = TRUE;
    if (Attached) {
        KeDetachProcess ();
    }

#if DBG
    if (MmDebug & MM_DBG_FORK) {
        DbgPrint("ending clone operation process to clone = %lx\n",
            ProcessToClone);
    }
#endif //DBG

    return STATUS_SUCCESS;

    //
    // Error returns.
    //

ErrorReturn4:
        ExFreePool (CloneDescriptor);
ErrorReturn3:
        ExFreePool (CloneHeader);
ErrorReturn2:
        ExFreePool (CloneProtos);
ErrorReturn1:
        UNLOCK_ADDRESS_SPACE (CurrentProcess);
        if (Attached) {
            KeDetachProcess ();
        }
        return status;
}

ULONG
MiDecrementCloneBlockReference (
    IN PMMCLONE_DESCRIPTOR CloneDescriptor,
    IN PMMCLONE_BLOCK CloneBlock,
    IN PEPROCESS CurrentProcess
    )

/*++

Routine Description:

    This routine decrements the reference count field of a "fork prototype
    PTE" (clone-block).  If the reference count becomes zero, the reference
    count for the clone-descriptor is decremented and if that becomes zero,
    it is deallocated and the number of process count for the clone header is
    decremented.  If the number of process count becomes zero, the clone
    header is deallocated.

Arguments:

    CloneDescriptor - Supplies the clone descriptor which describes the
                      clone block.

    CloneBlock - Supplies the clone block to decrement the reference count of.

    CurrentProcess - Supplies the current process.

Return Value:

    TRUE if the working set mutex was released, FALSE if it was not.

Environment:

    Kernel mode, APC's disabled, working set mutex and PFN mutex held.

--*/

{

    ULONG MutexReleased = FALSE;
    MMPTE CloneContents;
    PMMPFN Pfn3;
    KIRQL OldIrql;
    PMMCLONE_BLOCK OldCloneBlock;
    LONG NewCount;

    OldIrql = APC_LEVEL;

    MutexReleased = MiMakeSystemAddressValidPfnWs (CloneBlock, CurrentProcess);

    while (CurrentProcess->ForkInProgress) {
        MiWaitForForkToComplete (CurrentProcess);
        MiMakeSystemAddressValidPfnWs (CloneBlock, CurrentProcess);
        MutexReleased = TRUE;
    }

    CloneBlock->CloneRefCount -= 1;
    NewCount = CloneBlock->CloneRefCount;

    ASSERT (NewCount >= 0);

    if (NewCount == 0) {
        CloneContents = CloneBlock->ProtoPte;
    } else {
        CloneContents = ZeroPte;
    }

    if ((NewCount == 0) && (CloneContents.u.Long != 0)) {

        //
        // The last reference to a fork prototype PTE
        // has been removed.  Deallocate any page file
        // space and the transition page, if any.
        //


        //
        // Assert that the page is no longer valid.
        //

        ASSERT (CloneContents.u.Hard.Valid == 0);

        //
        // Assert that the PTE is not in subsection format (doesn't point
        // to a file).
        //

        ASSERT (CloneContents.u.Soft.Prototype == 0);

        if (CloneContents.u.Soft.Transition == 1) {

            //
            // Prototype PTE in transition, put the page
            // on the free list.
            //

            Pfn3 = MI_PFN_ELEMENT (CloneContents.u.Trans.PageFrameNumber);
            MI_SET_PFN_DELETED (Pfn3);

            MiDecrementShareCount (Pfn3->PteFrame);

            //
            // Check the reference count for the page, if the reference
            // count is zero and the page is not on the freelist,
            // move the page to the free list, if the reference
            // count is not zero, ignore this page.
            // When the refernce count goes to zero, it will be placed on the
            // free list.
            //

            if ((Pfn3->u3.e2.ReferenceCount == 0) &&
                (Pfn3->u3.e1.PageLocation != FreePageList)) {

                MiUnlinkPageFromList (Pfn3);
                MiReleasePageFileSpace (Pfn3->OriginalPte);
                MiInsertPageInList (MmPageLocationList[FreePageList],
                             CloneContents.u.Trans.PageFrameNumber);
            }
        } else {

            if (IS_PTE_NOT_DEMAND_ZERO (CloneContents)) {
                MiReleasePageFileSpace (CloneContents);
            }
        }
    }

    //
    // Decrement the number of references to the
    // clone descriptor.
    //

    CloneDescriptor->NumberOfReferences -= 1;

    if (CloneDescriptor->NumberOfReferences == 0) {

        //
        // There are no longer any PTEs in this process which refer
        // to the fork prototype PTEs for this clone descriptor.
        // Remove the CloneDescriptor and decrement the CloneHeader
        // number of process's reference count.
        //

        CloneDescriptor->CloneHeader->NumberOfProcessReferences -= 1;

        if (CloneDescriptor->CloneHeader->NumberOfProcessReferences == 0) {

            //
            // There are no more processes pointing to this fork header
            // blow it away.
            //

            UNLOCK_PFN (OldIrql);
            UNLOCK_WS (CurrentProcess);
            MutexReleased = TRUE;

            OldCloneBlock = CloneDescriptor->CloneHeader->ClonePtes;

#if DBG
        {
        ULONG i;
            for (i = 0; i < CloneDescriptor->CloneHeader->NumberOfPtes; i++) {
                if (OldCloneBlock->CloneRefCount != 0) {
                    DbgPrint("fork block with non zero ref count %lx %lx %lx\n",
                        OldCloneBlock, CloneDescriptor,
                        CloneDescriptor->CloneHeader);
                    KeBugCheck (MEMORY_MANAGEMENT);
                }
            }

            if (MmDebug & MM_DBG_FORK) {
                DbgPrint("removing clone header at address %lx\n",
                        CloneDescriptor->CloneHeader);
            }
        }
#endif //DBG

            ExFreePool (CloneDescriptor->CloneHeader->ClonePtes);

            ExFreePool (CloneDescriptor->CloneHeader);

            LOCK_WS (CurrentProcess);
            LOCK_PFN (OldIrql);

        }

        MiRemoveClone (CloneDescriptor);

#if DBG
        if (MmDebug & MM_DBG_FORK) {
          DbgPrint("removing clone descriptor at address %lx\n",CloneDescriptor);
        }
#endif //DBG

        //
        // Return the pool for the global structures referenced by the
        // clone descriptor.
        //

        UNLOCK_PFN (OldIrql);

        if (CurrentProcess->ForkWasSuccessful != FALSE) {

            PsReturnPoolQuota (CurrentProcess,
                               PagedPool,
                               CloneDescriptor->PagedPoolQuotaCharge);

            PsReturnPoolQuota (CurrentProcess,
                               NonPagedPool,
                               sizeof(MMCLONE_HEADER));
        }

        ExFreePool (CloneDescriptor);
        LOCK_PFN (OldIrql);
    }

    return MutexReleased;
}

VOID
MiWaitForForkToComplete (
    IN PEPROCESS CurrentProcess
    )

/*++

Routine Description:

    This routine waits for the current process to complete a fork
    operation.

Arguments:

    CurrentProcess - Supplies the current process value.

Return Value:

    None.

Environment:

    Kernel mode, APC's disabled, working set mutex and PFN mutex held.

--*/

{
    KIRQL OldIrql = APC_LEVEL;

    //
    // A fork operation is in progress and the count of clone-blocks
    // and other structures may not be changed.  Release the mutexes
    // and wait for the address creation mutex which governs the
    // fork operation.
    //

    UNLOCK_PFN (OldIrql);
    UNLOCK_WS (CurrentProcess);

    LOCK_WS_AND_ADDRESS_SPACE (CurrentProcess);

    //
    // Release the address creation mutex, the working set mutex
    // must be held to set the ForkInProgress field.
    //

    UNLOCK_ADDRESS_SPACE (CurrentProcess);

    //
    // Get the PFN mutex again.
    //

    LOCK_PFN (OldIrql);
    return;
}
#if DBG
VOID
CloneTreeWalk (
    PMMCLONE_DESCRIPTOR Start
    )

{
    Start;
    NodeTreeWalk ( (PMMADDRESS_NODE)(PsGetCurrentProcess()->CloneRoot));
    return;
}
#endif //DBG

VOID
MiUpPfnReferenceCount (
    IN ULONG Page,
    IN USHORT Count
    )

    // non paged helper routine.

{
    KIRQL OldIrql;
    PMMPFN Pfn1;

    Pfn1 = MI_PFN_ELEMENT (Page);
    LOCK_PFN (OldIrql);
    Pfn1->u3.e2.ReferenceCount += Count;
    UNLOCK_PFN (OldIrql);
    return;
}

VOID
MiDownPfnReferenceCount (
    IN ULONG Page
    )

    // non paged helper routine.

{
    KIRQL OldIrql;

    LOCK_PFN (OldIrql);
    MiDecrementReferenceCount (Page);
    UNLOCK_PFN (OldIrql);
    return;
}

VOID
MiUpControlAreaRefs (
    IN PCONTROL_AREA ControlArea
    )

{
    KIRQL OldIrql;

    LOCK_PFN (OldIrql);

    ControlArea->NumberOfMappedViews += 1;
    ControlArea->NumberOfUserReferences += 1;

    UNLOCK_PFN (OldIrql);
    return;
}


ULONG
MiDoneWithThisPageGetAnother (
    IN PULONG PageFrameIndex,
    IN PMMPTE PointerPde,
    IN PEPROCESS CurrentProcess
    )

{
    KIRQL OldIrql;
    ULONG ReleasedMutex;

    LOCK_PFN (OldIrql);

    if (*PageFrameIndex != 0xFFFFFFFF) {

        //
        // Decrement the share count of the last page which
        // we operated on.
        //

        MiDecrementShareCountOnly (*PageFrameIndex);
    }

    ReleasedMutex =
                  MiEnsureAvailablePageOrWait (
                                        CurrentProcess,
                                        NULL);

    *PageFrameIndex = MiRemoveZeroPage (
                   MI_PAGE_COLOR_PTE_PROCESS (PointerPde,
                                              &CurrentProcess->NextPageColor));
    UNLOCK_PFN (OldIrql);
    return ReleasedMutex;
}

VOID
MiUpCloneProtoRefCount (
    IN PMMCLONE_BLOCK CloneProto,
    IN PEPROCESS CurrentProcess
    )

{
    KIRQL OldIrql;

    LOCK_PFN (OldIrql);

    MiMakeSystemAddressValidPfnWs (CloneProto,
                                   CurrentProcess );

    CloneProto->CloneRefCount += 1;

    UNLOCK_PFN (OldIrql);
    return;
}

ULONG
MiHandleForkTransitionPte (
    IN PMMPTE PointerPte,
    IN PMMPTE PointerNewPte,
    IN PMMCLONE_BLOCK ForkProtoPte
    )

{
    KIRQL OldIrql;
    PMMPFN Pfn2;
    MMPTE PteContents;
    PMMPTE ContainingPte;
    ULONG PageTablePage;
    MMPTE TempPte;
    PMMPFN PfnForkPtePage;


    LOCK_PFN (OldIrql);

    //
    // Now that we have the PFN mutex which prevents pages from
    // leaving the transition state, examine the PTE again to
    // ensure that it is still transtion.
    //

    PteContents = *(volatile PMMPTE)PointerPte;

    if ((PteContents.u.Soft.Transition == 0) ||
        (PteContents.u.Soft.Prototype == 1)) {

        //
        // The PTE is no longer in transition... do this
        // loop again.
        //

        UNLOCK_PFN (OldIrql);
        return TRUE;

    } else {

        //
        // The PTE is still in transition, handle like a
        // valid PTE.
        //

        Pfn2 = MI_PFN_ELEMENT (PteContents.u.Trans.PageFrameNumber);

        //
        // Assertion that PTE is ont in prototype PTE format.
        //

        ASSERT (Pfn2->u3.e1.PrototypePte != 1);

        //
        // This is a private page in transition state,
        // create a fork prototype PTE
        // which becomes the "prototype" PTE for this page.
        //

        ForkProtoPte->ProtoPte = PteContents;

        //
        // Make the protection write-copy if writable.
        //

        MI_MAKE_PROTECT_WRITE_COPY (ForkProtoPte->ProtoPte);

        ForkProtoPte->CloneRefCount = 2;

        //
        // Transform the PFN element to reference this new fork
        // prototype PTE.
        //

        //
        // Decrement the share count for the page table
        // page which contains the PTE as it is no longer
        // valid or in transition.
        //
        Pfn2->PteAddress = &ForkProtoPte->ProtoPte;
        Pfn2->u3.e1.PrototypePte = 1;

        //
        // Make original PTE copy on write.
        //

        MI_MAKE_PROTECT_WRITE_COPY (Pfn2->OriginalPte);

        ContainingPte = MiGetPteAddress(&ForkProtoPte->ProtoPte);

        PageTablePage = Pfn2->PteFrame;

        Pfn2->PteFrame =
                        ContainingPte->u.Hard.PageFrameNumber;

        //
        // Increment the share count for the page containing
        // the fork prototype PTEs as we have just placed
        // a transition PTE into the page.
        //

        PfnForkPtePage = MI_PFN_ELEMENT (
                        ContainingPte->u.Hard.PageFrameNumber );

        PfnForkPtePage->u2.ShareCount += 1;

        TempPte.u.Long =
                    MiProtoAddressForPte (Pfn2->PteAddress);
        TempPte.u.Proto.Prototype = 1;
        *PointerPte = TempPte;
        *PointerNewPte = TempPte;

        //
        // Decrement the share count for the page table
        // page which contains the PTE as it is no longer
        // valid or in transition.
        //

        MiDecrementShareCount (PageTablePage);
    }
    UNLOCK_PFN (OldIrql);
    return FALSE;
}

VOID
MiDownShareCountFlushEntireTb (
    IN ULONG PageFrameIndex
    )

{
    KIRQL OldIrql;

    LOCK_PFN (OldIrql);

    if (PageFrameIndex != 0xFFFFFFFF) {

        //
        // Decrement the share count of the last page which
        // we operated on.
        //

        MiDecrementShareCountOnly (PageFrameIndex);
    }

    KeFlushEntireTb (FALSE, FALSE);
    UNLOCK_PFN (OldIrql);
    return;
}

VOID
MiUpForkPageShareCount(
    IN PMMPFN PfnForkPtePage
    )
{
    KIRQL OldIrql;

    LOCK_PFN (OldIrql);
    PfnForkPtePage->u2.ShareCount += 1;

    UNLOCK_PFN (OldIrql);
    return;
}