Loading...
   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
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
/*
 * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * The contents of this file constitute Original Code as defined in and
 * are subject to the Apple Public Source License Version 1.1 (the
 * "License").  You may not use this file except in compliance with the
 * License.  Please obtain a copy of the License at
 * http://www.apple.com/publicsource and read it before using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/* 
 * Mach Operating System
 * Copyright (c) 1987 Carnegie-Mellon University
 * All rights reserved.  The CMU software License Agreement specifies
 * the terms and conditions for use and redistribution.
 */

/*
 */


#include <meta_features.h>

#include <kern/task.h>
#include <kern/thread.h>
#include <kern/debug.h>
#include <kern/lock.h>
#include <mach/mach_traps.h>
#include <mach/time_value.h>
#include <mach/vm_map.h>
#include <mach/vm_param.h>
#include <mach/vm_prot.h>
#include <mach/port.h>

#include <sys/file_internal.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/dir.h>
#include <sys/namei.h>
#include <sys/proc_internal.h>
#include <sys/kauth.h>
#include <sys/vm.h>
#include <sys/file.h>
#include <sys/vnode_internal.h>
#include <sys/mount.h>
#include <sys/trace.h>
#include <sys/kernel.h>
#include <sys/ubc_internal.h>
#include <sys/user.h>
#include <sys/syslog.h>
#include <sys/stat.h>
#include <sys/sysproto.h>
#include <sys/mman.h>
#include <sys/sysctl.h>

#include <bsm/audit_kernel.h>
#include <bsm/audit_kevents.h>

#include <kern/kalloc.h>
#include <vm/vm_map.h>
#include <vm/vm_kern.h>

#include <machine/spl.h>

#include <mach/shared_memory_server.h>
#include <vm/vm_shared_memory_server.h>

#include <vm/vm_protos.h>

void
log_nx_failure(addr64_t vaddr, vm_prot_t prot)
{
        printf("NX failure: %s  -  vaddr=%qx,  prot=%x\n", current_proc()->p_comm, vaddr, prot);
}


int
useracc(
	user_addr_t	addr,
	user_size_t	len,
	int	prot)
{
	return (vm_map_check_protection(
			current_map(),
			vm_map_trunc_page(addr), vm_map_round_page(addr+len),
			prot == B_READ ? VM_PROT_READ : VM_PROT_WRITE));
}

int
vslock(
	user_addr_t	addr,
	user_size_t	len)
{
	kern_return_t kret;
	kret = vm_map_wire(current_map(), vm_map_trunc_page(addr),
			vm_map_round_page(addr+len), 
			VM_PROT_READ | VM_PROT_WRITE ,FALSE);

	switch (kret) {
	case KERN_SUCCESS:
		return (0);
	case KERN_INVALID_ADDRESS:
	case KERN_NO_SPACE:
		return (ENOMEM);
	case KERN_PROTECTION_FAILURE:
		return (EACCES);
	default:
		return (EINVAL);
	}
}

int
vsunlock(
	user_addr_t addr,
	user_size_t len,
	__unused int dirtied)
{
#if FIXME  /* [ */
	pmap_t		pmap;
	vm_page_t	pg;
	vm_map_offset_t	vaddr;
	ppnum_t		paddr;
#endif  /* FIXME ] */
	kern_return_t kret;

#if FIXME  /* [ */
	if (dirtied) {
		pmap = get_task_pmap(current_task());
		for (vaddr = vm_map_trunc_page(addr);
		     vaddr < vm_map_round_page(addr+len);
				vaddr += PAGE_SIZE) {
			paddr = pmap_extract(pmap, vaddr);
			pg = PHYS_TO_VM_PAGE(paddr);
			vm_page_set_modified(pg);
		}
	}
#endif  /* FIXME ] */
#ifdef	lint
	dirtied++;
#endif	/* lint */
	kret = vm_map_unwire(current_map(), vm_map_trunc_page(addr),
				vm_map_round_page(addr+len), FALSE);
	switch (kret) {
	case KERN_SUCCESS:
		return (0);
	case KERN_INVALID_ADDRESS:
	case KERN_NO_SPACE:
		return (ENOMEM);
	case KERN_PROTECTION_FAILURE:
		return (EACCES);
	default:
		return (EINVAL);
	}
}

int
subyte(
	user_addr_t addr,
	int byte)
{
	char character;
	
	character = (char)byte;
	return (copyout((void *)&(character), addr, sizeof(char)) == 0 ? 0 : -1);
}

int
suibyte(
	user_addr_t addr,
	int byte)
{
	char character;
	
	character = (char)byte;
	return (copyout((void *)&(character), addr, sizeof(char)) == 0 ? 0 : -1);
}

int fubyte(user_addr_t addr)
{
	unsigned char byte;

	if (copyin(addr, (void *) &byte, sizeof(char)))
		return(-1);
	return(byte);
}

int fuibyte(user_addr_t addr)
{
	unsigned char byte;

	if (copyin(addr, (void *) &(byte), sizeof(char)))
		return(-1);
	return(byte);
}

int
suword(
	user_addr_t addr,
	long word)
{
	return (copyout((void *) &word, addr, sizeof(int)) == 0 ? 0 : -1);
}

long fuword(user_addr_t addr)
{
	long word;

	if (copyin(addr, (void *) &word, sizeof(int)))
		return(-1);
	return(word);
}

/* suiword and fuiword are the same as suword and fuword, respectively */

int
suiword(
	user_addr_t addr,
	long word)
{
	return (copyout((void *) &word, addr, sizeof(int)) == 0 ? 0 : -1);
}

long fuiword(user_addr_t addr)
{
	long word;

	if (copyin(addr, (void *) &word, sizeof(int)))
		return(-1);
	return(word);
}

/*
 * With a 32-bit kernel and mixed 32/64-bit user tasks, this interface allows the
 * fetching and setting of process-sized size_t and pointer values.
 */
int
sulong(user_addr_t addr, int64_t word)
{

	if (IS_64BIT_PROCESS(current_proc())) {
		return(copyout((void *)&word, addr, sizeof(word)) == 0 ? 0 : -1);
	} else {
		return(suiword(addr, (long)word));
	}
}

int64_t
fulong(user_addr_t addr)
{
	int64_t longword;

	if (IS_64BIT_PROCESS(current_proc())) {
		if (copyin(addr, (void *)&longword, sizeof(longword)) != 0)
			return(-1);
		return(longword);
	} else {
		return((int64_t)fuiword(addr));
	}
}

int
suulong(user_addr_t addr, uint64_t uword)
{

	if (IS_64BIT_PROCESS(current_proc())) {
		return(copyout((void *)&uword, addr, sizeof(uword)) == 0 ? 0 : -1);
	} else {
		return(suiword(addr, (u_long)uword));
	}
}

uint64_t
fuulong(user_addr_t addr)
{
	uint64_t ulongword;

	if (IS_64BIT_PROCESS(current_proc())) {
		if (copyin(addr, (void *)&ulongword, sizeof(ulongword)) != 0)
			return(-1ULL);
		return(ulongword);
	} else {
		return((uint64_t)fuiword(addr));
	}
}

int
swapon(__unused struct proc *procp, __unused struct swapon_args *uap, __unused int *retval)
{
	return(ENOTSUP);
}


kern_return_t
pid_for_task(
	struct pid_for_task_args *args)
{
	mach_port_name_t	t = args->t;
	user_addr_t		pid_addr  = args->pid;  
	struct proc * p;
	task_t		t1;
	int	pid = -1;
	kern_return_t	err = KERN_SUCCESS;
	boolean_t funnel_state;

	AUDIT_MACH_SYSCALL_ENTER(AUE_PIDFORTASK);
	AUDIT_ARG(mach_port1, t);

	funnel_state = thread_funnel_set(kernel_flock, TRUE);
	t1 = port_name_to_task(t);

	if (t1 == TASK_NULL) {
		err = KERN_FAILURE;
		goto pftout;
	} else {
		p = get_bsdtask_info(t1);
		if (p) {
			pid  = proc_pid(p);
			err = KERN_SUCCESS;
		} else {
			err = KERN_FAILURE;
		}
	}
	task_deallocate(t1);
pftout:
	AUDIT_ARG(pid, pid);
	(void) copyout((char *) &pid, pid_addr, sizeof(int));
	thread_funnel_set(kernel_flock, funnel_state);
	AUDIT_MACH_SYSCALL_EXIT(err);
	return(err);
}

/*
 *	Routine:	task_for_pid
 *	Purpose:
 *		Get the task port for another "process", named by its
 *		process ID on the same host as "target_task".
 *
 *		Only permitted to privileged processes, or processes
 *		with the same user ID.
 *
 * XXX This should be a BSD system call, not a Mach trap!!!
 */
/* 
 *
 * tfp_policy = KERN_TFP_POLICY_DENY; Deny Mode: None allowed except for self
 * tfp_policy = KERN_TFP_POLICY_PERMISSIVE; Permissive Mode: all permissive; related ones allowed or privileged
 * tfp_policy = KERN_TFP_POLICY_RESTRICTED; Restricted Mode: self access allowed; setgid (to tfp_group) are allowed for other tasks
 *
 */
static  int tfp_policy = KERN_TFP_POLICY_RESTRICTED;
/* the groutp is inited to kmem group and is modifiable by sysctl */
static int tfp_group_inited = 0; /* policy groups are loaded ... */
static  gid_t tfp_group_ronly = 0; /* procview group */
static  gid_t tfp_group_rw = 0; /* procmod group */

kern_return_t
task_for_pid(
	struct task_for_pid_args *args)
{
	mach_port_name_t	target_tport = args->target_tport;
	int			pid = args->pid;
	user_addr_t		task_addr = args->t;
	struct uthread		*uthread;
	struct proc	*p;
	struct proc *p1;
	task_t		t1;
	mach_port_name_t	tret;
	void * sright;
	int error = 0;
	int is_member = 0;
	boolean_t funnel_state;
	boolean_t ispermitted = FALSE;
#if DIAGNOSTIC
	char procname[MAXCOMLEN+1];
#endif /* DIAGNOSTIC */

