DragonFlyBSD Kernel Audit
sys/kern/kern_proc.c
← back
   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
/*
 * Copyright (c) 1982, 1986, 1989, 1991, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/sysctl.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/vnode.h>
#include <sys/jail.h>
#include <sys/filedesc.h>
#include <sys/tty.h>
#include <sys/dsched.h>
#include <sys/signalvar.h>
#include <sys/spinlock.h>
#include <sys/random.h>
#include <sys/exec.h>
#include <vm/vm.h>
#include <sys/lock.h>
#include <sys/kinfo.h>
#include <vm/pmap.h>
#include <vm/vm_map.h>
#include <machine/smp.h>

#include <sys/refcount.h>
#include <sys/spinlock2.h>

/*
 * Hash table size must be a power of two and is not currently dynamically
 * sized.  There is a trade-off between the linear scans which must iterate
 * all HSIZE elements and the number of elements which might accumulate
 * within each hash chain.
 */
#define ALLPROC_HSIZE	256
#define ALLPROC_HMASK	(ALLPROC_HSIZE - 1)
#define ALLPROC_HASH(pid)	(pid & ALLPROC_HMASK)
#define PGRP_HASH(pid)	(pid & ALLPROC_HMASK)
#define SESS_HASH(pid)	(pid & ALLPROC_HMASK)

/*
 * pid_doms[] management, used to control how quickly a PID can be recycled.
 * Must be a multiple of ALLPROC_HSIZE for the proc_makepid() inner loops.
 *
 * WARNING! PIDDOM_DELAY should not be defined > 20 or so unless you change
 *	    the array from int8_t's to int16_t's.
 */
#define PIDDOM_COUNT	10	/* 10 pids per domain - reduce array size */
#define PIDDOM_DELAY	10	/* min 10 seconds after exit before reuse */
#define PIDDOM_SCALE	10	/* (10,000*SCALE)/sec performance guarantee */
#define PIDSEL_DOMAINS	rounddown(PID_MAX * PIDDOM_SCALE / PIDDOM_COUNT, ALLPROC_HSIZE)

/* Used by libkvm */
int allproc_hsize = ALLPROC_HSIZE;

LIST_HEAD(pidhashhead, proc);

static MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
MALLOC_DEFINE(M_SESSION, "session", "session header");
MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
MALLOC_DEFINE(M_LWP, "lwp", "lwp structures");
MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
MALLOC_DEFINE(M_UPMAP, "upmap", "upmap/kpmap/lpmap structures");

int ps_showallprocs = 1;
static int ps_showallthreads = 1;
SYSCTL_INT(_security, OID_AUTO, ps_showallprocs, CTLFLAG_RW,
    &ps_showallprocs, 0,
    "Unprivileged processes can see processes with different UID/GID");
SYSCTL_INT(_security, OID_AUTO, ps_showallthreads, CTLFLAG_RW,
    &ps_showallthreads, 0,
    "Unprivileged processes can see kernel threads");
static u_int pid_domain_skips;
SYSCTL_UINT(_kern, OID_AUTO, pid_domain_skips, CTLFLAG_RW,
    &pid_domain_skips, 0,
    "Number of pid_doms[] skipped");
static u_int pid_inner_skips;
SYSCTL_UINT(_kern, OID_AUTO, pid_inner_skips, CTLFLAG_RW,
    &pid_inner_skips, 0,
    "Number of pid_doms[] skipped");

static void orphanpg(struct pgrp *pg);
static void proc_makepid(struct proc *p, int random_offset);

/*
 * Process related lists (for proc_token, allproc, allpgrp, and allsess)
 */
typedef struct procglob procglob_t;

static procglob_t	procglob[ALLPROC_HSIZE];

/*
 * We try our best to avoid recycling a PID too quickly.  We do this by
 * storing (uint8_t)time_second in the related pid domain on-reap and then
 * using that to skip-over the domain on-allocate.
 *
 * This array has to be fairly large to support a high fork/exec rate.
 * A ~100,000 entry array will support a 10-second reuse latency at
 * 10,000 execs/second, worst case.  Best-case multiply by PIDDOM_COUNT
 * (approximately 100,000 execs/second).
 *
 * Currently we allocate around a megabyte, making the worst-case fork
 * rate around 100,000/second.
 */
static uint8_t *pid_doms;

/*
 * Random component to nextpid generation.  We mix in a random factor to make
 * it a little harder to predict.  We sanity check the modulus value to avoid
 * doing it in critical paths.  Don't let it be too small or we pointlessly
 * waste randomness entropy, and don't let it be impossibly large.  Using a
 * modulus that is too big causes a LOT more process table scans and slows
 * down fork processing as the pidchecked caching is defeated.
 */
static int randompid = 0;

static __inline
struct ucred *
pcredcache(struct ucred *cr, struct proc *p)
{
	if (cr != p->p_ucred) {
		if (cr)
			crfree(cr);
		spin_lock(&p->p_spin);
		if ((cr = p->p_ucred) != NULL)
			crhold(cr);
		spin_unlock(&p->p_spin);
	}
	return cr;
}

/*
 * No requirements.
 */
static int
sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
{
	int error, pid;

	pid = randompid;
	error = sysctl_handle_int(oidp, &pid, 0, req);
	if (error || !req->newptr)
		return (error);
	if (pid < 0 || pid > PID_MAX - 100)     /* out of range */
		pid = PID_MAX - 100;
	else if (pid < 2)                       /* NOP */
		pid = 0;
	else if (pid < 100)                     /* Make it reasonable */
		pid = 100;
	randompid = pid;
	return (error);
}

SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
	    0, 0, sysctl_kern_randompid, "I", "Random PID modulus");

/*
 * Initialize global process hashing structures.
 *
 * These functions are ONLY called from the low level boot code and do
 * not lock their operations.
 */
void
procinit(void)
{
	u_long i;

	/*
	 * Allocate dynamically.  This array can be large (~1MB) so don't
	 * waste boot loader space.
	 */
	pid_doms = kmalloc(sizeof(pid_doms[0]) * PIDSEL_DOMAINS,
			   M_PROC, M_WAITOK | M_ZERO);

	/*
	 * Avoid unnecessary stalls due to pid_doms[] values all being
	 * the same.  Make sure that the allocation of pid 1 and pid 2
	 * succeeds.
	 */
	for (i = 0; i < PIDSEL_DOMAINS; ++i)
		pid_doms[i] = (int8_t)i - (int8_t)(PIDDOM_DELAY + 1);

	/*
	 * Other misc init.
	 */
	for (i = 0; i < ALLPROC_HSIZE; ++i) {
		procglob_t *prg = &procglob[i];
		LIST_INIT(&prg->allproc);
		LIST_INIT(&prg->allsess);
		LIST_INIT(&prg->allpgrp);
		lwkt_token_init(&prg->proc_token, "allproc");
	}
	uihashinit();
}

void
procinsertinit(struct proc *p)
{
	LIST_INSERT_HEAD(&procglob[ALLPROC_HASH(p->p_pid)].allproc,
			 p, p_list);
}

void
pgrpinsertinit(struct pgrp *pg)
{
	LIST_INSERT_HEAD(&procglob[ALLPROC_HASH(pg->pg_id)].allpgrp,
			 pg, pg_list);
}

void
sessinsertinit(struct session *sess)
{
	LIST_INSERT_HEAD(&procglob[ALLPROC_HASH(sess->s_sid)].allsess,
			 sess, s_list);
}

/*
 * Process hold/release support functions.  Called via the PHOLD(),
 * PRELE(), and PSTALL() macros.
 *
 * p->p_lock is a simple hold count with a waiting interlock.  No wakeup()
 * is issued unless someone is actually waiting for the process.
 *
 * Most holds are short-term, allowing a process scan or other similar
 * operation to access a proc structure without it getting ripped out from
 * under us.  procfs and process-list sysctl ops also use the hold function
 * interlocked with various p_flags to keep the vmspace intact when reading
 * or writing a user process's address space.
 *
 * There are two situations where a hold count can be longer.  Exiting lwps
 * hold the process until the lwp is reaped, and the parent will hold the
 * child during vfork()/exec() sequences while the child is marked P_PPWAIT.
 *
 * The kernel waits for the hold count to drop to 0 (or 1 in some cases) at
 * various critical points in the fork/exec and exit paths before proceeding.
 */
