#include #include #include #include #include #include #include #include #include #include #include #include #include /* tboot= */ static char __initdata opt_tboot[20] = ""; string_param("tboot", opt_tboot); /* Global pointer to shared data; NULL means no measured launch. */ tboot_shared_t *g_tboot_shared; static vmac_t domain_mac; /* MAC for all domains during S3 */ static vmac_t xenheap_mac; /* MAC for xen heap during S3 */ static vmac_t frametable_mac; /* MAC for frame table during S3 */ static const uuid_t tboot_shared_uuid = TBOOT_SHARED_UUID; /* used by tboot_protect_mem_regions() and/or tboot_parse_dmar_table() */ static uint64_t __initdata txt_heap_base, __initdata txt_heap_size; static uint64_t __initdata sinit_base, __initdata sinit_size; /* * TXT configuration registers (offsets from TXT_{PUB, PRIV}_CONFIG_REGS_BASE) */ #define TXT_PUB_CONFIG_REGS_BASE 0xfed30000 #define TXT_PRIV_CONFIG_REGS_BASE 0xfed20000 /* # pages for each config regs space - used by fixmap */ #define NR_TXT_CONFIG_PAGES ((TXT_PUB_CONFIG_REGS_BASE - \ TXT_PRIV_CONFIG_REGS_BASE) >> PAGE_SHIFT) /* offsets from pub/priv config space */ #define TXTCR_SINIT_BASE 0x0270 #define TXTCR_SINIT_SIZE 0x0278 #define TXTCR_HEAP_BASE 0x0300 #define TXTCR_HEAP_SIZE 0x0308 extern char __init_begin[], __bss_start[]; #define SHA1_SIZE 20 typedef uint8_t sha1_hash_t[SHA1_SIZE]; typedef struct __packed { uint32_t version; /* currently 6 */ sha1_hash_t bios_acm_id; uint32_t edx_senter_flags; uint64_t mseg_valid; sha1_hash_t sinit_hash; sha1_hash_t mle_hash; sha1_hash_t stm_hash; sha1_hash_t lcp_policy_hash; uint32_t lcp_policy_control; uint32_t rlp_wakeup_addr; uint32_t reserved; uint32_t num_mdrs; uint32_t mdrs_off; uint32_t num_vtd_dmars; uint32_t vtd_dmars_off; } sinit_mle_data_t; static void tboot_copy_memory(unsigned char *va, uint32_t size, unsigned long pa) { unsigned long map_base = 0; unsigned char *map_addr = NULL; unsigned int i; for ( i = 0; i < size; i++ ) { if ( map_base != PFN_DOWN(pa + i) ) { map_base = PFN_DOWN(pa + i); set_fixmap(FIX_TBOOT_MAP_ADDRESS, map_base << PAGE_SHIFT); map_addr = (unsigned char *)fix_to_virt(FIX_TBOOT_MAP_ADDRESS); } va[i] = map_addr[pa + i - (map_base << PAGE_SHIFT)]; } } void __init tboot_probe(void) { tboot_shared_t *tboot_shared; unsigned long p_tboot_shared; /* Look for valid page-aligned address for shared page. */ p_tboot_shared = simple_strtoul(opt_tboot, NULL, 0); if ( (p_tboot_shared == 0) || ((p_tboot_shared & ~PAGE_MASK) != 0) ) return; /* Map and check for tboot UUID. */ set_fixmap(FIX_TBOOT_SHARED_BASE, p_tboot_shared); tboot_shared = (tboot_shared_t *)fix_to_virt(FIX_TBOOT_SHARED_BASE); if ( tboot_shared == NULL ) return; if ( memcmp(&tboot_shared_uuid, (uuid_t *)tboot_shared, sizeof(uuid_t)) ) return; /* new tboot_shared (w/ GAS support, integrity, etc.) is not backwards compatible */ if ( tboot_shared->version < 4 ) { printk("unsupported version of tboot (%u)\n", tboot_shared->version); return; } g_tboot_shared = tboot_shared; printk("TBOOT: found shared page at phys addr %lx:\n", p_tboot_shared); printk(" version: %d\n", tboot_shared->version); printk(" log_addr: 0x%08x\n", tboot_shared->log_addr); printk(" shutdown_entry: 0x%08x\n", tboot_shared->shutdown_entry); printk(" tboot_base: 0x%08x\n", tboot_shared->tboot_base); printk(" tboot_size: 0x%x\n", tboot_shared->tboot_size); /* these will be needed by tboot_protect_mem_regions() and/or tboot_parse_dmar_table(), so get them now */ txt_heap_base = txt_heap_size = sinit_base = sinit_size = 0; /* TXT Heap */ tboot_copy_memory((unsigned char *)&txt_heap_base, sizeof(txt_heap_base), TXT_PUB_CONFIG_REGS_BASE + TXTCR_HEAP_BASE); tboot_copy_memory((unsigned char *)&txt_heap_size, sizeof(txt_heap_size), TXT_PUB_CONFIG_REGS_BASE + TXTCR_HEAP_SIZE); /* SINIT */ tboot_copy_memory((unsigned char *)&sinit_base, sizeof(sinit_base), TXT_PUB_CONFIG_REGS_BASE + TXTCR_SINIT_BASE); tboot_copy_memory((unsigned char *)&sinit_size, sizeof(sinit_size), TXT_PUB_CONFIG_REGS_BASE + TXTCR_SINIT_SIZE); } /* definitions from xen/drivers/passthrough/vtd/iommu.h * used to walk through vtd page tables */ #define LEVEL_STRIDE (9) #define PTE_NUM (1<> PAGE_SHIFT_4K); vmac_update((void *)pt_vaddr, PAGE_SIZE, ctx); for ( i = 0; i < PTE_NUM; i++ ) { pte = &pt_vaddr[i]; if ( !dma_pte_present(*pte) ) continue; if ( next_level >= 1 ) update_iommu_mac(ctx, dma_pte_addr(*pte), next_level); } unmap_domain_page(pt_vaddr); } #define is_page_in_use(page) \ (page_state_is(page, inuse) || page_state_is(page, offlining)) static void update_pagetable_mac(vmac_ctx_t *ctx) { unsigned long mfn; for ( mfn = 0; mfn < max_page; mfn++ ) { struct page_info *page = mfn_to_page(mfn); if ( !mfn_valid(mfn) ) continue; if ( is_page_in_use(page) && !is_xen_heap_page(page) ) { if ( page->count_info & PGC_page_table ) { void *pg = map_domain_page(mfn); vmac_update(pg, PAGE_SIZE, ctx); unmap_domain_page(pg); } } } } static void tboot_gen_domain_integrity(const uint8_t key[TB_KEY_SIZE], vmac_t *mac) { struct domain *d; struct page_info *page; uint8_t nonce[16] = {}; vmac_ctx_t ctx; vmac_set_key((uint8_t *)key, &ctx); for_each_domain( d ) { if ( !d->arch.s3_integrity ) continue; printk("MACing Domain %u\n", d->domain_id); spin_lock(&d->page_alloc_lock); page_list_for_each(page, &d->page_list) { void *pg = __map_domain_page(page); vmac_update(pg, PAGE_SIZE, &ctx); unmap_domain_page(pg); } spin_unlock(&d->page_alloc_lock); if ( !is_idle_domain(d) ) { struct hvm_iommu *hd = domain_hvm_iommu(d); update_iommu_mac(&ctx, hd->pgd_maddr, agaw_to_level(hd->agaw)); } } /* MAC all shadow page tables */ update_pagetable_mac(&ctx); *mac = vmac(NULL, 0, nonce, NULL, &ctx); /* wipe ctx to ensure key is not left in memory */ memset(&ctx, 0, sizeof(ctx)); } /* * For stack overflow detection in debug build, a guard page is set up. * This fn is used to detect whether a page is in the guarded pages for * the above reason. */ static int mfn_in_guarded_stack(unsigned long mfn) { extern void *stack_base[NR_CPUS]; void *p; int i; for ( i = 0; i < NR_CPUS; i++ ) { if ( !stack_base[i] ) continue; p = (void *)((unsigned long)stack_base[i] + STACK_SIZE - PRIMARY_STACK_SIZE - PAGE_SIZE); if ( mfn == virt_to_mfn(p) ) return -1; } return 0; } static void tboot_gen_xenheap_integrity(const uint8_t key[TB_KEY_SIZE], vmac_t *mac) { unsigned long mfn; uint8_t nonce[16] = {}; vmac_ctx_t ctx; vmac_set_key((uint8_t *)key, &ctx); for ( mfn = 0; mfn < max_page; mfn++ ) { struct page_info *page = __mfn_to_page(mfn); if ( !mfn_valid(mfn) ) continue; if ( (mfn << PAGE_SHIFT) < __pa(&_end) ) continue; /* skip Xen */ if ( (mfn >= PFN_DOWN(g_tboot_shared->tboot_base - 3 * PAGE_SIZE)) && (mfn < PFN_UP(g_tboot_shared->tboot_base + g_tboot_shared->tboot_size + 3 * PAGE_SIZE)) ) continue; /* skip tboot and its page tables */ if ( is_page_in_use(page) && is_xen_heap_page(page) ) { void *pg; if ( mfn_in_guarded_stack(mfn) ) continue; /* skip guard stack, see memguard_guard_stack() in mm.c */ pg = mfn_to_virt(mfn); vmac_update((uint8_t *)pg, PAGE_SIZE, &ctx); } } *mac = vmac(NULL, 0, nonce, NULL, &ctx); /* wipe ctx to ensure key is not left in memory */ memset(&ctx, 0, sizeof(ctx)); } static void tboot_gen_frametable_integrity(const uint8_t key[TB_KEY_SIZE], vmac_t *mac) { unsigned int sidx, eidx, nidx; unsigned int max_idx = (max_pdx + PDX_GROUP_COUNT - 1)/PDX_GROUP_COUNT; uint8_t nonce[16] = {}; vmac_ctx_t ctx; vmac_set_key((uint8_t *)key, &ctx); for ( sidx = 0; ; sidx = nidx ) { eidx = find_next_zero_bit(pdx_group_valid, max_idx, sidx); nidx = find_next_bit(pdx_group_valid, max_idx, eidx); if ( nidx >= max_idx ) break; vmac_update((uint8_t *)pdx_to_page(sidx * PDX_GROUP_COUNT), pdx_to_page(eidx * PDX_GROUP_COUNT) - pdx_to_page(sidx * PDX_GROUP_COUNT), &ctx); } vmac_update((uint8_t *)pdx_to_page(sidx * PDX_GROUP_COUNT), pdx_to_page(max_pdx - 1) + 1 - pdx_to_page(sidx * PDX_GROUP_COUNT), &ctx); *mac = vmac(NULL, 0, nonce, NULL, &ctx); /* wipe ctx to ensure key is not left in memory */ memset(&ctx, 0, sizeof(ctx)); } void tboot_shutdown(uint32_t shutdown_type) { uint32_t map_base, map_size; int err; g_tboot_shared->shutdown_type = shutdown_type; local_irq_disable(); /* Create identity map for tboot shutdown code. */ /* do before S3 integrity because mapping tboot may change xenheap */ map_base = PFN_DOWN(g_tboot_shared->tboot_base); map_size = PFN_UP(g_tboot_shared->tboot_size); err = map_pages_to_xen(map_base << PAGE_SHIFT, map_base, map_size, __PAGE_HYPERVISOR); if ( err != 0 ) { printk("error (0x%x) mapping tboot pages (mfns) @ 0x%x, 0x%x\n", err, map_base, map_size); return; } /* if this is S3 then set regions to MAC */ if ( shutdown_type == TB_SHUTDOWN_S3 ) { /* * Xen regions for tboot to MAC */ g_tboot_shared->num_mac_regions = 3; /* S3 resume code (and other real mode trampoline code) */ g_tboot_shared->mac_regions[0].start = bootsym_phys(trampoline_start); g_tboot_shared->mac_regions[0].size = bootsym_phys(trampoline_end) - bootsym_phys(trampoline_start); /* hypervisor code + data */ g_tboot_shared->mac_regions[1].start = (uint64_t)__pa(&_stext); g_tboot_shared->mac_regions[1].size = __pa(&__init_begin) - __pa(&_stext); /* bss */ g_tboot_shared->mac_regions[2].start = (uint64_t)__pa(&__bss_start); g_tboot_shared->mac_regions[2].size = __pa(&_end) - __pa(&__bss_start); /* * MAC domains and other Xen memory */ /* Xen has no better entropy source for MAC key than tboot's */ /* MAC domains first in case it perturbs xenheap */ tboot_gen_domain_integrity(g_tboot_shared->s3_key, &domain_mac); tboot_gen_frametable_integrity(g_tboot_shared->s3_key, &frametable_mac); tboot_gen_xenheap_integrity(g_tboot_shared->s3_key, &xenheap_mac); } write_ptbase(idle_vcpu[0]); ((void(*)(void))(unsigned long)g_tboot_shared->shutdown_entry)(); BUG(); /* should not reach here */ } int tboot_in_measured_env(void) { return (g_tboot_shared != NULL); } int __init tboot_protect_mem_regions(void) { int rc; if ( !tboot_in_measured_env() ) return 1; /* TXT Heap */ if ( txt_heap_base == 0 ) return 0; rc = e820_change_range_type( &e820, txt_heap_base, txt_heap_base + txt_heap_size, E820_RESERVED, E820_UNUSABLE); if ( !rc ) return 0; /* SINIT */ if ( sinit_base == 0 ) return 0; rc = e820_change_range_type( &e820, sinit_base, sinit_base + sinit_size, E820_RESERVED, E820_UNUSABLE); if ( !rc ) return 0; /* TXT Private Space */ rc = e820_change_range_type( &e820, TXT_PRIV_CONFIG_REGS_BASE, TXT_PRIV_CONFIG_REGS_BASE + NR_TXT_CONFIG_PAGES * PAGE_SIZE, E820_RESERVED, E820_UNUSABLE); if ( !rc ) return 0; return 1; } int __init tboot_parse_dmar_table(acpi_table_handler dmar_handler) { struct acpi_table_header *dmar_table; int rc; uint64_t size; uint32_t dmar_table_length; unsigned long pa; sinit_mle_data_t sinit_mle_data; unsigned char *dmar_table_raw; if ( !tboot_in_measured_env() ) return acpi_table_parse(ACPI_SIG_DMAR, dmar_handler); /* ACPI tables may not be DMA protected by tboot, so use DMAR copy */ /* SINIT saved in SinitMleData in TXT heap (which is DMA protected) */ if ( txt_heap_base == 0 ) return 1; /* map TXT heap into Xen addr space */ /* walk heap to SinitMleData */ pa = txt_heap_base; /* skip BiosData */ tboot_copy_memory((unsigned char *)&size, sizeof(size), pa); pa += size; /* skip OsMleData */ tboot_copy_memory((unsigned char *)&size, sizeof(size), pa); pa += size; /* skip OsSinitData */ tboot_copy_memory((unsigned char *)&size, sizeof(size), pa); pa += size; /* now points to SinitMleDataSize; set to SinitMleData */ pa += sizeof(uint64_t); tboot_copy_memory((unsigned char *)&sinit_mle_data, sizeof(sinit_mle_data), pa); /* get addr of DMAR table */ pa += sinit_mle_data.vtd_dmars_off - sizeof(uint64_t); tboot_copy_memory((unsigned char *)&dmar_table_length, sizeof(dmar_table_length), pa + sizeof(char) * ACPI_NAME_SIZE); dmar_table_raw = xmalloc_array(unsigned char, dmar_table_length); tboot_copy_memory(dmar_table_raw, dmar_table_length, pa); dmar_table = (struct acpi_table_header *)dmar_table_raw; rc = dmar_handler(dmar_table); xfree(dmar_table_raw); /* acpi_parse_dmar() zaps APCI DMAR signature in TXT heap table */ /* but dom0 will read real table, so must zap it there too */ dmar_table = NULL; acpi_get_table(ACPI_SIG_DMAR, 0, &dmar_table); if ( dmar_table != NULL ) { dmar_table->signature[0] = 'X'; dmar_table->checksum -= 'X'-'D'; } return rc; } int tboot_s3_resume(void) { vmac_t mac; if ( !tboot_in_measured_env() ) return 0; /* need to do these in reverse order of shutdown */ tboot_gen_xenheap_integrity(g_tboot_shared->s3_key, &mac); printk("MAC for xenheap before S3 is: 0x%08"PRIx64"\n", xenheap_mac); printk("MAC for xenheap after S3 is: 0x%08"PRIx64"\n", mac); if ( mac != xenheap_mac ) return -1; tboot_gen_frametable_integrity(g_tboot_shared->s3_key, &mac); printk("MAC for frametable before S3 is: 0x%08"PRIx64"\n", frametable_mac); printk("MAC for frametable after S3 is: 0x%08"PRIx64"\n", mac); if ( mac != frametable_mac ) return -2; tboot_gen_domain_integrity(g_tboot_shared->s3_key, &mac); printk("MAC for domains before S3 is: 0x%08"PRIx64"\n", domain_mac); printk("MAC for domains after S3 is: 0x%08"PRIx64"\n", mac); if ( mac != domain_mac ) return -3; return 0; } /* * Local variables: * mode: C * c-set-style: "BSD" * c-basic-offset: 4 * tab-width: 4 * indent-tabs-mode: nil * End: */ n371'>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
/*
 *  GPIO Button Hotplug driver
 *
 *  Copyright (C) 2012 Felix Fietkau <nbd@nbd.name>
 *  Copyright (C) 2008-2010 Gabor Juhos <juhosg@openwrt.org>
 *
 *  Based on the diag.c - GPIO interface driver for Broadcom boards
 *    Copyright (C) 2006 Mike Baker <mbm@openwrt.org>,
 *    Copyright (C) 2006-2007 Felix Fietkau <nbd@nbd.name>
 *    Copyright (C) 2008 Andy Boyett <agb@openwrt.org>
 *
 *  This program is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License version 2 as published
 *  by the Free Software Foundation.
 */