	AUDIT_MACH_SYSCALL_ENTER(AUE_TASKFORPID);
	AUDIT_ARG(pid, pid);
	AUDIT_ARG(mach_port1, target_tport);

	t1 = port_name_to_task(target_tport);
	if (t1 == TASK_NULL) {
		(void ) copyout((char *)&t1, task_addr, sizeof(mach_port_name_t));
		AUDIT_MACH_SYSCALL_EXIT(KERN_FAILURE);
		return(KERN_FAILURE);
	} 

	funnel_state = thread_funnel_set(kernel_flock, TRUE);

	p1 = current_proc();

	/*
	 * Delayed binding of thread credential to process credential, if we
	 * are not running with an explicitly set thread credential.
	 */
	uthread = get_bsdthread_info(current_thread());
	if (uthread->uu_ucred != p1->p_ucred &&
	    (uthread->uu_flag & UT_SETUID) == 0) {
		kauth_cred_t old = uthread->uu_ucred;
		proc_lock(p1);
		kauth_cred_ref(p1->p_ucred);
		uthread->uu_ucred = p1->p_ucred;
		proc_unlock(p1);
		if (IS_VALID_CRED(old))
			kauth_cred_unref(&old);
	}

	p = pfind(pid);
	AUDIT_ARG(process, p);

	/*
	 * XXX p_ucred check can be bogus in multithreaded processes,
	 * XXX unless the funnel is held.
	 */
	switch (tfp_policy) {

		case KERN_TFP_POLICY_PERMISSIVE:
			/* self or suser or related ones */
			if ((p != (struct proc *) 0)
				&& (p->p_stat != SZOMB)
				&& (p1 != (struct proc *) 0)
				&& (
					(p1 == p)
					|| !(suser(kauth_cred_get(), 0))
					|| ((kauth_cred_getuid(p->p_ucred) == kauth_cred_getuid(kauth_cred_get())) && 
						((p->p_ucred->cr_ruid == kauth_cred_get()->cr_ruid))
						&& ((p->p_flag & P_SUGID) == 0))
					)
				)
					ispermitted = TRUE;
			break;

		case KERN_TFP_POLICY_RESTRICTED:
			/* self or suser or  setgid and related ones only */
			if ((p != (struct proc *) 0)
				&& (p1 != (struct proc *) 0)
				&& (p->p_stat != SZOMB)
				&& (
					(p1 == p)
					|| !(suser(kauth_cred_get(), 0))
					|| (((tfp_group_inited != 0) && 
							(
							((kauth_cred_ismember_gid(kauth_cred_get(), 
									tfp_group_ronly, &is_member) == 0) && is_member)
							||((kauth_cred_ismember_gid(kauth_cred_get(), 
									tfp_group_rw, &is_member) == 0) && is_member)
							)
					   )
					   && ((kauth_cred_getuid(p->p_ucred) == kauth_cred_getuid(kauth_cred_get())) && 
							((p->p_ucred->cr_ruid == kauth_cred_get()->cr_ruid))
							&& ((p->p_flag & P_SUGID) == 0))
					  )
					)
				)
					ispermitted = TRUE;

			break;

		case KERN_TFP_POLICY_DENY:
			/* self or suser only */
		default:
			/* do not return task port of other task at all */
			if ((p1 != (struct proc *) 0) && (p != (struct proc *) 0) && (p->p_stat != SZOMB)
					&& ((p1 == p)  || !(suser(kauth_cred_get(), 0))))
				ispermitted = TRUE;
			else
				ispermitted = FALSE;
			break;
	};


	if (ispermitted == TRUE) {
		if (p->task != TASK_NULL) {
			task_reference(p->task);
			sright = (void *)convert_task_to_port(p->task);
			tret = ipc_port_copyout_send(
						sright, 
						get_task_ipcspace(current_task()));
			} else
				tret  = MACH_PORT_NULL;
			AUDIT_ARG(mach_port2, tret);
			(void ) copyout((char *)&tret, task_addr, sizeof(mach_port_name_t));
	        task_deallocate(t1);
			error = KERN_SUCCESS;
			goto tfpout;
	}
#if DIAGNOSTIC
	else {
		/* 
		 * There is no guarantee that p_comm is null terminated and
		 * kernel implementation of string functions are complete. So 
		 * ensure stale info is not leaked out, bzero the  buffer
		 */
		bzero(&procname[0], MAXCOMLEN+1);
		strncpy(&procname[0], &p1->p_comm[0], MAXCOMLEN);
		if (tfp_policy != KERN_TFP_POLICY_PERMISSIVE)
			log(LOG_NOTICE, "(%d: %s)tfp: failed on %d:\n",
				((p1 != PROC_NULL)?(p1->p_pid):0), &procname[0],
				((p != PROC_NULL)?(p->p_pid):0));
	}
#endif /* DIAGNOSTIC */

    task_deallocate(t1);
	tret = MACH_PORT_NULL;
	(void) copyout((char *) &tret, task_addr, sizeof(mach_port_name_t));
	error = KERN_FAILURE;
tfpout:
	thread_funnel_set(kernel_flock, funnel_state);
	AUDIT_MACH_SYSCALL_EXIT(error);
	return(error);
}

/*
 *	Routine:	task_name_for_pid
 *	Purpose:
 *		Get the task name port for another "process", named by its
 *		process ID on the same host as "target_task".
 *
 *		Only permitted to privileged processes, or processes
 *		with the same user ID.
 *
 * XXX This should be a BSD system call, not a Mach trap!!!
 */

kern_return_t
task_name_for_pid(
	struct task_name_for_pid_args *args)
{
	mach_port_name_t	target_tport = args->target_tport;
	int			pid = args->pid;
	user_addr_t		task_addr = args->t;
	struct uthread		*uthread;
	struct proc	*p;
	struct proc *p1;
	task_t		t1;
	mach_port_name_t	tret;
	void * sright;
	int error = 0;
	boolean_t funnel_state;

	AUDIT_MACH_SYSCALL_ENTER(AUE_TASKNAMEFORPID);
	AUDIT_ARG(pid, pid);
	AUDIT_ARG(mach_port1, target_tport);

	t1 = port_name_to_task(target_tport);
	if (t1 == TASK_NULL) {
		(void ) copyout((char *)&t1, task_addr, sizeof(mach_port_name_t));
		AUDIT_MACH_SYSCALL_EXIT(KERN_FAILURE);
		return(KERN_FAILURE);
	} 

	funnel_state = thread_funnel_set(kernel_flock, TRUE);

	p1 = current_proc();

	/*
	 * Delayed binding of thread credential to process credential, if we
	 * are not running with an explicitly set thread credential.
	 */
	/*
	 * XXX p_ucred check can be bogus in multithreaded processes,
	 * XXX unless the funnel is held.
	 */
	uthread = get_bsdthread_info(current_thread());
	if (uthread->uu_ucred != p1->p_ucred &&
	    (uthread->uu_flag & UT_SETUID) == 0) {
		kauth_cred_t old = uthread->uu_ucred;
		proc_lock(p1);
		kauth_cred_ref(p1->p_ucred);
		uthread->uu_ucred = p1->p_ucred;
		proc_unlock(p1);
		if (IS_VALID_CRED(old))
			kauth_cred_unref(&old);
	}

	p = pfind(pid);
	AUDIT_ARG(process, p);

	if ((p != (struct proc *) 0)
	    && (p->p_stat != SZOMB)
	    && (p1 != (struct proc *) 0)
	    && ((p1 == p)
		|| !(suser(kauth_cred_get(), 0))
		|| ((kauth_cred_getuid(p->p_ucred) == kauth_cred_getuid(kauth_cred_get())) && 
		    ((p->p_ucred->cr_ruid == kauth_cred_get()->cr_ruid)))))
	{
		if (p->task != TASK_NULL)
		{
			task_reference(p->task);
			sright = (void *)convert_task_name_to_port(p->task);
			tret = ipc_port_copyout_send(
						sright, 
						get_task_ipcspace(current_task()));
		} else
			tret  = MACH_PORT_NULL;
		AUDIT_ARG(mach_port2, tret);
		(void ) copyout((char *)&tret, task_addr, sizeof(mach_port_name_t));
	        task_deallocate(t1);
		error = KERN_SUCCESS;
		goto tnfpout;
	}

	task_deallocate(t1);
	tret = MACH_PORT_NULL;
	(void) copyout((char *) &tret, task_addr, sizeof(mach_port_name_t));
	error = KERN_FAILURE;
tnfpout:
	thread_funnel_set(kernel_flock, funnel_state);
	AUDIT_MACH_SYSCALL_EXIT(error);
	return(error);
}

static int
sysctl_settfp_policy(__unused struct sysctl_oid *oidp, void *arg1,
    __unused int arg2, struct sysctl_req *req)
{
    int error = 0;
	int new_value;

    error = SYSCTL_OUT(req, arg1, sizeof(int));
    if (error || req->newptr == USER_ADDR_NULL)
        return(error);

	if (!is_suser())
		return(EPERM);

	if ((error = SYSCTL_IN(req, &new_value, sizeof(int)))) {
		goto out;
	}
	if ((new_value == KERN_TFP_POLICY_DENY) 
		|| (new_value == KERN_TFP_POLICY_PERMISSIVE)
		|| (new_value == KERN_TFP_POLICY_RESTRICTED))
			tfp_policy = new_value;
	else
			error = EINVAL;		
out:
    return(error);

}