#define PLOCK_WAITING	0x40000000	/* tsleep() on p_lock */
#define PLOCK_ZOMB	0x20000000	/* zombie interlock held */
#define PLOCK_WAITRES	0x10000000	/* wait reservation held */
#define PLOCK_MASK	0x0FFFFFFF

/*
 * Returns non-zero if the WAITRES flag has been set
 */
int
pwaitres_pending(struct proc *p)
{
	if (p->p_lock & PLOCK_WAITRES)
		return 1;
	return 0;
}

/*
 * Caller holds PLOCK_ZOMB.  Sets PLOCK_WAITRES and wakes up anyone in
 * pholdzomb() (which will fail).
 */
void
pwaitres_set(struct proc *p)
{
	int o;

	KKASSERT((p->p_lock & (PLOCK_ZOMB | PLOCK_WAITRES)) == PLOCK_ZOMB);
	o = p->p_lock;
	cpu_ccfence();
	for (;;) {
		if (atomic_fcmpset_int(&p->p_lock, &o,
				       (o | PLOCK_WAITRES) & ~PLOCK_WAITING)) {
			if (o & PLOCK_WAITING)
				wakeup(&p->p_lock);
			return;
		}
	}
}

void
pstall(struct proc *p, const char *wmesg, int count)
{
	int o;
	int n;

	for (;;) {
		o = p->p_lock;
		cpu_ccfence();
		if ((o & PLOCK_MASK) <= count)
			break;
		n = o | PLOCK_WAITING;
		tsleep_interlock(&p->p_lock, 0);

		/*
		 * If someone is trying to single-step the process during
		 * an exec or an exit they can deadlock us because procfs
		 * sleeps with the process held.
		 */
		if (p->p_stops) {
			if (p->p_flags & P_INEXEC) {
				wakeup(&p->p_stype);
			} else if (p->p_flags & P_POSTEXIT) {
				spin_lock(&p->p_spin);
				p->p_stops = 0;
				p->p_step = 0;
				spin_unlock(&p->p_spin);
				wakeup(&p->p_stype);
			}
		}

		if (atomic_cmpset_int(&p->p_lock, o, n)) {
			tsleep(&p->p_lock, PINTERLOCKED, wmesg, 0);
		}
	}
}

void
phold(struct proc *p)
{
	atomic_add_int(&p->p_lock, 1);
}

/*
 * WARNING!  On last release (p) can become instantly invalid due to
 *	     MP races.
 */
void
prele(struct proc *p)
{
	int o;
	int n;

	/*
	 * Fast path
	 */
	if (atomic_cmpset_int(&p->p_lock, 1, 0))
		return;

	/*
	 * Slow path
	 */
	for (;;) {
		o = p->p_lock;
		KKASSERT((o & PLOCK_MASK) > 0);
		cpu_ccfence();
		n = (o - 1) & ~PLOCK_WAITING;
		if (atomic_cmpset_int(&p->p_lock, o, n)) {
			if (o & PLOCK_WAITING)
				wakeup(&p->p_lock);
			break;
		}
	}
}

/*
 * Hold and flag serialized for zombie reaping purposes.  Fail if we had
 * to sleep or if another thread has reserved the reap (WAITRES).
 *
 * This function will fail if it has to block, returning non-zero with
 * neither the flag set or the hold count bumped.  Note that (p) may
 * not be valid in this case if the caller does not have some other
 * reference on (p).
 *
 * This function does not block on other PHOLD()s, only on other
 * PHOLDZOMB()s.
 *
 * Zero is returned on success.  The hold count will be incremented and
 * the serialization flag acquired.  Note that serialization is only against
 * other pholdzomb() calls, not against phold() calls.
 */
int
pholdzomb(struct proc *p)
{
	int o;
	int n;

	/*
	 * Fast path
	 */
	if (atomic_cmpset_int(&p->p_lock, 0, PLOCK_ZOMB | 1))
		return(0);

	/*
	 * Slow path
	 */
	for (;;) {
		o = p->p_lock;
		cpu_ccfence();
		if ((o & (PLOCK_ZOMB | PLOCK_WAITRES)) == 0) {
			n = (o + 1) | PLOCK_ZOMB;
			if (atomic_cmpset_int(&p->p_lock, o, n))
				return(0);
		} else if (o & PLOCK_WAITRES) {
			return(1);
		} else {
			KKASSERT((o & PLOCK_MASK) > 0);
			n = o | PLOCK_WAITING;
			tsleep_interlock(&p->p_lock, 0);
			if (atomic_cmpset_int(&p->p_lock, o, n)) {
				tsleep(&p->p_lock, PINTERLOCKED, "phldz", 0);
				/* (p) can be ripped out at this point */
				return(1);
			}
		}
	}
}

/*
 * Release PLOCK_ZOMB, PLOCK_WAITRES, and the hold count, waking up any
 * waiters.
 *
 * WARNING!  On last release (p) can become instantly invalid due to
 *	     MP races.
 */
void
prelezomb(struct proc *p)
{
	int o;
	int n;

	/*
	 * Fast path
	 */
	if (atomic_cmpset_int(&p->p_lock, PLOCK_ZOMB | 1, 0))
		return;

	/*
	 * Slow path
	 */
	KKASSERT(p->p_lock & PLOCK_ZOMB);
	for (;;) {
		o = p->p_lock;
		KKASSERT((o & PLOCK_MASK) > 0);
		cpu_ccfence();
		n = (o - 1) & ~(PLOCK_ZOMB | PLOCK_WAITING | PLOCK_WAITRES);
		if (atomic_cmpset_int(&p->p_lock, o, n)) {
			if (o & PLOCK_WAITING)
				wakeup(&p->p_lock);
			break;
		}
	}
}

/*
 * Is p an inferior of the current process?
 *
 * No requirements.
 */
int
inferior(struct proc *p)
{
	struct proc *p2;

	PHOLD(p);
	lwkt_gettoken_shared(&p->p_token);
	while (p != curproc) {
		if (p->p_pid == 0) {
			lwkt_reltoken(&p->p_token);
			return (0);
		}
		p2 = p->p_pptr;
		PHOLD(p2);
		lwkt_reltoken(&p->p_token);
		PRELE(p);
		lwkt_gettoken_shared(&p2->p_token);
		p = p2;
	}
	lwkt_reltoken(&p->p_token);
	PRELE(p);

	return (1);
}

/*
 * Locate a process by number.  The returned process will be referenced and
 * must be released with PRELE().
 *
 * No requirements.
 */
struct proc *
pfind(pid_t pid)
{
	struct proc *p = curproc;
	procglob_t *prg;
	int n;

	/*
	 * Shortcut the current process
	 */
	if (p && p->p_pid == pid) {
		PHOLD(p);
		return (p);
	}

	/*
	 * Otherwise find it in the hash table.
	 */
	n = ALLPROC_HASH(pid);
	prg = &procglob[n];

	lwkt_gettoken_shared(&prg->proc_token);
	LIST_FOREACH(p, &prg->allproc, p_list) {
		if (p->p_stat == SZOMB)
			continue;
		if (p->p_pid == pid) {
			PHOLD(p);
			lwkt_reltoken(&prg->proc_token);
			return (p);
		}
	}
	lwkt_reltoken(&prg->proc_token);

	return (NULL);
}

/*
 * Locate a process by number.  The returned process is NOT referenced.
 * The result will not be stable and is typically only used to validate
 * against a process that the caller has in-hand.
 *
 * No requirements.
 */
struct proc *
pfindn(pid_t pid)
{
	struct proc *p = curproc;
	procglob_t *prg;
	int n;

	/*
	 * Shortcut the current process
	 */
	if (p && p->p_pid == pid)
		return (p);

	/*
	 * Otherwise find it in the hash table.
	 */
	n = ALLPROC_HASH(pid);
	prg = &procglob[n];

	lwkt_gettoken_shared(&prg->proc_token);
	LIST_FOREACH(p, &prg->allproc, p_list) {
		if (p->p_stat == SZOMB)
			continue;
		if (p->p_pid == pid) {
			lwkt_reltoken(&prg->proc_token);
			return (p);
		}
	}
	lwkt_reltoken(&prg->proc_token);

	return (NULL);
}

/*
 * Locate a process on the zombie list.  Return a process or NULL.
 * The returned process will be referenced and the caller must release
 * it with PRELE().
 *
 * No other requirements.
 */
