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
/* $NetBSD: gpio.c,v 1.72 2022/12/13 21:50:43 jakllsch Exp $ */
/*	$OpenBSD: gpio.c,v 1.6 2006/01/14 12:33:49 grange Exp $	*/

/*
 * Copyright (c) 2008, 2009, 2010, 2011 Marc Balmer <marc@msys.ch>
 * Copyright (c) 2004, 2006 Alexander Yurchenko <grange@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifdef _KERNEL_OPT
#include "opt_fdt.h"
#endif

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: gpio.c,v 1.72 2022/12/13 21:50:43 jakllsch Exp $");

/*
 * General Purpose Input/Output framework.
 */

#include <sys/param.h>
#include <sys/callout.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/device.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <sys/gpio.h>
#include <sys/kernel.h>
#include <sys/vnode.h>
#include <sys/kmem.h>
#include <sys/mutex.h>
#include <sys/condvar.h>
#include <sys/queue.h>
#include <sys/kauth.h>
#include <sys/module.h>

#include <dev/gpio/gpiovar.h>

#ifdef FDT
#include <dev/fdt/fdtvar.h>
#endif

#include "ioconf.h"
#include "locators.h"

#ifdef GPIO_DEBUG
#define DPRINTFN(n, x)	do { if (gpiodebug > (n)) printf x; } while (0)
int gpiodebug = 0;
#else
#define DPRINTFN(n, x)
#endif
#define DPRINTF(x)	DPRINTFN(0, x)

struct gpio_softc {
	device_t		 sc_dev;

	gpio_chipset_tag_t	 sc_gc;		/* GPIO controller */
	gpio_pin_t		*sc_pins;	/* pins array */
	int			 sc_npins;	/* number of pins */

	kmutex_t		 sc_mtx;
	kcondvar_t		 sc_ioctl;	/* ioctl in progress */
	int			 sc_ioctl_busy;	/* ioctl is busy */
	kcondvar_t		 sc_attach;	/* attach/detach in progress */
	int			 sc_attach_busy;/* busy in attach/detach */
#ifdef COMPAT_50
	LIST_HEAD(, gpio_dev)	 sc_devs;	/* devices */
#endif
	LIST_HEAD(, gpio_name)	 sc_names;	/* named pins */
};

static int	gpio_match(device_t, cfdata_t, void *);
int		gpio_submatch(device_t, cfdata_t, const int *, void *);
static void	gpio_attach(device_t, device_t, void *);
static int	gpio_rescan(device_t, const char *, const int *);
static void	gpio_childdetached(device_t, device_t);
static bool	gpio_resume(device_t, const pmf_qual_t *);
static int	gpio_detach(device_t, int);
static int	gpio_search(device_t, cfdata_t, const int *, void *);
static int	gpio_print(void *, const char *);
static int	gpio_pinbyname(struct gpio_softc *, char *);
static int	gpio_ioctl(struct gpio_softc *, u_long, void *, int,
    struct lwp *);

#ifdef COMPAT_50
/* Old API */
static int	gpio_ioctl_oapi(struct gpio_softc *, u_long, void *, int,
    struct lwp *);
#endif

CFATTACH_DECL3_NEW(gpio, sizeof(struct gpio_softc),
    gpio_match, gpio_attach, gpio_detach, NULL, gpio_rescan,
    gpio_childdetached, DVF_DETACH_SHUTDOWN);

dev_type_open(gpioopen);
dev_type_close(gpioclose);
dev_type_ioctl(gpioioctl);
dev_type_ioctl(gpioioctl_locked);

const struct cdevsw gpio_cdevsw = {
	.d_open = gpioopen,
	.d_close = gpioclose,
	.d_read = noread,
	.d_write = nowrite,
	.d_ioctl = gpioioctl,
	.d_stop = nostop,
	.d_tty = notty,
	.d_poll = nopoll,
	.d_mmap = nommap,
	.d_kqfilter = nokqfilter,
	.d_discard = nodiscard,
	.d_flag = D_OTHER | D_MPSAFE
};

static int
gpio_match(device_t parent, cfdata_t cf, void *aux)
{
	return 1;
}

int
gpio_submatch(device_t parent, cfdata_t cf, const int *ip, void *aux)
{
	struct gpio_attach_args *ga = aux;

	if (ga->ga_offset == -1)
		return 0;

	return strcmp(ga->ga_dvname, cf->cf_name) == 0;
}