static int
sysctl_settfp_groups(__unused struct sysctl_oid *oidp, void *arg1,
    __unused int arg2, struct sysctl_req *req)
{
    int error = 0;
	int new_value;

    error = SYSCTL_OUT(req, arg1, sizeof(int));
    if (error || req->newptr == USER_ADDR_NULL)
        return(error);

	if (!is_suser())
		return(EPERM);

	/* 
	 * Once set; cannot be reset till next boot. Launchd will set this
	 * in its pid 1 init and no one can set after that.
	 */
	if (tfp_group_inited != 0)
		return(EPERM);
		
	if ((error = SYSCTL_IN(req, &new_value, sizeof(int)))) {
		goto out;
	}

	if (new_value >= 100) 
			error = EINVAL;		
	else {
		if (arg1 == &tfp_group_ronly) 
			tfp_group_ronly = new_value;
		else if (arg1 == &tfp_group_rw)
			tfp_group_rw = new_value;
		else
			error = EINVAL;
		if ((tfp_group_ronly != 0 ) && (tfp_group_rw != 0 ))
			tfp_group_inited = 1;
	}

out:
    return(error);
}

SYSCTL_NODE(_kern, KERN_TFP, tfp, CTLFLAG_RW, 0, "tfp");
SYSCTL_PROC(_kern_tfp, KERN_TFP_POLICY, policy, CTLTYPE_INT | CTLFLAG_RW,
    &tfp_policy, sizeof(uint32_t), &sysctl_settfp_policy ,"I","policy");
SYSCTL_PROC(_kern_tfp, KERN_TFP_READ_GROUP, read_group, CTLTYPE_INT | CTLFLAG_RW,
    &tfp_group_ronly, sizeof(uint32_t), &sysctl_settfp_groups ,"I","read_group");
SYSCTL_PROC(_kern_tfp, KERN_TFP_RW_GROUP, rw_group, CTLTYPE_INT | CTLFLAG_RW,
    &tfp_group_rw, sizeof(uint32_t), &sysctl_settfp_groups ,"I","rw_group");


SYSCTL_INT(_vm, OID_AUTO, shared_region_trace_level, CTLFLAG_RW, &shared_region_trace_level, 0, "");

/*
 * Try and cap the number of mappings the user might be trying to deal with,
 * so that we don't end up allocating insane amounts of wired memory in the
 * kernel based on bogus user arguments.
 * There are 2 shared regions (TEXT and DATA). The size of each submap
 * is SHARED_TEXT_REGION_SIZE and we can have at most 1 VM map entry per page,
 * so the maximum number of mappings we could ever have to deal with is...
 */
#define SHARED_REGION_MAX_MAPPINGS ((2 *SHARED_TEXT_REGION_SIZE) >> PAGE_SHIFT)

/*
 * shared_region_make_private_np:
 *
 * This system call is for "dyld" only.
 * 
 * It creates a private copy of the current process's "shared region" for
 * split libraries.  "dyld" uses this when the shared region is full or
 * it needs to load a split library that conflicts with an already loaded one
 * that this process doesn't need.  "dyld" specifies a set of address ranges
 * that it wants to keep in the now-private "shared region".  These cover
 * the set of split libraries that the process needs so far.  The kernel needs
 * to deallocate the rest of the shared region, so that it's available for 
 * more libraries for this process.
 */
int
shared_region_make_private_np(
	struct proc					*p,
	struct shared_region_make_private_np_args	*uap,
	__unused int					*retvalp)
{
	int				error;
	kern_return_t			kr;
	boolean_t			using_shared_regions;
	user_addr_t			user_ranges;
	unsigned int			range_count;
	vm_size_t			ranges_size;
	struct shared_region_range_np	*ranges;
	shared_region_mapping_t 	shared_region;
	struct shared_region_task_mappings	task_mapping_info;
	shared_region_mapping_t		next;

	ranges = NULL;

	range_count = uap->rangeCount;
	user_ranges = uap->ranges;
	ranges_size = (vm_size_t) (range_count * sizeof (ranges[0]));

	SHARED_REGION_TRACE(
		SHARED_REGION_TRACE_INFO,
		("shared_region: %p [%d(%s)] "
		 "make_private(rangecount=%d)\n",
		 current_thread(), p->p_pid, p->p_comm, range_count));

	/* allocate kernel space for the "ranges" */
	if (range_count != 0) {
		if (range_count > SHARED_REGION_MAX_MAPPINGS) {
			error = EINVAL;
			goto done;
		}
		if ((mach_vm_size_t) ranges_size !=
		    (mach_vm_size_t) range_count * sizeof (ranges[0])) {
			/* 32-bit integer overflow */
			error = EINVAL;
			goto done;
		}
		kr = kmem_alloc(kernel_map,
				(vm_offset_t *) &ranges,
				ranges_size);
		if (kr != KERN_SUCCESS) {
			error = ENOMEM;
			goto done;
		}

		/* copy "ranges" from user-space */
		error = copyin(user_ranges,
			       ranges,
			       ranges_size);
		if (error) {
			goto done;
		}
	}

	if (p->p_flag & P_NOSHLIB) {
		/* no split library has been mapped for this process so far */
		using_shared_regions = FALSE;
	} else {
		/* this process has already mapped some split libraries */
		using_shared_regions = TRUE;
	}

	/*
	 * Get a private copy of the current shared region.
	 * Do not chain it to the system-wide shared region, as we'll want
	 * to map other split libraries in place of the old ones.  We want
	 * to completely detach from the system-wide shared region and go our
	 * own way after this point, not sharing anything with other processes.
	 */
	error = clone_system_shared_regions(using_shared_regions,
					    FALSE, /* chain_regions */
					    ENV_DEFAULT_ROOT);
	if (error) {
		goto done;
	}

	/* get info on the newly allocated shared region */
	vm_get_shared_region(current_task(), &shared_region);
	task_mapping_info.self = (vm_offset_t) shared_region;
	shared_region_mapping_info(shared_region,
				   &(task_mapping_info.text_region),
				   &(task_mapping_info.text_size),
				   &(task_mapping_info.data_region),
				   &(task_mapping_info.data_size),
				   &(task_mapping_info.region_mappings),
				   &(task_mapping_info.client_base),
				   &(task_mapping_info.alternate_base),
				   &(task_mapping_info.alternate_next),
				   &(task_mapping_info.fs_base),
				   &(task_mapping_info.system),
				   &(task_mapping_info.flags),
				   &next);

	/*
	 * We now have our private copy of the shared region, as it was before
	 * the call to clone_system_shared_regions().  We now need to clean it
	 * up and keep only the memory areas described by the "ranges" array.
	 */
	kr = shared_region_cleanup(range_count, ranges, &task_mapping_info);
	switch (kr) {
	case KERN_SUCCESS:
		error = 0;
		break;
	default:
		error = EINVAL;
		goto done;
	}

done:
	if (ranges != NULL) {
		kmem_free(kernel_map,
			  (vm_offset_t) ranges,
			  ranges_size);
		ranges = NULL;
	}

	SHARED_REGION_TRACE(
		SHARED_REGION_TRACE_INFO,
		("shared_region: %p [%d(%s)] "
		 "make_private(rangecount=%d) -> %d "
		 "shared_region=%p[%x,%x,%x]\n",
		 current_thread(), p->p_pid, p->p_comm,
		 range_count, error, shared_region,
		 task_mapping_info.fs_base,
		 task_mapping_info.system,
		 task_mapping_info.flags));

	return error;
}


/*
 * shared_region_map_file_np:
 *
 * This system call is for "dyld" only.
 *
 * "dyld" wants to map parts of a split library in the shared region.
 * We get a file descriptor on the split library to be mapped and a set
 * of mapping instructions, describing which parts of the file to map in\
 * which areas of the shared segment and with what protection.
 * The "shared region" is split in 2 areas:
 * 0x90000000 - 0xa0000000 : read-only area (for TEXT and LINKEDIT sections), 
 * 0xa0000000 - 0xb0000000 : writable area (for DATA sections).
 *
 */
