Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*-
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 1999 Kazutaka YOKOTA <yokota@zodiac.mech.utsunomiya-u.ac.jp>
 * 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 as
 *    the first lines of this file unmodified.
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_kbd.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/conf.h>
#include <sys/fcntl.h>
#include <sys/poll.h>
#include <sys/priv.h>
#include <sys/proc.h>
#include <sys/selinfo.h>
#include <sys/sysctl.h>
#include <sys/uio.h>

#include <sys/kbio.h>

#include <dev/evdev/input-event-codes.h>
#include <dev/kbd/kbdreg.h>

#define KBD_INDEX(dev)	dev2unit(dev)

#define KB_QSIZE	512
#define KB_BUFSIZE	64

typedef struct genkbd_softc {
	int		gkb_flags;	/* flag/status bits */
#define KB_ASLEEP	(1 << 0)
	struct selinfo	gkb_rsel;
	char		gkb_q[KB_QSIZE];		/* input queue */
	unsigned int	gkb_q_start;
	unsigned int	gkb_q_length;
} genkbd_softc_t;

static u_char	*genkbd_get_fkeystr(keyboard_t *kbd, int fkey, size_t *len);
static void	genkbd_diag(keyboard_t *kbd, int level);

static	SLIST_HEAD(, keyboard_driver) keyboard_drivers =
	SLIST_HEAD_INITIALIZER(keyboard_drivers);

SET_DECLARE(kbddriver_set, keyboard_driver_t);

/* local arrays */

/*
 * We need at least one entry each in order to initialize a keyboard
 * for the kernel console.  The arrays will be increased dynamically
 * when necessary.
 */

static int		keyboards = 1;
static keyboard_t	*kbd_ini;
static keyboard_t	**keyboard = &kbd_ini;

static int keymap_restrict_change;
static SYSCTL_NODE(_hw, OID_AUTO, kbd, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
    "kbd");
SYSCTL_INT(_hw_kbd, OID_AUTO, keymap_restrict_change, CTLFLAG_RW,
    &keymap_restrict_change, 0, "restrict ability to change keymap");

#define ARRAY_DELTA	4

static int
kbd_realloc_array(void)
{
	keyboard_t **new_kbd;
	int newsize;
	int s;

	s = spltty();
	newsize = rounddown(keyboards + ARRAY_DELTA, ARRAY_DELTA);
	new_kbd = malloc(sizeof(*new_kbd)*newsize, M_DEVBUF, M_NOWAIT|M_ZERO);
	if (new_kbd == NULL) {
		splx(s);
		return (ENOMEM);
	}
	bcopy(keyboard, new_kbd, sizeof(*keyboard)*keyboards);
	if (keyboards > 1)
		free(keyboard, M_DEVBUF);
	keyboard = new_kbd;
	keyboards = newsize;
	splx(s);

	if (bootverbose)
		printf("kbd: new array size %d\n", keyboards);

	return (0);
}

/*
 * Low-level keyboard driver functions
 * Keyboard subdrivers, such as the AT keyboard driver and the USB keyboard
 * driver, call these functions to initialize the keyboard_t structure
 * and register it to the virtual keyboard driver `kbd'.
 */

/* initialize the keyboard_t structure */
void
kbd_init_struct(keyboard_t *kbd, char *name, int type, int unit, int config,
		int port, int port_size)
{
	kbd->kb_flags = KB_NO_DEVICE;	/* device has not been found */
	kbd->kb_name = name;
	kbd->kb_type = type;
	kbd->kb_unit = unit;
	kbd->kb_config = config & ~KB_CONF_PROBE_ONLY;
	kbd->kb_led = 0;		/* unknown */
	kbd->kb_io_base = port;
	kbd->kb_io_size = port_size;
	kbd->kb_data = NULL;
	kbd->kb_keymap = NULL;
	kbd->kb_accentmap = NULL;
	kbd->kb_fkeytab = NULL;
	kbd->kb_fkeytab_size = 0;
	kbd->kb_delay1 = KB_DELAY1;	/* these values are advisory only */
	kbd->kb_delay2 = KB_DELAY2;
	kbd->kb_count = 0L;
	bzero(kbd->kb_lastact, sizeof(kbd->kb_lastact));
}

void
kbd_set_maps(keyboard_t *kbd, keymap_t *keymap, accentmap_t *accmap,
	     fkeytab_t *fkeymap, int fkeymap_size)
{
	kbd->kb_keymap = keymap;
	kbd->kb_accentmap = accmap;
	kbd->kb_fkeytab = fkeymap;
	kbd->kb_fkeytab_size = fkeymap_size;
}

/* declare a new keyboard driver */
int
kbd_add_driver(keyboard_driver_t *driver)
{

	if ((driver->flags & KBDF_REGISTERED) != 0)
		return (0);

	KASSERT(SLIST_NEXT(driver, link) == NULL,
	    ("%s: keyboard driver list garbage detected", __func__));
	if (driver->kbdsw->get_fkeystr == NULL)
		driver->kbdsw->get_fkeystr = genkbd_get_fkeystr;
	if (driver->kbdsw->diag == NULL)
		driver->kbdsw->diag = genkbd_diag;

	driver->flags |= KBDF_REGISTERED;
	SLIST_INSERT_HEAD(&keyboard_drivers, driver, link);
	return (0);
}

int
kbd_delete_driver(keyboard_driver_t *driver)
{

	if ((driver->flags & KBDF_REGISTERED) == 0)
		return (EINVAL);

	driver->flags &= ~KBDF_REGISTERED;
	SLIST_REMOVE(&keyboard_drivers, driver, keyboard_driver, link);
	SLIST_NEXT(driver, link) = NULL;
	return (0);
}