static bool
gpio_resume(device_t self, const pmf_qual_t *qual)
{
	struct gpio_softc *sc = device_private(self);
	int pin;

	for (pin = 0; pin < sc->sc_npins; pin++) {
		gpiobus_pin_ctl(sc->sc_gc, pin, sc->sc_pins[pin].pin_flags);
		gpiobus_pin_write(sc->sc_gc, pin, sc->sc_pins[pin].pin_state);
	}
	return true;
}

static void
gpio_childdetached(device_t self, device_t child)
{
#ifdef COMPAT_50
	struct gpio_dev *gdev;
	struct gpio_softc *sc;
	int error;

	/*
	 * gpio_childetached is serialized because it can be entered in
	 * different ways concurrently, e.g. via the GPIODETACH ioctl and
	 * drvctl(8) or modunload(8).
	 */
	sc = device_private(self);
	error = 0;
	mutex_enter(&sc->sc_mtx);
	while (sc->sc_attach_busy) {
		error = cv_wait_sig(&sc->sc_attach, &sc->sc_mtx);
		if (error)
			break;
	}
	if (!error)
		sc->sc_attach_busy = 1;
	mutex_exit(&sc->sc_mtx);
	if (error)
		return;

	KERNEL_LOCK(1, NULL);
	LIST_FOREACH(gdev, &sc->sc_devs, sc_next)
		if (gdev->sc_dev == child) {
			LIST_REMOVE(gdev, sc_next);
			kmem_free(gdev, sizeof(struct gpio_dev));
			break;
		}
	KERNEL_UNLOCK_ONE(NULL);

	mutex_enter(&sc->sc_mtx);
	sc->sc_attach_busy = 0;
	cv_signal(&sc->sc_attach);
	mutex_exit(&sc->sc_mtx);
#endif
}

static int
gpio_rescan(device_t self, const char *ifattr, const int *locators)
{

	KERNEL_LOCK(1, NULL);
	config_search(self, NULL,
	    CFARGS(.search = gpio_search));
	KERNEL_UNLOCK_ONE(NULL);

	return 0;
}

static const char *
gpio_pin_defname(struct gpio_softc *sc, int pin)
{
	KASSERT(pin >= 0);

#ifdef FDT
	devhandle_t devhandle = device_handle(sc->sc_dev);

	if (devhandle_type(devhandle) == DEVHANDLE_TYPE_OF) {
		return fdtbus_get_string_index(devhandle_to_of(devhandle),
		    "gpio-line-names", pin);
	}
#endif /* FDT */

	return NULL;
}

static void
gpio_attach(device_t parent, device_t self, void *aux)
{
	struct gpio_softc *sc = device_private(self);
	struct gpiobus_attach_args *gba = aux;
	struct gpio_name *nm;
	int pin;

	sc->sc_dev = self;
	sc->sc_gc = gba->gba_gc;
	sc->sc_pins = gba->gba_pins;
	sc->sc_npins = gba->gba_npins;

	aprint_normal(": %d pins\n", sc->sc_npins);
	aprint_naive("\n");

	/* Configure default pin names */
	for (pin = 0; pin < sc->sc_npins; pin++) {
		const char *defname;

		defname = gpio_pin_defname(sc, pin);
		if (defname == NULL &&
		    sc->sc_pins[pin].pin_defname[0] != '\0') {
			defname = sc->sc_pins[pin].pin_defname;
		}
		if (defname == NULL) {
			continue;
		}
		nm = kmem_alloc(sizeof(*nm), KM_SLEEP);
		strlcpy(nm->gp_name, defname, sizeof(nm->gp_name));
		nm->gp_pin = pin;
		LIST_INSERT_HEAD(&sc->sc_names, nm, gp_next);
	}

	if (!pmf_device_register(self, NULL, gpio_resume))
		aprint_error_dev(self, "couldn't establish power handler\n");
	mutex_init(&sc->sc_mtx, MUTEX_DEFAULT, IPL_VM);
	cv_init(&sc->sc_ioctl, "gpioctl");
	cv_init(&sc->sc_attach, "gpioatch");
	/*
	 * Attach all devices that can be connected to the GPIO pins
	 * described in the kernel configuration file.
	 */
	gpio_rescan(self, "gpio", NULL);
}