int
shared_region_map_file_np(
	struct proc				*p,
	struct shared_region_map_file_np_args	*uap,
	__unused int				*retvalp)
{
	int					error;
	kern_return_t				kr;
	int					fd;
	unsigned int				mapping_count;
	user_addr_t				user_mappings; /* 64-bit */
	user_addr_t				user_slide_p;  /* 64-bit */
	struct shared_file_mapping_np 		*mappings;
	vm_size_t				mappings_size;
	struct fileproc				*fp;
	mach_vm_offset_t 			slide;
	struct vnode				*vp;
	struct vfs_context 			context;
	memory_object_control_t 		file_control;
	memory_object_size_t			file_size;
	shared_region_mapping_t 		shared_region;
	struct shared_region_task_mappings	task_mapping_info;
	shared_region_mapping_t			next;
	shared_region_mapping_t			default_shared_region;
	boolean_t				using_default_region;
	unsigned int				j;
	vm_prot_t				max_prot;
	mach_vm_offset_t			base_offset, end_offset;
	mach_vm_offset_t			original_base_offset;
	boolean_t				mappings_in_segment;
#define SFM_MAX_STACK	6
	struct shared_file_mapping_np		stack_mappings[SFM_MAX_STACK];

	mappings_size = 0;
	mappings = NULL;
	mapping_count = 0;
	fp = NULL;
	vp = NULL;

	/* get file descriptor for split library from arguments */
	fd = uap->fd;

	/* get file structure from file descriptor */
	error = fp_lookup(p, fd, &fp, 0);
	if (error) {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_ERROR,
			("shared_region: %p [%d(%s)] map_file: "
			 "fd=%d lookup failed (error=%d)\n",
			 current_thread(), p->p_pid, p->p_comm, fd, error));
		goto done;
	}

	/* make sure we're attempting to map a vnode */
	if (fp->f_fglob->fg_type != DTYPE_VNODE) {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_ERROR,
			("shared_region: %p [%d(%s)] map_file: "
			 "fd=%d not a vnode (type=%d)\n",
			 current_thread(), p->p_pid, p->p_comm,
			 fd, fp->f_fglob->fg_type));
		error = EINVAL;
		goto done;
	}

	/* we need at least read permission on the file */
	if (! (fp->f_fglob->fg_flag & FREAD)) {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_ERROR,
			("shared_region: %p [%d(%s)] map_file: "
			 "fd=%d not readable\n",
			 current_thread(), p->p_pid, p->p_comm, fd));
		error = EPERM;
		goto done;
	}

	/* get vnode from file structure */
	error = vnode_getwithref((vnode_t)fp->f_fglob->fg_data);
	if (error) {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_ERROR,
			("shared_region: %p [%d(%s)] map_file: "
			 "fd=%d getwithref failed (error=%d)\n",
			 current_thread(), p->p_pid, p->p_comm, fd, error));
		goto done;
	}
	vp = (struct vnode *) fp->f_fglob->fg_data;

	/* make sure the vnode is a regular file */
	if (vp->v_type != VREG) {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_ERROR,
			("shared_region: %p [%d(%s)] map_file(%p:'%s'): "
			 "not a file (type=%d)\n",
			 current_thread(), p->p_pid, p->p_comm,
			 vp, vp->v_name, vp->v_type));
		error = EINVAL;
		goto done;
	}

	/* get vnode size */
	{
		off_t	fs;
		
		context.vc_proc = p;
		context.vc_ucred = kauth_cred_get();
		if ((error = vnode_size(vp, &fs, &context)) != 0) {
			SHARED_REGION_TRACE(
				SHARED_REGION_TRACE_ERROR,
				("shared_region: %p [%d(%s)] "
				 "map_file(%p:'%s'): "
				 "vnode_size(%p) failed (error=%d)\n",
				 current_thread(), p->p_pid, p->p_comm,
				 vp, vp->v_name, vp));
			goto done;
		}
		file_size = fs;
	}

	/*
	 * Get the list of mappings the caller wants us to establish.
	 */
	mapping_count = uap->mappingCount; /* the number of mappings */
	mappings_size = (vm_size_t) (mapping_count * sizeof (mappings[0]));
	if (mapping_count == 0) {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_INFO,
			("shared_region: %p [%d(%s)] map_file(%p:'%s'): "
			 "no mappings\n",
			 current_thread(), p->p_pid, p->p_comm,
			 vp, vp->v_name));
		error = 0;	/* no mappings: we're done ! */
		goto done;
	} else if (mapping_count <= SFM_MAX_STACK) {
		mappings = &stack_mappings[0];
	} else {
		if (mapping_count > SHARED_REGION_MAX_MAPPINGS) {
			error = EINVAL;
			goto done;
		}
		if ((mach_vm_size_t) mappings_size !=
		    (mach_vm_size_t) mapping_count * sizeof (mappings[0])) {
			/* 32-bit integer overflow */
			error = EINVAL;
			goto done;
		}
		kr = kmem_alloc(kernel_map,
				(vm_offset_t *) &mappings,
				mappings_size);
		if (kr != KERN_SUCCESS) {
			SHARED_REGION_TRACE(
				SHARED_REGION_TRACE_ERROR,
				("shared_region: %p [%d(%s)] "
				 "map_file(%p:'%s'): "
				 "failed to allocate %d mappings (kr=0x%x)\n",
				 current_thread(), p->p_pid, p->p_comm,
				 vp, vp->v_name, mapping_count, kr));
			error = ENOMEM;
			goto done;
		}
	}

	user_mappings = uap->mappings;	   /* the mappings, in user space */
	error = copyin(user_mappings,
		       mappings,
		       mappings_size);
	if (error != 0) {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_ERROR,
			("shared_region: %p [%d(%s)] map_file(%p:'%s'): "
			 "failed to copyin %d mappings (error=%d)\n",
			 current_thread(), p->p_pid, p->p_comm,
			 vp, vp->v_name, mapping_count, error));
		goto done;
	}

	/*
	 * If the caller provides a "slide" pointer, it means they're OK
	 * with us moving the mappings around to make them fit.
	 */
	user_slide_p = uap->slide_p;

	/*
	 * Make each mapping address relative to the beginning of the
	 * shared region.  Check that all mappings are in the shared region.
	 * Compute the maximum set of protections required to tell the
	 * buffer cache how we mapped the file (see call to ubc_map() below).
	 */
	max_prot = VM_PROT_NONE;
	base_offset = -1LL;
	end_offset = 0;
	mappings_in_segment = TRUE;
	for (j = 0; j < mapping_count; j++) {
		mach_vm_offset_t segment;
		segment = (mappings[j].sfm_address &
			   GLOBAL_SHARED_SEGMENT_MASK);
		if (segment != GLOBAL_SHARED_TEXT_SEGMENT &&
		    segment != GLOBAL_SHARED_DATA_SEGMENT) {
			/* this mapping is not in the shared region... */
			if (user_slide_p == NULL) {
				/* ... and we can't slide it in: fail */
				SHARED_REGION_TRACE(
					SHARED_REGION_TRACE_CONFLICT,
					("shared_region: %p [%d(%s)] "
					 "map_file(%p:'%s'): "
					 "mapping %p not in shared segment & "
					 "no sliding\n",
					 current_thread(), p->p_pid, p->p_comm,
					 vp, vp->v_name,
					 mappings[j].sfm_address));
				error = EINVAL;
				goto done;
			}
			if (j == 0) {
				/* expect all mappings to be outside */
				mappings_in_segment = FALSE;
			} else if (mappings_in_segment != FALSE) {
				/* other mappings were not outside: fail */
				SHARED_REGION_TRACE(
					SHARED_REGION_TRACE_CONFLICT,
					("shared_region: %p [%d(%s)] "
					 "map_file(%p:'%s'): "
					 "mapping %p not in shared segment & "
					 "other mappings in shared segment\n",
					 current_thread(), p->p_pid, p->p_comm,
					 vp, vp->v_name,
					 mappings[j].sfm_address));
				error = EINVAL;
				goto done;
			}
			/* we'll try and slide that mapping in the segments */
		} else {
			if (j == 0) {
				/* expect all mappings to be inside */
				mappings_in_segment = TRUE;
			} else if (mappings_in_segment != TRUE) {
				/* other mappings were not inside: fail */
				SHARED_REGION_TRACE(
					SHARED_REGION_TRACE_CONFLICT,
					("shared_region: %p [%d(%s)] "
					 "map_file(%p:'%s'): "
					 "mapping %p in shared segment & "
					 "others in shared segment\n",
					 current_thread(), p->p_pid, p->p_comm,
					 vp, vp->v_name,
					 mappings[j].sfm_address));
				error = EINVAL;
				goto done;
			}
			/* get a relative offset inside the shared segments */
			mappings[j].sfm_address -= GLOBAL_SHARED_TEXT_SEGMENT;
		}
		if ((mappings[j].sfm_address & SHARED_TEXT_REGION_MASK)
		    < base_offset) {
			base_offset = (mappings[j].sfm_address &
				       SHARED_TEXT_REGION_MASK);
		}
		if ((mappings[j].sfm_address & SHARED_TEXT_REGION_MASK) +
		    mappings[j].sfm_size > end_offset) {
			end_offset =
				(mappings[j].sfm_address &
				 SHARED_TEXT_REGION_MASK) +
				mappings[j].sfm_size;
		}
		max_prot |= mappings[j].sfm_max_prot;
	}
	/* Make all mappings relative to the base_offset */
	base_offset = vm_map_trunc_page(base_offset);
	end_offset = vm_map_round_page(end_offset);
	for (j = 0; j < mapping_count; j++) {
		mappings[j].sfm_address -= base_offset;
	}
	original_base_offset = base_offset;
	if (mappings_in_segment == FALSE) {
		/*
		 * We're trying to map a library that was not pre-bound to
		 * be in the shared segments.  We want to try and slide it
		 * back into the shared segments but as far back as possible,
		 * so that it doesn't clash with pre-bound libraries.  Set
		 * the base_offset to the end of the region, so that it can't
		 * possibly fit there and will have to be slid.
		 */
		base_offset = SHARED_TEXT_REGION_SIZE - end_offset;
	}

	/* get the file's memory object handle */
	UBCINFOCHECK("shared_region_map_file_np", vp);
	file_control = ubc_getobject(vp, UBC_HOLDOBJECT);
	if (file_control == MEMORY_OBJECT_CONTROL_NULL) {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_ERROR,
			("shared_region: %p [%d(%s)] map_file(%p:'%s'): "
			 "ubc_getobject() failed\n",
			 current_thread(), p->p_pid, p->p_comm,
			 vp, vp->v_name));
		error = EINVAL;
		goto done;
	}

	/*
	 * Get info about the current process's shared region.
	 * This might change if we decide we need to clone the shared region.
	 */
	vm_get_shared_region(current_task(), &shared_region);
	task_mapping_info.self = (vm_offset_t) shared_region;
	shared_region_mapping_info(shared_region,
				   &(task_mapping_info.text_region),
				   &(task_mapping_info.text_size),
				   &(task_mapping_info.data_region),
				   &(task_mapping_info.data_size),
				   &(task_mapping_info.region_mappings),
				   &(task_mapping_info.client_base),
				   &(task_mapping_info.alternate_base),
				   &(task_mapping_info.alternate_next),
				   &(task_mapping_info.fs_base),
				   &(task_mapping_info.system),
				   &(task_mapping_info.flags),
				   &next);

	/*
	 * Are we using the system's current shared region
	 * for this environment ?
	 */
	default_shared_region =
		lookup_default_shared_region(ENV_DEFAULT_ROOT,
					     task_mapping_info.system);
	if (shared_region == default_shared_region) {
		using_default_region = TRUE;
	} else {
		using_default_region = FALSE;
	}
	shared_region_mapping_dealloc(default_shared_region);

	if (vp->v_mount != rootvnode->v_mount &&
	    using_default_region) {
		/*
		 * The split library is not on the root filesystem.  We don't
		 * want to polute the system-wide ("default") shared region
		 * with it.
		 * Reject the mapping.  The caller (dyld) should "privatize"
		 * (via shared_region_make_private()) the shared region and
		 * try to establish the mapping privately for this process.
		 */
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_CONFLICT,
			("shared_region: %p [%d(%s)] "
			 "map_file(%p:'%s'): "
			 "not on root volume\n",
			 current_thread(), p->p_pid, p->p_comm,
			 vp->v_name));
		error = EXDEV;
		goto done;
	}


	/*
	 * Map the split library.
	 */
	kr = map_shared_file(mapping_count,
			     mappings,
			     file_control,
			     file_size,
			     &task_mapping_info,
			     base_offset,
			     (user_slide_p) ? &slide : NULL);

	if (kr == KERN_SUCCESS) {
		/*
		 * The mapping was successful.  Let the buffer cache know
		 * that we've mapped that file with these protections.  This
		 * prevents the vnode from getting recycled while it's mapped.
		 */
		(void) ubc_map(vp, max_prot);
		error = 0;
	} else {
		SHARED_REGION_TRACE(
			SHARED_REGION_TRACE_CONFLICT,
			("shared_region: %p [%d(%s)] "
			 "map_file(%p:'%s'): "
			 "map_shared_file failed, kr=0x%x\n",
			 current_thread(), p->p_pid, p->p_comm,
			 vp, vp->v_name, kr));
		switch (kr) {
		case KERN_INVALID_ADDRESS:
			error = EFAULT;
			goto done;
		case KERN_PROTECTION_FAILURE:
			error = EPERM;
			goto done;
		case KERN_NO_SPACE:
			error = ENOMEM;
			goto done;
		case KERN_FAILURE:
		case KERN_INVALID_ARGUMENT:
		default:
			error = EINVAL;
			goto done;
		}
	}

	if (p->p_flag & P_NOSHLIB) {
		/* signal that this process is now using split libraries */
		p->p_flag &= ~P_NOSHLIB;
	}

	if (user_slide_p) {
		/*
		 * The caller provided a pointer to a "slide" offset.  Let
		 * them know by how much we slid the mappings.
		 */
		if (mappings_in_segment == FALSE) {
			/*
			 * We faked the base_offset earlier, so undo that
			 * and take into account the real base_offset.
			 */
			slide += SHARED_TEXT_REGION_SIZE - end_offset;
			slide -= original_base_offset;
			/*
			 * The mappings were slid into the shared segments
			 * and "slide" is relative to the beginning of the
			 * shared segments.  Adjust it to be absolute.
			 */
			slide += GLOBAL_SHARED_TEXT_SEGMENT;
		}
		error = copyout(&slide,
				user_slide_p,
				sizeof (slide));
		if (slide != 0) {
			SHARED_REGION_TRACE(
				SHARED_REGION_TRACE_CONFLICT,
				("shared_region: %p [%d(%s)] "
				 "map_file(%p:'%s'): "
				 "slid by 0x%llx\n",
				 current_thread(), p->p_pid, p->p_comm,
				 vp, vp->v_name, slide));
		}
	}