struct proc *
zpfind(pid_t pid)
{
	struct proc *p = curproc;
	procglob_t *prg;
	int n;

	/*
	 * Shortcut the current process
	 */
	if (p && p->p_pid == pid) {
		PHOLD(p);
		return (p);
	}

	/*
	 * Otherwise find it in the hash table.
	 */
	n = ALLPROC_HASH(pid);
	prg = &procglob[n];

	lwkt_gettoken_shared(&prg->proc_token);
	LIST_FOREACH(p, &prg->allproc, p_list) {
		if (p->p_stat != SZOMB)
			continue;
		if (p->p_pid == pid) {
			PHOLD(p);
			lwkt_reltoken(&prg->proc_token);
			return (p);
		}
	}
	lwkt_reltoken(&prg->proc_token);

	return (NULL);
}

/*
 * Caller must hold the process token shared or exclusive.
 * The returned lwp, if not NULL, will be held.  Caller must
 * LWPRELE() it when done.
 */
struct lwp *
lwpfind(struct proc *p, lwpid_t tid)
{
	struct lwp *lp;

	lp = lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, tid);
	if (lp)
		LWPHOLD(lp);
	return lp;
}

void
pgref(struct pgrp *pgrp)
{
	refcount_acquire(&pgrp->pg_refs);
}

void
pgrel(struct pgrp *pgrp)
{
	procglob_t *prg;
	int count;
	int n;

	n = PGRP_HASH(pgrp->pg_id);
	prg = &procglob[n];

	for (;;) {
		count = pgrp->pg_refs;
		cpu_ccfence();
		KKASSERT(count > 0);
		if (count == 1) {
			lwkt_gettoken(&prg->proc_token);
			if (atomic_cmpset_int(&pgrp->pg_refs, 1, 0))
				break;
			lwkt_reltoken(&prg->proc_token);
			/* retry */
		} else {
			if (atomic_cmpset_int(&pgrp->pg_refs, count, count - 1))
				return;
			/* retry */
		}
	}

	/*
	 * Successful 1->0 transition, pghash_spin is held.
	 */
	LIST_REMOVE(pgrp, pg_list);
	if (pid_doms[pgrp->pg_id % PIDSEL_DOMAINS] != (uint8_t)time_second)
		pid_doms[pgrp->pg_id % PIDSEL_DOMAINS] = (uint8_t)time_second;

	/*
	 * Reset any sigio structures pointing to us as a result of
	 * F_SETOWN with our pgid.
	 */
	funsetownlst(&pgrp->pg_sigiolst);

	if (pgrp->pg_session->s_ttyp != NULL &&
	    pgrp->pg_session->s_ttyp->t_pgrp == pgrp) {
		pgrp->pg_session->s_ttyp->t_pgrp = NULL;
	}
	lwkt_reltoken(&prg->proc_token);

	sess_rele(pgrp->pg_session);
	kfree(pgrp, M_PGRP);
}

/*
 * Locate a process group by number.  The returned process group will be
 * referenced w/pgref() and must be released with pgrel() (or assigned
 * somewhere if you wish to keep the reference).
 *
 * No requirements.
 */
struct pgrp *
pgfind(pid_t pgid)
{
	struct pgrp *pgrp;
	procglob_t *prg;
	int n;

	n = PGRP_HASH(pgid);
	prg = &procglob[n];
	lwkt_gettoken_shared(&prg->proc_token);

	LIST_FOREACH(pgrp, &prg->allpgrp, pg_list) {
		if (pgrp->pg_id == pgid) {
			refcount_acquire(&pgrp->pg_refs);
			lwkt_reltoken(&prg->proc_token);
			return (pgrp);
		}
	}
	lwkt_reltoken(&prg->proc_token);
	return (NULL);
}

/*
 * Move p to a new or existing process group (and session)
 *
 * No requirements.
 */
int
enterpgrp(struct proc *p, pid_t pgid, int mksess)
{
	struct pgrp *pgrp;
	struct pgrp *opgrp;
	int error;

	pgrp = pgfind(pgid);

	KASSERT(pgrp == NULL || !mksess,
		("enterpgrp: setsid into non-empty pgrp"));
	KASSERT(!SESS_LEADER(p),
		("enterpgrp: session leader attempted setpgrp"));

	if (pgrp == NULL) {
		pid_t savepid = p->p_pid;
		struct proc *np;
		procglob_t *prg;
		int n;

		/*
		 * new process group
		 */
		KASSERT(p->p_pid == pgid,
			("enterpgrp: new pgrp and pid != pgid"));
		pgrp = kmalloc(sizeof(struct pgrp), M_PGRP, M_WAITOK | M_ZERO);
		pgrp->pg_id = pgid;
		LIST_INIT(&pgrp->pg_members);
		pgrp->pg_jobc = 0;
		SLIST_INIT(&pgrp->pg_sigiolst);
		lwkt_token_init(&pgrp->pg_token, "pgrp_token");
		refcount_init(&pgrp->pg_refs, 1);
		lockinit(&pgrp->pg_lock, "pgwt", 0, 0);

		n = PGRP_HASH(pgid);
		prg = &procglob[n];

		if ((np = pfindn(savepid)) == NULL || np != p) {
			lwkt_reltoken(&prg->proc_token);
			error = ESRCH;
			kfree(pgrp, M_PGRP);
			goto fatal;
		}

		lwkt_gettoken(&prg->proc_token);
		if (mksess) {
			struct session *sess;

			/*
			 * new session
			 */
			sess = kmalloc(sizeof(struct session), M_SESSION,
				       M_WAITOK | M_ZERO);
			lwkt_gettoken(&p->p_token);
			sess->s_prg = prg;
			sess->s_leader = p;
			sess->s_sid = p->p_pid;
			sess->s_count = 1;
			sess->s_ttyvp = NULL;
			sess->s_ttyp = NULL;
			bcopy(p->p_session->s_login, sess->s_login,
			      sizeof(sess->s_login));
			pgrp->pg_session = sess;
			KASSERT(p == curproc,
				("enterpgrp: mksession and p != curproc"));
			p->p_flags &= ~P_CONTROLT;
			LIST_INSERT_HEAD(&prg->allsess, sess, s_list);
			lwkt_reltoken(&p->p_token);
		} else {
			lwkt_gettoken(&p->p_token);
			pgrp->pg_session = p->p_session;
			sess_hold(pgrp->pg_session);
			lwkt_reltoken(&p->p_token);
		}
		LIST_INSERT_HEAD(&prg->allpgrp, pgrp, pg_list);

		lwkt_reltoken(&prg->proc_token);
	} else if (pgrp == p->p_pgrp) {
		pgrel(pgrp);
		goto done;
	} /* else pgfind() referenced the pgrp */

	lwkt_gettoken(&pgrp->pg_token);
	lwkt_gettoken(&p->p_token);

	/*
	 * Replace p->p_pgrp, handling any races that occur.
	 */
	while ((opgrp = p->p_pgrp) != NULL) {
		pgref(opgrp);
		lwkt_gettoken(&opgrp->pg_token);
		if (opgrp != p->p_pgrp) {
			lwkt_reltoken(&opgrp->pg_token);
			pgrel(opgrp);
			continue;
		}
		LIST_REMOVE(p, p_pglist);
		break;
	}
	p->p_pgrp = pgrp;
	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);

	/*
	 * Adjust eligibility of affected pgrps to participate in job control.
	 * Increment eligibility counts before decrementing, otherwise we
	 * could reach 0 spuriously during the first call.
	 */
	fixjobc(p, pgrp, 1);
	if (opgrp) {
		fixjobc(p, opgrp, 0);
		lwkt_reltoken(&opgrp->pg_token);
		pgrel(opgrp);	/* manual pgref */
		pgrel(opgrp);	/* p->p_pgrp ref */
	}
	lwkt_reltoken(&p->p_token);
	lwkt_reltoken(&pgrp->pg_token);
done:
	error = 0;
fatal:
	return (error);
}

/*
 * Remove process from process group
 *
 * No requirements.
 */