#include <linux/module.h>
#include <linux/version.h>
#include <linux/kmod.h>

#include <linux/workqueue.h>
#include <linux/skbuff.h>
#include <linux/netlink.h>
#include <linux/kobject.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/of_gpio.h>
#include <linux/of_irq.h>
#include <linux/gpio_keys.h>
#include <linux/gpio/consumer.h>

#define BH_SKB_SIZE	2048

#define DRV_NAME	"gpio-keys"
#define PFX	DRV_NAME ": "

struct bh_event {
	const char		*name;
	unsigned int		type;
	char			*action;
	unsigned long		seen;

	struct sk_buff		*skb;
	struct work_struct	work;
};

struct bh_map {
	unsigned int	code;
	const char	*name;
};

struct gpio_keys_button_data {
	struct delayed_work work;
	unsigned long seen;
	int map_entry;
	int last_state;
	int count;
	int threshold;
	int can_sleep;
	int irq;
	unsigned int software_debounce;
	struct gpio_desc *gpiod;
	const struct gpio_keys_button *b;
};

extern u64 uevent_next_seqnum(void);

#define BH_MAP(_code, _name)		\
	{				\
		.code = (_code),	\
		.name = (_name),	\
	}

static struct bh_map button_map[] = {
	BH_MAP(BTN_0,			"BTN_0"),
	BH_MAP(BTN_1,			"BTN_1"),
	BH_MAP(BTN_2,			"BTN_2"),
	BH_MAP(BTN_3,			"BTN_3"),
	BH_MAP(BTN_4,			"BTN_4"),
	BH_MAP(BTN_5,			"BTN_5"),
	BH_MAP(BTN_6,			"BTN_6"),
	BH_MAP(BTN_7,			"BTN_7"),
	BH_MAP(BTN_8,			"BTN_8"),
	BH_MAP(BTN_9,			"BTN_9"),
	BH_MAP(KEY_BRIGHTNESS_ZERO,	"brightness_zero"),
	BH_MAP(KEY_CONFIG,		"config"),
	BH_MAP(KEY_COPY,		"copy"),
	BH_MAP(KEY_EJECTCD,		"eject"),
	BH_MAP(KEY_HELP,		"help"),
	BH_MAP(KEY_LIGHTS_TOGGLE,	"lights_toggle"),
	BH_MAP(KEY_PHONE,		"phone"),
	BH_MAP(KEY_POWER,		"power"),
	BH_MAP(KEY_POWER2,		"reboot"),
	BH_MAP(KEY_RESTART,		"reset"),
	BH_MAP(KEY_RFKILL,		"rfkill"),
	BH_MAP(KEY_VIDEO,		"video"),
	BH_MAP(KEY_VOLUMEDOWN,		"volume_down"),
	BH_MAP(KEY_VOLUMEUP,		"volume_up"),
	BH_MAP(KEY_WIMAX,		"wwan"),
	BH_MAP(KEY_WLAN,		"wlan"),
	BH_MAP(KEY_WPS_BUTTON,		"wps"),
};