/* register a keyboard and associate it with a function table */
int
kbd_register(keyboard_t *kbd)
{
	const keyboard_driver_t *p;
	keyboard_t *mux;
	keyboard_info_t ki;
	int index;

	mux = kbd_get_keyboard(kbd_find_keyboard("kbdmux", -1));

	for (index = 0; index < keyboards; ++index) {
		if (keyboard[index] == NULL)
			break;
	}
	if (index >= keyboards) {
		if (kbd_realloc_array())
			return (-1);
	}

	kbd->kb_index = index;
	KBD_UNBUSY(kbd);
	KBD_VALID(kbd);
	kbd->kb_active = 0;	/* disabled until someone calls kbd_enable() */
	kbd->kb_token = NULL;
	kbd->kb_callback.kc_func = NULL;
	kbd->kb_callback.kc_arg = NULL;

	SLIST_FOREACH(p, &keyboard_drivers, link) {
		if (strcmp(p->name, kbd->kb_name) == 0) {
			kbd->kb_drv = p;
			keyboard[index] = kbd;

			if (mux != NULL) {
				bzero(&ki, sizeof(ki));
				strcpy(ki.kb_name, kbd->kb_name);
				ki.kb_unit = kbd->kb_unit;

				(void)kbdd_ioctl(mux, KBADDKBD, (caddr_t) &ki);
			}

			return (index);
		}
	}

	return (-1);
}

int
kbd_unregister(keyboard_t *kbd)
{
	int error;
	int s;

	if ((kbd->kb_index < 0) || (kbd->kb_index >= keyboards))
		return (ENOENT);
	if (keyboard[kbd->kb_index] != kbd)
		return (ENOENT);

	s = spltty();
	if (KBD_IS_BUSY(kbd)) {
		error = (*kbd->kb_callback.kc_func)(kbd, KBDIO_UNLOADING,
		    kbd->kb_callback.kc_arg);
		if (error) {
			splx(s);
			return (error);
		}
		if (KBD_IS_BUSY(kbd)) {
			splx(s);
			return (EBUSY);
		}
	}
	KBD_INVALID(kbd);
	keyboard[kbd->kb_index] = NULL;

	splx(s);
	return (0);
}

/* find a function table by the driver name */
keyboard_switch_t *
kbd_get_switch(char *driver)
{
	const keyboard_driver_t *p;

	SLIST_FOREACH(p, &keyboard_drivers, link) {
		if (strcmp(p->name, driver) == 0)
			return (p->kbdsw);
	}

	return (NULL);
}

/*
 * Keyboard client functions
 * Keyboard clients, such as the console driver `syscons' and the keyboard
 * cdev driver, use these functions to claim and release a keyboard for
 * exclusive use.
 */

/*
 * find the keyboard specified by a driver name and a unit number
 * starting at given index
 */
int
kbd_find_keyboard2(char *driver, int unit, int index)
{
	int i;

	if ((index < 0) || (index >= keyboards))
		return (-1);

	for (i = index; i < keyboards; ++i) {
		if (keyboard[i] == NULL)
			continue;
		if (!KBD_IS_VALID(keyboard[i]))
			continue;
		if (strcmp("*", driver) && strcmp(keyboard[i]->kb_name, driver))
			continue;
		if ((unit != -1) && (keyboard[i]->kb_unit != unit))
			continue;
		return (i);
	}

	return (-1);
}

/* find the keyboard specified by a driver name and a unit number */
int
kbd_find_keyboard(char *driver, int unit)
{
	return (kbd_find_keyboard2(driver, unit, 0));
}

/* allocate a keyboard */
int
kbd_allocate(char *driver, int unit, void *id, kbd_callback_func_t *func,
	     void *arg)
{
	int index;
	int s;

	if (func == NULL)
		return (-1);

	s = spltty();
	index = kbd_find_keyboard(driver, unit);
	if (index >= 0) {
		if (KBD_IS_BUSY(keyboard[index])) {
			splx(s);
			return (-1);
		}
		keyboard[index]->kb_token = id;
		KBD_BUSY(keyboard[index]);
		keyboard[index]->kb_callback.kc_func = func;
		keyboard[index]->kb_callback.kc_arg = arg;
		kbdd_clear_state(keyboard[index]);
	}
	splx(s);
	return (index);
}

int
kbd_release(keyboard_t *kbd, void *id)
{
	int error;
	int s;

	s = spltty();
	if (!KBD_IS_VALID(kbd) || !KBD_IS_BUSY(kbd)) {
		error = EINVAL;
	} else if (kbd->kb_token != id) {
		error = EPERM;
	} else {
		kbd->kb_token = NULL;
		KBD_UNBUSY(kbd);
		kbd->kb_callback.kc_func = NULL;
		kbd->kb_callback.kc_arg = NULL;
		kbdd_clear_state(kbd);
		error = 0;
	}
	splx(s);
	return (error);
}

int
kbd_change_callback(keyboard_t *kbd, void *id, kbd_callback_func_t *func,
		    void *arg)
{
	int error;
	int s;

	s = spltty();
	if (!KBD_IS_VALID(kbd) || !KBD_IS_BUSY(kbd)) {
		error = EINVAL;
	} else if (kbd->kb_token != id) {
		error = EPERM;
	} else if (func == NULL) {
		error = EINVAL;
	} else {
		kbd->kb_callback.kc_func = func;
		kbd->kb_callback.kc_arg = arg;
		error = 0;
	}
	splx(s);
	return (error);
}