int
leavepgrp(struct proc *p)
{
	struct pgrp *pg = p->p_pgrp;

	lwkt_gettoken(&p->p_token);
	while ((pg = p->p_pgrp) != NULL) {
		pgref(pg);
		lwkt_gettoken(&pg->pg_token);
		if (p->p_pgrp != pg) {
			lwkt_reltoken(&pg->pg_token);
			pgrel(pg);
			continue;
		}
		p->p_pgrp = NULL;
		LIST_REMOVE(p, p_pglist);
		lwkt_reltoken(&pg->pg_token);
		pgrel(pg);	/* manual pgref */
		pgrel(pg);	/* p->p_pgrp ref */
		break;
	}
	lwkt_reltoken(&p->p_token);

	return (0);
}

/*
 * Adjust the ref count on a session structure.  When the ref count falls to
 * zero the tty is disassociated from the session and the session structure
 * is freed.  Note that tty assocation is not itself ref-counted.
 *
 * No requirements.
 */
void
sess_hold(struct session *sp)
{
	atomic_add_int(&sp->s_count, 1);
}

/*
 * No requirements.
 */
void
sess_rele(struct session *sess)
{
	procglob_t *prg;
	struct tty *tp;
	int count;
	int n;

	n = SESS_HASH(sess->s_sid);
	prg = &procglob[n];

	for (;;) {
		count = sess->s_count;
		cpu_ccfence();
		KKASSERT(count > 0);
		if (count == 1) {
			lwkt_gettoken(&prg->proc_token);
			if (atomic_cmpset_int(&sess->s_count, 1, 0))
				break;
			lwkt_reltoken(&prg->proc_token);
			/* retry */
		} else {
			if (atomic_cmpset_int(&sess->s_count, count, count - 1))
				return;
			/* retry */
		}
	}

	/*
	 * Successful 1->0 transition and prg->proc_token is held.
	 */
	LIST_REMOVE(sess, s_list);
	if (pid_doms[sess->s_sid % PIDSEL_DOMAINS] != (uint8_t)time_second)
		pid_doms[sess->s_sid % PIDSEL_DOMAINS] = (uint8_t)time_second;

	if (sess->s_ttyp && sess->s_ttyp->t_session) {
#ifdef TTY_DO_FULL_CLOSE
		/* FULL CLOSE, see ttyclearsession() */
		KKASSERT(sess->s_ttyp->t_session == sess);
		sess->s_ttyp->t_session = NULL;
#else
		/* HALF CLOSE, see ttyclearsession() */
		if (sess->s_ttyp->t_session == sess)
			sess->s_ttyp->t_session = NULL;
#endif
	}
	if ((tp = sess->s_ttyp) != NULL) {
		sess->s_ttyp = NULL;
		ttyunhold(tp);
	}
	lwkt_reltoken(&prg->proc_token);

	kfree(sess, M_SESSION);
}

/*
 * Adjust pgrp jobc counters when specified process changes process group.
 * We count the number of processes in each process group that "qualify"
 * the group for terminal job control (those with a parent in a different
 * process group of the same session).  If that count reaches zero, the
 * process group becomes orphaned.  Check both the specified process'
 * process group and that of its children.
 * entering == 0 => p is leaving specified group.
 * entering == 1 => p is entering specified group.
 *
 * No requirements.
 */
void
fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
{
	struct pgrp *hispgrp;
	struct session *mysession;
	struct proc *np;

	/*
	 * Check p's parent to see whether p qualifies its own process
	 * group; if so, adjust count for p's process group.
	 */
	lwkt_gettoken(&p->p_token);	/* p_children scan */
	lwkt_gettoken(&pgrp->pg_token);

	mysession = pgrp->pg_session;
	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
	    hispgrp->pg_session == mysession) {
		if (entering)
			pgrp->pg_jobc++;
		else if (--pgrp->pg_jobc == 0)
			orphanpg(pgrp);
	}

	/*
	 * Check this process' children to see whether they qualify
	 * their process groups; if so, adjust counts for children's
	 * process groups.
	 */
	LIST_FOREACH(np, &p->p_children, p_sibling) {
		PHOLD(np);
		lwkt_gettoken(&np->p_token);
		if ((hispgrp = np->p_pgrp) != pgrp &&
		    hispgrp->pg_session == mysession &&
		    np->p_stat != SZOMB) {
			pgref(hispgrp);
			lwkt_gettoken(&hispgrp->pg_token);
			if (entering)
				hispgrp->pg_jobc++;
			else if (--hispgrp->pg_jobc == 0)
				orphanpg(hispgrp);
			lwkt_reltoken(&hispgrp->pg_token);
			pgrel(hispgrp);
		}
		lwkt_reltoken(&np->p_token);
		PRELE(np);
	}
	KKASSERT(pgrp->pg_refs > 0);
	lwkt_reltoken(&pgrp->pg_token);
	lwkt_reltoken(&p->p_token);
}

/*
 * A process group has become orphaned;
 * if there are any stopped processes in the group,
 * hang-up all process in that group.
 *
 * The caller must hold pg_token.
 */
static void
orphanpg(struct pgrp *pg)
{
	struct proc *p;

	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
		if (p->p_stat == SSTOP) {
			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
				ksignal(p, SIGHUP);
				ksignal(p, SIGCONT);
			}
			return;
		}
	}
}

/*
 * Add a new process to the allproc list and the PID hash.  This
 * also assigns a pid to the new process.
 *
 * No requirements.
 */
void
proc_add_allproc(struct proc *p)
{
	int random_offset;

	if ((random_offset = randompid) != 0) {
		read_random(&random_offset, sizeof(random_offset), 1);
		random_offset = (random_offset & 0x7FFFFFFF) % randompid;
	}
	proc_makepid(p, random_offset);
}

/*
 * Calculate a new process pid.  This function is integrated into
 * proc_add_allproc() to guarentee that the new pid is not reused before
 * the new process can be added to the allproc list.
 *
 * p_pid is assigned and the process is added to the allproc hash table
 *
 * WARNING! We need to allocate PIDs sequentially during early boot.
 *	    In particular, init needs to have a pid of 1.
 */
static
void
proc_makepid(struct proc *p, int random_offset)
{
	static pid_t nextpid = 1;	/* heuristic, allowed to race */
	procglob_t *prg;
	struct pgrp *pg;
	struct proc *ps;
	struct session *sess;
	pid_t base;
	int8_t delta8;
	int retries;
	int n;

	/*
	 * Select the next pid base candidate.
	 *
	 * Check cyclement, do not allow a pid < 100.
	 */
	retries = 0;
retry:
	base = atomic_fetchadd_int(&nextpid, 1) + random_offset;
	if (base <= 0 || base >= PID_MAX) {
		base = base % PID_MAX;
		if (base < 0)
			base = 100;
		if (base < 100)
			base += 100;
		nextpid = base;		/* reset (SMP race ok) */
	}

	/*
	 * Do not allow a base pid to be selected from a domain that has
	 * recently seen a pid/pgid/sessid reap.  Sleep a little if we looped
	 * through all available domains.
	 *
	 * WARNING: We want the early pids to be allocated linearly,
	 *	    particularly pid 1 and pid 2.
	 */
	if (++retries >= PIDSEL_DOMAINS)
		tsleep(&nextpid, 0, "makepid", 1);
	if (base >= 100) {
		delta8 = (int8_t)time_second -
			 (int8_t)pid_doms[base % PIDSEL_DOMAINS];
		if (delta8 >= 0 && delta8 <= PIDDOM_DELAY) {
			++pid_domain_skips;
			goto retry;
		}
	}

	/*
	 * Calculate a hash index and find an unused process id within
	 * the table, looping if we cannot find one.
	 *
	 * The inner loop increments by ALLPROC_HSIZE which keeps the
	 * PID at the same pid_doms[] index as well as the same hash index.
	 */
	n = ALLPROC_HASH(base);
	prg = &procglob[n];
	lwkt_gettoken(&prg->proc_token);

restart1:
	LIST_FOREACH(ps, &prg->allproc, p_list) {
		if (ps->p_pid == base) {
			base += ALLPROC_HSIZE;
			if (base >= PID_MAX) {
				lwkt_reltoken(&prg->proc_token);
				goto retry;
			}
			++pid_inner_skips;
			goto restart1;
		}
	}
	LIST_FOREACH(pg, &prg->allpgrp, pg_list) {
		if (pg->pg_id == base) {
			base += ALLPROC_HSIZE;
			if (base >= PID_MAX) {
				lwkt_reltoken(&prg->proc_token);
				goto retry;
			}
			++pid_inner_skips;
			goto restart1;
		}
	}
	LIST_FOREACH(sess, &prg->allsess, s_list) {
		if (sess->s_sid == base) {
			base += ALLPROC_HSIZE;
			if (base >= PID_MAX) {
				lwkt_reltoken(&prg->proc_token);
				goto retry;
			}
			++pid_inner_skips;
			goto restart1;
		}
	}

	/*
	 * Assign the pid and insert the process.
	 */
	p->p_pid = base;
	LIST_INSERT_HEAD(&prg->allproc, p, p_list);
	lwkt_reltoken(&prg->proc_token);
}