/* -------------------------------------------------------------------------*/

static __printf(3, 4)
int bh_event_add_var(struct bh_event *event, int argv, const char *format, ...)
{
	char buf[128];
	char *s;
	va_list args;
	int len;

	if (argv)
		return 0;

	va_start(args, format);
	len = vsnprintf(buf, sizeof(buf), format, args);
	va_end(args);

	if (len >= sizeof(buf)) {
		WARN(1, "buffer size too small");
		return -ENOMEM;
	}

	s = skb_put(event->skb, len + 1);
	strcpy(s, buf);

	pr_debug(PFX "added variable '%s'\n", s);

	return 0;
}

static int button_hotplug_fill_event(struct bh_event *event)
{
	int ret;

	ret = bh_event_add_var(event, 0, "HOME=%s", "/");
	if (ret)
		return ret;

	ret = bh_event_add_var(event, 0, "PATH=%s",
					"/sbin:/bin:/usr/sbin:/usr/bin");
	if (ret)
		return ret;

	ret = bh_event_add_var(event, 0, "SUBSYSTEM=%s", "button");
	if (ret)
		return ret;

	ret = bh_event_add_var(event, 0, "ACTION=%s", event->action);
	if (ret)
		return ret;

	ret = bh_event_add_var(event, 0, "BUTTON=%s", event->name);
	if (ret)
		return ret;

	if (event->type == EV_SW) {
		ret = bh_event_add_var(event, 0, "TYPE=%s", "switch");
		if (ret)
			return ret;
	}

	ret = bh_event_add_var(event, 0, "SEEN=%ld", event->seen);
	if (ret)
		return ret;

	ret = bh_event_add_var(event, 0, "SEQNUM=%llu", uevent_next_seqnum());

	return ret;
}