/* get a keyboard structure */
keyboard_t *
kbd_get_keyboard(int index)
{
	if ((index < 0) || (index >= keyboards))
		return (NULL);
	if (keyboard[index] == NULL)
		return (NULL);
	if (!KBD_IS_VALID(keyboard[index]))
		return (NULL);
	return (keyboard[index]);
}

/*
 * The back door for the console driver; configure keyboards
 * This function is for the kernel console to initialize keyboards
 * at very early stage.
 */

int
kbd_configure(int flags)
{
	const keyboard_driver_t *p;

	SLIST_FOREACH(p, &keyboard_drivers, link) {
		if (p->configure != NULL)
			(*p->configure)(flags);
	}

	return (0);
}

#ifdef KBD_INSTALL_CDEV

/*
 * Virtual keyboard cdev driver functions
 * The virtual keyboard driver dispatches driver functions to
 * appropriate subdrivers.
 */

#define KBD_UNIT(dev)	dev2unit(dev)

static d_open_t		genkbdopen;
static d_close_t	genkbdclose;
static d_read_t		genkbdread;
static d_write_t	genkbdwrite;
static d_ioctl_t	genkbdioctl;
static d_poll_t		genkbdpoll;


static struct cdevsw kbd_cdevsw = {
	.d_version =	D_VERSION,
	.d_flags =	D_NEEDGIANT,
	.d_open =	genkbdopen,
	.d_close =	genkbdclose,
	.d_read =	genkbdread,
	.d_write =	genkbdwrite,
	.d_ioctl =	genkbdioctl,
	.d_poll =	genkbdpoll,
	.d_name =	"kbd",
};

int
kbd_attach(keyboard_t *kbd)
{

	if (kbd->kb_index >= keyboards)
		return (EINVAL);
	if (keyboard[kbd->kb_index] != kbd)
		return (EINVAL);

	kbd->kb_dev = make_dev(&kbd_cdevsw, kbd->kb_index, UID_ROOT, GID_WHEEL,
	    0600, "%s%r", kbd->kb_name, kbd->kb_unit);
	make_dev_alias(kbd->kb_dev, "kbd%r", kbd->kb_index);
	kbd->kb_dev->si_drv1 = malloc(sizeof(genkbd_softc_t), M_DEVBUF,
	    M_WAITOK | M_ZERO);
	printf("kbd%d at %s%d\n", kbd->kb_index, kbd->kb_name, kbd->kb_unit);
	return (0);
}

int
kbd_detach(keyboard_t *kbd)
{

	if (kbd->kb_index >= keyboards)
		return (EINVAL);
	if (keyboard[kbd->kb_index] != kbd)
		return (EINVAL);

	free(kbd->kb_dev->si_drv1, M_DEVBUF);
	destroy_dev(kbd->kb_dev);

	return (0);
}

/*
 * Generic keyboard cdev driver functions
 * Keyboard subdrivers may call these functions to implement common
 * driver functions.
 */

static void
genkbd_putc(genkbd_softc_t *sc, char c)
{
	unsigned int p;

	if (sc->gkb_q_length == KB_QSIZE)
		return;

	p = (sc->gkb_q_start + sc->gkb_q_length) % KB_QSIZE;
	sc->gkb_q[p] = c;
	sc->gkb_q_length++;
}

static size_t
genkbd_getc(genkbd_softc_t *sc, char *buf, size_t len)
{

	/* Determine copy size. */
	if (sc->gkb_q_length == 0)
		return (0);
	if (len >= sc->gkb_q_length)
		len = sc->gkb_q_length;
	if (len >= KB_QSIZE - sc->gkb_q_start)
		len = KB_QSIZE - sc->gkb_q_start;

	/* Copy out data and progress offset. */
	memcpy(buf, sc->gkb_q + sc->gkb_q_start, len);
	sc->gkb_q_start = (sc->gkb_q_start + len) % KB_QSIZE;
	sc->gkb_q_length -= len;

	return (len);
}

static kbd_callback_func_t genkbd_event;

static int
genkbdopen(struct cdev *dev, int mode, int flag, struct thread *td)
{
	keyboard_t *kbd;
	genkbd_softc_t *sc;
	int s;
	int i;

	s = spltty();
	sc = dev->si_drv1;
	kbd = kbd_get_keyboard(KBD_INDEX(dev));
	if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
		splx(s);
		return (ENXIO);
	}
	i = kbd_allocate(kbd->kb_name, kbd->kb_unit, sc,
	    genkbd_event, (void *)sc);
	if (i < 0) {
		splx(s);
		return (EBUSY);
	}
	/* assert(i == kbd->kb_index) */
	/* assert(kbd == kbd_get_keyboard(i)) */

	/*
	 * NOTE: even when we have successfully claimed a keyboard,
	 * the device may still be missing (!KBD_HAS_DEVICE(kbd)).
	 */

	sc->gkb_q_length = 0;
	splx(s);

	return (0);
}

static int
genkbdclose(struct cdev *dev, int mode, int flag, struct thread *td)
{
	keyboard_t *kbd;
	genkbd_softc_t *sc;
	int s;

	/*
	 * NOTE: the device may have already become invalid.
	 * kbd == NULL || !KBD_IS_VALID(kbd)
	 */
	s = spltty();
	sc = dev->si_drv1;
	kbd = kbd_get_keyboard(KBD_INDEX(dev));
	if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
		/* XXX: we shall be forgiving and don't report error... */
	} else {
		kbd_release(kbd, (void *)sc);
	}
	splx(s);
	return (0);
}