/*
 * Called from exit1 to place the process into a zombie state.
 * The process is removed from the pid hash and p_stat is set
 * to SZOMB.  Normal pfind[n]() calls will not find it any more.
 *
 * Caller must hold p->p_token.  We are required to wait until p_lock
 * becomes zero before we can manipulate the list, allowing allproc
 * scans to guarantee consistency during a list scan.
 */
void
proc_move_allproc_zombie(struct proc *p)
{
	procglob_t *prg;
	int n;

	n = ALLPROC_HASH(p->p_pid);
	prg = &procglob[n];
	PSTALL(p, "reap1", 0);
	lwkt_gettoken(&prg->proc_token);

	PSTALL(p, "reap1a", 0);
	p->p_stat = SZOMB;

	lwkt_reltoken(&prg->proc_token);
	dsched_exit_proc(p);
}

/*
 * This routine is called from kern_wait() and will remove the process
 * from the zombie list and the sibling list.  This routine will block
 * if someone has a lock on the proces (p_lock).
 *
 * Caller must hold p->p_token.  We are required to wait until p_lock
 * becomes one before we can manipulate the list, allowing allproc
 * scans to guarantee consistency during a list scan.
 *
 * Assumes caller has one ref.
 */
void
proc_remove_zombie(struct proc *p)
{
	procglob_t *prg;
	int n;

	n = ALLPROC_HASH(p->p_pid);
	prg = &procglob[n];

	PSTALL(p, "reap2", 1);
	lwkt_gettoken(&prg->proc_token);
	PSTALL(p, "reap2a", 1);
	LIST_REMOVE(p, p_list);		/* from remove master list */
	LIST_REMOVE(p, p_sibling);	/* and from sibling list */
	p->p_pptr = NULL;
	p->p_ppid = 0;
	if (pid_doms[p->p_pid % PIDSEL_DOMAINS] != (uint8_t)time_second)
		pid_doms[p->p_pid % PIDSEL_DOMAINS] = (uint8_t)time_second;
	lwkt_reltoken(&prg->proc_token);
}

/*
 * Handle various requirements prior to returning to usermode.  Called from
 * platform trap and system call code.
 */
void
lwpuserret(struct lwp *lp)
{
	struct proc *p = lp->lwp_proc;

	if (lp->lwp_mpflags & LWP_MP_VNLRU) {
		atomic_clear_int(&lp->lwp_mpflags, LWP_MP_VNLRU);
		allocvnode_gc();
	}
	if (lp->lwp_mpflags & LWP_MP_WEXIT) {
		lwkt_gettoken(&p->p_token);
		lwp_exit(0, NULL);
		lwkt_reltoken(&p->p_token);     /* NOT REACHED */
	}
}

/*
 * Kernel threads run from user processes can also accumulate deferred
 * actions which need to be acted upon.  Callers include:
 *
 * nfsd		- Can allocate lots of vnodes
 */
void
lwpkthreaddeferred(void)
{
	struct lwp *lp = curthread->td_lwp;

	if (lp) {
		if (lp->lwp_mpflags & LWP_MP_VNLRU) {
			atomic_clear_int(&lp->lwp_mpflags, LWP_MP_VNLRU);
			allocvnode_gc();
		}
	}
}

void
proc_usermap(struct proc *p, int invfork)
{
	struct sys_upmap *upmap;

	lwkt_gettoken(&p->p_token);
	upmap = kmalloc(roundup2(sizeof(*upmap), PAGE_SIZE), M_UPMAP,
			M_WAITOK | M_ZERO);
	if (p->p_upmap == NULL && (p->p_flags & P_POSTEXIT) == 0) {
		upmap->header[0].type = UKPTYPE_VERSION;
		upmap->header[0].offset = offsetof(struct sys_upmap, version);
		upmap->header[1].type = UPTYPE_RUNTICKS;
		upmap->header[1].offset = offsetof(struct sys_upmap, runticks);
		upmap->header[2].type = UPTYPE_FORKID;
		upmap->header[2].offset = offsetof(struct sys_upmap, forkid);
		upmap->header[3].type = UPTYPE_PID;
		upmap->header[3].offset = offsetof(struct sys_upmap, pid);
		upmap->header[4].type = UPTYPE_PROC_TITLE;
		upmap->header[4].offset = offsetof(struct sys_upmap,proc_title);
		upmap->header[5].type = UPTYPE_INVFORK;
		upmap->header[5].offset = offsetof(struct sys_upmap, invfork);

		upmap->version = UPMAP_VERSION;
		upmap->pid = p->p_pid;
		upmap->forkid = p->p_forkid;
		upmap->invfork = invfork;
		p->p_upmap = upmap;
	} else {
		kfree(upmap, M_UPMAP);
	}
	lwkt_reltoken(&p->p_token);
}

void
proc_userunmap(struct proc *p)
{
	struct sys_upmap *upmap;

	lwkt_gettoken(&p->p_token);
	if ((upmap = p->p_upmap) != NULL) {
		p->p_upmap = NULL;
		kfree(upmap, M_UPMAP);
	}
	lwkt_reltoken(&p->p_token);
}

/*
 * Called when the per-thread user/kernel shared page needs to be
 * allocated.  The function refuses to allocate the page if the
 * thread is exiting to avoid races against lwp_userunmap().
 */
void
lwp_usermap(struct lwp *lp, int invfork)
{
	struct sys_lpmap *lpmap;

	lwkt_gettoken(&lp->lwp_token);

	lpmap = kmalloc(roundup2(sizeof(*lpmap), PAGE_SIZE), M_UPMAP,
			M_WAITOK | M_ZERO);
	if (lp->lwp_lpmap == NULL && (lp->lwp_mpflags & LWP_MP_WEXIT) == 0) {
		lpmap->header[0].type = UKPTYPE_VERSION;
		lpmap->header[0].offset = offsetof(struct sys_lpmap, version);
		lpmap->header[1].type = LPTYPE_BLOCKALLSIGS;
		lpmap->header[1].offset = offsetof(struct sys_lpmap,
						   blockallsigs);
		lpmap->header[2].type = LPTYPE_THREAD_TITLE;
		lpmap->header[2].offset = offsetof(struct sys_lpmap,
						   thread_title);
		lpmap->header[3].type = LPTYPE_THREAD_TID;
		lpmap->header[3].offset = offsetof(struct sys_lpmap, tid);

		lpmap->version = LPMAP_VERSION;
		lpmap->tid = lp->lwp_tid;
		lp->lwp_lpmap = lpmap;
	} else {
		kfree(lpmap, M_UPMAP);
	}
	lwkt_reltoken(&lp->lwp_token);
}

/*
 * Called when a LWP (but not necessarily the whole process) exits.
 * Called when a process execs (after all other threads have been killed).
 *
 * lwp-specific mappings must be removed.  If userland didn't do it, then
 * we have to.  Otherwise we could end-up disclosing kernel memory due to
 * the ad-hoc pmap mapping.
 */
void
lwp_userunmap(struct lwp *lp)
{
	struct sys_lpmap *lpmap;
	struct vm_map *map;
	struct vm_map_backing *ba;
	struct vm_map_backing copy;

	lwkt_gettoken(&lp->lwp_token);
	map = &lp->lwp_proc->p_vmspace->vm_map;
	lpmap = lp->lwp_lpmap;
	lp->lwp_lpmap = NULL;

	spin_lock(&lp->lwp_spin);
	while ((ba = TAILQ_FIRST(&lp->lwp_lpmap_backing_list)) != NULL) {
		copy = *ba;
		spin_unlock(&lp->lwp_spin);

		lwkt_gettoken(&map->token);
		vm_map_remove(map, copy.start, copy.end);
		lwkt_reltoken(&map->token);

		spin_lock(&lp->lwp_spin);
	}
	spin_unlock(&lp->lwp_spin);

	if (lpmap)
		kfree(lpmap, M_UPMAP);
	lwkt_reltoken(&lp->lwp_token);
}