static int
gpio_detach(device_t self, int flags)
{
	struct gpio_softc *sc;
	int rc;

	sc = device_private(self);

	if ((rc = config_detach_children(self, flags)) != 0)
		return rc;
	mutex_destroy(&sc->sc_mtx);
	cv_destroy(&sc->sc_ioctl);
#if 0
	int maj, mn;

	/* Locate the major number */
	for (maj = 0; maj < nchrdev; maj++)
		if (cdevsw[maj].d_open == gpioopen)
			break;

	/* Nuke the vnodes for any open instances (calls close) */
	mn = device_unit(self);
	vdevgone(maj, mn, mn, VCHR);
#endif
	return 0;
}

static int
gpio_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
{
	struct gpio_attach_args ga;
	size_t namlen;

	ga.ga_gpio = device_private(parent);
	ga.ga_offset = cf->cf_loc[GPIOCF_OFFSET];
	ga.ga_mask = cf->cf_loc[GPIOCF_MASK];
	ga.ga_flags = cf->cf_loc[GPIOCF_FLAG];
	namlen = strlen(cf->cf_name) + 1;
	ga.ga_dvname = kmem_alloc(namlen, KM_SLEEP);
	strcpy(ga.ga_dvname, cf->cf_name);

	if (config_probe(parent, cf, &ga))
		config_attach(parent, cf, &ga, gpio_print, CFARGS_NONE);
	kmem_free(ga.ga_dvname, namlen);
	return 0;
}

int
gpio_print(void *aux, const char *pnp)
{
	struct gpio_attach_args *ga = aux;
	int i;

	aprint_normal(" pins");
	for (i = 0; i < 32; i++)
		if (ga->ga_mask & (1 << i))
			aprint_normal(" %d", ga->ga_offset + i);

	return UNCONF;
}

int
gpiobus_print(void *aux, const char *pnp)
{
#if 0
	struct gpiobus_attach_args *gba = aux;
#endif
	if (pnp != NULL)
		aprint_normal("gpiobus at %s", pnp);

	return UNCONF;
}

void *
gpio_find_device(const char *name)
{
	device_t gpio_dev;
	gpio_dev = device_find_by_xname(name);
	if (gpio_dev == NULL)
		return NULL;
	return device_private(gpio_dev);
}

const char *
gpio_get_name(void *gpio)
{
	struct gpio_softc *sc = gpio;
	return device_xname(sc->sc_dev);
}

/* return 1 if all pins can be mapped, 0 if not */
int
gpio_pin_can_map(void *gpio, int offset, uint32_t mask)
{
	struct gpio_softc *sc = gpio;
	int npins, pin, i;

	npins = gpio_npins(mask);
	if (npins > sc->sc_npins)
		return 0;

	for (npins = 0, i = 0; i < 32; i++)
		if (mask & (1 << i)) {
			pin = offset + i;
			if (pin < 0 || pin >= sc->sc_npins)
				return 0;
			if (sc->sc_pins[pin].pin_mapped)
				return 0;
		}

	return 1;
}

int
gpio_pin_map(void *gpio, int offset, uint32_t mask, struct gpio_pinmap *map)
{
	struct gpio_softc *sc = gpio;
	int npins, pin, i;

	npins = gpio_npins(mask);
	if (npins > sc->sc_npins)
		return 1;

	for (npins = 0, i = 0; i < 32; i++)
		if (mask & (1 << i)) {
			pin = offset + i;
			if (pin < 0 || pin >= sc->sc_npins)
				return 1;
			if (sc->sc_pins[pin].pin_mapped)
				return 1;
			sc->sc_pins[pin].pin_mapped = 1;
			map->pm_map[npins++] = pin;
		}
	map->pm_size = npins;

	return 0;
}

void
gpio_pin_unmap(void *gpio, struct gpio_pinmap *map)
{
	struct gpio_softc *sc = gpio;
	int pin, i;

	for (i = 0; i < map->pm_size; i++) {
		pin = map->pm_map[i];
		sc->sc_pins[pin].pin_mapped = 0;
	}
}

int
gpio_pin_read(void *gpio, struct gpio_pinmap *map, int pin)
{
	struct gpio_softc *sc = gpio;

	return gpiobus_pin_read(sc->sc_gc, map->pm_map[pin]);
}

void
gpio_pin_write(void *gpio, struct gpio_pinmap *map, int pin, int value)
{
	struct gpio_softc *sc = gpio;

	gpiobus_pin_write(sc->sc_gc, map->pm_map[pin], value);
	sc->sc_pins[map->pm_map[pin]].pin_state = value;
}