static int
genkbdread(struct cdev *dev, struct uio *uio, int flag)
{
	keyboard_t *kbd;
	genkbd_softc_t *sc;
	u_char buffer[KB_BUFSIZE];
	int len;
	int error;
	int s;

	/* wait for input */
	s = spltty();
	sc = dev->si_drv1;
	kbd = kbd_get_keyboard(KBD_INDEX(dev));
	if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
		splx(s);
		return (ENXIO);
	}
	while (sc->gkb_q_length == 0) {
		if (flag & O_NONBLOCK) {
			splx(s);
			return (EWOULDBLOCK);
		}
		sc->gkb_flags |= KB_ASLEEP;
		error = tsleep(sc, PZERO | PCATCH, "kbdrea", 0);
		kbd = kbd_get_keyboard(KBD_INDEX(dev));
		if ((kbd == NULL) || !KBD_IS_VALID(kbd)) {
			splx(s);
			return (ENXIO);	/* our keyboard has gone... */
		}
		if (error) {
			sc->gkb_flags &= ~KB_ASLEEP;
			splx(s);
			return (error);
		}
	}
	splx(s);

	/* copy as much input as possible */
	error = 0;
	while (uio->uio_resid > 0) {
		len = imin(uio->uio_resid, sizeof(buffer));
		len = genkbd_getc(sc, buffer, len);
		if (len <= 0)
			break;
		error = uiomove(buffer, len, uio);
		if (error)
			break;
	}

	return (error);
}

static int
genkbdwrite(struct cdev *dev, struct uio *uio, int flag)
{
	keyboard_t *kbd;

	kbd = kbd_get_keyboard(KBD_INDEX(dev));
	if ((kbd == NULL) || !KBD_IS_VALID(kbd))
		return (ENXIO);
	return (ENODEV);
}

static int
genkbdioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thread *td)
{
	keyboard_t *kbd;
	int error;

	kbd = kbd_get_keyboard(KBD_INDEX(dev));
	if ((kbd == NULL) || !KBD_IS_VALID(kbd))
		return (ENXIO);
	error = kbdd_ioctl(kbd, cmd, arg);
	if (error == ENOIOCTL)
		error = ENODEV;
	return (error);
}

static int
genkbdpoll(struct cdev *dev, int events, struct thread *td)
{
	keyboard_t *kbd;
	genkbd_softc_t *sc;
	int revents;
	int s;

	revents = 0;
	s = spltty();
	sc = dev->si_drv1;
	kbd = kbd_get_keyboard(KBD_INDEX(dev));
	if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
		revents =  POLLHUP;	/* the keyboard has gone */
	} else if (events & (POLLIN | POLLRDNORM)) {
		if (sc->gkb_q_length > 0)
			revents = events & (POLLIN | POLLRDNORM);
		else
			selrecord(td, &sc->gkb_rsel);
	}
	splx(s);
	return (revents);
}

static int
genkbd_event(keyboard_t *kbd, int event, void *arg)
{
	genkbd_softc_t *sc;
	size_t len;
	u_char *cp;
	int mode;
	u_int c;

	/* assert(KBD_IS_VALID(kbd)) */
	sc = (genkbd_softc_t *)arg;

	switch (event) {
	case KBDIO_KEYINPUT:
		break;
	case KBDIO_UNLOADING:
		/* the keyboard is going... */
		kbd_release(kbd, (void *)sc);
		if (sc->gkb_flags & KB_ASLEEP) {
			sc->gkb_flags &= ~KB_ASLEEP;
			wakeup(sc);
		}
		selwakeuppri(&sc->gkb_rsel, PZERO);
		return (0);
	default:
		return (EINVAL);
	}

	/* obtain the current key input mode */
	if (kbdd_ioctl(kbd, KDGKBMODE, (caddr_t)&mode))
		mode = K_XLATE;

	/* read all pending input */
	while (kbdd_check_char(kbd)) {
		c = kbdd_read_char(kbd, FALSE);
		if (c == NOKEY)
			continue;
		if (c == ERRKEY)	/* XXX: ring bell? */
			continue;
		if (!KBD_IS_BUSY(kbd))
			/* the device is not open, discard the input */
			continue;

		/* store the byte as is for K_RAW and K_CODE modes */
		if (mode != K_XLATE) {
			genkbd_putc(sc, KEYCHAR(c));
			continue;
		}

		/* K_XLATE */
		if (c & RELKEY)	/* key release is ignored */
			continue;

		/* process special keys; most of them are just ignored... */
		if (c & SPCLKEY) {
			switch (KEYCHAR(c)) {
			default:
				/* ignore them... */
				continue;
			case BTAB:	/* a backtab: ESC [ Z */
				genkbd_putc(sc, 0x1b);
				genkbd_putc(sc, '[');
				genkbd_putc(sc, 'Z');
				continue;
			}
		}

		/* normal chars, normal chars with the META, function keys */
		switch (KEYFLAGS(c)) {
		case 0:			/* a normal char */
			genkbd_putc(sc, KEYCHAR(c));
			break;
		case MKEY:		/* the META flag: prepend ESC */
			genkbd_putc(sc, 0x1b);
			genkbd_putc(sc, KEYCHAR(c));
			break;
		case FKEY | SPCLKEY:	/* a function key, return string */
			cp = kbdd_get_fkeystr(kbd, KEYCHAR(c), &len);
			if (cp != NULL) {
				while (len-- >  0)
					genkbd_putc(sc, *cp++);
			}
			break;
		}
	}

	/* wake up sleeping/polling processes */
	if (sc->gkb_q_length > 0) {
		if (sc->gkb_flags & KB_ASLEEP) {
			sc->gkb_flags &= ~KB_ASLEEP;
			wakeup(sc);
		}
		selwakeuppri(&sc->gkb_rsel, PZERO);
	}

	return (0);
}

#endif /* KBD_INSTALL_CDEV */