/*
 * Scan all processes on the allproc list.  The process is automatically
 * held for the callback.  A return value of -1 terminates the loop.
 * Zombie procs are skipped.
 *
 * The callback is made with the process held and proc_token held.
 *
 * We limit the scan to the number of processes as-of the start of
 * the scan so as not to get caught up in an endless loop if new processes
 * are created more quickly than we can scan the old ones.  Add a little
 * slop to try to catch edge cases since nprocs can race.
 *
 * No requirements.
 */
void
allproc_scan(int (*callback)(struct proc *, void *), void *data, int segmented)
{
	int limit = nprocs + ncpus;
	struct proc *p;
	int ns;
	int ne;
	int r;
	int n;

	if (segmented) {
		int id = mycpu->gd_cpuid;
		ns = id * ALLPROC_HSIZE / ncpus;
		ne = (id + 1) * ALLPROC_HSIZE / ncpus;
	} else {
		ns = 0;
		ne = ALLPROC_HSIZE;
	}

	/*
	 * prg->proc_token protects the allproc list and PHOLD() prevents the
	 * process from being removed from the allproc list or the zombproc
	 * list.
	 */
	for (n = ns; n < ne; ++n) {
		procglob_t *prg = &procglob[n];
		if (LIST_FIRST(&prg->allproc) == NULL)
			continue;
		lwkt_gettoken(&prg->proc_token);
		LIST_FOREACH(p, &prg->allproc, p_list) {
			if (p->p_stat == SZOMB)
				continue;
			PHOLD(p);
			r = callback(p, data);
			PRELE(p);
			if (r < 0)
				break;
			if (--limit < 0)
				break;
		}
		lwkt_reltoken(&prg->proc_token);

		/*
		 * Check if asked to stop early
		 */
		if (p)
			break;
	}
}

/*
 * Scan all lwps of processes on the allproc list.  The lwp is automatically
 * held for the callback.  A return value of -1 terminates the loop.
 *
 * The callback is made with the proces and lwp both held, and proc_token held.
 *
 * No requirements.
 */
void
alllwp_scan(int (*callback)(struct lwp *, void *), void *data, int segmented)
{
	struct proc *p;
	struct lwp *lp;
	int ns;
	int ne;
	int r = 0;
	int n;

	if (segmented) {
		int id = mycpu->gd_cpuid;
		ns = id * ALLPROC_HSIZE / ncpus;
		ne = (id + 1) * ALLPROC_HSIZE / ncpus;
	} else {
		ns = 0;
		ne = ALLPROC_HSIZE;
	}

	for (n = ns; n < ne; ++n) {
		procglob_t *prg = &procglob[n];

		if (LIST_FIRST(&prg->allproc) == NULL)
			continue;
		lwkt_gettoken(&prg->proc_token);
		LIST_FOREACH(p, &prg->allproc, p_list) {
			if (p->p_stat == SZOMB)
				continue;
			PHOLD(p);
			lwkt_gettoken(&p->p_token);
			FOREACH_LWP_IN_PROC(lp, p) {
				LWPHOLD(lp);
				r = callback(lp, data);
				LWPRELE(lp);
			}
			lwkt_reltoken(&p->p_token);
			PRELE(p);
			if (r < 0)
				break;
		}
		lwkt_reltoken(&prg->proc_token);

		/*
		 * Asked to exit early
		 */
		if (p)
			break;
	}
}

/*
 * Scan all processes on the zombproc list.  The process is automatically
 * held for the callback.  A return value of -1 terminates the loop.
 *
 * No requirements.
 * The callback is made with the proces held and proc_token held.
 */
void
zombproc_scan(int (*callback)(struct proc *, void *), void *data)
{
	struct proc *p;
	int r;
	int n;

	/*
	 * prg->proc_token protects the allproc list and PHOLD() prevents the
	 * process from being removed from the allproc list or the zombproc
	 * list.
	 */
	for (n = 0; n < ALLPROC_HSIZE; ++n) {
		procglob_t *prg = &procglob[n];

		if (LIST_FIRST(&prg->allproc) == NULL)
			continue;
		lwkt_gettoken(&prg->proc_token);
		LIST_FOREACH(p, &prg->allproc, p_list) {
			if (p->p_stat != SZOMB)
				continue;
			PHOLD(p);
			r = callback(p, data);
			PRELE(p);
			if (r < 0)
				break;
		}
		lwkt_reltoken(&prg->proc_token);

		/*
		 * Check if asked to stop early
		 */
		if (p)
			break;
	}
}

#include "opt_ddb.h"
#ifdef DDB
#include <ddb/ddb.h>

/*
 * Debugging only
 */
DB_SHOW_COMMAND(pgrpdump, pgrpdump)
{
	struct pgrp *pgrp;
	struct proc *p;
	procglob_t *prg;
	int i;

	for (i = 0; i < ALLPROC_HSIZE; ++i) {
		prg = &procglob[i];

		if (LIST_EMPTY(&prg->allpgrp))
			continue;
		kprintf("\tindx %d\n", i);
		LIST_FOREACH(pgrp, &prg->allpgrp, pg_list) {
			kprintf("\tpgrp %p, pgid %ld, sess %p, "
				"sesscnt %d, mem %p\n",
				(void *)pgrp, (long)pgrp->pg_id,
				(void *)pgrp->pg_session,
				pgrp->pg_session->s_count,
				(void *)LIST_FIRST(&pgrp->pg_members));
			LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
				kprintf("\t\tpid %ld addr %p pgrp %p\n",
					(long)p->p_pid, (void *)p,
					(void *)p->p_pgrp);
			}
		}
	}
}
#endif /* DDB */

/*
 * The caller must hold proc_token.
 */
static int
sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
{
	struct kinfo_proc ki;
	struct lwp *lp;
	int skip_lwp = 0;
	int had_output = 0;
	int error;

	bzero(&ki, sizeof(ki));
	lwkt_gettoken_shared(&p->p_token);
	fill_kinfo_proc(p, &ki);
	if ((flags & KERN_PROC_FLAG_LWP) == 0)
		skip_lwp = 1;
	error = 0;
	FOREACH_LWP_IN_PROC(lp, p) {
		LWPHOLD(lp);
		fill_kinfo_lwp(lp, &ki.kp_lwp);
		had_output = 1;
		if (skip_lwp == 0) {
			error = SYSCTL_OUT(req, &ki, sizeof(ki));
			bzero(&ki.kp_lwp, sizeof(ki.kp_lwp));
		}
		LWPRELE(lp);
		if (error)
			break;
	}
	lwkt_reltoken(&p->p_token);

	/*
	 * If aggregating threads, set the tid field to -1.
	 */
	if (skip_lwp)
		ki.kp_lwp.kl_tid = -1;

	/*
	 * We need to output at least the proc, even if there is no lwp.
	 * If skip_lwp is non-zero we aggregated the lwps and need to output
	 * the result.
	 */
	if (had_output == 0 || skip_lwp) {
		error = SYSCTL_OUT(req, &ki, sizeof(ki));
	}
	return (error);
}

/*
 * The caller must hold proc_token.
 */
static int
sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req)
{
	struct kinfo_proc ki;
	int error;

	fill_kinfo_proc_kthread(td, &ki);
	error = SYSCTL_OUT(req, &ki, sizeof(ki));

	return (error);
}

/*
 * No requirements.
 */