static void button_hotplug_work(struct work_struct *work)
{
	struct bh_event *event = container_of(work, struct bh_event, work);
	int ret = 0;

	event->skb = alloc_skb(BH_SKB_SIZE, GFP_KERNEL);
	if (!event->skb)
		goto out_free_event;

	ret = bh_event_add_var(event, 0, "%s@", event->action);
	if (ret)
		goto out_free_skb;

	ret = button_hotplug_fill_event(event);
	if (ret)
		goto out_free_skb;

	NETLINK_CB(event->skb).dst_group = 1;
	broadcast_uevent(event->skb, 0, 1, GFP_KERNEL);

 out_free_skb:
	if (ret) {
		pr_err(PFX "work error %d\n", ret);
		kfree_skb(event->skb);
	}
 out_free_event:
	kfree(event);
}

static int button_hotplug_create_event(const char *name, unsigned int type,
		unsigned long seen, int pressed)
{
	struct bh_event *event;

	pr_debug(PFX "create event, name=%s, seen=%lu, pressed=%d\n",
		 name, seen, pressed);

	event = kzalloc(sizeof(*event), GFP_KERNEL);
	if (!event)
		return -ENOMEM;

	event->name = name;
	event->type = type;
	event->seen = seen;
	event->action = pressed ? "pressed" : "released";

	INIT_WORK(&event->work, (void *)(void *)button_hotplug_work);
	schedule_work(&event->work);

	return 0;
}