/*
 * Generic low-level keyboard functions
 * The low-level functions in the keyboard subdriver may use these
 * functions.
 */

#ifndef KBD_DISABLE_KEYMAP_LOAD
static int key_change_ok(struct keyent_t *, struct keyent_t *, struct thread *);
static int keymap_change_ok(keymap_t *, keymap_t *, struct thread *);
static int accent_change_ok(accentmap_t *, accentmap_t *, struct thread *);
static int fkey_change_ok(fkeytab_t *, fkeyarg_t *, struct thread *);
#endif

int
genkbd_commonioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
{
	keymap_t *mapp;
	okeymap_t *omapp;
	keyarg_t *keyp;
	fkeyarg_t *fkeyp;
	int s;
	int i, j;
	int error;

	s = spltty();
	switch (cmd) {

	case KDGKBINFO:		/* get keyboard information */
		((keyboard_info_t *)arg)->kb_index = kbd->kb_index;
		i = imin(strlen(kbd->kb_name) + 1,
		    sizeof(((keyboard_info_t *)arg)->kb_name));
		bcopy(kbd->kb_name, ((keyboard_info_t *)arg)->kb_name, i);
		((keyboard_info_t *)arg)->kb_unit = kbd->kb_unit;
		((keyboard_info_t *)arg)->kb_type = kbd->kb_type;
		((keyboard_info_t *)arg)->kb_config = kbd->kb_config;
		((keyboard_info_t *)arg)->kb_flags = kbd->kb_flags;
		break;

	case KDGKBTYPE:		/* get keyboard type */
		*(int *)arg = kbd->kb_type;
		break;

	case KDGETREPEAT:	/* get keyboard repeat rate */
		((int *)arg)[0] = kbd->kb_delay1;
		((int *)arg)[1] = kbd->kb_delay2;
		break;

	case GIO_KEYMAP:	/* get keyboard translation table */
		error = copyout(kbd->kb_keymap, *(void **)arg,
		    sizeof(keymap_t));
		splx(s);
		return (error);
	case OGIO_KEYMAP:	/* get keyboard translation table (compat) */
		mapp = kbd->kb_keymap;
		omapp = (okeymap_t *)arg;
		omapp->n_keys = mapp->n_keys;
		for (i = 0; i < NUM_KEYS; i++) {
			for (j = 0; j < NUM_STATES; j++)
				omapp->key[i].map[j] =
				    mapp->key[i].map[j];
			omapp->key[i].spcl = mapp->key[i].spcl;
			omapp->key[i].flgs = mapp->key[i].flgs;
		}
		break;
	case PIO_KEYMAP:	/* set keyboard translation table */
	case OPIO_KEYMAP:	/* set keyboard translation table (compat) */
#ifndef KBD_DISABLE_KEYMAP_LOAD
		mapp = malloc(sizeof *mapp, M_TEMP, M_WAITOK);
		if (cmd == OPIO_KEYMAP) {
			omapp = (okeymap_t *)arg;
			mapp->n_keys = omapp->n_keys;
			for (i = 0; i < NUM_KEYS; i++) {
				for (j = 0; j < NUM_STATES; j++)
					mapp->key[i].map[j] =
					    omapp->key[i].map[j];
				mapp->key[i].spcl = omapp->key[i].spcl;
				mapp->key[i].flgs = omapp->key[i].flgs;
			}
		} else {
			error = copyin(*(void **)arg, mapp, sizeof *mapp);
			if (error != 0) {
				splx(s);
				free(mapp, M_TEMP);
				return (error);
			}
		}

		error = keymap_change_ok(kbd->kb_keymap, mapp, curthread);
		if (error != 0) {
			splx(s);
			free(mapp, M_TEMP);
			return (error);
		}
		bzero(kbd->kb_accentmap, sizeof(*kbd->kb_accentmap));
		bcopy(mapp, kbd->kb_keymap, sizeof(*kbd->kb_keymap));
		free(mapp, M_TEMP);
		break;
#else
		splx(s);
		return (ENODEV);
#endif

	case GIO_KEYMAPENT:	/* get keyboard translation table entry */
		keyp = (keyarg_t *)arg;
		if (keyp->keynum >= sizeof(kbd->kb_keymap->key) /
		    sizeof(kbd->kb_keymap->key[0])) {
			splx(s);
			return (EINVAL);
		}
		bcopy(&kbd->kb_keymap->key[keyp->keynum], &keyp->key,
		    sizeof(keyp->key));
		break;
	case PIO_KEYMAPENT:	/* set keyboard translation table entry */
#ifndef KBD_DISABLE_KEYMAP_LOAD
		keyp = (keyarg_t *)arg;
		if (keyp->keynum >= sizeof(kbd->kb_keymap->key) /
		    sizeof(kbd->kb_keymap->key[0])) {
			splx(s);
			return (EINVAL);
		}
		error = key_change_ok(&kbd->kb_keymap->key[keyp->keynum],
		    &keyp->key, curthread);
		if (error != 0) {
			splx(s);
			return (error);
		}
		bcopy(&keyp->key, &kbd->kb_keymap->key[keyp->keynum],
		    sizeof(keyp->key));
		break;
#else
		splx(s);
		return (ENODEV);
#endif

	case GIO_DEADKEYMAP:	/* get accent key translation table */
		bcopy(kbd->kb_accentmap, arg, sizeof(*kbd->kb_accentmap));
		break;
	case PIO_DEADKEYMAP:	/* set accent key translation table */
#ifndef KBD_DISABLE_KEYMAP_LOAD
		error = accent_change_ok(kbd->kb_accentmap,
		    (accentmap_t *)arg, curthread);
		if (error != 0) {
			splx(s);
			return (error);
		}
		bcopy(arg, kbd->kb_accentmap, sizeof(*kbd->kb_accentmap));
		break;
#else
		splx(s);
		return (ENODEV);
#endif

	case GETFKEY:		/* get functionkey string */
		fkeyp = (fkeyarg_t *)arg;
		if (fkeyp->keynum >= kbd->kb_fkeytab_size) {
			splx(s);
			return (EINVAL);
		}
		bcopy(kbd->kb_fkeytab[fkeyp->keynum].str, fkeyp->keydef,
		    kbd->kb_fkeytab[fkeyp->keynum].len);
		fkeyp->flen = kbd->kb_fkeytab[fkeyp->keynum].len;
		break;
	case SETFKEY:		/* set functionkey string */
#ifndef KBD_DISABLE_KEYMAP_LOAD
		fkeyp = (fkeyarg_t *)arg;
		if (fkeyp->keynum >= kbd->kb_fkeytab_size) {
			splx(s);
			return (EINVAL);
		}
		error = fkey_change_ok(&kbd->kb_fkeytab[fkeyp->keynum],
		    fkeyp, curthread);
		if (error != 0) {
			splx(s);
			return (error);
		}
		kbd->kb_fkeytab[fkeyp->keynum].len = min(fkeyp->flen, MAXFK);
		bcopy(fkeyp->keydef, kbd->kb_fkeytab[fkeyp->keynum].str,
		    kbd->kb_fkeytab[fkeyp->keynum].len);
		break;
#else
		splx(s);
		return (ENODEV);
#endif

	default:
		splx(s);
		return (ENOIOCTL);
	}

	splx(s);
	return (0);
}

