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
/*
 * Copyright (c) 2000 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@
 */
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
 * Copyright (c) 1982, 1986, 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * 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. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. 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.
 *
 *	@(#)sys_generic.c	8.9 (Berkeley) 2/14/95
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/filedesc.h>
#include <sys/ioctl.h>
#include <sys/file.h>
#include <sys/proc.h>
#include <sys/socketvar.h>
#include <sys/uio.h>
#include <sys/kernel.h>
#include <sys/stat.h>
#include <sys/malloc.h>

#if KTRACE
#include <sys/ktrace.h>
#endif

#include <sys/mount.h>
#include <sys/protosw.h>
#include <sys/ev.h>
#include <sys/user.h>
#include <sys/kdebug.h>
#include <kern/assert.h>
#include <kern/thread_act.h>

#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/errno.h>

#include <net/if.h>
#include <net/route.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/ip_var.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <netinet/tcp_fsm.h>
#include <netinet/tcp_seq.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#include <netinet/tcpip.h>
#include <netinet/tcp_debug.h>
/* for wait queue based select */
#include <kern/wait_queue.h>

/*
 * Read system call.
 */
struct read_args {
	int fd;
	char *cbuf;
	u_int nbyte;
};
/* ARGSUSED */
read(p, uap, retval)
	struct proc *p;
	register struct read_args *uap;
	register_t *retval;
{
	struct uio auio;
	struct iovec aiov;

	aiov.iov_base = (caddr_t)uap->cbuf;
	aiov.iov_len = uap->nbyte;
	auio.uio_iov = &aiov;
	auio.uio_iovcnt = 1;
	auio.uio_rw = UIO_READ;
	return (rwuio(p, uap->fd, &auio, UIO_READ, retval));	
}

struct readv_args {
	int fd;
	struct iovec *iovp;
	u_int iovcnt;
};
readv(p, uap, retval)
	struct proc *p;
	register struct readv_args *uap;
	int *retval;
{
	struct uio auio;
	register struct iovec *iov;
	int error;
	struct iovec aiov[UIO_SMALLIOV];

	if (uap->iovcnt > UIO_SMALLIOV) {
		if (uap->iovcnt > UIO_MAXIOV)
			return (EINVAL);	
		if ((iov = (struct iovec *)
			    kalloc(sizeof(struct iovec) * (uap->iovcnt))) == 0)
			return (ENOMEM);
	} else
		iov = aiov;
	auio.uio_iov = iov;
	auio.uio_iovcnt = uap->iovcnt;
	auio.uio_rw = UIO_READ;
	error = copyin((caddr_t)uap->iovp, (caddr_t)iov,
	    uap->iovcnt * sizeof (struct iovec));
	if (!error)
		error = rwuio(p, uap->fd, &auio, UIO_READ, retval);
	if (uap->iovcnt > UIO_SMALLIOV)
		kfree(iov, sizeof(struct iovec)*uap->iovcnt);
	return (error);
}

/*
 * Write system call
 */
struct write_args {
	int fd;
	char *cbuf;
	u_int nbyte;
};
write(p, uap, retval)
	struct proc *p;
	register struct write_args *uap;
	int *retval;
{
	struct uio auio;
	struct iovec aiov;

	aiov.iov_base = uap->cbuf;
	aiov.iov_len = uap->nbyte;
	auio.uio_iov = &aiov;
	auio.uio_iovcnt = 1;
	auio.uio_rw = UIO_WRITE;
	return (rwuio(p, uap->fd, &auio, UIO_WRITE, retval));
}

struct writev_args {
	int fd;
	struct iovec *iovp;
	u_int iovcnt;
};
writev(p, uap, retval)
	struct proc *p;
	register struct writev_args *uap;
	int *retval;
{
	struct uio auio;
	register struct iovec *iov;
	int error;
	struct iovec aiov[UIO_SMALLIOV];

	if (uap->iovcnt > UIO_SMALLIOV) {
		if (uap->iovcnt > UIO_MAXIOV)
			return (EINVAL);	
		if ((iov = (struct iovec *)
			    kalloc(sizeof(struct iovec) * (uap->iovcnt))) == 0)
			return (ENOMEM);
	} else
		iov = aiov;
	auio.uio_iov = iov;
	auio.uio_iovcnt = uap->iovcnt;
	auio.uio_rw = UIO_WRITE;
	error = copyin((caddr_t)uap->iovp, (caddr_t)iov,
	    uap->iovcnt * sizeof (struct iovec));
	if (!error)
		error = rwuio(p, uap->fd, &auio, UIO_WRITE, retval);
	if (uap->iovcnt > UIO_SMALLIOV)
		kfree(iov, sizeof(struct iovec)*uap->iovcnt);
	return (error);
}

rwuio(p, fdes, uio, rw, retval)
	struct proc *p;
	int fdes;
	register struct uio *uio;
	enum uio_rw rw;
	int *retval;
{
	struct file *fp;
	register struct iovec *iov;
	int i, count, flag, error;

	if (error = fdgetf(p, fdes, &fp))
		return (error);

	if ((fp->f_flag&(rw==UIO_READ ? FREAD : FWRITE)) == 0) {
		return(EBADF);
	}
	uio->uio_resid = 0;
	uio->uio_segflg = UIO_USERSPACE;
	uio->uio_procp = p;
	iov = uio->uio_iov;
	for (i = 0; i < uio->uio_iovcnt; i++) {
		if (iov->iov_len < 0) {
			return(EINVAL);
		}
		uio->uio_resid += iov->iov_len;
		if (uio->uio_resid < 0) {
			return(EINVAL);
		}
		iov++;
	}
	count = uio->uio_resid;
	if (rw == UIO_READ) {
		if (error = (*fp->f_ops->fo_read)(fp, uio, fp->f_cred))
				if (uio->uio_resid != count && (error == ERESTART ||
		    			error == EINTR || error == EWOULDBLOCK))
						error = 0;
	} else {
		if (error = (*fp->f_ops->fo_write)(fp, uio, fp->f_cred)) {
			if (uio->uio_resid != count && (error == ERESTART ||
		    	error == EINTR || error == EWOULDBLOCK))
				error = 0;
			if (error == EPIPE)
				psignal(p, SIGPIPE);
		}
	}
	*retval = count - uio->uio_resid;
	return(error);
}

/*
 * Ioctl system call
 */
struct ioctl_args {
	int fd;
	u_long com;
	caddr_t data;
};
/* ARGSUSED */
ioctl(p, uap, retval)
	struct proc *p;
	register struct ioctl_args *uap;
	register_t *retval;
{
	struct file *fp;
	register u_long com;
	register int error;
	register u_int size;
	caddr_t data, memp;
	int tmp;
#define STK_PARAMS	128
	char stkbuf[STK_PARAMS];

	if (error = fdgetf(p, uap->fd, &fp))
		return (error);

	if ((fp->f_flag & (FREAD | FWRITE)) == 0)
		return (EBADF);
		
	/*### LD 6/11/97 Hack Alert: this is to get AppleTalk to work
	 * while implementing an ATioctl system call
	 */
#if NETAT
	{
		extern int appletalk_inited;

		if (appletalk_inited && ((uap->com & 0x0000FFFF) == 0xff99)) {
#ifdef APPLETALK_DEBUG
			kprintf("ioctl: special AppleTalk \n");
#endif
			error = (*fp->f_ops->fo_ioctl)(fp, uap->com, uap->data, p);
			return(error);
		}
	}

#endif /* NETAT */


	switch (com = uap->com) {
	case FIONCLEX:
		*fdflags(p, uap->fd) &= ~UF_EXCLOSE;
		return (0);
	case FIOCLEX:
		*fdflags(p, uap->fd) |= UF_EXCLOSE;
		return (0);
	}

	/*
	 * Interpret high order word to find amount of data to be
	 * copied to/from the user's address space.
	 */
	size = IOCPARM_LEN(com);
	if (size > IOCPARM_MAX)
		return (ENOTTY);
	memp = NULL;
	if (size > sizeof (stkbuf)) {
		if ((memp = (caddr_t)kalloc(size)) == 0)
			return(ENOMEM);
		data = memp;
	} else
		data = stkbuf;
	if (com&IOC_IN) {
		if (size) {
			error = copyin(uap->data, data, (u_int)size);
			if (error) {
				if (memp)
					kfree(memp, size);
				return (error);
			}
		} else
			*(caddr_t *)data = uap->data;
	} else if ((com&IOC_OUT) && size)
		/*
		 * Zero the buffer so the user always
		 * gets back something deterministic.
		 */
		bzero(data, size);
	else if (com&IOC_VOID)
		*(caddr_t *)data = uap->data;

	switch (com) {

	case FIONBIO:
		if (tmp = *(int *)data)
			fp->f_flag |= FNONBLOCK;
		else
			fp->f_flag &= ~FNONBLOCK;
		error = (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
		break;

	case FIOASYNC:
		if (tmp = *(int *)data)
			fp->f_flag |= FASYNC;
		else
			fp->f_flag &= ~FASYNC;
		error = (*fp->f_ops->fo_ioctl)(fp, FIOASYNC, (caddr_t)&tmp, p);
		break;

	case FIOSETOWN:
		tmp = *(int *)data;
		if (fp->f_type == DTYPE_SOCKET) {
			((struct socket *)fp->f_data)->so_pgid = tmp;
			error = 0;
			break;
		}
		if (tmp <= 0) {
			tmp = -tmp;
		} else {
			struct proc *p1 = pfind(tmp);
			if (p1 == 0) {
				error = ESRCH;
				break;
			}
			tmp = p1->p_pgrp->pg_id;
		}
		error = (*fp->f_ops->fo_ioctl)
			(fp, (int)TIOCSPGRP, (caddr_t)&tmp, p);
		break;

	case FIOGETOWN:
		if (fp->f_type == DTYPE_SOCKET) {
			error = 0;
			*(int *)data = ((struct socket *)fp->f_data)->so_pgid;
			break;
		}
		error = (*fp->f_ops->fo_ioctl)(fp, TIOCGPGRP, data, p);
		*(int *)data = -*(int *)data;
		break;

	default:
		error = (*fp->f_ops->fo_ioctl)(fp, com, data, p);
		/*
		 * Copy any data to user, size was
		 * already set and checked above.
		 */
		if (error == 0 && (com&IOC_OUT) && size)
			error = copyout(data, uap->data, (u_int)size);
		break;
	}
	if (memp)
		kfree(memp, size);
	return (error);
}


int	selwait, nselcoll;
#define SEL_FIRSTPASS 1
#define SEL_SECONDPASS 2

/*
 * Select system call.
 */
struct select_args {
	int nd;
	u_int32_t *in;
	u_int32_t *ou;
	u_int32_t *ex;
	struct timeval *tv;
};

extern int selcontinue(int error);
extern int selprocess(int error, int sel_pass);
static int selscan(	struct proc *p, struct _select * sel,
					int nfd, register_t *retval, int sel_pass);
static int selcount(struct proc *p, u_int32_t *ibits, u_int32_t *obits,
					int nfd, int * count, int * nfcount);

select(p, uap, retval)
	register struct proc *p;
	register struct select_args *uap;
	register_t *retval;
{
	int s, error = 0, timo;
	u_int ni, nw, size;
	thread_act_t th_act;
	struct uthread	*uth;
	struct _select *sel;
	int needzerofill = 1;
	int kfcount =0;
	int nfcount = 0;
	int count = 0;

	th_act = current_act();
	uth = get_bsdthread_info(th_act);
	sel = &uth->uu_state.ss_select;
	retval = (int *)get_bsduthreadrval(th_act);
	*retval = 0;

	if (uap->nd < 0) {
		return (EINVAL);
	}

	if (uap->nd > p->p_fd->fd_nfiles)
		uap->nd = p->p_fd->fd_nfiles; /* forgiving; slightly wrong */

	nw = howmany(uap->nd, NFDBITS);
	ni = nw * sizeof(fd_mask);

	/*
	 * if this is the first select by the thread 
	 * allocate the space for bits.
	 */
	if (sel->nbytes == 0) {
		sel->nbytes = 3 * ni;
		MALLOC(sel->ibits, u_int32_t *, sel->nbytes, M_TEMP, M_WAITOK);
		MALLOC(sel->obits, u_int32_t *, sel->nbytes, M_TEMP, M_WAITOK);
		bzero((caddr_t)sel->ibits, sel->nbytes);
		bzero((caddr_t)sel->obits, sel->nbytes);
		needzerofill = 0;
	}

	/*
	 * if the previously allocated space for the bits
	 * is smaller than what is requested. Reallocate.
	 */
	if (sel->nbytes < (3 * ni)) {
		sel->nbytes = (3 * ni);
		FREE(sel->ibits, M_TEMP);
		FREE(sel->obits, M_TEMP);
		MALLOC(sel->ibits, u_int32_t *, sel->nbytes, M_TEMP, M_WAITOK);
		MALLOC(sel->obits, u_int32_t *, sel->nbytes, M_TEMP, M_WAITOK);
		bzero((caddr_t)sel->ibits, sel->nbytes);
		bzero((caddr_t)sel->obits, sel->nbytes);
		needzerofill = 0;
	}   

	if (needzerofill) {
		bzero((caddr_t)sel->ibits, sel->nbytes);
		bzero((caddr_t)sel->obits, sel->nbytes);
	}

	/*
	 * get the bits from the user address space
	 */
#define	getbits(name, x) \
	do { \
		if (uap->name && (error = copyin((caddr_t)uap->name, \
			(caddr_t)&sel->ibits[(x) * nw], ni))) \
			goto continuation; \
	} while (0)

	getbits(in, 0);
	getbits(ou, 1);
	getbits(ex, 2);
#undef	getbits

	if (uap->tv) {
		error = copyin((caddr_t)uap->tv, (caddr_t)&sel->atv,
			sizeof (sel->atv));
		if (error)
			goto continuation;
		if (itimerfix(&sel->atv)) {
			error = EINVAL;
			goto continuation;
		}

		timeradd(&sel->atv, &time, &sel->atv);
		timo = hzto(&sel->atv);
	} else
		timo = 0;
	sel->poll = timo;
	sel->nfcount = 0;
	if (error = selcount(p, sel->ibits, sel->obits, uap->nd, &count, &nfcount)) {
			goto continuation;
	}

	sel->nfcount = nfcount;
	sel->count = count;
	size = SIZEOF_WAITQUEUE_SUB + (count * SIZEOF_WAITQUEUE_LINK);
	if (sel->allocsize) {
		if (uth->uu_wqsub == 0)
			panic("select: wql memory smashed");
		/* needed for the select now */
		if (size > sel->allocsize) {
			kfree(uth->uu_wqsub,  sel->allocsize);
			sel->allocsize = size;
			uth->uu_wqsub = (wait_queue_sub_t)kalloc(sel->allocsize);
			if (uth->uu_wqsub == (wait_queue_sub_t)NULL)
				panic("failed to allocate memory for waitqueue\n");
			sel->wql = (char *)uth->uu_wqsub + SIZEOF_WAITQUEUE_SUB;
		}
	} else {
		sel->count = count;
		sel->allocsize = size;
		uth->uu_wqsub = (wait_queue_sub_t)kalloc(sel->allocsize);
		if (uth->uu_wqsub == (wait_queue_sub_t)NULL)
			panic("failed to allocate memory for waitqueue\n");
		sel->wql = (char *)uth->uu_wqsub + SIZEOF_WAITQUEUE_SUB;
	}
	bzero(uth->uu_wqsub, size);
	wait_queue_sub_init(uth->uu_wqsub, (SYNC_POLICY_FIFO | SYNC_POLICY_PREPOST));

continuation:
	selprocess(error, SEL_FIRSTPASS);
}

int
selcontinue(int error)
{
	selprocess(error, SEL_SECONDPASS);
}

int
selprocess(error, sel_pass)
{
	int s, ncoll, timo;
	u_int ni, nw;
	thread_act_t th_act;
	struct uthread	*uth;
	struct proc *p;
	struct select_args *uap;
	int *retval;
	struct _select *sel;
	int unwind = 1;
	int prepost =0;
	int somewakeup = 0;
	int doretry = 0;

	p = current_proc();
	th_act = current_act();
	uap = (struct select_args *)get_bsduthreadarg(th_act);
	retval = (int *)get_bsduthreadrval(th_act);
	uth = get_bsdthread_info(th_act);
	sel = &uth->uu_state.ss_select;

	/* if it is first pass wait queue is not setup yet */
	if ((error != 0) && (sel_pass == SEL_FIRSTPASS))
			unwind = 0;
	if (sel->count == 0)
			unwind = 0;
retry:
	if (error != 0) {
	  goto done;
	}

	ncoll = nselcoll;
	p->p_flag |= P_SELECT;
	/* skip scans if the select is just for timeouts */
	if (sel->count) {
		if (sel_pass == SEL_FIRSTPASS)
			wait_queue_sub_clearrefs(uth->uu_wqsub);

		error = selscan(p, sel, uap->nd, retval, sel_pass);
		if (error || *retval) {
			goto done;
		}
		if (prepost) {
			/* if the select of log, then we canwakeup and discover some one
		 	* else already read the data; go toselct again if time permits
		 	*/
		 	prepost = 0;
		 	doretry = 1;
		}
		if (somewakeup) {
		 	somewakeup = 0;
		 	doretry = 1;
		}
	}

	/* this should be timercmp(&time, &atv, >=) */
	if (uap->tv && (time.tv_sec > sel->atv.tv_sec ||
	    time.tv_sec == sel->atv.tv_sec && time.tv_usec >= sel->atv.tv_usec)) {
		goto done;
	}

	if (doretry) {
		/* cleanup obits and try again */
		doretry = 0;
		sel_pass = SEL_FIRSTPASS;
		goto retry;
	}

	/*
	 * To effect a poll, the timeout argument should be
	 * non-nil, pointing to a zero-valued timeval structure.
	 */
	timo = sel->poll;

	if (uap->tv && (timo == 0)) {
		goto done;
	}

	/* No spurious wakeups due to colls,no need to check for them */
	 if ((sel_pass == SEL_SECONDPASS) || ((p->p_flag & P_SELECT) == 0)) {
		sel_pass = SEL_FIRSTPASS;
		goto retry;
	}

	p->p_flag &= ~P_SELECT;

	/* if the select is just for timeout skip check */
	if (sel->count &&(sel_pass == SEL_SECONDPASS))
		panic("selprocess: 2nd pass assertwaiting");

	/* Wait Queue Subordinate has waitqueue as first element */
	if (wait_queue_assert_wait(uth->uu_wqsub, &selwait, THREAD_ABORTSAFE)) {
		/* If it is true then there are no preposted events */
        error = tsleep1((caddr_t)&selwait, PSOCK | PCATCH, "select", timo, selcontinue);
	} else  {
		prepost = 1;
		error = 0;
	}

	sel_pass = SEL_SECONDPASS;
	if (error == 0) {
		if (!prepost)
			somewakeup =1;
		goto retry;
	}
done:
	if (unwind)
		wait_subqueue_unlink_all(uth->uu_wqsub);
	p->p_flag &= ~P_SELECT;
	/* select is not restarted after signals... */
	if (error == ERESTART)
		error = EINTR;
	if (error == EWOULDBLOCK)
		error = 0;
	nw = howmany(uap->nd, NFDBITS);
	ni = nw * sizeof(fd_mask);

#define	putbits(name, x) \
	do { \
		if (uap->name && (error2 = copyout((caddr_t)&sel->obits[(x) * nw], \
			(caddr_t)uap->name, ni))) \
			error = error2; \
	} while (0)

	if (error == 0) {
		int error2;

		putbits(in, 0);
		putbits(ou, 1);
		putbits(ex, 2);
#undef putbits
	}

#if defined (__i386__)
	return(error);
#else
	unix_syscall_return(error);
#endif
}

static int
selscan(p, sel, nfd, retval, sel_pass)
	struct proc *p;
	struct _select *sel;
	int nfd;
	register_t *retval;
	int sel_pass;
{
	register struct filedesc *fdp = p->p_fd;
	register int msk, i, j, fd;
	register u_int32_t bits;
	struct file *fp;
	int n = 0;
	int nc = 0;
	static int flag[3] = { FREAD, FWRITE, 0 };
	u_int32_t *iptr, *optr;
	u_int nw;
	u_int32_t *ibits, *obits;
	char * wql;
	int nfunnel = 0;
	int count, nfcount;
	char * wql_ptr;

	/*
	 * Problems when reboot; due to MacOSX signal probs
	 * in Beaker1C ; verify that the p->p_fd is valid
	 */
	if (fdp == NULL) {
		*retval=0;
		return(EIO);
	}

	ibits = sel->ibits;
	obits = sel->obits;
	wql = sel->wql;

	count = sel->count;
	nfcount = sel->nfcount;

	if (nfcount > count)
		panic("selcount count<nfcount");

	nw = howmany(nfd, NFDBITS);

	nc = 0;
	if ( nfcount < count) {
		/* some or all in kernel funnel */
		for (msk = 0; msk < 3; msk++) {
			iptr = (u_int32_t *)&ibits[msk * nw];
			optr = (u_int32_t *)&obits[msk * nw];
			for (i = 0; i < nfd; i += NFDBITS) {
				bits = iptr[i/NFDBITS];
				while ((j = ffs(bits)) && (fd = i + --j) < nfd) {
					bits &= ~(1 << j);
					fp = fdp->fd_ofiles[fd];
					if (fp == NULL ||
						(fdp->fd_ofileflags[fd] & UF_RESERVED)) {
						return(EBADF);
					}
					if (sel_pass == SEL_SECONDPASS)
						wql_ptr = (char *)0;
					else
						wql_ptr = (wql+ nc * SIZEOF_WAITQUEUE_LINK);
					if (fp->f_ops && (fp->f_type != DTYPE_SOCKET) 
						&& (*fp->f_ops->fo_select)(fp, flag[msk], wql_ptr, p)) {
						optr[fd/NFDBITS] |= (1 << (fd % NFDBITS));
						n++;
					}
					nc++;
				}
			}
		}
	}

	if (nfcount) {
		/* socket file descriptors for scan */
		thread_funnel_switch(KERNEL_FUNNEL, NETWORK_FUNNEL);

		nc = 0;
		for (msk = 0; msk < 3; msk++) {
			iptr = (u_int32_t *)&ibits[msk * nw];
			optr = (u_int32_t *)&obits[msk * nw];
			for (i = 0; i < nfd; i += NFDBITS) {
				bits = iptr[i/NFDBITS];
				while ((j = ffs(bits)) && (fd = i + --j) < nfd) {
					bits &= ~(1 << j);
					fp = fdp->fd_ofiles[fd];
					if (fp == NULL ||
						(fdp->fd_ofileflags[fd] & UF_RESERVED)) {
						return(EBADF);
					}
					if (sel_pass == SEL_SECONDPASS)
						wql_ptr = (char *)0;
					else
						wql_ptr = (wql+ nc * SIZEOF_WAITQUEUE_LINK);
					if (fp->f_ops && (fp->f_type == DTYPE_SOCKET) &&
						(*fp->f_ops->fo_select)(fp, flag[msk], wql_ptr, p)) {
						optr[fd/NFDBITS] |= (1 << (fd % NFDBITS));
						n++;
					}
					nc++;
				}
			}
		}
		thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
	}

	*retval = n;
	return (0);
}

/*ARGSUSED*/
seltrue(dev, flag, p)
	dev_t dev;
	int flag;
	struct proc *p;
{

	return (1);
}

static int
selcount(p, ibits, obits, nfd, count, nfcount)
	struct proc *p;
	u_int32_t *ibits, *obits;
	int nfd;
	int *count;
	int *nfcount;
{
	register struct filedesc *fdp = p->p_fd;
	register int msk, i, j, fd;
	register u_int32_t bits;
	struct file *fp;
	int n = 0;
	int nc = 0;
	int nfc = 0;
	static int flag[3] = { FREAD, FWRITE, 0 };
	u_int32_t *iptr, *fptr, *fbits;
	u_int nw;

	/*
	 * Problems when reboot; due to MacOSX signal probs
	 * in Beaker1C ; verify that the p->p_fd is valid
	 */
	if (fdp == NULL) {
		*count=0;
		*nfcount=0;
		return(EIO);
	}

	nw = howmany(nfd, NFDBITS);


	for (msk = 0; msk < 3; msk++) {
		iptr = (u_int32_t *)&ibits[msk * nw];
		for (i = 0; i < nfd; i += NFDBITS) {
			bits = iptr[i/NFDBITS];
			while ((j = ffs(bits)) && (fd = i + --j) < nfd) {
				bits &= ~(1 << j);
				fp = fdp->fd_ofiles[fd];
				if (fp == NULL ||
					(fdp->fd_ofileflags[fd] & UF_RESERVED)) {
						*count=0;
						*nfcount=0;
						return(EBADF);
				}
				if (fp->f_type == DTYPE_SOCKET)
					nfc++;
				n++;
			}
		}
	}
	*count = n;
	*nfcount = nfc;
	return (0);
}

/*
 * Record a select request.
 */
void
selrecord(selector, sip, p_wql)
	struct proc *selector;
	struct selinfo *sip;
	void * p_wql;
{
	thread_act_t	cur_act = current_act();
	struct uthread * ut = get_bsdthread_info(cur_act);

	/* need to look at collisions */

	if ((p_wql == (void *)0) && ((sip->si_flags & SI_INITED) == 0)) {
		return;
	}

	/*do not record if this is second pass of select */
	if((p_wql == (void *)0)) {
		return;
	}

	if ((sip->si_flags & SI_INITED) == 0) {
		wait_queue_init(&sip->wait_queue, SYNC_POLICY_FIFO);
		sip->si_flags |= SI_INITED;
		sip->si_flags &= ~SI_CLEAR;
	}

	if (sip->si_flags & SI_RECORDED) {
		sip->si_flags |= SI_COLL;
	} else
		sip->si_flags &= ~SI_COLL;

	sip->si_flags |= SI_RECORDED;
	if (!wait_queue_member(&sip->wait_queue, ut->uu_wqsub))
		wait_queue_link_noalloc(&sip->wait_queue, ut->uu_wqsub, (wait_queue_link_t)p_wql);

	return;
}

void
selwakeup(sip)
	register struct selinfo *sip;
{
	
	if ((sip->si_flags & SI_INITED) == 0) {
		return;
	}

	if (sip->si_flags & SI_COLL) {
		nselcoll++;
		sip->si_flags &= ~SI_COLL;
#if 0
		/* will not  support */
		//wakeup((caddr_t)&selwait);
#endif
	}

	if (sip->si_flags & SI_RECORDED) {
		wait_queue_wakeup_all(&sip->wait_queue, &selwait, THREAD_AWAKENED);
		sip->si_flags &= ~SI_RECORDED;
	}

}

void 
selthreadclear(sip)
	register struct selinfo *sip;
{

	if ((sip->si_flags & SI_INITED) == 0) {
		return;
	}
	if (sip->si_flags & SI_RECORDED) {
			selwakeup(sip);
			sip->si_flags &= ~(SI_RECORDED | SI_COLL);
	}
	sip->si_flags |= SI_CLEAR;
	wait_queue_unlinkall_nofree(&sip->wait_queue);
}


extern struct eventqelt *evprocdeque(struct proc *p, struct eventqelt *eqp);

/*
 * called upon socket close. deque and free all events for
 * the socket
 */
evsofree(struct socket *sp)
{
  struct eventqelt *eqp, *next;

  if (sp == NULL) return;

  for (eqp = sp->so_evlist.tqh_first; eqp != NULL; eqp = next) {
    next = eqp->ee_slist.tqe_next;
    evprocdeque(eqp->ee_proc, eqp); // remove from proc q if there
    TAILQ_REMOVE(&sp->so_evlist, eqp, ee_slist); // remove from socket q
    FREE(eqp, M_TEMP);
  }
}


#define DBG_EVENT 0x10

#define DBG_POST 0x10
#define DBG_WATCH 0x11
#define DBG_WAIT 0x12
#define DBG_MOD 0x13
#define DBG_EWAKEUP 0x14
#define DBG_ENQUEUE 0x15
#define DBG_DEQUEUE 0x16

#define DBG_MISC_POST MISCDBG_CODE(DBG_EVENT,DBG_POST)
#define DBG_MISC_WATCH MISCDBG_CODE(DBG_EVENT,DBG_WATCH)
#define DBG_MISC_WAIT MISCDBG_CODE(DBG_EVENT,DBG_WAIT)
#define DBG_MISC_MOD MISCDBG_CODE(DBG_EVENT,DBG_MOD)
#define DBG_MISC_EWAKEUP MISCDBG_CODE(DBG_EVENT,DBG_EWAKEUP)
#define DBG_MISC_ENQUEUE MISCDBG_CODE(DBG_EVENT,DBG_ENQUEUE)
#define DBG_MISC_DEQUEUE MISCDBG_CODE(DBG_EVENT,DBG_DEQUEUE)


/*
 * enque this event if it's not already queued. wakeup
   the proc if we do queue this event to it.
 */
evprocenque(struct eventqelt *eqp)
{
  struct proc *p;

  assert(eqp);
  KERNEL_DEBUG(DBG_MISC_ENQUEUE|DBG_FUNC_START, eqp, eqp->ee_flags, eqp->ee_eventmask,0,0);
  if (eqp->ee_flags & EV_QUEUED) {
    KERNEL_DEBUG(DBG_MISC_ENQUEUE|DBG_FUNC_END, 0,0,0,0,0);
    return;
  }
  eqp->ee_flags |= EV_QUEUED;
  eqp->ee_eventmask = 0;  // disarm
  p = eqp->ee_proc;
  TAILQ_INSERT_TAIL(&p->p_evlist, eqp, ee_plist);
  KERNEL_DEBUG(DBG_MISC_EWAKEUP,0,0,0,eqp,0);
  wakeup(&p->p_evlist);
  KERNEL_DEBUG(DBG_MISC_ENQUEUE|DBG_FUNC_END, 0,0,0,0,0);
}

/*
 * given either a sockbuf or a socket run down the
 * event list and queue ready events found
 */
postevent(struct socket *sp, struct sockbuf *sb, int event)
{
  int mask;
  struct eventqelt *evq;
  register struct tcpcb *tp;

  if (sb) sp = sb->sb_so;
  if (!sp || sp->so_evlist.tqh_first == NULL) return;

  KERNEL_DEBUG(DBG_MISC_POST|DBG_FUNC_START, event,0,0,0,0);

  for (evq = sp->so_evlist.tqh_first;
       evq != NULL; evq = evq->ee_slist.tqe_next) {

    mask = 0;

    /* ready for reading:
       - byte cnt >= receive low water mark
       - read-half of conn closed
       - conn pending for listening sock
       - socket error pending

       ready for writing
       - byte cnt avail >= send low water mark
       - write half of conn closed
       - socket error pending
       - non-blocking conn completed successfully

       exception pending
       - out of band data
       - sock at out of band mark

    */
    switch (event & EV_DMASK) {

    case EV_RWBYTES:
    case EV_OOB:
    case EV_RWBYTES|EV_OOB:
      if (event & EV_OOB) {
      if ((evq->ee_eventmask & EV_EX)) {
	if (sp->so_oobmark || ((sp->so_state & SS_RCVATMARK))) {
	  mask |= EV_EX|EV_OOB;
	}
      }
      }
      if (event & EV_RWBYTES) {
      if ((evq->ee_eventmask & EV_RE) && soreadable(sp)) {
	if ((sp->so_type == SOCK_STREAM) && (sp->so_error == ECONNREFUSED) ||
	    (sp->so_error == ECONNRESET)) {
	  if ((sp->so_pcb == 0) ||
	      !(tp = sototcpcb(sp)) ||
	      (tp->t_state == TCPS_CLOSED)) {
	    mask |= EV_RE|EV_RESET;
	    break;
	  }
	}
	if (sp->so_state & SS_CANTRCVMORE) {
	  mask |= EV_RE|EV_FIN;
	  evq->ee_req.er_rcnt = sp->so_rcv.sb_cc;
	  break;
	}
	mask |= EV_RE;
	evq->ee_req.er_rcnt = sp->so_rcv.sb_cc;
      }

      if ((evq->ee_eventmask & EV_WR) && sowriteable(sp)) {
	if ((sp->so_type == SOCK_STREAM) &&(sp->so_error == ECONNREFUSED) ||
	    (sp->so_error == ECONNRESET)) {
	  if ((sp->so_pcb == 0) ||
	      !(tp = sototcpcb(sp)) ||
	      (tp->t_state == TCPS_CLOSED)) {
	  mask |= EV_WR|EV_RESET;
	  break;
	  }
	}
	mask |= EV_WR;
	evq->ee_req.er_wcnt = sbspace(&sp->so_snd);
      }
      }
    break;

    case EV_RCONN:
      if ((evq->ee_eventmask & EV_RE)) {
	evq->ee_req.er_rcnt = sp->so_qlen + 1;  // incl this one
	mask |= EV_RE|EV_RCONN;
      }
      break;

    case EV_WCONN:
      if ((evq->ee_eventmask & EV_WR)) {
	mask |= EV_WR|EV_WCONN;
      }
      break;

    case EV_RCLOSED:
      if ((evq->ee_eventmask & EV_RE)) {
	mask |= EV_RE|EV_RCLOSED;
      }
      break;

    case EV_WCLOSED:
      if ((evq->ee_eventmask & EV_WR)) {
	mask |= EV_WR|EV_WCLOSED;
      }
      break;

    case EV_FIN:
      if (evq->ee_eventmask & EV_RE) {
	mask |= EV_RE|EV_FIN;
      }
      break;

    case EV_RESET:
    case EV_TIMEOUT:
      if (evq->ee_eventmask & EV_RE) {
	mask |= EV_RE | event;
      } 
      if (evq->ee_eventmask & EV_WR) {
	mask |= EV_WR | event;
      }
      break;

    default:
      return;
    } /* switch */

    if (mask) {
      evq->ee_req.er_eventbits |= mask;
      KERNEL_DEBUG(DBG_MISC_POST, evq, evq->ee_req.er_eventbits, mask,0,0);
      evprocenque(evq);
    }
  }
  KERNEL_DEBUG(DBG_MISC_POST|DBG_FUNC_END, 0,0,0,0,0);
}

/*
 * remove and return the first event (eqp=NULL) or a specific
 * event, or return NULL if no events found
 */
struct eventqelt *
evprocdeque(struct proc *p, struct eventqelt *eqp)
{
  
  KERNEL_DEBUG(DBG_MISC_DEQUEUE|DBG_FUNC_START,p,eqp,0,0,0);

  if (eqp && ((eqp->ee_flags & EV_QUEUED) == NULL)) {
    KERNEL_DEBUG(DBG_MISC_DEQUEUE|DBG_FUNC_END,0,0,0,0,0);
    return(NULL);
  }
  if (p->p_evlist.tqh_first == NULL) {
    KERNEL_DEBUG(DBG_MISC_DEQUEUE|DBG_FUNC_END,0,0,0,0,0);
    return(NULL);
  }
  if (eqp == NULL) {  // remove first
    eqp = p->p_evlist.tqh_first;
  }
  TAILQ_REMOVE(&p->p_evlist, eqp, ee_plist);
  eqp->ee_flags &= ~EV_QUEUED;
  KERNEL_DEBUG(DBG_MISC_DEQUEUE|DBG_FUNC_END,eqp,0,0,0,0);
  return(eqp);
}

struct evwatch_args {
  struct eventreq  *u_req;
  int               u_eventmask;
};


/*
 * watchevent system call. user passes us an event to watch
 * for. we malloc an event object, initialize it, and queue
 * it to the open socket. when the event occurs, postevent()
 * will enque it back to our proc where we can retrieve it
 * via waitevent().
 *
 * should this prevent duplicate events on same socket?
 */
int
watchevent(p, uap, retval)
     struct proc *p;
     struct evwatch_args *uap;
     register_t *retval;
{
  struct eventqelt *eqp = (struct eventqelt *)0;
  struct eventqelt *np;
  struct eventreq *erp;
  struct file *fp;
  struct socket *sp;
  int error;

  KERNEL_DEBUG(DBG_MISC_WATCH|DBG_FUNC_START, 0,0,0,0,0);

  // get a qelt and fill with users req
  MALLOC(eqp, struct eventqelt *, sizeof(struct eventqelt), M_TEMP, M_WAITOK);
  if (!eqp) panic("can't MALLOC eqp");
  erp = &eqp->ee_req;
  // get users request pkt
  if (error = copyin((caddr_t)uap->u_req, (caddr_t)erp,
		     sizeof(struct eventreq))) {
    FREE(eqp, M_TEMP);
    KERNEL_DEBUG(DBG_MISC_WATCH|DBG_FUNC_END, error,0,0,0,0);
    return(error);
  }
  KERNEL_DEBUG(DBG_MISC_WATCH, erp->er_handle,uap->u_eventmask,eqp,0,0);
  // validate, freeing qelt if errors
  error = 0;
  if (erp->er_type != EV_FD) {
    error = EINVAL;
  } else  if (erp->er_handle < 0) {
    error = EBADF;
  } else  if (erp->er_handle > p->p_fd->fd_nfiles) {
    error = EBADF;
  } else if ((fp = *fdfile(p, erp->er_handle)) == NULL) {
    error = EBADF;
  } else if (fp->f_type != DTYPE_SOCKET) {
    error = EINVAL;
  }
  if (error) {
    FREE(eqp,M_TEMP);
    KERNEL_DEBUG(DBG_MISC_WATCH|DBG_FUNC_END, error,0,0,0,0);
    return(error);
  }

  erp->er_rcnt = erp->er_wcnt = erp->er_eventbits = 0;
  eqp->ee_proc = p;
  eqp->ee_eventmask = uap->u_eventmask & EV_MASK;
  eqp->ee_flags = 0;

  sp = (struct socket *)fp->f_data;
  assert(sp != NULL);

  // only allow one watch per file per proc
  for (np = sp->so_evlist.tqh_first; np != NULL; np = np->ee_slist.tqe_next) {
    if (np->ee_proc == p) {
      FREE(eqp,M_TEMP);
      KERNEL_DEBUG(DBG_MISC_WATCH|DBG_FUNC_END, EINVAL,0,0,0,0);
      return(EINVAL);
    }
  }

  TAILQ_INSERT_TAIL(&sp->so_evlist, eqp, ee_slist);
  postevent(sp, 0, EV_RWBYTES); // catch existing events
  KERNEL_DEBUG(DBG_MISC_WATCH|DBG_FUNC_END, 0,0,0,0,0);
  return(0);
}

struct evwait_args {
  struct eventreq *u_req;
  struct timeval *tv;
};

/*
 * waitevent system call.
 * grabs the next waiting event for this proc and returns
 * it. if no events, user can request to sleep with timeout
 * or poll mode (tv=NULL);
 */
int
waitevent(p, uap, retval)
     struct proc *p;
     struct evwait_args *uap;
     register_t *retval;
{
  int error = 0;
  struct eventqelt *eqp;
  int timo;
  struct timeval atv;
  int s;

	if (uap->tv) {
		error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
			sizeof (atv));
		if (error)
		        return(error);
		if (itimerfix(&atv)) {
			error = EINVAL;
			return(error);
		}
		s = splhigh();
		timeradd(&atv, &time, &atv);
		timo = hzto(&atv);
		splx(s);
	} else
		timo = 0;

  KERNEL_DEBUG(DBG_MISC_WAIT|DBG_FUNC_START, 0,0,0,0,0);

retry:
  s = splhigh();
  if ((eqp = evprocdeque(p,NULL)) != NULL) {
    splx(s);
    error = copyout((caddr_t)&eqp->ee_req, (caddr_t)uap->u_req,
		    sizeof(struct eventreq));
    KERNEL_DEBUG(DBG_MISC_WAIT|DBG_FUNC_END, error,
		 eqp->ee_req.er_handle,eqp->ee_req.er_eventbits,eqp,0);
    return(error);
  } else {
    if (uap->tv && (timo == 0)) {
        splx(s);
        *retval = 1;  // poll failed
		KERNEL_DEBUG(DBG_MISC_WAIT|DBG_FUNC_END, error,0,0,0,0);
	return(error);
    }

    KERNEL_DEBUG(DBG_MISC_WAIT, 1,&p->p_evlist,0,0,0);
    error = tsleep(&p->p_evlist, PSOCK | PCATCH, "waitevent", timo);
    KERNEL_DEBUG(DBG_MISC_WAIT, 2,&p->p_evlist,0,0,0);
    splx(s);
    if (error == 0)
      goto retry;
    if (error == ERESTART)
      error = EINTR;
    if (error == EWOULDBLOCK) {
      *retval = 1;
      error = 0;
    }
  }
  KERNEL_DEBUG(DBG_MISC_WAIT|DBG_FUNC_END, 0,0,0,0,0);
  return(error);
}

struct modwatch_args {
  struct eventreq *u_req;
  int               u_eventmask;
};

/*
 * modwatch system call. user passes in event to modify.
 * if we find it we reset the event bits and que/deque event
 * it needed.
 */
int
modwatch(p, uap, retval)
     struct proc *p;
     struct modwatch_args *uap;
     register_t *retval;
{
  struct eventreq er;
  struct eventreq *erp = &er;
  struct eventqelt *evq;
  int error;
  struct file *fp;
  struct socket *sp;
  int flag;

  KERNEL_DEBUG(DBG_MISC_MOD|DBG_FUNC_START, 0,0,0,0,0);

  // get users request pkt
  if (error = copyin((caddr_t)uap->u_req, (caddr_t)erp,
		     sizeof(struct eventreq))) return(error);

  if (erp->er_type != EV_FD) return(EINVAL);
  if (erp->er_handle < 0) return(EBADF);
  if (erp->er_handle > p->p_fd->fd_nfiles) return(EBADF);
  if ((fp = *fdfile(p, erp->er_handle)) == NULL)
    return(EBADF);
  if (fp->f_type != DTYPE_SOCKET) return(EINVAL); // for now must be sock
  sp = (struct socket *)fp->f_data;
  assert(sp != NULL);


  // locate event if possible
  for (evq = sp->so_evlist.tqh_first;
       evq != NULL; evq = evq->ee_slist.tqe_next) {
    if (evq->ee_proc == p) break;
  }

  if (evq == NULL) {
	KERNEL_DEBUG(DBG_MISC_MOD|DBG_FUNC_END, EINVAL,0,0,0,0);
    return(EINVAL);
  }
  KERNEL_DEBUG(DBG_MISC_MOD, erp->er_handle,uap->u_eventmask,evq,0,0);

    if (uap->u_eventmask == EV_RM) {
    evprocdeque(p, evq);
    TAILQ_REMOVE(&sp->so_evlist, evq, ee_slist);
    FREE(evq, M_TEMP);
	KERNEL_DEBUG(DBG_MISC_MOD|DBG_FUNC_END, 0,0,0,0,0);
    return(0);
    }

  switch (uap->u_eventmask & EV_MASK) {
 
  case 0:
    flag = 0;
    break;

  case EV_RE:
  case EV_WR:
  case EV_RE|EV_WR:
    flag = EV_RWBYTES;
    break;

  case EV_EX:
    flag = EV_OOB;
    break;

  case EV_EX|EV_RE:
  case EV_EX|EV_WR:
  case EV_EX|EV_RE|EV_WR:
    flag = EV_OOB|EV_RWBYTES;
    break;

  default:
    return(EINVAL);
  }

   evq->ee_eventmask = uap->u_eventmask & EV_MASK;
   evprocdeque(p, evq);
   evq->ee_req.er_eventbits = 0;
   postevent(sp, 0, flag);
   KERNEL_DEBUG(DBG_MISC_MOD|DBG_FUNC_END, evq->ee_req.er_handle,evq->ee_eventmask,sp,flag,0);
   return(0);
}