done:
	if (vp != NULL) {
		/*
		 * release the vnode...
		 * ubc_map() still holds it for us in the non-error case
		 */
		(void) vnode_put(vp);
		vp = NULL;
	}
	if (fp != NULL) {
		/* release the file descriptor */
		fp_drop(p, fd, fp, 0);
		fp = NULL;
	}
	if (mappings != NULL &&
	    mappings != &stack_mappings[0]) {
		kmem_free(kernel_map,
			  (vm_offset_t) mappings,
			  mappings_size);
	}
	mappings = NULL;

	return error;
}

int
load_shared_file(
	__unused struct proc *p,
	__unused struct load_shared_file_args *uap,
	__unused int *retval)
{
	return ENOSYS;
}

int
reset_shared_file(
	__unused struct proc *p,
	__unused struct reset_shared_file_args *uap,
	__unused int *retval)
{
	return ENOSYS;
}

int
new_system_shared_regions(
	__unused struct proc *p,
	__unused struct new_system_shared_regions_args *uap,
	__unused int *retval)
{
	return ENOSYS;
}



int
clone_system_shared_regions(
	int		shared_regions_active,
	int		chain_regions,
	int		base_vnode)
{
	shared_region_mapping_t	new_shared_region;
	shared_region_mapping_t	next;
	shared_region_mapping_t	old_shared_region;
	struct shared_region_task_mappings old_info;
	struct shared_region_task_mappings new_info;

	vm_get_shared_region(current_task(), &old_shared_region);
	old_info.self = (vm_offset_t)old_shared_region;
	shared_region_mapping_info(old_shared_region,
		&(old_info.text_region),   
		&(old_info.text_size),
		&(old_info.data_region),
		&(old_info.data_size),
		&(old_info.region_mappings),
		&(old_info.client_base),
		&(old_info.alternate_base),
		&(old_info.alternate_next), 
		&(old_info.fs_base),
		&(old_info.system),
		&(old_info.flags), &next);

	if (shared_regions_active ||
	    base_vnode == ENV_DEFAULT_ROOT) {
		if (shared_file_create_system_region(&new_shared_region,
						     old_info.fs_base,
						     old_info.system))
			return ENOMEM;
	} else {
		if (old_shared_region &&
		    base_vnode == ENV_DEFAULT_ROOT) {
			base_vnode = old_info.fs_base;
		}
		new_shared_region =
			lookup_default_shared_region(base_vnode,
						     old_info.system);
		if (new_shared_region == NULL) {
			shared_file_boot_time_init(base_vnode,
						   old_info.system);
			vm_get_shared_region(current_task(),
					     &new_shared_region);
		} else {
			vm_set_shared_region(current_task(), new_shared_region);
		}
		if (old_shared_region)
			shared_region_mapping_dealloc(old_shared_region);
	}
	new_info.self = (vm_offset_t)new_shared_region;
	shared_region_mapping_info(new_shared_region,
		&(new_info.text_region),   
		&(new_info.text_size),
		&(new_info.data_region),
		&(new_info.data_size),
		&(new_info.region_mappings),
		&(new_info.client_base),
		&(new_info.alternate_base),
		&(new_info.alternate_next), 
		&(new_info.fs_base),
		&(new_info.system),
		&(new_info.flags), &next);
	if(shared_regions_active) {
	   if(vm_region_clone(old_info.text_region, new_info.text_region)) {
	   panic("clone_system_shared_regions: shared region mis-alignment 1");
		shared_region_mapping_dealloc(new_shared_region);
		return(EINVAL);
	   }
	   if (vm_region_clone(old_info.data_region, new_info.data_region)) {
	   panic("clone_system_shared_regions: shared region mis-alignment 2");
		shared_region_mapping_dealloc(new_shared_region);
		return(EINVAL);
	   }
	   if (chain_regions) {
		   /*
		    * We want a "shadowed" clone, a private superset of the old
		    * shared region.  The info about the old mappings is still
		    * valid for us.
		    */
		   shared_region_object_chain_attach(
			   new_shared_region, old_shared_region);
	   }
	}
	if (!chain_regions) {
		/*
		 * We want a completely detached clone with no link to
		 * the old shared region.  We'll be removing some mappings
		 * in our private, cloned, shared region, so the old mappings
		 * will become irrelevant to us.  Since we have a private
		 * "shared region" now, it isn't going to be shared with
		 * anyone else and we won't need to maintain mappings info.
		 */
		shared_region_object_chain_detached(new_shared_region);
	}
	if (vm_map_region_replace(current_map(), old_info.text_region, 
			new_info.text_region, old_info.client_base, 
			old_info.client_base+old_info.text_size)) {
	panic("clone_system_shared_regions: shared region mis-alignment 3");
		shared_region_mapping_dealloc(new_shared_region);
		return(EINVAL);
	}
	if(vm_map_region_replace(current_map(), old_info.data_region, 
			new_info.data_region, 
			old_info.client_base + old_info.text_size, 
			old_info.client_base
				+ old_info.text_size + old_info.data_size)) {
	panic("clone_system_shared_regions: shared region mis-alignment 4");
		shared_region_mapping_dealloc(new_shared_region);
		return(EINVAL);
	}
	vm_set_shared_region(current_task(), new_shared_region);

	/* consume the reference which wasn't accounted for in object */
	/* chain attach */
	if (!shared_regions_active || !chain_regions)
		shared_region_mapping_dealloc(old_shared_region);

	SHARED_REGION_TRACE(
		SHARED_REGION_TRACE_INFO,
		("shared_region: %p task=%p "
		 "clone(active=%d, base=0x%x,chain=%d) "
		 "old=%p[%x,%x,%x] new=%p[%x,%x,%x]\n",
		 current_thread(), current_task(), 
		 shared_regions_active, base_vnode, chain_regions,
		 old_shared_region,
		 old_info.fs_base,
		 old_info.system,
		 old_info.flags,
		 new_shared_region,
		 new_info.fs_base,
		 new_info.system,
		 new_info.flags));

	return(0);

}

/* header for the profile name file.  The profiled app info is held */
/* in the data file and pointed to by elements in the name file     */

struct profile_names_header {
	unsigned int	number_of_profiles;
	unsigned int	user_id;
	unsigned int	version;
	off_t		element_array;
	unsigned int	spare1;
	unsigned int	spare2;
	unsigned int	spare3;
};

struct profile_element {
	off_t		addr;
	vm_size_t	size;
	unsigned int	mod_date;
	unsigned int	inode;
	char name[12];
};

struct global_profile {
	struct vnode	*names_vp;
	struct vnode	*data_vp;
	vm_offset_t	buf_ptr;
	unsigned int	user;
	unsigned int	age;
	unsigned int	busy;
};

struct global_profile_cache {
	int			max_ele;
	unsigned int		age;
	struct global_profile	profiles[3];
};

/* forward declarations */
int bsd_open_page_cache_files(unsigned int user,
			      struct global_profile **profile);