#ifndef KBD_DISABLE_KEYMAP_LOAD
#define RESTRICTED_KEY(key, i) \
	((key->spcl & (0x80 >> i)) && \
		(key->map[i] == RBT || key->map[i] == SUSP || \
		 key->map[i] == STBY || key->map[i] == DBG || \
		 key->map[i] == PNC || key->map[i] == HALT || \
		 key->map[i] == PDWN))

static int
key_change_ok(struct keyent_t *oldkey, struct keyent_t *newkey, struct thread *td)
{
	int i;

	/* Low keymap_restrict_change means any changes are OK. */
	if (keymap_restrict_change <= 0)
		return (0);

	/* High keymap_restrict_change means only root can change the keymap. */
	if (keymap_restrict_change >= 2) {
		for (i = 0; i < NUM_STATES; i++)
			if (oldkey->map[i] != newkey->map[i])
				return priv_check(td, PRIV_KEYBOARD);
		if (oldkey->spcl != newkey->spcl)
			return priv_check(td, PRIV_KEYBOARD);
		if (oldkey->flgs != newkey->flgs)
			return priv_check(td, PRIV_KEYBOARD);
		return (0);
	}

	/* Otherwise we have to see if any special keys are being changed. */
	for (i = 0; i < NUM_STATES; i++) {
		/*
		 * If either the oldkey or the newkey action is restricted
		 * then we must make sure that the action doesn't change.
		 */
		if (!RESTRICTED_KEY(oldkey, i) && !RESTRICTED_KEY(newkey, i))
			continue;
		if ((oldkey->spcl & (0x80 >> i)) == (newkey->spcl & (0x80 >> i))
		    && oldkey->map[i] == newkey->map[i])
			continue;
		return priv_check(td, PRIV_KEYBOARD);
	}

	return (0);
}

static int
keymap_change_ok(keymap_t *oldmap, keymap_t *newmap, struct thread *td)
{
	int keycode, error;

	for (keycode = 0; keycode < NUM_KEYS; keycode++) {
		if ((error = key_change_ok(&oldmap->key[keycode],
		    &newmap->key[keycode], td)) != 0)
			return (error);
	}
	return (0);
}

static int
accent_change_ok(accentmap_t *oldmap, accentmap_t *newmap, struct thread *td)
{
	struct acc_t *oldacc, *newacc;
	int accent, i;

	if (keymap_restrict_change <= 2)
		return (0);

	if (oldmap->n_accs != newmap->n_accs)
		return priv_check(td, PRIV_KEYBOARD);

	for (accent = 0; accent < oldmap->n_accs; accent++) {
		oldacc = &oldmap->acc[accent];
		newacc = &newmap->acc[accent];
		if (oldacc->accchar != newacc->accchar)
			return priv_check(td, PRIV_KEYBOARD);
		for (i = 0; i < NUM_ACCENTCHARS; ++i) {
			if (oldacc->map[i][0] != newacc->map[i][0])
				return priv_check(td, PRIV_KEYBOARD);
			if (oldacc->map[i][0] == 0)	/* end of table */
				break;
			if (oldacc->map[i][1] != newacc->map[i][1])
				return priv_check(td, PRIV_KEYBOARD);
		}
	}

	return (0);
}

static int
fkey_change_ok(fkeytab_t *oldkey, fkeyarg_t *newkey, struct thread *td)
{
	if (keymap_restrict_change <= 3)
		return (0);

	if (oldkey->len != newkey->flen ||
	    bcmp(oldkey->str, newkey->keydef, oldkey->len) != 0)
		return priv_check(td, PRIV_KEYBOARD);

	return (0);
}
#endif

/* get a pointer to the string associated with the given function key */
static u_char *
genkbd_get_fkeystr(keyboard_t *kbd, int fkey, size_t *len)
{
	if (kbd == NULL)
		return (NULL);
	fkey -= F_FN;
	if (fkey > kbd->kb_fkeytab_size)
		return (NULL);
	*len = kbd->kb_fkeytab[fkey].len;
	return (kbd->kb_fkeytab[fkey].str);
}