int
gpio_pin_get_conf(void *gpio, struct gpio_pinmap *map, int pin)
{
	struct gpio_softc *sc = gpio;
	int rv;

	mutex_enter(&sc->sc_mtx);
	rv = sc->sc_pins[map->pm_map[pin]].pin_flags;
	mutex_exit(&sc->sc_mtx);

	return (rv);
}

bool
gpio_pin_set_conf(void *gpio, struct gpio_pinmap *map, int pin, int flags)
{
	struct gpio_softc *sc = gpio;
	int checkflags = flags & GPIO_PIN_HWCAPS;

	if ((sc->sc_pins[map->pm_map[pin]].pin_caps & checkflags) != checkflags)
		return (false);

	gpio_pin_ctl(gpio, map, pin, flags);

	return (true);
}

void
gpio_pin_ctl(void *gpio, struct gpio_pinmap *map, int pin, int flags)
{
	struct gpio_softc *sc = gpio;

	/* loosey-goosey version of gpio_pin_set_conf(). */

	mutex_enter(&sc->sc_mtx);
	gpiobus_pin_ctl(sc->sc_gc, map->pm_map[pin], flags);
	sc->sc_pins[map->pm_map[pin]].pin_flags = flags;
	mutex_exit(&sc->sc_mtx);
}

int
gpio_pin_caps(void *gpio, struct gpio_pinmap *map, int pin)
{
	struct gpio_softc *sc = gpio;

	return sc->sc_pins[map->pm_map[pin]].pin_caps;
}

int
gpio_pin_intrcaps(void *gpio, struct gpio_pinmap *map, int pin)
{
	struct gpio_softc *sc = gpio;

	return sc->sc_pins[map->pm_map[pin]].pin_intrcaps;
}

static int
gpio_irqmode_sanitize(int irqmode)
{
	int has_edge, has_level;

	has_edge  = irqmode & GPIO_INTR_EDGE_MASK;
	has_level = irqmode & GPIO_INTR_LEVEL_MASK;

	/* Must specify an interrupt mode. */
	if ((irqmode & GPIO_INTR_MODE_MASK) == 0)
		return (0);

	/* Can't specify edge and level together */
	if (has_level && has_edge)
		return (0);

	/* "Be liberal in what you accept..." */
	if (has_edge) {
		if (irqmode & GPIO_INTR_DOUBLE_EDGE) {
			/* if DOUBLE is set, just pass through DOUBLE */
			irqmode = (irqmode & ~GPIO_INTR_EDGE_MASK) |
			    GPIO_INTR_DOUBLE_EDGE;
		} else if ((irqmode ^
			    (GPIO_INTR_POS_EDGE | GPIO_INTR_NEG_EDGE)) == 0) {
			/* both POS and NEG set; treat as DOUBLE */
			irqmode = (irqmode & ~GPIO_INTR_EDGE_MASK) |
			    GPIO_INTR_DOUBLE_EDGE;
		}
	} else {
		/* Can't specify both levels together. */
		if (has_level == GPIO_INTR_LEVEL_MASK)
			return (0);
	}

	return (irqmode);
}

bool
gpio_pin_irqmode_issupported(void *gpio, struct gpio_pinmap *map,
			     int pin, int irqmode)
{
	struct gpio_softc *sc = gpio;
	int match;

	irqmode = gpio_irqmode_sanitize(irqmode) & GPIO_INTR_MODE_MASK;

	/* Make sure the pin can do what is being asked. */
	match = sc->sc_pins[map->pm_map[pin]].pin_intrcaps & irqmode;

	return (irqmode && irqmode == match);
}

void *
gpio_intr_establish(void *gpio, struct gpio_pinmap *map, int pin, int ipl,
		    int irqmode, int (*func)(void *), void *arg)
{
	struct gpio_softc *sc = gpio;

	if (sc->sc_gc->gp_intr_establish == NULL)
		return (NULL);

	irqmode = gpio_irqmode_sanitize(irqmode);
	if (irqmode == 0)
		return (NULL);

	if (! gpio_pin_irqmode_issupported(gpio, map, pin, irqmode))
		return (NULL);

	/* XXX Right now, everything has to be at IPL_VM. */
	if (ipl != IPL_VM)
		return (NULL);

	return ((*sc->sc_gc->gp_intr_establish)(sc->sc_gc->gp_cookie,
	    sc->sc_pins[map->pm_map[pin]].pin_num, ipl, irqmode, func, arg));
}