void bsd_close_page_cache_files(struct global_profile *profile);
int bsd_search_page_cache_data_base(
	struct	vnode			*vp,
	struct profile_names_header	*database,
	char				*app_name,
	unsigned int			mod_date,
	unsigned int			inode,
	off_t				*profile,
	unsigned int			*profile_size);

struct global_profile_cache global_user_profile_cache =
	{3, 0, {{NULL, NULL, 0, 0, 0, 0},
		    {NULL, NULL, 0, 0, 0, 0},
		    {NULL, NULL, 0, 0, 0, 0}} };

/* BSD_OPEN_PAGE_CACHE_FILES:                                 */
/* Caller provides a user id.  This id was used in            */
/* prepare_profile_database to create two unique absolute     */
/* file paths to the associated profile files.  These files   */
/* are either opened or bsd_open_page_cache_files returns an  */
/* error.  The header of the names file is then consulted.    */
/* The header and the vnodes for the names and data files are */
/* returned. */

int
bsd_open_page_cache_files(
	unsigned int	user,
	struct global_profile **profile)
{
	const char *cache_path = "/var/vm/app_profile/";
	struct proc	*p;
	int		error;
	vm_size_t	resid;
	off_t		resid_off;
	unsigned int	lru;
	vm_size_t	size;

	struct	vnode	*names_vp;
	struct  vnode	*data_vp;
	vm_offset_t	names_buf;
	vm_offset_t	buf_ptr;

	int		profile_names_length;
	int		profile_data_length;
	char		*profile_data_string;
	char		*profile_names_string;
	char		*substring;

	off_t		file_size;
	struct vfs_context  context;

	kern_return_t	ret;

	struct nameidata nd_names;
	struct nameidata nd_data;
	int		i;


	p = current_proc();

	context.vc_proc = p;
	context.vc_ucred = kauth_cred_get();

restart:
	for(i = 0; i<global_user_profile_cache.max_ele; i++) {
		if((global_user_profile_cache.profiles[i].user == user) 
			&&  (global_user_profile_cache.profiles[i].data_vp 
								!= NULL)) {
			*profile = &global_user_profile_cache.profiles[i];
			/* already in cache, we're done */
			if ((*profile)->busy) {
       				/*
       				* drop funnel and wait 
       				*/
				(void)tsleep((void *)
					*profile, 
					PRIBIO, "app_profile", 0);
				goto restart;
			}
			(*profile)->busy = 1;
			(*profile)->age = global_user_profile_cache.age;

			/*
			 * entries in cache are held with a valid
			 * usecount... take an iocount which will
			 * be dropped in "bsd_close_page_cache_files"
			 * which is called after the read or writes to
			 * these files are done
			 */
			if ( (vnode_getwithref((*profile)->data_vp)) ) {
			  
			        vnode_rele((*profile)->data_vp);
			        vnode_rele((*profile)->names_vp);

				(*profile)->data_vp = NULL;
				(*profile)->busy = 0;
				wakeup(*profile);

				goto restart;
			}
			if ( (vnode_getwithref((*profile)->names_vp)) ) {

			        vnode_put((*profile)->data_vp);
			        vnode_rele((*profile)->data_vp);
			        vnode_rele((*profile)->names_vp);

				(*profile)->data_vp = NULL;
				(*profile)->busy = 0;
				wakeup(*profile);

				goto restart;
			}
			global_user_profile_cache.age+=1;
			return 0;
		}
	}

	lru = global_user_profile_cache.age;
	*profile = NULL;
	for(i = 0; i<global_user_profile_cache.max_ele; i++) {
		/* Skip entry if it is in the process of being reused */
		if(global_user_profile_cache.profiles[i].data_vp ==
						(struct vnode *)0xFFFFFFFF)
			continue;
		/* Otherwise grab the first empty entry */
		if(global_user_profile_cache.profiles[i].data_vp == NULL) {
			*profile = &global_user_profile_cache.profiles[i];
			(*profile)->age = global_user_profile_cache.age;
			break;
		}
		/* Otherwise grab the oldest entry */
		if(global_user_profile_cache.profiles[i].age < lru) {
			lru = global_user_profile_cache.profiles[i].age;
			*profile = &global_user_profile_cache.profiles[i];
		}
	}

	/* Did we set it? */
	if (*profile == NULL) {
		/*
		 * No entries are available; this can only happen if all
		 * of them are currently in the process of being reused;
		 * if this happens, we sleep on the address of the first
		 * element, and restart.  This is less than ideal, but we
		 * know it will work because we know that there will be a
		 * wakeup on any entry currently in the process of being
		 * reused.
		 *
		 * XXX Reccomend a two handed clock and more than 3 total
		 * XXX cache entries at some point in the future.
		 */
       		/*
       		* drop funnel and wait 
       		*/
		(void)tsleep((void *)
		 &global_user_profile_cache.profiles[0],
			PRIBIO, "app_profile", 0);
		goto restart;
	}

	/*
	 * If it's currently busy, we've picked the one at the end of the
	 * LRU list, but it's currently being actively used.  We sleep on
	 * its address and restart.
	 */
	if ((*profile)->busy) {
       		/*
       		* drop funnel and wait 
       		*/
		(void)tsleep((void *)
			*profile, 
			PRIBIO, "app_profile", 0);
		goto restart;
	}
	(*profile)->busy = 1;
	(*profile)->user = user;

	/*
	 * put dummy value in for now to get competing request to wait
	 * above until we are finished
	 *
	 * Save the data_vp before setting it, so we can set it before
	 * we kmem_free() or vrele().  If we don't do this, then we
	 * have a potential funnel race condition we have to deal with.
	 */
	data_vp = (*profile)->data_vp;
	(*profile)->data_vp = (struct vnode *)0xFFFFFFFF;

	/*
	 * Age the cache here in all cases; this guarantees that we won't
	 * be reusing only one entry over and over, once the system reaches
	 * steady-state.
	 */
	global_user_profile_cache.age+=1;

	if(data_vp != NULL) {
		kmem_free(kernel_map, 
				(*profile)->buf_ptr, 4 * PAGE_SIZE);
		if ((*profile)->names_vp) {
			vnode_rele((*profile)->names_vp);
			(*profile)->names_vp = NULL;
		}
		vnode_rele(data_vp);
	}
	
	/* Try to open the appropriate users profile files */
	/* If neither file is present, try to create them  */
	/* If one file is present and the other not, fail. */
	/* If the files do exist, check them for the app_file */
	/* requested and read it in if present */

	ret = kmem_alloc(kernel_map,
		(vm_offset_t *)&profile_data_string, PATH_MAX);

	if(ret) {
		(*profile)->data_vp = NULL;
		(*profile)->busy = 0;
		wakeup(*profile);
		return ENOMEM;
	}

	/* Split the buffer in half since we know the size of */
	/* our file path and our allocation is adequate for   */
	/* both file path names */
	profile_names_string = profile_data_string + (PATH_MAX/2);


	strcpy(profile_data_string, cache_path);
	strcpy(profile_names_string, cache_path);
	profile_names_length = profile_data_length 
			= strlen(profile_data_string);
	substring = profile_data_string + profile_data_length;
	sprintf(substring, "%x_data", user);
	substring = profile_names_string + profile_names_length;
	sprintf(substring, "%x_names", user);

	/* We now have the absolute file names */

	ret = kmem_alloc(kernel_map,
       			(vm_offset_t *)&names_buf, 4 * PAGE_SIZE);
	if(ret) {
		kmem_free(kernel_map, 
				(vm_offset_t)profile_data_string, PATH_MAX);
		(*profile)->data_vp = NULL;
		(*profile)->busy = 0;
		wakeup(*profile);
		return ENOMEM;
	}

	NDINIT(&nd_names, LOOKUP, FOLLOW | LOCKLEAF, 
			UIO_SYSSPACE32, CAST_USER_ADDR_T(profile_names_string), &context);
	NDINIT(&nd_data, LOOKUP, FOLLOW | LOCKLEAF, 
			UIO_SYSSPACE32, CAST_USER_ADDR_T(profile_data_string), &context);

	if ( (error = vn_open(&nd_data, FREAD | FWRITE, 0)) ) {
#ifdef notdef
		printf("bsd_open_page_cache_files: CacheData file not found %s\n",
			profile_data_string);
#endif
		kmem_free(kernel_map, 
				(vm_offset_t)names_buf, 4 * PAGE_SIZE);
		kmem_free(kernel_map, 
			(vm_offset_t)profile_data_string, PATH_MAX);
		(*profile)->data_vp = NULL;
		(*profile)->busy = 0;
		wakeup(*profile);
		return error;
	}
	data_vp = nd_data.ni_vp;

	if ( (error = vn_open(&nd_names, FREAD | FWRITE, 0)) ) {
		printf("bsd_open_page_cache_files: NamesData file not found %s\n",
			profile_data_string);
		kmem_free(kernel_map, 
				(vm_offset_t)names_buf, 4 * PAGE_SIZE);
		kmem_free(kernel_map, 
			(vm_offset_t)profile_data_string, PATH_MAX);

		vnode_rele(data_vp);
		vnode_put(data_vp);

		(*profile)->data_vp = NULL;
		(*profile)->busy = 0;
		wakeup(*profile);
		return error;
	}
	names_vp = nd_names.ni_vp;

	if ((error = vnode_size(names_vp, &file_size, &context)) != 0) {
		printf("bsd_open_page_cache_files: Can't stat name file %s\n", profile_names_string);
		kmem_free(kernel_map, 
			(vm_offset_t)profile_data_string, PATH_MAX);
		kmem_free(kernel_map, 
			(vm_offset_t)names_buf, 4 * PAGE_SIZE);

		vnode_rele(names_vp);
		vnode_put(names_vp);
		vnode_rele(data_vp);
		vnode_put(data_vp);

		(*profile)->data_vp = NULL;
		(*profile)->busy = 0;
		wakeup(*profile);
		return error;
	}