/* diagnostic dump */
static char *
get_kbd_type_name(int type)
{
	static struct {
		int type;
		char *name;
	} name_table[] = {
		{ KB_84,	"AT 84" },
		{ KB_101,	"AT 101/102" },
		{ KB_OTHER,	"generic" },
	};
	int i;

	for (i = 0; i < nitems(name_table); ++i) {
		if (type == name_table[i].type)
			return (name_table[i].name);
	}
	return ("unknown");
}

static void
genkbd_diag(keyboard_t *kbd, int level)
{
	if (level > 0) {
		printf("kbd%d: %s%d, %s (%d), config:0x%x, flags:0x%x",
		    kbd->kb_index, kbd->kb_name, kbd->kb_unit,
		    get_kbd_type_name(kbd->kb_type), kbd->kb_type,
		    kbd->kb_config, kbd->kb_flags);
		if (kbd->kb_io_base > 0)
			printf(", port:0x%x-0x%x", kbd->kb_io_base,
			    kbd->kb_io_base + kbd->kb_io_size - 1);
		printf("\n");
	}
}

#define set_lockkey_state(k, s, l)				\
	if (!((s) & l ## DOWN)) {				\
		int i;						\
		(s) |= l ## DOWN;				\
		(s) ^= l ## ED;					\
		i = (s) & LOCK_MASK;				\
		(void)kbdd_ioctl((k), KDSETLED, (caddr_t)&i);	\
	}

static u_int
save_accent_key(keyboard_t *kbd, u_int key, int *accents)
{
	int i;

	/* make an index into the accent map */
	i = key - F_ACC + 1;
	if ((i > kbd->kb_accentmap->n_accs)
	    || (kbd->kb_accentmap->acc[i - 1].accchar == 0)) {
		/* the index is out of range or pointing to an empty entry */
		*accents = 0;
		return (ERRKEY);
	}

	/*
	 * If the same accent key has been hit twice, produce the accent
	 * char itself.
	 */
	if (i == *accents) {
		key = kbd->kb_accentmap->acc[i - 1].accchar;
		*accents = 0;
		return (key);
	}

	/* remember the index and wait for the next key  */
	*accents = i;
	return (NOKEY);
}

static u_int
make_accent_char(keyboard_t *kbd, u_int ch, int *accents)
{
	struct acc_t *acc;
	int i;

	acc = &kbd->kb_accentmap->acc[*accents - 1];
	*accents = 0;

	/*
	 * If the accent key is followed by the space key,
	 * produce the accent char itself.
	 */
	if (ch == ' ')
		return (acc->accchar);

	/* scan the accent map */
	for (i = 0; i < NUM_ACCENTCHARS; ++i) {
		if (acc->map[i][0] == 0)	/* end of table */
			break;
		if (acc->map[i][0] == ch)
			return (acc->map[i][1]);
	}
	/* this char cannot be accented... */
	return (ERRKEY);
}

int
genkbd_keyaction(keyboard_t *kbd, int keycode, int up, int *shiftstate,
		 int *accents)
{
	struct keyent_t *key;
	int state = *shiftstate;
	int action;
	int f;
	int i;

	i = keycode;
	f = state & (AGRS | ALKED);
	if ((f == AGRS1) || (f == AGRS2) || (f == ALKED))
		i += ALTGR_OFFSET;
	key = &kbd->kb_keymap->key[i];
	i = ((state & SHIFTS) ? 1 : 0)
	    | ((state & CTLS) ? 2 : 0)
	    | ((state & ALTS) ? 4 : 0);
	if (((key->flgs & FLAG_LOCK_C) && (state & CLKED))
		|| ((key->flgs & FLAG_LOCK_N) && (state & NLKED)) )
		i ^= 1;

	if (up) {	/* break: key released */
		action = kbd->kb_lastact[keycode];
		kbd->kb_lastact[keycode] = NOP;
		switch (action) {
		case LSHA:
			if (state & SHIFTAON) {
				set_lockkey_state(kbd, state, ALK);
				state &= ~ALKDOWN;
			}
			action = LSH;
			/* FALL THROUGH */
		case LSH:
			state &= ~SHIFTS1;
			break;
		case RSHA:
			if (state & SHIFTAON) {
				set_lockkey_state(kbd, state, ALK);
				state &= ~ALKDOWN;
			}
			action = RSH;
			/* FALL THROUGH */
		case RSH:
			state &= ~SHIFTS2;
			break;
		case LCTRA:
			if (state & SHIFTAON) {
				set_lockkey_state(kbd, state, ALK);
				state &= ~ALKDOWN;
			}
			action = LCTR;
			/* FALL THROUGH */
		case LCTR:
			state &= ~CTLS1;
			break;
		case RCTRA:
			if (state & SHIFTAON) {
				set_lockkey_state(kbd, state, ALK);
				state &= ~ALKDOWN;
			}
			action = RCTR;
			/* FALL THROUGH */
		case RCTR:
			state &= ~CTLS2;
			break;
		case LALTA:
			if (state & SHIFTAON) {
				set_lockkey_state(kbd, state, ALK);
				state &= ~ALKDOWN;
			}
			action = LALT;
			/* FALL THROUGH */
		case LALT:
			state &= ~ALTS1;
			break;
		case RALTA:
			if (state & SHIFTAON) {
				set_lockkey_state(kbd, state, ALK);
				state &= ~ALKDOWN;
			}
			action = RALT;
			/* FALL THROUGH */
		case RALT:
			state &= ~ALTS2;
			break;
		case ASH:
			state &= ~AGRS1;
			break;
		case META:
			state &= ~METAS1;
			break;
		case NLK:
			state &= ~NLKDOWN;
			break;
		case CLK:
			state &= ~CLKDOWN;
			break;
		case SLK:
			state &= ~SLKDOWN;
			break;
		case ALK:
			state &= ~ALKDOWN;
			break;
		case NOP:
			/* release events of regular keys are not reported */
			*shiftstate &= ~SHIFTAON;
			return (NOKEY);
		}
		*shiftstate = state & ~SHIFTAON;
		return (SPCLKEY | RELKEY | action);
	} else {	/* make: key pressed */
		action = key->map[i];
		state &= ~SHIFTAON;
		if (key->spcl & (0x80 >> i)) {
			/* special keys */
			if (kbd->kb_lastact[keycode] == NOP)
				kbd->kb_lastact[keycode] = action;
			if (kbd->kb_lastact[keycode] != action)
				action = NOP;
			switch (action) {
			/* LOCKING KEYS */
			case NLK:
				set_lockkey_state(kbd, state, NLK);
				break;
			case CLK:
				set_lockkey_state(kbd, state, CLK);
				break;
			case SLK:
				set_lockkey_state(kbd, state, SLK);
				break;
			case ALK:
				set_lockkey_state(kbd, state, ALK);
				break;
			/* NON-LOCKING KEYS */
			case SPSC: case RBT:  case SUSP: case STBY:
			case DBG:  case NEXT: case PREV: case PNC:
			case HALT: case PDWN:
				*accents = 0;
				break;
			case BTAB:
				*accents = 0;
				action |= BKEY;
				break;
			case LSHA:
				state |= SHIFTAON;
				action = LSH;
				/* FALL THROUGH */
			case LSH:
				state |= SHIFTS1;
				break;
			case RSHA:
				state |= SHIFTAON;
				action = RSH;
				/* FALL THROUGH */
			case RSH:
				state |= SHIFTS2;
				break;
			case LCTRA:
				state |= SHIFTAON;
				action = LCTR;
				/* FALL THROUGH */
			case LCTR:
				state |= CTLS1;
				break;
			case RCTRA:
				state |= SHIFTAON;
				action = RCTR;
				/* FALL THROUGH */
			case RCTR:
				state |= CTLS2;
				break;
			case LALTA:
				state |= SHIFTAON;
				action = LALT;
				/* FALL THROUGH */
			case LALT:
				state |= ALTS1;
				break;
			case RALTA:
				state |= SHIFTAON;
				action = RALT;
				/* FALL THROUGH */
			case RALT:
				state |= ALTS2;
				break;
			case ASH:
				state |= AGRS1;
				break;
			case META:
				state |= METAS1;
				break;
			case NOP:
				*shiftstate = state;
				return (NOKEY);
			default:
				/* is this an accent (dead) key? */
				*shiftstate = state;
				if (action >= F_ACC && action <= L_ACC) {
					action = save_accent_key(kbd, action,
								 accents);
					switch (action) {
					case NOKEY:
					case ERRKEY:
						return (action);
					default:
						if (state & METAS)
							return (action | MKEY);
						else
							return (action);
					}
					/* NOT REACHED */
				}
				/* other special keys */
				if (*accents > 0) {
					*accents = 0;
					return (ERRKEY);
				}
				if (action >= F_FN && action <= L_FN)
					action |= FKEY;
				/* XXX: return fkey string for the FKEY? */
				return (SPCLKEY | action);
			}
			*shiftstate = state;
			return (SPCLKEY | action);
		} else {
			/* regular keys */
			kbd->kb_lastact[keycode] = NOP;
			*shiftstate = state;
			if (*accents > 0) {
				/* make an accented char */
				action = make_accent_char(kbd, action, accents);
				if (action == ERRKEY)
					return (action);
			}
			if (state & METAS)
				action |= MKEY;
			return (action);
		}
	}
	/* NOT REACHED */
}

void
kbd_ev_event(keyboard_t *kbd, uint16_t type, uint16_t code, int32_t value)
{
	int delay[2], led = 0, leds, oleds;

	if (type == EV_LED) {
		leds = oleds = KBD_LED_VAL(kbd);
		switch (code) {
		case LED_CAPSL:
			led = CLKED;
			break;
		case LED_NUML:
			led = NLKED;
			break;
		case LED_SCROLLL:
			led = SLKED;
			break;
		}

		if (value)
			leds |= led;
		else
			leds &= ~led;

		if (leds != oleds)
			kbdd_ioctl(kbd, KDSETLED, (caddr_t)&leds);

	} else if (type == EV_REP && code == REP_DELAY) {
		delay[0] = value;
		delay[1] = kbd->kb_delay2;
		kbdd_ioctl(kbd, KDSETREPEAT, (caddr_t)delay);
	} else if (type == EV_REP && code == REP_PERIOD) {
		delay[0] = kbd->kb_delay1;
		delay[1] = value;
		kbdd_ioctl(kbd, KDSETREPEAT, (caddr_t)delay);
	}
}

void
kbdinit(void)
{
	keyboard_driver_t *drv, **list;

	SET_FOREACH(list, kbddriver_set) {
		drv = *list;

		/*
		 * The following printfs will almost universally get dropped,
		 * with exception to kernel configs with EARLY_PRINTF and
		 * special setups where msgbufinit() is called early with a
		 * static buffer to capture output occurring before the dynamic
		 * message buffer is mapped.
		 */
		if (kbd_add_driver(drv) != 0)
			printf("kbd: failed to register driver '%s'\n",
			    drv->name);
		else if (bootverbose)
			printf("kbd: registered driver '%s'\n",
			    drv->name);
	}

}