void
gpio_intr_disestablish(void *gpio, void *ih)
{
	struct gpio_softc *sc = gpio;

	if (sc->sc_gc->gp_intr_disestablish != NULL && ih != NULL)
		(*sc->sc_gc->gp_intr_disestablish)(sc->sc_gc->gp_cookie, ih);
}

bool
gpio_intr_str(void *gpio, struct gpio_pinmap *map, int pin, int irqmode,
	      char *intrstr, size_t intrstrlen)
{
	struct gpio_softc *sc = gpio;
	const char *mode;
	char hwstr[64];

	if (sc->sc_gc->gp_intr_str == NULL)
		return (false);

	irqmode = gpio_irqmode_sanitize(irqmode);
	if (irqmode == 0)
		return (false);

	if (irqmode & GPIO_INTR_DOUBLE_EDGE)
		mode = "double edge";
	else if (irqmode & GPIO_INTR_POS_EDGE)
		mode = "positive edge";
	else if (irqmode & GPIO_INTR_NEG_EDGE)
		mode = "negative edge";
	else if (irqmode & GPIO_INTR_HIGH_LEVEL)
		mode = "high level";
	else if (irqmode & GPIO_INTR_LOW_LEVEL)
		mode = "low level";
	else
		return (false);

	if (! (*sc->sc_gc->gp_intr_str)(sc->sc_gc->gp_cookie,
					sc->sc_pins[map->pm_map[pin]].pin_num,
					irqmode, hwstr, sizeof(hwstr)))
		return (false);

	(void) snprintf(intrstr, intrstrlen, "%s (%s)", hwstr, mode);
	
	return (true);
}

int
gpio_npins(uint32_t mask)
{
	int npins, i;

	for (npins = 0, i = 0; i < 32; i++)
		if (mask & (1 << i))
			npins++;

	return npins;
}

int
gpio_lock(void *data)
{
	struct gpio_softc *sc;
	int error;

	error = 0;
	sc = data;
	mutex_enter(&sc->sc_mtx);
	while (sc->sc_ioctl_busy) {
		error = cv_wait_sig(&sc->sc_ioctl, &sc->sc_mtx);
		if (error)
			break;
	}
	if (!error)
		sc->sc_ioctl_busy = 1;
	mutex_exit(&sc->sc_mtx);
	return error;
}

void
gpio_unlock(void *data)
{
	struct gpio_softc *sc;

	sc = data;
	mutex_enter(&sc->sc_mtx);
	sc->sc_ioctl_busy = 0;
	cv_signal(&sc->sc_ioctl);
	mutex_exit(&sc->sc_mtx);
}

int
gpioopen(dev_t dev, int flag, int mode, struct lwp *l)
{
	struct gpio_softc *sc;

	sc = device_lookup_private(&gpio_cd, minor(dev));
	if (sc == NULL)
		return ENXIO;

	return gpiobus_open(sc->sc_gc, sc->sc_dev);
}

int
gpioclose(dev_t dev, int flag, int mode, struct lwp *l)
{
	struct gpio_softc *sc;

	sc = device_lookup_private(&gpio_cd, minor(dev));
	return gpiobus_close(sc->sc_gc, sc->sc_dev);
}

static int
gpio_pinbyname(struct gpio_softc *sc, char *gp_name)
{
        struct gpio_name *nm;

        LIST_FOREACH(nm, &sc->sc_names, gp_next)
                if (!strcmp(nm->gp_name, gp_name))
                        return nm->gp_pin;
        return -1;
}

int
gpioioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
{
	int error;
	struct gpio_softc *sc;

	sc = device_lookup_private(&gpio_cd, minor(dev));

	error = gpio_lock(sc);
	if (error)
		return error;

	error = gpio_ioctl(sc, cmd, data, flag, l);
	gpio_unlock(sc);
	return error;
}

static int
gpio_ioctl(struct gpio_softc *sc, u_long cmd, void *data, int flag,
    struct lwp *l)
{
	gpio_chipset_tag_t gc;
	struct gpio_info *info;
	struct gpio_attach *attach;
	struct gpio_attach_args ga;
	struct gpio_req *req;
	struct gpio_name *nm;
	struct gpio_set *set;
#ifdef COMPAT_50
	struct gpio_dev *gdev;
#endif
	device_t dv;
	cfdata_t cf;
	int locs[GPIOCF_NLOCS];
	int error, pin, value, flags;

	gc = sc->sc_gc;
	ga.ga_flags = 0;