static int
sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
{
	int *name = (int *)arg1;
	int oid = oidp->oid_number;
	u_int namelen = arg2;
	struct proc *p;
	struct thread *td;
	struct thread *marker;
	int flags = 0;
	int error = 0;
	int n;
	int origcpu;
	struct ucred *cr1 = curproc->p_ucred;
	struct ucred *crcache = NULL;

	flags = oid & KERN_PROC_FLAGMASK;
	oid &= ~KERN_PROC_FLAGMASK;

	if ((oid == KERN_PROC_ALL && namelen != 0) ||
	    (oid != KERN_PROC_ALL && namelen != 1))
	{
		return (EINVAL);
	}

	/*
	 * proc_token protects the allproc list and PHOLD() prevents the
	 * process from being removed from the allproc list or the zombproc
	 * list.
	 */
	if (oid == KERN_PROC_PID) {
		p = pfind((pid_t)name[0]);
		if (p) {
			crcache = pcredcache(crcache, p);
			if (PRISON_CHECK(cr1, crcache))
				error = sysctl_out_proc(p, req, flags);
			PRELE(p);
		}
		goto post_threads;
	}
	p = NULL;

	if (!req->oldptr) {
		/* overestimate by 5 procs */
		error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
		if (error)
			goto post_threads;
	}

	for (n = 0; n < ALLPROC_HSIZE; ++n) {
		procglob_t *prg = &procglob[n];

		if (LIST_EMPTY(&prg->allproc))
			continue;
		lwkt_gettoken_shared(&prg->proc_token);
		LIST_FOREACH(p, &prg->allproc, p_list) {
			/*
			 * Show a user only their processes.
			 */
			if (ps_showallprocs == 0) {
				crcache = pcredcache(crcache, p);
				if (crcache == NULL ||
				    p_trespass(cr1, crcache)) {
					continue;
				}
			}

			/*
			 * Skip embryonic processes.
			 */
			if (p->p_stat == SIDL)
				continue;

			/*
			 * TODO - make more efficient (see notes below).
			 * do by session.
			 */
			switch (oid) {
			case KERN_PROC_PGRP:
				/* could do this by traversing pgrp */
				if (p->p_pgrp == NULL || 
				    p->p_pgrp->pg_id != (pid_t)name[0])
					continue;
				break;

			case KERN_PROC_TTY:
				if ((p->p_flags & P_CONTROLT) == 0 ||
				    p->p_session == NULL ||
				    p->p_session->s_ttyp == NULL ||
				    devid_from_dev(p->p_session->s_ttyp->t_dev) !=
					(dev_t)name[0])
					continue;
				break;

			case KERN_PROC_UID:
				crcache = pcredcache(crcache, p);
				if (crcache == NULL ||
				    crcache->cr_uid != (uid_t)name[0]) {
					continue;
				}
				break;

			case KERN_PROC_RUID:
				crcache = pcredcache(crcache, p);
				if (crcache == NULL ||
				    crcache->cr_ruid != (uid_t)name[0]) {
					continue;
				}
				break;
			}

			crcache = pcredcache(crcache, p);
			if (!PRISON_CHECK(cr1, crcache))
				continue;
			PHOLD(p);
			error = sysctl_out_proc(p, req, flags);
			PRELE(p);
			if (error) {
				lwkt_reltoken(&prg->proc_token);
				goto post_threads;
			}
		}
		lwkt_reltoken(&prg->proc_token);
	}

	/*
	 * Iterate over all active cpus and scan their thread list.  Start
	 * with the next logical cpu and end with our original cpu.  We
	 * migrate our own thread to each target cpu in order to safely scan
	 * its thread list.  In the last loop we migrate back to our original
	 * cpu.
	 */
	origcpu = mycpu->gd_cpuid;
	if (!ps_showallthreads || jailed(cr1))
		goto post_threads;

	marker = kmalloc(sizeof(struct thread), M_TEMP, M_WAITOK|M_ZERO);
	marker->td_flags = TDF_MARKER;
	error = 0;

	for (n = 1; (flags & KERN_PROC_FLAG_LWKT) && n <= ncpus; ++n) {
		globaldata_t rgd;
		int nid;

		nid = (origcpu + n) % ncpus;
		if (CPUMASK_TESTBIT(smp_active_mask, nid) == 0)
			continue;
		rgd = globaldata_find(nid);
		lwkt_setcpu_self(rgd);

		crit_enter();
		TAILQ_INSERT_TAIL(&rgd->gd_tdallq, marker, td_allq);

		while ((td = TAILQ_PREV(marker, lwkt_queue, td_allq)) != NULL) {
			TAILQ_REMOVE(&rgd->gd_tdallq, marker, td_allq);
			TAILQ_INSERT_BEFORE(td, marker, td_allq);
			if (td->td_flags & TDF_MARKER)
				continue;
			if (td->td_proc)
				continue;

			lwkt_hold(td);
			crit_exit();

			switch (oid) {
			case KERN_PROC_PGRP:
			case KERN_PROC_TTY:
			case KERN_PROC_UID:
			case KERN_PROC_RUID:
				break;
			default:
				error = sysctl_out_proc_kthread(td, req);
				break;
			}
			lwkt_rele(td);
			crit_enter();
			if (error)
				break;
		}
		TAILQ_REMOVE(&rgd->gd_tdallq, marker, td_allq);
		crit_exit();

		if (error)
			break;
	}

	/*
	 * Userland scheduler expects us to return on the same cpu we
	 * started on.
	 */
	if (mycpu->gd_cpuid != origcpu)
		lwkt_setcpu_self(globaldata_find(origcpu));

	kfree(marker, M_TEMP);

post_threads:
	if (crcache)
		crfree(crcache);
	return (error);
}

/*
 * This sysctl allows a process to retrieve the argument list or process
 * title for another process without groping around in the address space
 * of the other process.  It also allow a process to set its own "process 
 * title to a string of its own choice.
 *
 * No requirements.
 */
static int
sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
{
	int *name = (int*) arg1;
	u_int namelen = arg2;
	size_t n;
	struct proc *p;
	struct lwp *lp;
#if 0
	struct pargs *opa;
#endif
	struct pargs *pa;
	int error = 0;
	struct ucred *cr1 = curproc->p_ucred;

	if (namelen != 1 && namelen != 2)
		return (EINVAL);

	lp = NULL;
	p = pfind((pid_t)name[0]);
	if (p == NULL)
		goto done;
	lwkt_gettoken(&p->p_token);

	if (namelen == 2) {
		lp = lwpfind(p, (lwpid_t)name[1]);
		if (lp)
			lwkt_gettoken(&lp->lwp_token);
	} else {
		lp = NULL;
	}

	if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
		goto done;

	if (req->newptr && curproc != p) {
		error = EPERM;
		goto done;
	}
	if (lp && lp->lwp_lpmap != NULL &&
	    lp->lwp_lpmap->thread_title[0]) {
		/*
		 * Args set via writable user thread mmap or
		 * sysctl().
		 *
		 * We must calculate the string length manually
		 * because the user data can change at any time.
		 */
		size_t n;
		char *base;

		base = lp->lwp_lpmap->thread_title;
		for (n = 0; n < LPMAP_MAXTHREADTITLE - 1; ++n) {
			if (base[n] == 0)
				break;
		}
		error = SYSCTL_OUT(req, base, n);
		if (error == 0)
			error = SYSCTL_OUT(req, "", 1);
	} else if (p->p_upmap != NULL && p->p_upmap->proc_title[0]) {
		/*
		 * Args set via writable user process mmap or
		 * sysctl().
		 *
		 * We must calculate the string length manually
		 * because the user data can change at any time.
		 */
		size_t n;
		char *base;

		base = p->p_upmap->proc_title;
		for (n = 0; n < UPMAP_MAXPROCTITLE - 1; ++n) {
			if (base[n] == 0)
				break;
		}
		error = SYSCTL_OUT(req, base, n);
		if (error == 0)
			error = SYSCTL_OUT(req, "", 1);
	} else if ((pa = p->p_args) != NULL) {
		/*
		 * Default/original arguments.
		 */
		refcount_acquire(&pa->ar_ref);
		error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
		if (refcount_release(&pa->ar_ref))
			kfree(pa, M_PARGS);
	}
	if (req->newptr == NULL)
		goto done;

	if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit) {
		goto done;
	}

	/*
	 * Get the new process or thread title from userland
	 */
	pa = kmalloc(sizeof(struct pargs) + req->newlen,
		     M_PARGS, M_WAITOK);
	refcount_init(&pa->ar_ref, 1);
	pa->ar_length = req->newlen;
	error = SYSCTL_IN(req, pa->ar_args, req->newlen);
	if (error) {
		kfree(pa, M_PARGS);
		goto done;
	}

	if (lp) {
		/*
		 * Update thread title
		 */
		if (lp->lwp_lpmap == NULL)
			lwp_usermap(lp, -1);
		if (lp->lwp_lpmap) {
			n = req->newlen;
			if (n >= sizeof(lp->lwp_lpmap->thread_title))
				n = sizeof(lp->lwp_lpmap->thread_title) - 1;
			lp->lwp_lpmap->thread_title[n] = 0;
			bcopy(pa->ar_args, lp->lwp_lpmap->thread_title, n);
		}
	} else {
		/*
		 * Update process title
		 */
		if (p->p_upmap == NULL)
			proc_usermap(p, -1);
		if (p->p_upmap) {
			n = req->newlen;
			if (n >= sizeof(lp->lwp_lpmap->thread_title))
				n = sizeof(lp->lwp_lpmap->thread_title) - 1;
			p->p_upmap->proc_title[n] = 0;
			bcopy(pa->ar_args, p->p_upmap->proc_title, n);
		}

#if 0
		/*
		 * XXX delete this code, keep original args intact for
		 * the setproctitle("") case.
		 * Scrap p->p_args, p->p_upmap->proc_title[] overrides it.
		 */
		opa = p->p_args;
		p->p_args = NULL;
		if (opa) {
			KKASSERT(opa->ar_ref > 0);
			if (refcount_release(&opa->ar_ref)) {
				kfree(opa, M_PARGS);
				/* opa = NULL; */
			}
		}
#endif
	}
	kfree(pa, M_PARGS);