/* -------------------------------------------------------------------------*/

static int button_get_index(unsigned int code)
{
	int i;

	for (i = 0; i < ARRAY_SIZE(button_map); i++)
		if (button_map[i].code == code)
			return i;

	return -1;
}

static int gpio_button_get_value(struct gpio_keys_button_data *bdata)
{
	int val;

	if (bdata->can_sleep)
		val = !!gpiod_get_value_cansleep(bdata->gpiod);
	else
		val = !!gpiod_get_value(bdata->gpiod);

	return val;
}

static void gpio_keys_handle_button(struct gpio_keys_button_data *bdata)
{
	unsigned int type = bdata->b->type ?: EV_KEY;
	int state = gpio_button_get_value(bdata);
	unsigned long seen = jiffies;

	pr_debug(PFX "event type=%u, code=%u, pressed=%d\n",
		 type, bdata->b->code, state);

	/* is this the initialization state? */
	if (bdata->last_state == -1) {
		/*
		 * Don't advertise unpressed buttons on initialization.
		 * Just save their state and continue otherwise this
		 * can cause OpenWrt to enter failsafe.
		 */
		if (type == EV_KEY && state == 0)
			goto set_state;
		/*
		 * But we are very interested in pressed buttons and
		 * initial switch state. These will be reported to
		 * userland.
		 */
	} else if (bdata->last_state == state) {
		/* reset asserted counter (only relevant for polled keys) */
		bdata->count = 0;
		return;
	}

	if (bdata->count < bdata->threshold) {
		bdata->count++;
		return;
	}

	if (bdata->seen == 0)
		bdata->seen = seen;

	button_hotplug_create_event(button_map[bdata->map_entry].name, type,
				    (seen - bdata->seen) / HZ, state);
	bdata->seen = seen;

set_state:
	bdata->last_state = state;
	bdata->count = 0;
}