	if (cmd != GPIOINFO && !device_is_active(sc->sc_dev)) {
		DPRINTF(("%s: device is not active\n",
		    device_xname(sc->sc_dev)));
		return EBUSY;
	}

	switch (cmd) {
	case GPIOINFO:
		info = data;
		info->gpio_npins = sc->sc_npins;
		break;
	case GPIOREAD:
		req = data;

		if (req->gp_name[0] != '\0')
			req->gp_pin = gpio_pinbyname(sc, req->gp_name);
		pin = req->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;

		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
		    kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		/* return read value */
		req->gp_value = gpiobus_pin_read(gc, pin);
		LIST_FOREACH(nm, &sc->sc_names, gp_next)
			if (nm->gp_pin == pin) {
				strlcpy(req->gp_name, nm->gp_name, GPIOMAXNAME);
				break;
			}
		break;
	case GPIOWRITE:
		if ((flag & FWRITE) == 0)
			return EBADF;

		req = data;

		if (req->gp_name[0] != '\0')
			pin = gpio_pinbyname(sc, req->gp_name);
		else
			pin = req->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;

		if (sc->sc_pins[pin].pin_mapped)
			return EBUSY;

		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
		    kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		value = req->gp_value;
		if (value != GPIO_PIN_LOW && value != GPIO_PIN_HIGH)
			return EINVAL;

		/* return old value */
		req->gp_value = gpiobus_pin_read(gc, pin);
		gpiobus_pin_write(gc, pin, value);
		/* update current value */
		sc->sc_pins[pin].pin_state = value;
		break;
	case GPIOTOGGLE:
		if ((flag & FWRITE) == 0)
			return EBADF;

		req = data;

		if (req->gp_name[0] != '\0')
			pin = gpio_pinbyname(sc, req->gp_name);
		else
			pin = req->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;

		if (sc->sc_pins[pin].pin_mapped)
			return EBUSY;

		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
		    kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		value = (sc->sc_pins[pin].pin_state == GPIO_PIN_LOW ?
		    GPIO_PIN_HIGH : GPIO_PIN_LOW);
		gpiobus_pin_write(gc, pin, value);
		/* return old value */
		req->gp_value = sc->sc_pins[pin].pin_state;
		/* update current value */
		sc->sc_pins[pin].pin_state = value;
		break;
	case GPIOATTACH:
		attach = data;
		ga.ga_flags = attach->ga_flags;
#ifdef COMPAT_50
		/* FALLTHROUGH */
	case GPIOATTACH50:
		/*
		 * The double assignment to 'attach' in case of GPIOATTACH
		 * and COMPAT_50 is on purpose. It ensures backward
		 * compatibility in case we are called through the old
		 * GPIOATTACH50 ioctl(2), which had not the ga_flags field
		 * in struct gpio_attach.
		 */
		attach = data;
#endif
		if (kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		/* do not try to attach if the pins are already mapped */
		if (!gpio_pin_can_map(sc, attach->ga_offset, attach->ga_mask))
			return EBUSY;

		error = 0;
		mutex_enter(&sc->sc_mtx);
		while (sc->sc_attach_busy) {
			error = cv_wait_sig(&sc->sc_attach, &sc->sc_mtx);
			if (error)
				break;
		}
		if (!error)
			sc->sc_attach_busy = 1;
		mutex_exit(&sc->sc_mtx);
		if (error)
			return EBUSY;

		ga.ga_gpio = sc;
		/* Don't access attach->ga_flags here. */
		ga.ga_dvname = attach->ga_dvname;
		ga.ga_offset = attach->ga_offset;
		ga.ga_mask = attach->ga_mask;
		DPRINTF(("%s: attach %s with offset %d, mask "
		    "0x%02x, and flags 0x%02x\n", device_xname(sc->sc_dev),
		    ga.ga_dvname, ga.ga_offset, ga.ga_mask, ga.ga_flags));

		locs[GPIOCF_OFFSET] = ga.ga_offset;
		locs[GPIOCF_MASK] = ga.ga_mask;
		locs[GPIOCF_FLAG] = ga.ga_flags;

		KERNEL_LOCK(1, NULL);
		cf = config_search(sc->sc_dev, &ga,
		    CFARGS(.locators = locs));
		if (cf != NULL) {
			dv = config_attach(sc->sc_dev, cf, &ga,
			    gpiobus_print,
			    CFARGS(.locators = locs));
#ifdef COMPAT_50
			if (dv != NULL) {
				gdev = kmem_alloc(sizeof(struct gpio_dev),
				    KM_SLEEP);
				gdev->sc_dev = dv;
				LIST_INSERT_HEAD(&sc->sc_devs, gdev, sc_next);
			} else
				error = EINVAL;
#else
			if (dv == NULL)
				error = EINVAL;
#endif
		} else
			error = EINVAL;
		KERNEL_UNLOCK_ONE(NULL);

		mutex_enter(&sc->sc_mtx);
		sc->sc_attach_busy = 0;
		cv_signal(&sc->sc_attach);
		mutex_exit(&sc->sc_mtx);
		return error;
	case GPIOSET:
		if (kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		set = data;

		if (set->gp_name[0] != '\0')
			pin = gpio_pinbyname(sc, set->gp_name);
		else
			pin = set->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;
		flags = set->gp_flags;

		/* check that the controller supports all requested flags */
		if ((flags & sc->sc_pins[pin].pin_caps) != flags)
			return ENODEV;
		flags = set->gp_flags;

		set->gp_caps = sc->sc_pins[pin].pin_caps;
		/* return old value */
		set->gp_flags = sc->sc_pins[pin].pin_flags;

		if (flags > 0) {
			flags |= GPIO_PIN_SET;
			gpiobus_pin_ctl(gc, pin, flags);
			/* update current value */
			sc->sc_pins[pin].pin_flags = flags;
		}

		/* rename pin or new pin? */
		if (set->gp_name2[0] != '\0') {
			struct gpio_name *gnm;

			gnm = NULL;
			LIST_FOREACH(nm, &sc->sc_names, gp_next) {
				if (!strcmp(nm->gp_name, set->gp_name2) &&
				    nm->gp_pin != pin)
					return EINVAL;	/* duplicate name */
				if (nm->gp_pin == pin)
					gnm = nm;
			}
			if (gnm != NULL)
				strlcpy(gnm->gp_name, set->gp_name2,
				    sizeof(gnm->gp_name));
			else  {
				nm = kmem_alloc(sizeof(struct gpio_name),
				    KM_SLEEP);
				strlcpy(nm->gp_name, set->gp_name2,
				    sizeof(nm->gp_name));
				nm->gp_pin = set->gp_pin;
				LIST_INSERT_HEAD(&sc->sc_names, nm, gp_next);
			}
		}
		break;
	case GPIOUNSET:
		if (kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		set = data;
		if (set->gp_name[0] != '\0')
			pin = gpio_pinbyname(sc, set->gp_name);
		else
			pin = set->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;
		if (sc->sc_pins[pin].pin_mapped)
			return EBUSY;
		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET))
			return EINVAL;

		LIST_FOREACH(nm, &sc->sc_names, gp_next) {
			if (nm->gp_pin == pin) {
				LIST_REMOVE(nm, gp_next);
				kmem_free(nm, sizeof(struct gpio_name));
				break;
			}
		}
		sc->sc_pins[pin].pin_flags &= ~GPIO_PIN_SET;
		break;
	default:
#ifdef COMPAT_50
		/* Try the old API */
		DPRINTF(("%s: trying the old API\n", device_xname(sc->sc_dev)));
		return gpio_ioctl_oapi(sc, cmd, data, flag, l);
#else
		return ENOTTY;
#endif
	}
	return 0;
}

#ifdef COMPAT_50
static int
gpio_ioctl_oapi(struct gpio_softc *sc, u_long cmd, void *data, int flag,
    struct lwp *l)
{
	gpio_chipset_tag_t gc;
	struct gpio_pin_op *op;
	struct gpio_pin_ctl *ctl;
	struct gpio_attach *attach;
	struct gpio_dev *gdev;