done:
	if (lp) {
		lwkt_reltoken(&lp->lwp_token);
		LWPRELE(lp);
	}
	if (p) {
		lwkt_reltoken(&p->p_token);
		PRELE(p);
	}
	return (error);
}

static int
sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
{
	int *name = (int*) arg1;
	u_int namelen = arg2;
	struct proc *p;
	int error = 0;
	char *fullpath, *freepath;
	struct ucred *cr1 = curproc->p_ucred;

	if (namelen != 1) 
		return (EINVAL);

	p = pfind((pid_t)name[0]);
	if (p == NULL)
		goto done;
	lwkt_gettoken_shared(&p->p_token);

	/*
	 * If we are not allowed to see other args, we certainly shouldn't
	 * get the cwd either. Also check the usual trespassing.
	 */
	if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
		goto done;

	if (p->p_fd != NULL && p->p_fd->fd_ncdir.ncp) {
		struct nchandle nch;

		cache_copy(&p->p_fd->fd_ncdir, &nch);
		error = cache_fullpath(p, &nch, NULL,
				       &fullpath, &freepath, 0);
		cache_drop(&nch);
		if (error)
			goto done;
		error = SYSCTL_OUT(req, fullpath, strlen(fullpath) + 1);
		kfree(freepath, M_TEMP);
	}

done:
	if (p) {
		lwkt_reltoken(&p->p_token);
		PRELE(p);
	}
	return (error);
}

/*
 * This sysctl allows a process to retrieve the path of the executable for
 * itself or another process.
 */
static int
sysctl_kern_proc_pathname(SYSCTL_HANDLER_ARGS)
{
	pid_t *pidp = (pid_t *)arg1;
	unsigned int arglen = arg2;
	struct proc *p;
	char *retbuf, *freebuf;
	int error = 0;
	struct nchandle nch;

	if (arglen != 1)
		return (EINVAL);
	if (*pidp == -1) {	/* -1 means this process */
		p = curproc;
	} else {
		p = pfind(*pidp);
		if (p == NULL)
			return (ESRCH);
	}
	lwkt_gettoken_shared(&p->p_token);	/* deal with exit race */
	if (p->p_textnch.ncp) {
		cache_copy(&p->p_textnch, &nch);
		error = cache_fullpath(p, &nch, NULL, &retbuf, &freebuf, 0);
		cache_drop(&nch);
	} else {
		error = EINVAL;
	}
	lwkt_reltoken(&p->p_token);
	if (error)
		goto done;
	error = SYSCTL_OUT(req, retbuf, strlen(retbuf) + 1);
	kfree(freebuf, M_TEMP);
done:
	if (*pidp != -1)
		PRELE(p);

	return (error);
}

static int
sysctl_kern_proc_sigtramp(SYSCTL_HANDLER_ARGS)
{
        /*int *name = (int *)arg1;*/
        u_int namelen = arg2;
        struct kinfo_sigtramp kst;
        const struct sysentvec *sv;
        int error;

        if (namelen > 1)
                return (EINVAL);
        /* ignore pid if passed in (freebsd compatibility) */

        sv = curproc->p_sysent;
        bzero(&kst, sizeof(kst));
        if (sv->sv_szsigcode) {
		intptr_t sigbase;

		sigbase = trunc_page64((intptr_t)PS_STRINGS -
				       *sv->sv_szsigcode);
		sigbase -= SZSIGCODE_EXTRA_BYTES;

                kst.ksigtramp_start = (void *)sigbase;
                kst.ksigtramp_end = (void *)(sigbase + *sv->sv_szsigcode);
        }
        error = SYSCTL_OUT(req, &kst, sizeof(kst));

        return (error);
}

SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");

#define SYSCTL_KERN_PROC_ALLFLAGS(which, affix)				\
    SYSCTL_NODE(_kern_proc,						\
	which,								\
	affix,								\
	CTLFLAG_RD | CTLFLAG_NOLOCK,					\
	sysctl_kern_proc, "Process Table");				\
    SYSCTL_NODE(_kern_proc,						\
	(which | KERN_PROC_FLAG_LWP),					\
	affix ## _lwp,							\
	CTLFLAG_RD | CTLFLAG_NOLOCK,					\
	sysctl_kern_proc, "Process Table");				\
    SYSCTL_NODE(_kern_proc,						\
	(which | KERN_PROC_FLAG_LWKT),					\
	affix ## _lwkt,							\
	CTLFLAG_RD | CTLFLAG_NOLOCK,					\
	sysctl_kern_proc, "Process Table");				\
    SYSCTL_NODE(_kern_proc, 						\
	(which | KERN_PROC_FLAG_LWP | KERN_PROC_FLAG_LWKT),		\
	affix ## _lwp_lwkt,						\
	CTLFLAG_RD | CTLFLAG_NOLOCK,					\
	sysctl_kern_proc, "Process Table")

SYSCTL_PROC(_kern_proc,
	KERN_PROC_ALL,
	all,
	CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_NOLOCK,
	0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");

SYSCTL_NODE(_kern_proc,
	(KERN_PROC_ALL | KERN_PROC_FLAG_LWP),
	all_lwp,
	CTLFLAG_RD | CTLFLAG_NOLOCK,
	sysctl_kern_proc, "Process table");

SYSCTL_NODE(_kern_proc,
	(KERN_PROC_ALL | KERN_PROC_FLAG_LWKT),
	all_lwkt,
	CTLFLAG_RD | CTLFLAG_NOLOCK,
	sysctl_kern_proc, "Process table");

SYSCTL_NODE(_kern_proc,
	(KERN_PROC_ALL | KERN_PROC_FLAG_LWP | KERN_PROC_FLAG_LWKT),
	all_lwp_lwkt,
	CTLFLAG_RD | CTLFLAG_NOLOCK,
	sysctl_kern_proc, "Process table");

SYSCTL_KERN_PROC_ALLFLAGS(KERN_PROC_PGRP, pgrp);
SYSCTL_KERN_PROC_ALLFLAGS(KERN_PROC_TTY, tty);
SYSCTL_KERN_PROC_ALLFLAGS(KERN_PROC_UID, uid);
SYSCTL_KERN_PROC_ALLFLAGS(KERN_PROC_RUID, ruid);
SYSCTL_KERN_PROC_ALLFLAGS(KERN_PROC_PID, pid);


SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args,
	CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NOLOCK,
	sysctl_kern_proc_args, "Process argument list");

SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd,
	CTLFLAG_RD | CTLFLAG_ANYBODY | CTLFLAG_NOLOCK,
	sysctl_kern_proc_cwd, "Process argument list");

static SYSCTL_NODE(_kern_proc, KERN_PROC_PATHNAME, pathname,
	CTLFLAG_RD | CTLFLAG_NOLOCK,
	sysctl_kern_proc_pathname, "Process executable path");

SYSCTL_PROC(_kern_proc, KERN_PROC_SIGTRAMP, sigtramp,
	CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_NOLOCK,
        0, 0, sysctl_kern_proc_sigtramp, "S,sigtramp",
        "Return sigtramp address range");