struct gpio_keys_button_dev {
	int polled;
	struct delayed_work work;

	struct device *dev;
	struct gpio_keys_platform_data *pdata;
	struct gpio_keys_button_data data[0];
};

static void gpio_keys_polled_queue_work(struct gpio_keys_button_dev *bdev)
{
	struct gpio_keys_platform_data *pdata = bdev->pdata;
	unsigned long delay = msecs_to_jiffies(pdata->poll_interval);

	if (delay >= HZ)
		delay = round_jiffies_relative(delay);
	schedule_delayed_work(&bdev->work, delay);
}

static void gpio_keys_polled_poll(struct work_struct *work)
{
	struct gpio_keys_button_dev *bdev =
		container_of(work, struct gpio_keys_button_dev, work.work);
	int i;

	for (i = 0; i < bdev->pdata->nbuttons; i++) {
		struct gpio_keys_button_data *bdata = &bdev->data[i];

		if (bdata->gpiod)
			gpio_keys_handle_button(bdata);
	}
	gpio_keys_polled_queue_work(bdev);
}

static void gpio_keys_polled_close(struct gpio_keys_button_dev *bdev)
{
	struct gpio_keys_platform_data *pdata = bdev->pdata;

	cancel_delayed_work_sync(&bdev->work);

	if (pdata->disable)
		pdata->disable(bdev->dev);
}

static void gpio_keys_irq_work_func(struct work_struct *work)
{
	struct gpio_keys_button_data *bdata = container_of(work,
		struct gpio_keys_button_data, work.work);

	gpio_keys_handle_button(bdata);
}

static irqreturn_t button_handle_irq(int irq, void *_bdata)
{
	struct gpio_keys_button_data *bdata =
		(struct gpio_keys_button_data *) _bdata;

	mod_delayed_work(system_wq, &bdata->work,
			 msecs_to_jiffies(bdata->software_debounce));

	return IRQ_HANDLED;
}

#ifdef CONFIG_OF
static struct gpio_keys_platform_data *
gpio_keys_get_devtree_pdata(struct device *dev)
{
	struct device_node *node, *pp;
	struct gpio_keys_platform_data *pdata;
	struct gpio_keys_button *button;
	int nbuttons;
	int i = 0;

	node = dev->of_node;
	if (!node)
		return NULL;

	nbuttons = of_get_child_count(node);
	if (nbuttons == 0)
		return ERR_PTR(-EINVAL);

	pdata = devm_kzalloc(dev, sizeof(*pdata) + nbuttons * (sizeof *button),
		GFP_KERNEL);
	if (!pdata)
		return ERR_PTR(-ENOMEM);

	pdata->buttons = (struct gpio_keys_button *)(pdata + 1);
	pdata->nbuttons = nbuttons;

	pdata->rep = !!of_get_property(node, "autorepeat", NULL);
	of_property_read_u32(node, "poll-interval", &pdata->poll_interval);

	for_each_child_of_node(node, pp) {
		button = (struct gpio_keys_button *)(&pdata->buttons[i++]);

		if (of_property_read_u32(pp, "linux,code", &button->code)) {
			dev_err(dev, "Button node '%s' without keycode\n",
				pp->full_name);
			of_node_put(pp);
			return ERR_PTR(-EINVAL);
		}

		button->desc = of_get_property(pp, "label", NULL);

		if (of_property_read_u32(pp, "linux,input-type", &button->type))
			button->type = EV_KEY;

		button->wakeup = !!of_get_property(pp, "gpio-key,wakeup", NULL);

		if (of_property_read_u32(pp, "debounce-interval",
					&button->debounce_interval))
			button->debounce_interval = 5;

		button->irq = irq_of_parse_and_map(pp, 0);
		button->gpio = -ENOENT; /* mark this as device-tree */
	}

	return pdata;
}