	size = file_size;
	if(size > 4 * PAGE_SIZE) 
		size = 4 * PAGE_SIZE;
	buf_ptr = names_buf;
	resid_off = 0;

	while(size) {
		int resid_int;
		error = vn_rdwr(UIO_READ, names_vp, (caddr_t)buf_ptr, 
			size, resid_off,
			UIO_SYSSPACE32, IO_NODELOCKED, kauth_cred_get(),
			&resid_int, p);
		resid = (vm_size_t) resid_int;
		if((error) || (size == resid)) {
			if(!error) {
				error = EINVAL;
			}
			kmem_free(kernel_map, 
				(vm_offset_t)profile_data_string, PATH_MAX);
			kmem_free(kernel_map, 
				(vm_offset_t)names_buf, 4 * PAGE_SIZE);

			vnode_rele(names_vp);
			vnode_put(names_vp);
			vnode_rele(data_vp);
			vnode_put(data_vp);

			(*profile)->data_vp = NULL;
			(*profile)->busy = 0;
			wakeup(*profile);
			return error;
		}
		buf_ptr += size-resid;
		resid_off += size-resid;
		size = resid;
	}
	kmem_free(kernel_map, (vm_offset_t)profile_data_string, PATH_MAX);

	(*profile)->names_vp = names_vp;
	(*profile)->data_vp = data_vp;
	(*profile)->buf_ptr = names_buf;

	/*
	 * at this point, the both the names_vp and the data_vp have
	 * both a valid usecount and an iocount held
	 */
	return 0;

}

void
bsd_close_page_cache_files(
	struct global_profile *profile)
{
        vnode_put(profile->data_vp);
	vnode_put(profile->names_vp);

	profile->busy = 0;
	wakeup(profile);
}

int
bsd_read_page_cache_file(
	unsigned int	user,
	int		*fid,
	int		*mod,
	char		*app_name,
	struct vnode	*app_vp,
	vm_offset_t	*buffer,
	vm_offset_t	*bufsize)
{

	boolean_t	funnel_state;

	struct proc	*p;
	int		error;
	unsigned int	resid;

	off_t		profile;
	unsigned int	profile_size;

	vm_offset_t	names_buf;
	struct vnode_attr	va;
	struct vfs_context  context;

	kern_return_t	ret;

	struct	vnode	*names_vp;
	struct	vnode	*data_vp;

	struct global_profile *uid_files;

	funnel_state = thread_funnel_set(kernel_flock, TRUE);

	/* Try to open the appropriate users profile files */
	/* If neither file is present, try to create them  */
	/* If one file is present and the other not, fail. */
	/* If the files do exist, check them for the app_file */
	/* requested and read it in if present */


	error = bsd_open_page_cache_files(user, &uid_files);
	if(error) {
		thread_funnel_set(kernel_flock, funnel_state);
		return EINVAL;
	}

	p = current_proc();

	names_vp = uid_files->names_vp;
	data_vp = uid_files->data_vp;
	names_buf = uid_files->buf_ptr;

	context.vc_proc = p;
	context.vc_ucred = kauth_cred_get();

	VATTR_INIT(&va);
	VATTR_WANTED(&va, va_fileid);
	VATTR_WANTED(&va, va_modify_time);
	
	if ((error = vnode_getattr(app_vp, &va, &context))) {
		printf("bsd_read_cache_file: Can't stat app file %s\n", app_name);
		bsd_close_page_cache_files(uid_files);
		thread_funnel_set(kernel_flock, funnel_state);
		return error;
	}

	*fid = (u_long)va.va_fileid;
	*mod = va.va_modify_time.tv_sec;
		
	if (bsd_search_page_cache_data_base(
		    names_vp,
		    (struct profile_names_header *)names_buf,
		    app_name, 
		    (unsigned int) va.va_modify_time.tv_sec,  
		    (u_long)va.va_fileid, &profile, &profile_size) == 0) {
		/* profile is an offset in the profile data base */
		/* It is zero if no profile data was found */
		
		if(profile_size == 0) {
			*buffer = 0;
			*bufsize = 0;
			bsd_close_page_cache_files(uid_files);
			thread_funnel_set(kernel_flock, funnel_state);
			return 0;
		}
		ret = (vm_offset_t)(kmem_alloc(kernel_map, buffer, profile_size));
		if(ret) {
			bsd_close_page_cache_files(uid_files);
			thread_funnel_set(kernel_flock, funnel_state);
			return ENOMEM;
		}
		*bufsize = profile_size;
		while(profile_size) {
			int resid_int;
			error = vn_rdwr(UIO_READ, data_vp, 
				(caddr_t) *buffer, profile_size, 
				profile, UIO_SYSSPACE32, IO_NODELOCKED, 
				kauth_cred_get(), &resid_int, p);
			resid = (vm_size_t) resid_int;
			if((error) || (profile_size == resid)) {
				bsd_close_page_cache_files(uid_files);
				kmem_free(kernel_map, (vm_offset_t)*buffer, profile_size);
				thread_funnel_set(kernel_flock, funnel_state);
				return EINVAL;
			}
		        profile += profile_size - resid;
			profile_size = resid;
		}
		bsd_close_page_cache_files(uid_files);
		thread_funnel_set(kernel_flock, funnel_state);
		return 0;
	} else {
		bsd_close_page_cache_files(uid_files);
		thread_funnel_set(kernel_flock, funnel_state);
		return EINVAL;
	}
	
}

int
bsd_search_page_cache_data_base(
	struct	vnode			*vp,
	struct profile_names_header	*database,
	char				*app_name,
	unsigned int			mod_date,
	unsigned int			inode,
	off_t				*profile,
	unsigned int			*profile_size)
{

	struct proc		*p;

	unsigned int 		i;
	struct profile_element	*element;
	unsigned int		ele_total;
	unsigned int		extended_list = 0;
	off_t			file_off = 0;
	unsigned int		size;
	off_t			resid_off;
	unsigned int		resid;
	vm_offset_t		local_buf = 0;

	int			error;
	kern_return_t		ret;

	p = current_proc();

	if(((vm_offset_t)database->element_array) !=
				sizeof(struct profile_names_header)) {
		return EINVAL;
	}
	element = (struct profile_element *)(
			(vm_offset_t)database->element_array + 
						(vm_offset_t)database);

	ele_total = database->number_of_profiles;
	
	*profile = 0;
	*profile_size = 0;
	while(ele_total) {
		/* note: code assumes header + n*ele comes out on a page boundary */
		if(((local_buf == 0) && (sizeof(struct profile_names_header) + 
			(ele_total * sizeof(struct profile_element))) 
					> (PAGE_SIZE * 4)) ||
			((local_buf != 0) && 
				(ele_total * sizeof(struct profile_element))
					 > (PAGE_SIZE * 4))) {
			extended_list = ele_total;
			if(element == (struct profile_element *)
				((vm_offset_t)database->element_array + 
						(vm_offset_t)database)) {
				ele_total = ((PAGE_SIZE * 4)/sizeof(struct profile_element)) - 1;
			} else {
				ele_total = (PAGE_SIZE * 4)/sizeof(struct profile_element);
			}
			extended_list -= ele_total;
		}
		for (i=0; i<ele_total; i++) {
			if((mod_date == element[i].mod_date) 
					&& (inode == element[i].inode)) {
				if(strncmp(element[i].name, app_name, 12) == 0) {
					*profile = element[i].addr;
					*profile_size = element[i].size;
					if(local_buf != 0) {
						kmem_free(kernel_map, local_buf, 4 * PAGE_SIZE);
					}
					return 0;
				}
			}
		}
		if(extended_list == 0)
			break;
		if(local_buf == 0) {
			ret = kmem_alloc(kernel_map, &local_buf, 4 * PAGE_SIZE);
			if(ret != KERN_SUCCESS) {
				return ENOMEM;
			}
		}
		element = (struct profile_element *)local_buf;
		ele_total = extended_list;
		extended_list = 0;
		file_off +=  4 * PAGE_SIZE;
		if((ele_total * sizeof(struct profile_element)) > 
							(PAGE_SIZE * 4)) {
			size = PAGE_SIZE * 4;
		} else {
			size = ele_total * sizeof(struct profile_element);
		}
		resid_off = 0;
		while(size) {
			int resid_int;
			error = vn_rdwr(UIO_READ, vp, 
				CAST_DOWN(caddr_t, (local_buf + resid_off)),
				size, file_off + resid_off, UIO_SYSSPACE32, 
				IO_NODELOCKED, kauth_cred_get(), &resid_int, p);
			resid = (vm_size_t) resid_int;
			if((error) || (size == resid)) {
				if(local_buf != 0) {
					kmem_free(kernel_map, local_buf, 4 * PAGE_SIZE);
				}
				return EINVAL;
			}
			resid_off += size-resid;
			size = resid;
		}
	}
	if(local_buf != 0) {
		kmem_free(kernel_map, local_buf, 4 * PAGE_SIZE);
	}
	return 0;
}