	int error, pin, value, flags;

	gc = sc->sc_gc;

	switch (cmd) {
	case GPIOPINREAD:
		op = data;

		pin = op->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;

		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
		    kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		/* return read value */
		op->gp_value = gpiobus_pin_read(gc, pin);
		break;
	case GPIOPINWRITE:
		if ((flag & FWRITE) == 0)
			return EBADF;

		op = data;

		pin = op->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;

		if (sc->sc_pins[pin].pin_mapped)
			return EBUSY;

		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
		    kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		value = op->gp_value;
		if (value != GPIO_PIN_LOW && value != GPIO_PIN_HIGH)
			return EINVAL;

		gpiobus_pin_write(gc, pin, value);
		/* return old value */
		op->gp_value = sc->sc_pins[pin].pin_state;
		/* update current value */
		sc->sc_pins[pin].pin_state = value;
		break;
	case GPIOPINTOGGLE:
		if ((flag & FWRITE) == 0)
			return EBADF;

		op = data;

		pin = op->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;

		if (sc->sc_pins[pin].pin_mapped)
			return EBUSY;

		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
		    kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		value = (sc->sc_pins[pin].pin_state == GPIO_PIN_LOW ?
		    GPIO_PIN_HIGH : GPIO_PIN_LOW);
		gpiobus_pin_write(gc, pin, value);
		/* return old value */
		op->gp_value = sc->sc_pins[pin].pin_state;
		/* update current value */
		sc->sc_pins[pin].pin_state = value;
		break;
	case GPIOPINCTL:
		ctl = data;

		if (kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		pin = ctl->gp_pin;

		if (pin < 0 || pin >= sc->sc_npins)
			return EINVAL;
		if (sc->sc_pins[pin].pin_mapped)
			return EBUSY;
		flags = ctl->gp_flags;

		/* check that the controller supports all requested flags */
		if ((flags & sc->sc_pins[pin].pin_caps) != flags)
			return ENODEV;

		ctl->gp_caps = sc->sc_pins[pin].pin_caps;
		/* return old value */
		ctl->gp_flags = sc->sc_pins[pin].pin_flags;
		if (flags > 0) {
			gpiobus_pin_ctl(gc, pin, flags);
			/* update current value */
			sc->sc_pins[pin].pin_flags = flags;
		}
		break;
	case GPIODETACH50:
		/* FALLTHOUGH */
	case GPIODETACH:
		if (kauth_authorize_device(l->l_cred,
		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
			return EPERM;

		error = 0;
		mutex_enter(&sc->sc_mtx);
		while (sc->sc_attach_busy) {
			error = cv_wait_sig(&sc->sc_attach, &sc->sc_mtx);
			if (error)
				break;
		}
		if (!error)
			sc->sc_attach_busy = 1;
		mutex_exit(&sc->sc_mtx);
		if (error)
			return EBUSY;

		KERNEL_LOCK(1, NULL);
		attach = data;
		LIST_FOREACH(gdev, &sc->sc_devs, sc_next) {
			if (strcmp(device_xname(gdev->sc_dev),
			    attach->ga_dvname) == 0) {
				mutex_enter(&sc->sc_mtx);
				sc->sc_attach_busy = 0;
				cv_signal(&sc->sc_attach);
				mutex_exit(&sc->sc_mtx);

				if (config_detach(gdev->sc_dev, 0) == 0) {
					KERNEL_UNLOCK_ONE(NULL);
					return 0;
				}
				break;
			}
		}
		KERNEL_UNLOCK_ONE(NULL);

		if (gdev == NULL) {
			mutex_enter(&sc->sc_mtx);
			sc->sc_attach_busy = 0;
			cv_signal(&sc->sc_attach);
			mutex_exit(&sc->sc_mtx);
		}
		return EINVAL;

	default:
		return ENOTTY;
	}
	return 0;
}
#endif	/* COMPAT_50 */

MODULE(MODULE_CLASS_DRIVER, gpio, NULL);

#ifdef _MODULE
#include "ioconf.c"
#endif

static int
gpio_modcmd(modcmd_t cmd, void *opaque)
{
#ifdef _MODULE
	devmajor_t cmajor = NODEVMAJOR, bmajor = NODEVMAJOR;
	int error;
#endif
	switch (cmd) {
	case MODULE_CMD_INIT:
#ifdef _MODULE
		error = devsw_attach(gpio_cd.cd_name, NULL, &bmajor,
		    &gpio_cdevsw, &cmajor);
		if (error) {
			aprint_error("%s: unable to register devsw\n",
			    gpio_cd.cd_name);
			return error;
		}
		error = config_init_component(cfdriver_ioconf_gpio,
		    cfattach_ioconf_gpio, cfdata_ioconf_gpio);
		if (error) {
			aprint_error("%s: unable to init component\n",
			    gpio_cd.cd_name);
			devsw_detach(NULL, &gpio_cdevsw);
			return error;
		}
#endif
		return 0;
	case MODULE_CMD_FINI:
#ifdef _MODULE
		config_fini_component(cfdriver_ioconf_gpio,
		    cfattach_ioconf_gpio, cfdata_ioconf_gpio);
		devsw_detach(NULL, &gpio_cdevsw);
#endif
		return 0;
	default:
		return ENOTTY;
	}
}