static struct of_device_id gpio_keys_of_match[] = {
	{ .compatible = "gpio-keys", },
	{ },
};
MODULE_DEVICE_TABLE(of, gpio_keys_of_match);

static struct of_device_id gpio_keys_polled_of_match[] = {
	{ .compatible = "gpio-keys-polled", },
	{ },
};
MODULE_DEVICE_TABLE(of, gpio_keys_polled_of_match);

#else

static inline struct gpio_keys_platform_data *
gpio_keys_get_devtree_pdata(struct device *dev)
{
	return NULL;
}
#endif

static int gpio_keys_button_probe(struct platform_device *pdev,
		struct gpio_keys_button_dev **_bdev, int polled)
{
	struct device *dev = &pdev->dev;
	struct gpio_keys_platform_data *pdata = dev_get_platdata(dev);
	struct gpio_keys_button_dev *bdev;
	struct gpio_keys_button *buttons;
	struct device_node *prev = NULL;
	int error = 0;
	int i;

	if (!pdata) {
		pdata = gpio_keys_get_devtree_pdata(dev);
		if (IS_ERR(pdata))
			return PTR_ERR(pdata);
		if (!pdata) {
			dev_err(dev, "missing platform data\n");
			return -EINVAL;
		}
	}

	if (polled && !pdata->poll_interval) {
		dev_err(dev, "missing poll_interval value\n");
		return -EINVAL;
	}

	buttons = devm_kzalloc(dev, pdata->nbuttons * sizeof(struct gpio_keys_button),
		       GFP_KERNEL);
	if (!buttons) {
		dev_err(dev, "no memory for button data\n");
		return -ENOMEM;
	}
	memcpy(buttons, pdata->buttons, pdata->nbuttons * sizeof(struct gpio_keys_button));

	bdev = devm_kzalloc(dev, sizeof(struct gpio_keys_button_dev) +
		       pdata->nbuttons * sizeof(struct gpio_keys_button_data),
		       GFP_KERNEL);
	if (!bdev) {
		dev_err(dev, "no memory for private data\n");
		return -ENOMEM;
	}

	bdev->polled = polled;

	for (i = 0; i < pdata->nbuttons; i++) {
		struct gpio_keys_button *button = &buttons[i];
		struct gpio_keys_button_data *bdata = &bdev->data[i];
		const char *desc = button->desc ? button->desc : DRV_NAME;

		if (button->wakeup) {
			dev_err(dev, "does not support wakeup\n");
			error = -EINVAL;
			goto out;
		}

		bdata->map_entry = button_get_index(button->code);
		if (bdata->map_entry < 0) {
			dev_err(dev, "does not support key code:%u\n",
				button->code);
			error = -EINVAL;
			goto out;
		}

		if (!(button->type == 0 || button->type == EV_KEY ||
		      button->type == EV_SW)) {
			dev_err(dev, "only supports buttons or switches\n");
			error = -EINVAL;
			goto out;
		}

		if (gpio_is_valid(button->gpio)) {
			/* legacy platform data... but is it the lookup table? */
			bdata->gpiod = devm_gpiod_get_index(dev, desc, i,
							    GPIOD_IN);
			if (IS_ERR(bdata->gpiod)) {
				/* or the legacy (button->gpio is good) way? */
				error = devm_gpio_request_one(dev,
					button->gpio, GPIOF_IN | (
					button->active_low ? GPIOF_ACTIVE_LOW :
					0), desc);
				if (error) {
					if (error != -EPROBE_DEFER) {
						dev_err(dev, "unable to claim gpio %d, err=%d\n",
							button->gpio, error);
					}
					goto out;
				}

				bdata->gpiod = gpio_to_desc(button->gpio);
			}
		} else {
			/* Device-tree */
			struct device_node *child =
				of_get_next_child(dev->of_node, prev);

			bdata->gpiod = devm_gpiod_get_from_of_node(dev,
				child, "gpios", 0, GPIOD_IN, desc);

			prev = child;
		}

		if (IS_ERR_OR_NULL(bdata->gpiod)) {
			error = IS_ERR(bdata->gpiod) ? PTR_ERR(bdata->gpiod) :
				-EINVAL;
			goto out;
		}

		bdata->can_sleep = gpiod_cansleep(bdata->gpiod);
		bdata->last_state = -1; /* Unknown state on boot */

		if (bdev->polled) {
			bdata->threshold = DIV_ROUND_UP(button->debounce_interval,
							pdata->poll_interval);
		} else {
			/* bdata->threshold = 0; already initialized */

			if (button->debounce_interval) {
				error = gpiod_set_debounce(bdata->gpiod,
					button->debounce_interval * 1000);
				/*
				 * use timer if gpiolib doesn't provide
				 * debounce.
				 */
				if (error < 0) {
					bdata->software_debounce =
						button->debounce_interval;
				}
			}
		}

		bdata->b = &pdata->buttons[i];
	}