int
bsd_write_page_cache_file(
	unsigned int	user,
	char	 	*file_name,
	caddr_t		buffer,
	vm_size_t	size,
	int		mod,
	int		fid)
{
	struct proc		*p;
	int				resid;
	off_t			resid_off;
	int				error;
	boolean_t		funnel_state;
	off_t			file_size;
	struct vfs_context	context;
	off_t			profile;
	unsigned int	profile_size;

	vm_offset_t	names_buf;
	struct	vnode	*names_vp;
	struct	vnode	*data_vp;
	struct	profile_names_header *profile_header;
	off_t			name_offset;
	struct global_profile *uid_files;


	funnel_state = thread_funnel_set(kernel_flock, TRUE);


	error = bsd_open_page_cache_files(user, &uid_files);
	if(error) {
		thread_funnel_set(kernel_flock, funnel_state);
		return EINVAL;
	}

	p = current_proc();

	names_vp = uid_files->names_vp;
	data_vp = uid_files->data_vp;
	names_buf = uid_files->buf_ptr;

	/* Stat data file for size */

	context.vc_proc = p;
	context.vc_ucred = kauth_cred_get();

	if ((error = vnode_size(data_vp, &file_size, &context)) != 0) {
		printf("bsd_write_page_cache_file: Can't stat profile data %s\n", file_name);
		bsd_close_page_cache_files(uid_files);
		thread_funnel_set(kernel_flock, funnel_state);
		return error;
	}
		
	if (bsd_search_page_cache_data_base(names_vp, 
			(struct profile_names_header *)names_buf, 
			file_name, (unsigned int) mod,  
			fid, &profile, &profile_size) == 0) {
		/* profile is an offset in the profile data base */
		/* It is zero if no profile data was found */
		
		if(profile_size == 0) {
			unsigned int	header_size;
			vm_offset_t	buf_ptr;

			/* Our Write case */

			/* read header for last entry */
			profile_header = 
				(struct profile_names_header *)names_buf;
			name_offset = sizeof(struct profile_names_header) + 
				(sizeof(struct profile_element) 
					* profile_header->number_of_profiles);
			profile_header->number_of_profiles += 1;

			if(name_offset < PAGE_SIZE * 4) {
				struct profile_element	*name;
				/* write new entry */
				name = (struct profile_element *)
					(names_buf + (vm_offset_t)name_offset);
				name->addr =  file_size;
				name->size = size;
				name->mod_date = mod;
				name->inode = fid;
				strncpy (name->name, file_name, 12);
			} else {
				unsigned int	ele_size;
				struct profile_element	name;
				/* write new entry */
				name.addr = file_size;
				name.size = size;
				name.mod_date = mod;
				name.inode = fid;
				strncpy (name.name, file_name, 12);
				/* write element out separately */
				ele_size = sizeof(struct profile_element);
				buf_ptr = (vm_offset_t)&name;
				resid_off = name_offset;

				while(ele_size) {
					error = vn_rdwr(UIO_WRITE, names_vp, 
						(caddr_t)buf_ptr, 
						ele_size, resid_off, 
						UIO_SYSSPACE32, IO_NODELOCKED, 
						kauth_cred_get(), &resid, p);
					if(error) {
						printf("bsd_write_page_cache_file: Can't write name_element %x\n", user);
						bsd_close_page_cache_files(
							uid_files);
						thread_funnel_set(
							kernel_flock, 
							funnel_state);
						return error;
					}
					buf_ptr += (vm_offset_t)
							ele_size-resid;
					resid_off += ele_size-resid;
					ele_size = resid;
				}
			}

			if(name_offset < PAGE_SIZE * 4) {
				header_size = name_offset + 
					sizeof(struct profile_element);
				
			} else {
				header_size = 
					sizeof(struct profile_names_header);
			}
			buf_ptr = (vm_offset_t)profile_header;
			resid_off = 0;

			/* write names file header */
			while(header_size) {
				error = vn_rdwr(UIO_WRITE, names_vp, 
					(caddr_t)buf_ptr, 
					header_size, resid_off, 
					UIO_SYSSPACE32, IO_NODELOCKED, 
					kauth_cred_get(), &resid, p);
				if(error) {
					printf("bsd_write_page_cache_file: Can't write header %x\n", user);
					bsd_close_page_cache_files(
						uid_files);
					thread_funnel_set(
						kernel_flock, funnel_state);
					return error;
				}
				buf_ptr += (vm_offset_t)header_size-resid;
				resid_off += header_size-resid;
				header_size = resid;
			}
			/* write profile to data file */
			resid_off = file_size;
			while(size) {
				error = vn_rdwr(UIO_WRITE, data_vp, 
					(caddr_t)buffer, size, resid_off, 
					UIO_SYSSPACE32, IO_NODELOCKED, 
					kauth_cred_get(), &resid, p);
				if(error) {
					printf("bsd_write_page_cache_file: Can't write header %x\n", user);
					bsd_close_page_cache_files(
						uid_files);
					thread_funnel_set(
						kernel_flock, funnel_state);
					return error;
				}
				buffer += size-resid;
				resid_off += size-resid;
				size = resid;
			}
			bsd_close_page_cache_files(uid_files);
			thread_funnel_set(kernel_flock, funnel_state);
			return 0;
		}
		/* Someone else wrote a twin profile before us */
		bsd_close_page_cache_files(uid_files);
		thread_funnel_set(kernel_flock, funnel_state);
		return 0;
	} else {		
		bsd_close_page_cache_files(uid_files);
		thread_funnel_set(kernel_flock, funnel_state);
		return EINVAL;
	}
	
}

int
prepare_profile_database(int	user)
{
	const char *cache_path = "/var/vm/app_profile/";
	struct proc	*p;
	int		error;
	int		resid;
	off_t		resid_off;
	vm_size_t	size;

	struct	vnode	*names_vp;
	struct  vnode	*data_vp;
	vm_offset_t	names_buf;
	vm_offset_t	buf_ptr;

	int		profile_names_length;
	int		profile_data_length;
	char		*profile_data_string;
	char		*profile_names_string;
	char		*substring;

	struct vnode_attr va;
	struct vfs_context context;

	struct	profile_names_header *profile_header;
	kern_return_t	ret;

	struct nameidata nd_names;
	struct nameidata nd_data;

	p = current_proc();

	context.vc_proc = p;
	context.vc_ucred = kauth_cred_get();

	ret = kmem_alloc(kernel_map,
		(vm_offset_t *)&profile_data_string, PATH_MAX);

	if(ret) {
		return ENOMEM;
	}

	/* Split the buffer in half since we know the size of */
	/* our file path and our allocation is adequate for   */
	/* both file path names */
	profile_names_string = profile_data_string + (PATH_MAX/2);


	strcpy(profile_data_string, cache_path);
	strcpy(profile_names_string, cache_path);
	profile_names_length = profile_data_length 
			= strlen(profile_data_string);
	substring = profile_data_string + profile_data_length;
	sprintf(substring, "%x_data", user);
	substring = profile_names_string + profile_names_length;
	sprintf(substring, "%x_names", user);

	/* We now have the absolute file names */

	ret = kmem_alloc(kernel_map,
       			(vm_offset_t *)&names_buf, 4 * PAGE_SIZE);
	if(ret) {
		kmem_free(kernel_map, 
				(vm_offset_t)profile_data_string, PATH_MAX);
		return ENOMEM;
	}

	NDINIT(&nd_names, LOOKUP, FOLLOW, 
			UIO_SYSSPACE32, CAST_USER_ADDR_T(profile_names_string), &context);
	NDINIT(&nd_data, LOOKUP, FOLLOW,
			UIO_SYSSPACE32, CAST_USER_ADDR_T(profile_data_string), &context);

	if ( (error = vn_open(&nd_data, 
							O_CREAT | O_EXCL | FWRITE, S_IRUSR|S_IWUSR)) ) {
			kmem_free(kernel_map, 
					(vm_offset_t)names_buf, 4 * PAGE_SIZE);
			kmem_free(kernel_map, 
				(vm_offset_t)profile_data_string, PATH_MAX);
			
			return 0;
	}
	data_vp = nd_data.ni_vp;

	if ( (error = vn_open(&nd_names, 
							O_CREAT | O_EXCL | FWRITE, S_IRUSR|S_IWUSR)) ) {
			printf("prepare_profile_database: Can't create CacheNames %s\n",
				profile_data_string);
			kmem_free(kernel_map, 
					(vm_offset_t)names_buf, 4 * PAGE_SIZE);
			kmem_free(kernel_map, 
				(vm_offset_t)profile_data_string, PATH_MAX);

			vnode_rele(data_vp);
			vnode_put(data_vp);

			return error;
	}
	names_vp = nd_names.ni_vp;

	/* Write Header for new names file */

	profile_header = (struct profile_names_header *)names_buf;

	profile_header->number_of_profiles = 0;
	profile_header->user_id =  user;
	profile_header->version = 1;
	profile_header->element_array = 
				sizeof(struct profile_names_header);
	profile_header->spare1 = 0;
	profile_header->spare2 = 0;
	profile_header->spare3 = 0;

	size = sizeof(struct profile_names_header);
	buf_ptr = (vm_offset_t)profile_header;
	resid_off = 0;

	while(size) {
		error = vn_rdwr(UIO_WRITE, names_vp, 
				(caddr_t)buf_ptr, size, resid_off,
				UIO_SYSSPACE32, IO_NODELOCKED, 
				kauth_cred_get(), &resid, p);
		if(error) {
			printf("prepare_profile_database: Can't write header %s\n", profile_names_string);
			kmem_free(kernel_map, 
				(vm_offset_t)names_buf, 4 * PAGE_SIZE);
			kmem_free(kernel_map, 
				(vm_offset_t)profile_data_string, 
				PATH_MAX);

			vnode_rele(names_vp);
			vnode_put(names_vp);
			vnode_rele(data_vp);
			vnode_put(data_vp);

			return error;
		}
		buf_ptr += size-resid;
		resid_off += size-resid;
		size = resid;
	}
	VATTR_INIT(&va);
	VATTR_SET(&va, va_uid, user);

       	error = vnode_setattr(names_vp, &va, &context);
	if(error) {
		printf("prepare_profile_database: "
			"Can't set user %s\n", profile_names_string);
	}
	vnode_rele(names_vp);
	vnode_put(names_vp);
	
	VATTR_INIT(&va);
	VATTR_SET(&va, va_uid, user);
       	error = vnode_setattr(data_vp, &va, &context);
	if(error) {
		printf("prepare_profile_database: "
			"Can't set user %s\n", profile_data_string);
	}
	vnode_rele(data_vp);
	vnode_put(data_vp);

	kmem_free(kernel_map, 
			(vm_offset_t)profile_data_string, PATH_MAX);
	kmem_free(kernel_map, 
			(vm_offset_t)names_buf, 4 * PAGE_SIZE);
	return 0;

}