	bdev->dev = &pdev->dev;
	bdev->pdata = pdata;
	platform_set_drvdata(pdev, bdev);

	*_bdev = bdev;
	error = 0;

out:
	of_node_put(prev);
	return error;
}

static int gpio_keys_probe(struct platform_device *pdev)
{
	struct gpio_keys_platform_data *pdata;
	struct gpio_keys_button_dev *bdev;
	int ret, i;

	ret = gpio_keys_button_probe(pdev, &bdev, 0);
	if (ret)
		return ret;

	pdata = bdev->pdata;
	for (i = 0; i < pdata->nbuttons; i++) {
		const struct gpio_keys_button *button = &pdata->buttons[i];
		struct gpio_keys_button_data *bdata = &bdev->data[i];
		unsigned long irqflags = IRQF_ONESHOT;

		INIT_DELAYED_WORK(&bdata->work, gpio_keys_irq_work_func);

		if (!button->irq) {
			bdata->irq = gpiod_to_irq(bdata->gpiod);
			if (bdata->irq < 0) {
				dev_err(&pdev->dev, "failed to get irq for gpio:%d\n",
					button->gpio);
				continue;
			}

			irqflags |= IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
		} else {
			bdata->irq = button->irq;
		}

		schedule_delayed_work(&bdata->work,
				      msecs_to_jiffies(bdata->software_debounce));

		ret = devm_request_threaded_irq(&pdev->dev,
			bdata->irq, NULL, button_handle_irq,
			irqflags, dev_name(&pdev->dev), bdata);
		if (ret < 0) {
			bdata->irq = 0;
			dev_err(&pdev->dev, "failed to request irq:%d for gpio:%d\n",
				bdata->irq, button->gpio);
			continue;
		} else {
			dev_dbg(&pdev->dev, "gpio:%d has irq:%d\n",
				button->gpio, bdata->irq);
		}
	}

	return 0;
}

static int gpio_keys_polled_probe(struct platform_device *pdev)
{
	struct gpio_keys_platform_data *pdata;
	struct gpio_keys_button_dev *bdev;
	int ret;

	ret = gpio_keys_button_probe(pdev, &bdev, 1);
	if (ret)
		return ret;

	INIT_DELAYED_WORK(&bdev->work, gpio_keys_polled_poll);

	pdata = bdev->pdata;
	if (pdata->enable)
		pdata->enable(bdev->dev);

	gpio_keys_polled_queue_work(bdev);

	return ret;
}

static void gpio_keys_irq_close(struct gpio_keys_button_dev *bdev)
{
	struct gpio_keys_platform_data *pdata = bdev->pdata;
	size_t i;

	for (i = 0; i < pdata->nbuttons; i++) {
		struct gpio_keys_button_data *bdata = &bdev->data[i];

		disable_irq(bdata->irq);
		cancel_delayed_work_sync(&bdata->work);
	}
}

static int gpio_keys_remove(struct platform_device *pdev)
{
	struct gpio_keys_button_dev *bdev = platform_get_drvdata(pdev);

	platform_set_drvdata(pdev, NULL);

	if (bdev->polled)
		gpio_keys_polled_close(bdev);
	else
		gpio_keys_irq_close(bdev);

	return 0;
}

static struct platform_driver gpio_keys_driver = {
	.probe	= gpio_keys_probe,
	.remove	= gpio_keys_remove,
	.driver	= {
		.name	= "gpio-keys",
		.owner	= THIS_MODULE,
		.of_match_table = of_match_ptr(gpio_keys_of_match),
	},
};

static struct platform_driver gpio_keys_polled_driver = {
	.probe	= gpio_keys_polled_probe,
	.remove	= gpio_keys_remove,
	.driver	= {
		.name	= "gpio-keys-polled",
		.owner	= THIS_MODULE,
		.of_match_table = of_match_ptr(gpio_keys_polled_of_match),
	},
};

static int __init gpio_button_init(void)
{
	int ret;

	ret = platform_driver_register(&gpio_keys_driver);
	if (ret)
		return ret;

	ret = platform_driver_register(&gpio_keys_polled_driver);
	if (ret)
		platform_driver_unregister(&gpio_keys_driver);

	return ret;
}

static void __exit gpio_button_exit(void)
{
	platform_driver_unregister(&gpio_keys_driver);
	platform_driver_unregister(&gpio_keys_polled_driver);
}

module_init(gpio_button_init);
module_exit(gpio_button_exit);

MODULE_AUTHOR("Gabor Juhos <juhosg@openwrt.org>");
MODULE_AUTHOR("Felix Fietkau <nbd@nbd.name>");
MODULE_DESCRIPTION("Polled GPIO Buttons hotplug driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:" DRV_NAME);